rstubs/arch/
paging.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//! Virtual memory paging data structures.

use core::arch::asm;
use core::fmt;
use core::mem::{align_of, size_of};

/// Enable paging
pub fn enable() {
    super::regs::Cr0::update(|v| v.with_paging(true).with_write_protect(true));
}
/// Invalidate the corresponding TLB entry
pub fn invalidate_tlb(page: Virtual) {
    unsafe { asm!("invlpg [{}]", in(reg) page.ptr()) };
}

/// A correctly sized and aligned page.
///
/// The page can be virtual or physical.
#[derive(Clone)]
#[repr(align(0x1000))]
pub struct Page {
    pub data: [u8; Page::SIZE],
}

const _: () = assert!(size_of::<Page>() == Page::SIZE);
const _: () = assert!(align_of::<Page>() == Page::SIZE);

impl Page {
    pub const BITS: usize = 12; // 2^12 => 4KiB
    pub const SIZE: usize = 1 << Self::BITS;
    pub const fn new() -> Self {
        Self {
            data: [0; Self::SIZE],
        }
    }
}

pub const ENTRIES: usize = Page::SIZE / size_of::<usize>();

// TODO: BST B1 - Implement paging data structures

/// Virtual page number.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Virtual(pub usize);

impl Virtual {
    pub fn new<T>(ptr: *mut T) -> Self {
        Self(ptr as usize / Page::SIZE)
    }
    pub const fn idx(dir: usize, table: usize) -> Self {
        Self(dir * ENTRIES + table)
    }
    pub const fn ptr(self) -> *mut Page {
        (self.0 * Page::SIZE) as _
    }
}
impl fmt::Debug for Virtual {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "V{:x}", self.0)
    }
}

/// Physical page frame number.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Physical(pub usize);

impl Physical {
    pub fn new<T>(ptr: *const T) -> Self {
        Self(ptr as usize / Page::SIZE)
    }
    pub const fn ptr(self) -> *mut Page {
        (self.0 * Page::SIZE) as _
    }
    pub const fn from_bits(v: u32) -> Self {
        Self(v as _)
    }
    pub const fn into_bits(self) -> u32 {
        self.0 as _
    }
}
impl fmt::Debug for Physical {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "P{:x}", self.0)
    }
}