garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /boot/src/pc.rs

raw

//! Starting the kernel on a PC, by Multiboot2 (its specification, 2.0),
//! as GRUB did: the kernel's ELF read whole, its segments put at their
//! physical addresses once the boot services are left, and the kernel
//! entered at its ELF entry in 32-bit protected mode with paging off, the
//! magic in EAX and the information in EBX: the command line, the memory
//! map, the framebuffer UEFI's GOP has on, and ACPI's root pointers.
//!
//! Leaving long mode takes a few instructions that must run below 4 GiB,
//! identity mapped (`TRAMPOLINE`): copied to a page there with the GDT
//! they load.

use crate::efi::{self, Firmware, memory};

const PAGE: usize = 4096;
const BELOW_4GIB: u64 = 0xffff_f000;

/// What one ELF segment puts where.
#[derive(Clone, Copy, Default)]
struct Segment {
    virtual_: u64,
    physical: u64,
    file: u64,
    file_size: u64,
    memory_size: u64,
}

fn u16_at(b: &[u8], at: usize) -> u16 {
    u16::from_le_bytes([b[at], b[at + 1]])
}
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 overlaps(a: (u64, u64), b: (u64, u64)) -> bool {
    a.0 < b.1 && b.0 < a.1
}

/// Allocates `pages` below 4 GiB away from `avoid`, trying a few times.
fn allocate_away(firmware: &Firmware, pages: usize, avoid: (u64, u64)) -> Option<u64> {
    for _ in 0..8 {
        let at = firmware.allocate(pages, Some(BELOW_4GIB))?;
        if !overlaps((at, at + (pages * PAGE) as u64), avoid) {
            return Some(at);
        }
    }
    None
}

core::arch::global_asm!(
    ".globl pinnacle_trampoline",
    ".globl pinnacle_trampoline_end",
    // Entered in long mode with the information in EDI, the entry in ESI,
    // the GDT's pointer in RDX. All three below 4 GiB, as this code is.
    "pinnacle_trampoline:",
    "cli",
    "cld",
    "lgdt [rdx]",
    "push 0x08",
    "lea rax, [rip + 2f]",
    "push rax",
    "retfq",
    ".code32",
    "2:",
    "mov ax, 0x10",
    "mov ds, ax",
    "mov es, ax",
    "mov fs, ax",
    "mov gs, ax",
    "mov ss, ax",
    // Paging off leaves long mode; then long mode's enable bit off.
    "mov eax, cr0",
    "and eax, 0x7fffffff",
    "mov cr0, eax",
    "mov ecx, 0xc0000080",
    "rdmsr",
    "and eax, 0xfffffeff",
    "wrmsr",
    "mov eax, cr4",
    "and eax, 0xffffffdf",
    "mov cr4, eax",
    "mov eax, 0x36d76289",
    "mov ebx, edi",
    "jmp esi",
    ".code64",
    "pinnacle_trampoline_end:",
);

unsafe extern "C" {
    static pinnacle_trampoline: u8;
    static pinnacle_trampoline_end: u8;
}

