garage44.eu/jeroen/pinnacle

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

.. /kernel/src/mm/space.rs

raw

//! A program's address space: its own translation tables for the lower
//! half, with 4 KiB pages, tagged with an ASID so that switching between
//! programs is one register write and no TLB flush.

use super::{PAGE, pages};
use crate::mmu::physical;

const ENTRIES: usize = 512;
/// The top of the lower half: 39-bit addresses.
pub const USER_TOP: usize = 1 << 39;

const VALID: u64 = 1;
/// A table descriptor at levels 1 and 2, a page descriptor at level 3.
const TABLE_OR_PAGE: u64 = 0b11;
const ATTR_NORMAL: u64 = 1 << 2;
const EL0_ACCESS: u64 = 1 << 6;
const READ_ONLY: u64 = 1 << 7;
const INNER_SHAREABLE: u64 = 0b11 << 8;
const ACCESSED: u64 = 1 << 10;
/// Not global: the TLB keeps it under this space's ASID only.
const NOT_GLOBAL: u64 = 1 << 11;
const PRIVILEGED_NEVER_EXECUTE: u64 = 1 << 53;
const USER_NEVER_EXECUTE: u64 = 1 << 54;
/// Software bit: the page is shared memory the space maps but does not own.
const SHARED: u64 = 1 << 55;
const ADDRESS: u64 = 0x0000_ffff_ffff_f000;
/// Unmapping more pages than this invalidates the whole ASID at once.
const PAGES_ONE_BY_ONE: usize = 32;

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Access {
    ReadExecute,
    Read,
    ReadWrite,
}

pub struct OutOfMemory;

pub struct AddressSpace {
    /// The level-1 table, by its kernel address.
    root: usize,
    asid: u16,
}

fn zeroed_page() -> Result<usize, OutOfMemory> {
    let page = pages::alloc(0).ok_or(OutOfMemory)?;
    // SAFETY: a page just allocated, ours alone.
    unsafe { core::ptr::write_bytes(page as *mut u8, 0, PAGE) };
    Ok(page)
}

fn table(address: usize) -> &'static mut [u64; ENTRIES] {
    // SAFETY: a table page this space owns; one reference at a time.
    unsafe { &mut *(address as *mut [u64; ENTRIES]) }
}

fn index(va: usize, level: u32) -> usize {
    (va >> (12 + 9 * (3 - level))) & (ENTRIES - 1)
}

impl AddressSpace {
    /// A new, empty space with an ASID of its own.
    pub fn new() -> Result<Self, OutOfMemory> {
        let asid = allocate_asid().ok_or(OutOfMemory)?;
        // The ASID may still tag a previous owner's entries.
        // SAFETY: TLB maintenance only.
        unsafe {
            core::arch::asm!(
                "dsb ishst",
                "tlbi aside1is, {}",
                "dsb ish",
                in(reg) u64::from(asid) << 48,
                options(nostack),
            );
        }
        let root = zeroed_page().inspect_err(|_| free_asid(asid))?;
        Ok(Self { root, asid })
    }

    /// The value for TTBR0_EL1: the root's physical address and the ASID.
    pub fn ttbr(&self) -> u64 {
        physical(self.root) as u64 | (u64::from(self.asid) << 48)
    }

    /// Maps the page at `va` to the page at kernel address `frame`, which
    /// the space then owns and frees.
    pub fn map(&mut self, va: usize, frame: usize, access: Access) -> Result<(), OutOfMemory> {
        assert!(va < USER_TOP && va.is_multiple_of(PAGE) && frame.is_multiple_of(PAGE));
        let mut at = self.root;
        for level in 1..3 {
            let entry = &mut table(at)[index(va, level)];
            if *entry & VALID == 0 {
                *entry = physical(zeroed_page()?) as u64 | TABLE_OR_PAGE;
            }
            at = crate::mmu::virt((*entry & ADDRESS) as usize);
        }
        let permissions = match access {
            Access::ReadExecute => EL0_ACCESS | READ_ONLY,
            Access::Read => EL0_ACCESS | READ_ONLY | USER_NEVER_EXECUTE,
            Access::ReadWrite => EL0_ACCESS | USER_NEVER_EXECUTE,
        };
        table(at)[index(va, 3)] = physical(frame) as u64
            | TABLE_OR_PAGE
            | ATTR_NORMAL
            | INNER_SHAREABLE
            | ACCESSED
            | NOT_GLOBAL
            | PRIVILEGED_NEVER_EXECUTE
            | permissions;
        Ok(())
    }

    /// Maps `pages` pages of shared memory at kernel address `frames` from
    /// `va`, writable and never executable; the space does not free them.
    pub fn map_shared(&mut self, va: usize, frames: usize, pages: usize) -> Result<(), OutOfMemory> {
        for page in 0..pages {
            self.map(va + page * PAGE, frames + page * PAGE, Access::ReadWrite)?;
            let mut at = self.root;
            for level in 1..3 {
                at = crate::mmu::virt((table(at)[index(va + page * PAGE, level)] & ADDRESS) as usize);
            }
            table(at)[index(va + page * PAGE, 3)] |= SHARED;
        }
        Ok(())
    }

    /// Takes away `pages` pages of shared memory mapped from `va` (by
    /// [`map_shared`](Self::map_shared)), on every core's TLB. Returns false,
    /// changing nothing, unless every page is shared memory mapped here.
    pub fn unmap_shared(&mut self, va: usize, pages: usize) -> bool {
        self.unmap(va, pages, true)
    }

