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
86
87
88
89
90
91
92
93
//! Virtual memory paging data structures.

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

use super::regs;

/// 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 << Page::BITS;
    pub const fn new() -> Self {
        Self {
            data: [0; Page::SIZE],
        }
    }
}

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

/// 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 fn idx(dir: usize, table: usize) -> Self {
        Self(dir * ENTRIES + table)
    }
    pub const fn ptr(self) -> *mut Page {
        (self.0 * Page::SIZE) as _
    }
    pub fn dir_idx(self) -> usize {
        self.0 / ENTRIES
    }
    pub fn table_idx(self) -> usize {
        self.0 % ENTRIES
    }
}
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: *mut 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)
    }
}

// TODO: A2 - Page Directory and Page Table implementations