pub fn start(firmware: &Firmware, line: &str) -> &'static str {
    let Some((file, size)) = firmware.read_file("\\PINNACLE\\KERNEL", Some(BELOW_4GIB)) else {
        return "no kernel at PINNACLE/KERNEL";
    };
    // SAFETY: the pages the file was read into.
    let elf = unsafe { core::slice::from_raw_parts(file as *const u8, size) };
    if size < 64 || &elf[..4] != b"\x7fELF" || elf[4] != 2 || u16_at(elf, 18) != 0x3e {
        return "PINNACLE/KERNEL is not an x86-64 ELF";
    }
    let entry = u64_at(elf, 24);
    let (table, entry_size, count) = (
        u64_at(elf, 32) as usize,
        u16_at(elf, 54) as usize,
        u16_at(elf, 56) as usize,
    );
    let mut segments = [Segment::default(); 16];
    let mut n = 0;
    let mut span = (u64::MAX, 0u64);
    for i in 0..count {
        let h = &elf[table + i * entry_size..];
        // PT_LOAD only.
        if u32_at(h, 0) != 1 || n == segments.len() {
            continue;
        }
        let s = Segment {
            virtual_: u64_at(h, 16),
            physical: u64_at(h, 24),
            file: u64_at(h, 8),
            file_size: u64_at(h, 32),
            memory_size: u64_at(h, 40),
        };
        if s.file + s.file_size > size as u64 || s.physical + s.memory_size > 1 << 32 {
            return "the kernel's ELF has a segment that does not fit";
        }
        span = (span.0.min(s.physical), span.1.max(s.physical + s.memory_size));
        segments[n] = s;
        n += 1;
    }
    // An entry in a segment's virtual addresses is where that segment's
    // physical ones put it, as GRUB has it.
    let entry = segments[..n]
        .iter()
        .find(|s| (s.virtual_..s.virtual_ + s.memory_size).contains(&entry))
        .map_or(entry, |s| entry - s.virtual_ + s.physical);
    if n == 0 || entry >= 1 << 32 {
        return "the kernel's ELF has nothing to load below 4 GiB";
    }
    // The file must not lie where it goes: then it is read again elsewhere.
    let file = if overlaps((file, file + size as u64), span) {
        let Some(again) = allocate_away(firmware, size.div_ceil(PAGE), span) else {
            return "no memory for the kernel away from where it goes";
        };
        // SAFETY: both ranges are ours, apart.
        unsafe { core::ptr::copy_nonoverlapping(file as *const u8, again as *mut u8, size) };
        again
    } else {
        file
    };

    // The information, the trampoline and its GDT, all below 4 GiB and away
    // from the kernel.
    let info_pages = 16;
    let (Some(info), Some(low), Some(tables)) = (
        allocate_away(firmware, info_pages, span),
        allocate_away(firmware, 1, span),
        allocate_away(firmware, 2, span),
    ) else {
        return "no memory below 4 GiB for the kernel's information";
    };
    // Page tables of our own for the copy: the firmware's may lie where
    // the kernel goes. All of the first 512 GiB, identity mapped in 1 GiB
    // pages, wherever the firmware put this loader and its stack.
    // SAFETY: the two pages just allocated.
    unsafe {
        let (pml4, pdpt) = (tables as *mut u64, (tables + PAGE as u64) as *mut u64);
        core::ptr::write_bytes(pml4, 0, 512);
        pml4.write(tables + PAGE as u64 | 0b11);
        for i in 0..512u64 {
            pdpt.add(i as usize).write(i << 30 | 0x83);
        }
    }
    // SAFETY: the trampoline's bytes, and a page of ours for them, the GDT
    // and its pointer.
    unsafe {
        let from = &raw const pinnacle_trampoline;
        let len = (&raw const pinnacle_trampoline_end as usize) - from as usize;
        core::ptr::copy_nonoverlapping(from, low as *mut u8, len);
        let gdt = (low + 2048) as *mut u64;
        gdt.write(0);
        gdt.add(1).write(0x00cf_9a00_0000_ffff); // 0x08: 32-bit code
        gdt.add(2).write(0x00cf_9200_0000_ffff); // 0x10: data
        let pointer = (low + 2048 + 64) as *mut u8;
        (pointer as *mut u16).write_unaligned(23);
        (pointer.add(2) as *mut u64).write_unaligned(gdt as u64);
    }

    let framebuffer = framebuffer(firmware);
    let rsdp = firmware
        .configuration(efi::ACPI_20)
        .map(|t| (t as u64, true))
        .or_else(|| firmware.configuration(efi::ACPI_10).map(|t| (t as u64, false)));

    firmware.print("Pinnacle: starting the kernel\n");
    let mut map = [0u8; 32 * 1024];
    for _ in 0..4 {
        let Some((map_size, key, descriptor)) = firmware.memory_map(&mut map) else {
            return "no memory map";
        };
        // SAFETY: the pages allocated for the information.
        let out = unsafe { core::slice::from_raw_parts_mut(info as *mut u8, info_pages * PAGE) };
        let Some(_) = information(out, line, &map[..map_size], descriptor, framebuffer, rsdp) else {
            return "the kernel's information does not fit";
        };
        if firmware.exit(key) {
            // SAFETY: the boot services are left: all of memory is ours.
            unsafe {
                core::arch::asm!("cli", "mov cr3, {}", in(reg) tables, options(nostack));
                for s in &segments[..n] {
                    core::ptr::copy(
                        (file + s.file) as *const u8,
                        s.physical as *mut u8,
                        s.file_size as usize,
                    );
                    core::ptr::write_bytes(
                        (s.physical + s.file_size) as *mut u8,
                        0,
                        (s.memory_size - s.file_size) as usize,
                    );
                }
                core::arch::asm!(
                    "jmp rax",
                    in("rax") low,
                    in("rdi") info,
                    in("rsi") entry,
                    in("rdx") low + 2048 + 64,
                    options(noreturn),
                )
            }
        }
    }
    "the firmware's boot services could not be left"
}

