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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
//! The `page_table` module defines a 3-level page table
//! that follows the RISC-V Sv39 page table specification.
//! The page table supports 512 GB of virtual-address space.

#![macro_use]
use alloc::{vec, vec::Vec};

use bitflags::bitflags;

use crate::mem::{
    frame_allocator::{allocate_frame, FrameTracker},
    FrameNumber,
    PageNumber,
    PhysicalAddress,
    VirtualAddress,
};

bitflags! {
    #[derive(Copy, Clone)]
    pub struct PTEFlags: usize {
        const V = 1 << 0;
        const R = 1 << 1;
        const W = 1 << 2;
        const X = 1 << 3;
        const U = 1 << 4;
        const G = 1 << 5;
        const A = 1 << 6;
        const D = 1 << 7;
        const COW = 1 << 8;
    }
}

#[derive(Copy, Clone, Default)]
#[repr(C)]
pub struct PageTableEntry {
    bits: usize,
}

impl PageTableEntry {
    pub fn new(frame_number: FrameNumber, flag: PTEFlags) -> Self {
        PageTableEntry {
            bits: usize::from(frame_number) << 10 | flag.bits(),
        }
    }

    pub fn frame_number(&self) -> FrameNumber {
        FrameNumber::from(self.bits >> 10 & ((1 << 44) - 1))
    }

    pub fn flags(&self) -> PTEFlags {
        PTEFlags::from_bits(self.bits & ((1 << 10) - 1)).unwrap()
    }

    pub fn is_valid(&self) -> bool {
        self.flags().contains(PTEFlags::V)
    }

    pub fn is_readable(&self) -> bool {
        self.flags().contains(PTEFlags::R)
    }

    pub fn is_writable(&self) -> bool {
        self.flags().contains(PTEFlags::W)
    }

    pub fn is_executable(&self) -> bool {
        self.flags().contains(PTEFlags::X)
    }

    pub fn is_cow(&self) -> bool {
        self.flags().contains(PTEFlags::COW)
    }
}

#[repr(C)]
pub struct PageTable {
    root_frame_number: FrameNumber,
    frame_list: Vec<FrameTracker>,
}

impl PageTable {
    pub fn new() -> Self {
        let frame = allocate_frame().unwrap();
        PageTable {
            root_frame_number: frame.frame_number(),
            frame_list: vec![frame],
        }
    }

    /// Returns the value of the `satp` register that points to the page table.
    pub fn satp(&self) -> usize {
        8 << 60 | usize::from(self.root_frame_number)
    }

    /// Creates a [PageTable] where the `root_frame_number` points to the frame in the `satp`
    /// register.
    pub fn from_satp(satp: usize) -> Self {
        Self {
            root_frame_number: FrameNumber::from(satp & ((1 << 44) - 1)),
            frame_list: Vec::new(),
        }
    }

    /// Maps a [PageNumber] to a [FrameNumber] and sets the [PageTableEntry] with [PTEFlags].
    pub fn map(&mut self, page_number: PageNumber, frame_number: FrameNumber, flags: PTEFlags) {
        let pte = self.create_pte(page_number).unwrap();
        *pte = PageTableEntry::new(frame_number, flags | PTEFlags::V);
    }

    /// Clears the [PageTableEntry] corresponding to the [PageNumber].
    pub fn unmap(&mut self, page_number: PageNumber) {
        let pte = self.find_pte(page_number).unwrap();
        *pte = PageTableEntry::default();
    }

    /// Finds the page table with a [VirtualAddress] and returns a [PhysicalAddress].
    pub fn translate(&self, virtual_address: VirtualAddress) -> Option<PhysicalAddress> {
        let page_number = PageNumber::from(virtual_address);
        self.find_pte(page_number).map(|pte| {
            let frame_number = pte.frame_number();
            PhysicalAddress::from(frame_number) + virtual_address.page_offset()
        })
    }

    /// Finds the page table with a [PageNumber] and returns a [PageTableEntry].
    pub fn translate_page(&self, page_number: PageNumber) -> Option<PageTableEntry> {
        self.find_pte(page_number).map(|pte| *pte)
    }

    /// Finds the page table with a [PageNumber] and returns a mutable reference to a
    /// [PageTableEntry].
    fn find_pte(&self, page_number: PageNumber) -> Option<&mut PageTableEntry> {
        let index = page_number.index();
        let mut frame_number = self.root_frame_number;
        for (i, pte_index) in index.iter().enumerate() {
            let pte = &mut frame_number.as_pte_mut()[*pte_index];
            if i == 2 {
                return Some(pte);
            }

            if pte.is_valid() {
                frame_number = pte.frame_number();
            } else {
                return None;
            }
        }
        None
    }

    /// Finds the page table with a [PageNumber] and returns a mutable reference to a
    /// [PageTableEntry]. Creates a new [PageTableEntry] if not existed.
    fn create_pte(&mut self, page_number: PageNumber) -> Option<&mut PageTableEntry> {
        let index = page_number.index();
        let mut frame_number = self.root_frame_number;
        for (i, pte_index) in index.iter().enumerate() {
            let pte = &mut frame_number.as_pte_mut()[*pte_index];
            if i == 2 {
                return Some(pte);
            }

            if !pte.is_valid() {
                let frame = allocate_frame().unwrap();
                *pte = PageTableEntry::new(frame.frame_number(), PTEFlags::V);
                self.frame_list.push(frame);
            }
            frame_number = pte.frame_number();
        }
        None
    }
}