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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
use super::frame_alloc::*;
use super::page_table::*;
use addr::*;
pub trait Mapper {
type P: PhysicalAddress;
type V: VirtualAddress;
type MapperFlush: MapperFlushable;
type Entry: PTE;
fn map_to(
&mut self,
page: PageWith<Self::V>,
frame: FrameWith<Self::P>,
flags: PageTableFlags,
allocator: &mut impl FrameAllocatorFor<<Self as Mapper>::P>,
) -> Result<Self::MapperFlush, MapToError>;
fn unmap(
&mut self,
page: PageWith<Self::V>,
) -> Result<(FrameWith<Self::P>, Self::MapperFlush), UnmapError<<Self as Mapper>::P>>;
fn ref_entry(&mut self, page: PageWith<Self::V>) -> Result<&mut Self::Entry, FlagUpdateError>;
fn update_flags(
&mut self,
page: PageWith<Self::V>,
flags: PageTableFlags,
) -> Result<Self::MapperFlush, FlagUpdateError> {
self.ref_entry(page).map(|e| {
e.set(e.frame::<Self::P>(), flags);
Self::MapperFlush::new(page)
})
}
fn translate_page(&mut self, page: PageWith<Self::V>) -> Option<FrameWith<Self::P>> {
match self.ref_entry(page) {
Ok(e) => {
if e.is_unused() {
None
} else {
Some(e.frame())
}
}
Err(_) => None,
}
}
fn identity_map(
&mut self,
frame: FrameWith<Self::P>,
flags: PageTableFlags,
allocator: &mut impl FrameAllocatorFor<<Self as Mapper>::P>,
) -> Result<Self::MapperFlush, MapToError> {
let page = PageWith::of_addr(Self::V::new(frame.start_address().as_usize()));
self.map_to(page, frame, flags, allocator)
}
}
pub trait MapperFlushable {
fn new<T: VirtualAddress>(page: PageWith<T>) -> Self;
fn flush(self);
fn ignore(self);
}
#[must_use = "Page Table changes must be flushed or ignored."]
pub struct MapperFlush(usize);
impl MapperFlushable for MapperFlush {
fn new<T: VirtualAddress>(page: PageWith<T>) -> Self {
MapperFlush(page.start_address().as_usize())
}
fn flush(self) {
unsafe {
crate::asm::sfence_vma(0, self.0);
}
}
fn ignore(self) {}
}
#[derive(Debug)]
pub enum MapToError {
FrameAllocationFailed,
ParentEntryHugePage,
PageAlreadyMapped,
}
#[derive(Debug)]
pub enum UnmapError<P: PhysicalAddress> {
ParentEntryHugePage,
PageNotMapped,
InvalidFrameAddress(P),
}
#[derive(Debug)]
pub enum FlagUpdateError {
PageNotMapped,
}
pub trait MapperExt {
type Page;
type Frame;
}
impl<T: Mapper> MapperExt for T {
type Page = PageWith<<T as Mapper>::V>;
type Frame = FrameWith<<T as Mapper>::P>;
}