/// GOP's framebuffer: address, pitch, width, height, and the byte order of
/// its pixels (true: blue first). None when there is none to draw on.
fn framebuffer(firmware: &Firmware) -> Option<(u64, u32, u32, u32, bool)> {
    let gop: *mut efi::GraphicsOutput = firmware.locate(efi::GRAPHICS_OUTPUT)?;
    // SAFETY: the protocol the firmware answered with, and its mode.
    unsafe {
        fit_mode(gop);
        let mode = &*(*gop).mode;
        let info = &*mode.info;
        let bgr = match info.pixel_format {
            0 => false,
            1 => true,
            _ => return None,
        };
        (mode.framebuffer != 0).then_some((
            mode.framebuffer,
            info.pixels_per_line * 4,
            info.width,
            info.height,
            bgr,
        ))
    }
}

/// Whether the kernel can have a framebuffer of `width` × `height`: its
/// `drivers::display::fits` (one block of pages, 16 MiB, at most 4096 a
/// side).
fn fits(width: u32, height: u32) -> bool {
    (320..=4096).contains(&width) && (320..=4096).contains(&height) && width * height * 4 <= 16 << 20
}

/// Leaves GOP's mode as the firmware set it when the kernel can draw at
/// that size; else (a laptop's 2880×1800 or 4K panel, at its own size)
/// sets the largest mode that fits, of the same shape where there is one,
/// which the panel scales up.
///
/// # Safety
/// `gop` is the firmware's graphics output protocol, boot services on.
unsafe fn fit_mode(gop: *mut efi::GraphicsOutput) {
    let mode = unsafe { &*(*gop).mode };
    let now = unsafe { &*mode.info };
    if fits(now.width, now.height) {
        return;
    }
    let (w0, h0) = (u64::from(now.width), u64::from(now.height));
    let mut best: Option<(bool, u32, u32)> = None;
    for n in 0..mode.max_mode {
        let mut size = 0usize;
        let mut info: *const efi::GraphicsInfo = core::ptr::null();
        if unsafe { ((*gop).query_mode)(gop, n, &mut size, &mut info) } != efi::SUCCESS || info.is_null() {
            continue;
        }
        let i = unsafe { &*info };
        if i.pixel_format > 1 || !fits(i.width, i.height) {
            continue;
        }
        let (w, h) = (u64::from(i.width), u64::from(i.height));
        // Within 2 % of the panel's shape.
        let shaped = (w * h0).abs_diff(h * w0) * 50 <= w0 * h0;
        let key = (shaped, i.width * i.height, n);
        if best.is_none_or(|(s, area, _)| (key.0, key.1) > (s, area)) {
            best = Some(key);
        }
    }
    if let Some((_, _, n)) = best {
        unsafe { ((*gop).set_mode)(gop, n) };
    }
}

