garage44.eu/jeroen/pinnacle

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

.. /kernel/src/mm/pages.rs

raw

//! The physical page allocator: a buddy allocator over the board's RAM.
//! Blocks are handed out by their kernel (top-half) address.
//!
//! Blocks are 2^order pages, order 0 to [`MAX_ORDER`] (4 KiB to 16 MiB), so a
//! driver gets physically contiguous memory (a framebuffer, a DMA ring) and
//! freeing merges a block with its buddy at once. Every operation is O(orders):
//! free blocks are linked through their own first bytes (a doubly linked list
//! per order, so a buddy leaves its list in O(1)), and one byte per page says
//! whether that page heads a free block, and of which order.

use super::{PAGE, RAM};
use crate::sync::{Global, SpinLock};

/// 16 MiB: a 1920×1080 framebuffer, or a window that size, in one block.
pub const MAX_ORDER: usize = 12;
const ORDERS: usize = MAX_ORDER + 1;
const PAGES: usize = (RAM.1 - RAM.0) / PAGE;
const NONE: usize = usize::MAX;

/// The link a free block keeps in its first bytes.
#[repr(C)]
struct Link {
    next: usize,
    prev: usize,
}

struct Pages {
    /// Per order, the address of the first free block, or [`NONE`].
    heads: [usize; ORDERS],
    /// Free pages in all.
    free: usize,
}

static ALLOCATOR: SpinLock<Pages> = SpinLock::new(Pages {
    heads: [NONE; ORDERS],
    free: 0,
});
/// Per page: 0 when it does not head a free block, else its order + 1. Kept
/// apart from [`ALLOCATOR`] so it lies in `.bss`: 1 MiB on a 4 GiB board that
/// would otherwise be in the image. Touched only under [`ALLOCATOR`]'s lock.
static FREE_ORDER: Global<[u8; PAGES]> = Global::new([0; PAGES]);

fn pfn(address: usize) -> usize {
    let address = crate::mmu::physical(address);
    (address - RAM.0) / PAGE
}

fn address(pfn: usize) -> usize {
    crate::mmu::virt(RAM.0 + pfn * PAGE)
}

fn link(address: usize) -> *mut Link {
    address as *mut Link
}

impl Pages {
    fn push(&mut self, pfn: usize, order: usize) {
        let at = address(pfn);
        let next = self.heads[order];
        // SAFETY: the block is free, so its first bytes are ours.
        unsafe {
            link(at).write(Link { next, prev: NONE });
            if next != NONE {
                (*link(next)).prev = at;
            }
        }
        self.heads[order] = at;
        free_order()[pfn] = order as u8 + 1;
    }

    fn remove(&mut self, pfn: usize, order: usize) {
        let at = address(pfn);
        // SAFETY: the block is on the list for `order`.
        unsafe {
            let Link { next, prev } = link(at).read();
            if prev == NONE {
                self.heads[order] = next;
            } else {
                (*link(prev)).next = next;
            }
            if next != NONE {
                (*link(next)).prev = prev;
            }
        }
        free_order()[pfn] = 0;
    }

    fn alloc(&mut self, order: usize) -> Option<usize> {
        let from = (order..ORDERS).find(|&o| self.heads[o] != NONE)?;
        let pfn = pfn(self.heads[from]);
        self.remove(pfn, from);
        // Split down, freeing the upper halves.
        for o in (order..from).rev() {
            self.push(pfn + (1 << o), o);
        }
        self.free -= 1 << order;
        Some(address(pfn))
    }

    fn release(&mut self, mut pfn: usize, mut order: usize) {
        self.free += 1 << order;
        while order < MAX_ORDER {
            let buddy = pfn ^ (1 << order);
            if buddy >= PAGES || free_order()[buddy] != order as u8 + 1 {
                break;
            }
            self.remove(buddy, order);
            pfn = pfn.min(buddy);
            order += 1;
        }
        self.push(pfn, order);
    }
}

/// Gives `start..end` (page aligned) to the allocator, in the largest
/// aligned blocks that fit.
pub fn add(start: usize, end: usize) {
    let mut pages = ALLOCATOR.lock();
    let (mut pfn, end) = (pfn(start), pfn(end));
    while pfn < end {
        let order = (0..=MAX_ORDER)
            .rev()
            .find(|&o| pfn.is_multiple_of(1 << o) && pfn + (1 << o) <= end)
            .unwrap();
        pages.release(pfn, order);
        pfn += 1 << order;
    }
}

/// 2^order contiguous pages, aligned to their size; `None` when none are left.
pub fn alloc(order: usize) -> Option<usize> {
    assert!(order <= MAX_ORDER);
    ALLOCATOR.lock().alloc(order)
}

/// Returns a block [`alloc`] gave out, with the same order.
pub fn free(address: usize, order: usize) {
    ALLOCATOR.lock().release(pfn(address), order);
}

/// Free pages, and free blocks of the largest order.
pub fn stats() -> (usize, usize) {
    let pages = ALLOCATOR.lock();
    let largest = free_order()
        .iter()
        .filter(|&&o| o as usize == MAX_ORDER + 1)
        .count();
    (pages.free, largest)
}

/// Whether any free block overlaps the physical range `start..end`: what
/// the self-check asks of memory the allocator was told to leave alone.
pub fn any_free_in(start: usize, end: usize) -> bool {
    let _pages = ALLOCATOR.lock();
    free_order().iter().enumerate().any(|(pfn, &order)| {
        let block = RAM.0 + pfn * PAGE;
        order != 0 && block < end && block + (PAGE << (order - 1)) > start
    })
}

/// The smallest order whose block holds `bytes`.
pub fn order_for(bytes: usize) -> usize {
    bytes.div_ceil(PAGE).next_power_of_two().trailing_zeros() as usize
}

/// [`FREE_ORDER`], from inside an [`ALLOCATOR`] operation: its lock is held
/// there and nothing else touches the table.
fn free_order() -> &'static mut [u8; PAGES] {
    // SAFETY: as above; callers hold no other reference across a call.
    unsafe { FREE_ORDER.get() }
}