garage44.eu/jeroen/pinnacle

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

.. /kernel/src/mm/mod.rs

raw

//! Memory: physical pages ([`pages`]) and the kernel heap on top of them
//! ([`heap`]). The kernel reaches all of RAM in the top half, at
//! [`KERNEL_OFFSET`](crate::mmu::KERNEL_OFFSET) above its physical address.

pub mod heap;
pub mod pages;
#[cfg_attr(target_arch = "x86_64", path = "../x86_64/space.rs")]
pub mod space;

use crate::mmu::{Kind, Region, virt};

pub const PAGE: usize = 4096;

unsafe extern "C" {
    static __kernel_start: u8;
    static __kernel_end: u8;
}

/// The board's RAM: its first Normal region. Both boards have one.
const fn ram(regions: &[Region]) -> (usize, usize) {
    let mut i = 0;
    while i < regions.len() {
        if let Kind::Normal = regions[i].kind {
            return (regions[i].start as usize, regions[i].end as usize);
        }
        i += 1;
    }
    panic!("the board has no RAM")
}

pub const RAM: (usize, usize) = ram(crate::board::MEMORY);

/// Hands every page of RAM to the page allocator except the kernel image,
/// what the board reserves (firmware) and the device tree, worked out in
/// physical addresses (the device tree's from the loader is one too).
pub fn init(device_tree: usize) {
    init_without(device_tree, core::iter::empty(), None);
}

/// As [`init`], keeping `firmware`'s ranges (physical) out as well: what a
/// PC's memory map does not call RAM, which also says where RAM ends.
#[cfg_attr(target_arch = "aarch64", allow(dead_code))]
pub fn init_from_map(firmware: impl Iterator<Item = (usize, usize)>, end: usize) {
    init_without(0, firmware, Some(end));
}

fn init_without(device_tree: usize, firmware: impl Iterator<Item = (usize, usize)>, end: Option<usize>) {
    let kernel = (
        crate::mmu::physical(&raw const __kernel_start as usize),
        crate::mmu::physical(&raw const __kernel_end as usize),
    );
    let mut taken = [(0, 0); 32];
    let mut n = 0;
    taken[n] = kernel;
    n += 1;
    for &range in crate::board::RESERVED {
        taken[n] = range;
        n += 1;
    }
    for range in firmware {
        if n < taken.len() {
            taken[n] = range;
            n += 1;
        }
    }
    if let Some(size) = device_tree_size(device_tree) {
        taken[n] = (device_tree, device_tree + size);
        n += 1;
        // What the loader reserved: firmware, and the screen it lit.
        if let Some(tree) = crate::fdt::DeviceTree::at(device_tree) {
            tree.reserved(|address, size| {
                if n < taken.len() && size > 0 {
                    taken[n] = (address as usize, (address + size) as usize);
                    n += 1;
                }
            });
        }
    }
    // The lit screen's memory, however it was found (`drivers::scanout`).
    if let Some(scanout) = crate::drivers::scanout::get()
        && n < taken.len()
    {
        taken[n] = scanout.range();
        n += 1;
    }
    let taken = &mut taken[..n];
    taken.sort_unstable();

    // What every machine of the board has first (reading the device tree
    // allocates, so the heap needs pages before it); the rest once the
    // device tree has said how much there is.
    let first = RAM.1.min(RAM.0 + LEAST).min(end.unwrap_or(usize::MAX));
    add_pages(RAM.0, first, taken);
    let end = end.map_or_else(|| ram_end(device_tree), |end| end.min(RAM.1));
    RAM_END.store(end, core::sync::atomic::Ordering::Relaxed);
    if end > first {
        add_pages(first, end, taken);
    }
}

/// The RAM a machine of the board has at least: QEMU's of the self-check.
const LEAST: usize = 256 << 20;

/// Hands the pages from `from` to `to` (physical) to the allocator, but those
/// `taken` (sorted).
fn add_pages(from: usize, to: usize, taken: &[(usize, usize)]) {
    let mut start = from;
    for &(hole, hole_end) in taken {
        let (hole, hole_end) = (hole & !(PAGE - 1), hole_end.next_multiple_of(PAGE));
        if hole > start && start < to {
            pages::add(virt(start), virt(hole.min(to)));
        }
        start = start.max(hole_end);
    }
    if start < to {
        pages::add(virt(start), virt(to));
    }
}

/// Where RAM ends, once `init` has found it (`ram_end`).
static RAM_END: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(RAM.1);

/// Where RAM starts and ends, physical.
pub fn ram_range() -> (usize, usize) {
    (RAM.0, RAM_END.load(core::sync::atomic::Ordering::Relaxed))
}

/// The bytes of RAM the machine has (from its start to its end).
pub fn ram_size() -> usize {
    RAM_END.load(core::sync::atomic::Ordering::Relaxed) - RAM.0
}

/// Where RAM ends: as the device tree's memory node says (a machine of
/// less than the board allows, QEMU's of any `-m`), within what the board
/// maps; the board's end without one.
fn ram_end(device_tree: usize) -> usize {
    let mut end = None;
    if let Some(tree) = crate::fdt::DeviceTree::at(device_tree) {
        tree.nodes(|node| {
            if node.device_type() == Some("memory") {
                for (start, size) in node.regs() {
                    if start as usize == RAM.0 {
                        end = Some((start + size) as usize);
                    }
                }
            }
        });
    }
    end.map_or(RAM.1, |end| end.min(RAM.1))
}

/// The size a flattened device tree's header gives, if `address` holds one.
fn device_tree_size(address: usize) -> Option<usize> {
    const MAGIC: u32 = 0xd00d_feed;
    if address == 0 || !address.is_multiple_of(8) || address < RAM.0 || address >= RAM.1 {
        return None;
    }
    // SAFETY: inside RAM, mapped Normal; the header is big-endian.
    let (magic, size) = unsafe {
        let header = virt(address) as *const u32;
        (u32::from_be(header.read()), u32::from_be(header.add(1).read()))
    };
    (magic == MAGIC).then_some(size as usize)
}