/// Writes the Multiboot2 information into `out`: its size.
fn information(
    out: &mut [u8],
    line: &str,
    map: &[u8],
    descriptor: usize,
    framebuffer: Option<(u64, u32, u32, u32, bool)>,
    rsdp: Option<(u64, bool)>,
) -> Option<usize> {
    let mut at = 8;
    let mut tag =
        |out: &mut [u8], kind: u32, body: &mut dyn FnMut(&mut [u8]) -> Option<usize>| -> Option<()> {
            let start = at;
            let size = 8 + body(out.get_mut(start + 8..)?)?;
            let header = out.get_mut(start..start + 8)?;
            header[..4].copy_from_slice(&kind.to_le_bytes());
            header[4..].copy_from_slice(&(size as u32).to_le_bytes());
            at = (start + size).next_multiple_of(8);
            Some(())
        };
    tag(out, 1, &mut |b| {
        b.get_mut(..line.len() + 1)?[..line.len()].copy_from_slice(line.as_bytes());
        b[line.len()] = 0;
        Some(line.len() + 1)
    })?;
    // The memory map, in Multiboot's kinds, neighbours of a kind merged.
    tag(out, 6, &mut |b| {
        let header = b.get_mut(..8)?;
        header[..4].copy_from_slice(&24u32.to_le_bytes());
        header[4..].fill(0);
        let mut n = 8;
        let mut last: Option<(u64, u64, u32)> = None;
        let put = |b: &mut [u8], n: &mut usize, (start, end, kind): (u64, u64, u32)| -> Option<()> {
            let e = b.get_mut(*n..*n + 24)?;
            e[..8].copy_from_slice(&start.to_le_bytes());
            e[8..16].copy_from_slice(&(end - start).to_le_bytes());
            e[16..20].copy_from_slice(&kind.to_le_bytes());
            e[20..24].fill(0);
            *n += 24;
            Some(())
        };
        for d in map.chunks_exact(descriptor) {
            let kind = match u32_at(d, 0) {
                memory::LOADER_CODE
                | memory::LOADER_DATA
                | memory::BOOT_SERVICES_CODE
                | memory::BOOT_SERVICES_DATA
                | memory::CONVENTIONAL => 1,
                memory::ACPI_RECLAIM => 3,
                memory::ACPI_NVS => 4,
                memory::UNUSABLE => 5,
                _ => 2,
            };
            let start = u64_at(d, 8);
            let end = start + u64_at(d, 24) * PAGE as u64;
            last = match last {
                Some((s, e, k)) if k == kind && e == start => Some((s, end, k)),
                Some(previous) => {
                    put(b, &mut n, previous)?;
                    Some((start, end, kind))
                }
                None => Some((start, end, kind)),
            };
        }
        if let Some(previous) = last {
            put(b, &mut n, previous)?;
        }
        Some(n)
    })?;
    if let Some((address, pitch, width, height, bgr)) = framebuffer {
        tag(out, 8, &mut |b| {
            let f = b.get_mut(..30)?;
            f[..8].copy_from_slice(&address.to_le_bytes());
            f[8..12].copy_from_slice(&pitch.to_le_bytes());
            f[12..16].copy_from_slice(&width.to_le_bytes());
            f[16..20].copy_from_slice(&height.to_le_bytes());
            f[20] = 32;
            f[21] = 1; // RGB
            f[22..24].fill(0);
            // Each colour's position and size: red, green, blue.
            let (red, blue) = if bgr { (16, 0) } else { (0, 16) };
            f[24..30].copy_from_slice(&[red, 8, 8, 8, blue, 8]);
            Some(30)
        })?;
    }
    if let Some((address, new)) = rsdp {
        let len = if new { 36 } else { 20 };
        // SAFETY: the root pointer the firmware's table points at.
        let bytes = unsafe { core::slice::from_raw_parts(address as *const u8, len) };
        tag(out, if new { 15 } else { 14 }, &mut |b| {
            b.get_mut(..len)?.copy_from_slice(bytes);
            Some(len)
        })?;
    }
    tag(out, 0, &mut |_| Some(0))?;
    let header = out.get_mut(..8)?;
    header[..4].copy_from_slice(&(at as u32).to_le_bytes());
    header[4..].fill(0);
    Some(at)
}