    /// Takes away and frees `pages` pages of the space's own writable
    /// memory from `va` (as [`map`](Self::map) made it), on every core's
    /// TLB before a page is freed. Returns false, changing nothing, unless
    /// every page is such memory.
    pub fn unmap_private(&mut self, va: usize, pages: usize) -> bool {
        self.unmap(va, pages, false)
    }

    fn unmap(&mut self, va: usize, pages: usize, shared: bool) -> bool {
        let leaf_table = |va: usize| {
            let mut at = self.root;
            for level in 1..3 {
                let entry = table(at)[index(va, level)];
                if entry & VALID == 0 {
                    return None;
                }
                at = crate::mmu::virt((entry & ADDRESS) as usize);
            }
            Some(at)
        };
        let all = (0..pages).all(|p| {
            self.leaf(va + p * PAGE).is_some_and(|e| {
                if shared {
                    e & SHARED != 0
                } else {
                    e & (SHARED | READ_ONLY) == 0 && e & EL0_ACCESS != 0
                }
            })
        });
        if pages == 0 || !all {
            return false;
        }
        let mut frames = alloc::vec::Vec::new();
        // Past a few pages, one invalidation of the whole ASID costs less
        // than one a page with a barrier each: freeing 16 MiB took 0.5 ms.
        let whole = pages > PAGES_ONE_BY_ONE;
        for p in 0..pages {
            let page = va + p * PAGE;
            let at = leaf_table(page).expect("checked above");
            if !shared {
                frames.push(crate::mmu::virt((table(at)[index(page, 3)] & ADDRESS) as usize));
            }
            table(at)[index(page, 3)] = 0;
            if !whole {
                // SAFETY: TLB maintenance only: this page, this ASID, every core.
                unsafe {
                    core::arch::asm!(
                        "dsb ishst",
                        "tlbi vae1is, {}",
                        in(reg) (page as u64 >> 12) | (u64::from(self.asid) << 48),
                        options(nostack),
                    );
                }
            }
        }
        if whole {
            // SAFETY: TLB maintenance only: this ASID, every core, after
            // the entries cleared above are written.
            unsafe {
                core::arch::asm!(
                    "dsb ishst",
                    "tlbi aside1is, {}",
                    in(reg) u64::from(self.asid) << 48,
                    options(nostack),
                );
            }
        }
        // SAFETY: barriers only: the invalidations are done before we go on.
        unsafe { core::arch::asm!("dsb ish", "isb", options(nostack)) };
        // No core can reach them now.
        for frame in frames {
            pages::free(frame, 0);
        }
        true
    }

    fn leaf(&self, va: usize) -> Option<u64> {
        if va >= USER_TOP {
            return None;
        }
        let mut at = self.root;
        for level in 1..3 {
            let entry = table(at)[index(va, level)];
            if entry & VALID == 0 {
                return None;
            }
            at = crate::mmu::virt((entry & ADDRESS) as usize);
        }
        let entry = table(at)[index(va, 3)];
        (entry & VALID != 0).then_some(entry)
    }

    /// Whether the program may read (or write) all of `va..va + len`: how a
    /// system call checks a pointer before the kernel follows it.
    pub fn allows(&self, va: usize, len: usize, write: bool) -> bool {
        // Nothing to read or write: an empty slice's pointer may be anything
        // (Rust gives a dangling, aligned one), and it is never followed.
        if len == 0 {
            return true;
        }
        let Some(end) = va.checked_add(len) else {
            return false;
        };
        (va & !(PAGE - 1)..end).step_by(PAGE).all(|page| {
            self.leaf(page)
                .is_some_and(|e| e & EL0_ACCESS != 0 && !(write && e & READ_ONLY != 0))
        })
    }
}

impl Drop for AddressSpace {
    /// Frees every page and table. The caller has already switched TTBR0
    /// away from this space.
    fn drop(&mut self) {
        fn free(address: usize, level: u32) {
            if level < 3 {
                for &entry in table(address).iter() {
                    if entry & VALID != 0 {
                        free(crate::mmu::virt((entry & ADDRESS) as usize), level + 1);
                    }
                }
            } else {
                for &entry in table(address).iter() {
                    if entry & VALID != 0 && entry & SHARED == 0 {
                        pages::free(crate::mmu::virt((entry & ADDRESS) as usize), 0);
                    }
                }
            }
            pages::free(address, 0);
        }
        free(self.root, 1);
        // SAFETY: TLB maintenance only.
        unsafe {
            core::arch::asm!(
                "dsb ishst",
                "tlbi aside1is, {}",
                "dsb ish",
                in(reg) u64::from(self.asid) << 48,
                options(nostack),
            );
        }
        free_asid(self.asid);
    }
}

/// ASIDs in use, one bit each; ASID 0 is never handed out. A process holds
/// one for its life, shared by all its threads.
static ASIDS: crate::sync::SpinLock<[u64; 4]> = crate::sync::SpinLock::new([1, 0, 0, 0]);

fn allocate_asid() -> Option<u16> {
    let mut used = ASIDS.lock();
    let asid = (1..256).find(|&a| used[a / 64] & (1 << (a % 64)) == 0)?;
    used[asid / 64] |= 1 << (asid % 64);
    Some(asid as u16)
}

fn free_asid(asid: u16) {
    let a = usize::from(asid);
    ASIDS.lock()[a / 64] &= !(1 << (a % 64));
}