garage44.eu/jeroen/pinnacle

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

.. /kernel/src/x86_64/space.rs

raw

//! A program's address space on a PC: a four-level table of its own whose
//! lower half (the first 512 GiB, the root's entry 0, as on ARM) is the
//! program's and whose upper half is the kernel's, copied from the
//! kernel's root, so the kernel runs on the program's tables unchanged.
//! The interface is ARM's (`mm/space.rs`).
//!
//! Switching programs reloads CR3, which flushes the program's entries
//! from this core's TLB (no PCIDs yet). Taking a page away invalidates it
//! here only: another core running a thread of the same program keeps it
//! until its next switch. Shared memory is the only thing taken away while
//! a program runs, and only from a program with one thread so far; a TLB
//! shootdown comes with threads of a program spread over cores.

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

const ENTRIES: usize = 512;
/// The top of the lower half that is a program's: 39 bits, as on ARM.
pub const USER_TOP: usize = 1 << 39;

const PRESENT: u64 = 1;
const WRITABLE: u64 = 1 << 1;
const USER: u64 = 1 << 2;
/// Software bit: the page is shared memory the space maps but does not own.
const SHARED: u64 = 1 << 9;
const NO_EXECUTE: u64 = 1 << 63;
const ADDRESS: u64 = 0x000f_ffff_ffff_f000;

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

pub struct OutOfMemory;

pub struct AddressSpace {
    /// The root table, by its kernel address.
    root: usize,
}

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]) }
}

/// The entry for `va` in a table of `level` (0 is the root).
fn index(va: usize, level: u32) -> usize {
    (va >> (39 - 9 * level)) & (ENTRIES - 1)
}

impl AddressSpace {
    /// A new space: an empty lower half, the kernel's upper half.
    pub fn new() -> Result<Self, OutOfMemory> {
        let root = zeroed_page()?;
        let kernel = table(crate::mmu::kernel_root());
        table(root)[ENTRIES / 2..].copy_from_slice(&kernel[ENTRIES / 2..]);
        Ok(Self { root })
    }

    /// The value for CR3: the root's physical address.
    pub fn ttbr(&self) -> u64 {
        physical(self.root) as u64
    }

    /// The last-level table for `va`, made on the way when `make`.
    fn leaf_table(&self, va: usize, make: bool) -> Result<Option<usize>, OutOfMemory> {
        let mut at = self.root;
        for level in 0..3 {
            let entry = &mut table(at)[index(va, level)];
            if *entry & PRESENT == 0 {
                if !make {
                    return Ok(None);
                }
                *entry = physical(zeroed_page()?) as u64 | PRESENT | WRITABLE | USER;
            }
            at = crate::mmu::virt((*entry & ADDRESS) as usize);
        }
        Ok(Some(at))
    }

    /// 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 at = self.leaf_table(va, true)?.expect("made");
        let permissions = match access {
            Access::ReadExecute => 0,
            Access::Read => NO_EXECUTE,
            Access::ReadWrite => WRITABLE | NO_EXECUTE,
        };
        table(at)[index(va, 3)] = physical(frame) as u64 | PRESENT | USER | 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 {
            let va = va + page * PAGE;
            self.map(va, frames + page * PAGE, Access::ReadWrite)?;
            let at = self.leaf_table(va, false)?.expect("just mapped");
            table(at)[index(va, 3)] |= SHARED;
        }
        Ok(())
    }

    /// Takes away `pages` pages of shared memory mapped from `va`. Returns
    /// false, changing nothing, unless every page is shared memory mapped
    /// here.
    pub fn unmap_shared(&mut self, va: usize, pages: usize) -> bool {
        let all_shared = (0..pages).all(|p| self.leaf(va + p * PAGE).is_some_and(|e| e & SHARED != 0));
        if !all_shared {
            return false;
        }
        for p in 0..pages {
            let page = va + p * PAGE;
            if let Ok(Some(at)) = self.leaf_table(page, false) {
                table(at)[index(page, 3)] = 0;
            }
            // SAFETY: TLB maintenance only, this core's.
            unsafe { core::arch::asm!("invlpg [{}]", in(reg) page, options(nostack)) };
        }
        true
    }

    /// Would take away and free the space's own memory; refuses, changing
    /// nothing: `invlpg` reaches this core's TLB only, and another core
    /// running a thread of the program could still write a freed page.
    pub fn unmap_private(&mut self, _va: usize, _pages: usize) -> bool {
        false
    }

    fn leaf(&self, va: usize) -> Option<u64> {
        if va >= USER_TOP {
            return None;
        }
        let at = self.leaf_table(va, false).ok()??;
        let entry = table(at)[index(va, 3)];
        (entry & PRESENT != 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 {
        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 & USER != 0 && !(write && e & WRITABLE == 0))
        })
    }
}

impl Drop for AddressSpace {
    /// Frees every page and table of the lower half. The caller has
    /// already switched CR3 away from this space.
    fn drop(&mut self) {
        fn free(address: usize, level: u32) {
            for &entry in table(address).iter() {
                if entry & PRESENT == 0 {
                    continue;
                }
                let next = crate::mmu::virt((entry & ADDRESS) as usize);
                if level < 3 {
                    free(next, level + 1);
                } else if entry & SHARED == 0 {
                    pages::free(next, 0);
                }
            }
            pages::free(address, 0);
        }
        // Only the lower half is the space's: the upper is the kernel's.
        for i in 0..ENTRIES / 2 {
            let entry = table(self.root)[i];
            if entry & PRESENT != 0 {
                free(crate::mmu::virt((entry & ADDRESS) as usize), 1);
            }
        }
        pages::free(self.root, 0);
    }
}