Skip to main content

strat9_kernel/s9vm/
mmu.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! s9vm : second-level translation (hardware page tables).
24//!
25//! The module builds and walks the tables that translate guest physical
26//! addresses (GPA) to host physical addresses (HPA), following the Intel
27//! SDM (second-level translation, "EPT"). It is **pure**: it knows
28//! neither `HHDM` nor a frame allocator. Memory access to the tables is
29//! provided by a [`TableMemory`] (the kernel provides an HHDM
30//! implementation, the tests a host-memory implementation).
31//!
32//! Convention: the addresses handled are **physical** addresses; the
33//! [`TableMemory`] provider knows how to read and write them.
34
35/// Size of a base page.
36pub const PAGE_SIZE: u64 = 4096;
37/// Number of entries per table.
38pub const ENTRY_COUNT: usize = 512;
39/// Level shifts of the 4-level page-table walk.
40pub const SHIFT_PML4: u32 = 39;
41pub const SHIFT_PDPT: u32 = 30;
42pub const SHIFT_PD: u32 = 21;
43pub const SHIFT_PT: u32 = 12;
44/// Maximum guest physical address width covered (48 bits).
45pub const MAX_GPA: u64 = 1 << 48;
46
47/// Bits and masks of second-level table entries.
48pub mod entry {
49    /// Present entry.
50    pub const PRESENT: u64 = 1 << 0;
51    /// Read allowed (EPT bit 0).
52    pub const READ: u64 = 1 << 0;
53    /// Write allowed (EPT bit 1).
54    pub const WRITE: u64 = 1 << 1;
55    /// Execute allowed (EPT bit 2).
56    pub const EXECUTE: u64 = 1 << 2;
57    /// *Write-back* memory type (bits 5:3 = 6).
58    pub const MEMTYPE_WB: u64 = 6 << 3;
59    /// Large page (bit 7, 2 MiB page at the PD level).
60    pub const LARGE_PAGE: u64 = 1 << 7;
61    /// Mask of the encoded physical address (bits 51:12).
62    pub const ADDR_MASK: u64 = 0x000F_FFFF_FFFF_F000;
63    /// Alignment of a 2 MiB page.
64    pub const LARGE_2MB: u64 = 2 * 1024 * 1024;
65    /// Alignment of a 1 GiB page.
66    pub const LARGE_1GB: u64 = 1024 * 1024 * 1024;
67}
68
69/// Permissions for intermediate (non-leaf) EPT entries. EPT permissions are
70/// AND-ed across all levels, so an intermediate entry must grant read, write
71/// and execute; the effective access is then constrained by the leaf. Omitting
72/// execute here would make every guest instruction fetch fault with an EPT
73/// violation regardless of the leaf permission.
74const INTERMEDIATE_PERMS: u64 = entry::READ | entry::WRITE | entry::EXECUTE;
75
76/// Encoding of the entries of a second-level translation.
77///
78/// Intel EPT and AMD nested page tables (NPT) share the 4-level walk, the
79/// present bit (bit 0), the large-page bit (bit 7) and the address field
80/// (bits 51:12); they differ in how permissions are encoded, which is all this
81/// enum captures.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum Format {
84    /// Intel EPT: R/W/X in bits 2:0, memory type in bits 5:3.
85    Ept,
86    /// AMD NPT: regular x86 page-table entries. Every access of a guest is
87    /// treated as a user access, so `U` (bit 2) is mandatory at every level;
88    /// execute permission is the inverse of `NX` (bit 63). Read access is
89    /// implied by `P`.
90    Npt,
91}
92
93/// NPT/x86 `W` bit.
94const NPT_WRITE: u64 = 1 << 1;
95/// NPT/x86 `U` bit.
96const NPT_USER: u64 = 1 << 2;
97/// NPT/x86 `NX` bit.
98const NPT_NO_EXECUTE: u64 = 1 << 63;
99
100impl Format {
101    /// Bits of an intermediate (non-leaf) entry.
102    const fn intermediate(self) -> u64 {
103        match self {
104            Self::Ept => INTERMEDIATE_PERMS,
105            // Permissions are AND-ed across levels in NPT too: grant
106            // everything here, the leaf restricts.
107            Self::Npt => entry::PRESENT | NPT_WRITE | NPT_USER,
108        }
109    }
110
111    /// Permission and attribute bits of a leaf (without address or `LARGE_PAGE`).
112    const fn leaf(self, perms: Perms) -> Result<u64, MmuError> {
113        match self {
114            Self::Ept => Ok(perms.bits() | entry::MEMTYPE_WB),
115            Self::Npt => {
116                // A present NPT leaf is always readable: write-only or
117                // execute-only mappings cannot be expressed.
118                if !perms.read {
119                    return Err(MmuError::UnsupportedPerms);
120                }
121                let mut bits = entry::PRESENT | NPT_USER;
122                if perms.write {
123                    bits |= NPT_WRITE;
124                }
125                if !perms.execute {
126                    bits |= NPT_NO_EXECUTE;
127                }
128                Ok(bits)
129            }
130        }
131    }
132}
133
134/// Permissions requested for a mapping.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub struct Perms {
137    pub read: bool,
138    pub write: bool,
139    pub execute: bool,
140}
141
142impl Perms {
143    /// Read-only and execute (guest code).
144    pub const fn read_execute() -> Self {
145        Self {
146            read: true,
147            write: false,
148            execute: true,
149        }
150    }
151
152    /// Read/write (guest data).
153    pub const fn read_write() -> Self {
154        Self {
155            read: true,
156            write: true,
157            execute: false,
158        }
159    }
160
161    /// All permissions (regular RAM).
162    pub const fn read_write_execute() -> Self {
163        Self {
164            read: true,
165            write: true,
166            execute: true,
167        }
168    }
169
170    /// Encodes the permissions into bits 2:0 of an entry.
171    pub const fn bits(self) -> u64 {
172        let mut bits = 0;
173        if self.read {
174            bits |= entry::READ;
175        }
176        if self.write {
177            bits |= entry::WRITE;
178        }
179        if self.execute {
180            bits |= entry::EXECUTE;
181        }
182        bits
183    }
184}
185
186/// Table manipulation errors.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub enum MmuError {
189    /// The provider has no more table available.
190    OutOfMemory,
191    /// Invalid address or length.
192    InvalidRange,
193    /// A 2 MiB page is misaligned.
194    Misaligned,
195    /// The memory obtained from the provider is not usable.
196    BadMemory,
197    /// The requested mapping overlaps an existing incompatible mapping.
198    Conflict,
199    /// The permission combination cannot be encoded by the table format
200    /// (NPT cannot express a non-readable mapping).
201    UnsupportedPerms,
202}
203
204/// Memory provider for the tables (allocation, read, write).
205///
206/// The kernel implements this trait by allocating frames and going through the
207/// HHDM; the tests use a host-memory table. Each handle
208/// (`table`) identifies a table of 512 8-byte entries.
209pub trait TableMemory {
210    /// Allocates a zeroed table and returns its handle (physical identifier).
211    fn alloc_table(&mut self) -> Option<u64>;
212    /// Frees a previously allocated table.
213    fn free_table(&mut self, table: u64);
214    /// Reads entry `index` of the table.
215    fn read_entry(&self, table: u64, index: usize) -> u64;
216    /// Writes entry `index` of the table.
217    fn write_entry(&mut self, table: u64, index: usize, value: u64);
218}
219
220/// Root of a second-level translation.
221#[derive(Debug)]
222pub struct SecondLevel {
223    root: u64,
224    format: Format,
225}
226
227impl SecondLevel {
228    /// Creates an empty Intel EPT translation (a zeroed root table).
229    pub fn new<M: TableMemory>(memory: &mut M) -> Result<Self, MmuError> {
230        Self::with_format(memory, Format::Ept)
231    }
232
233    /// Creates an empty AMD NPT translation (a zeroed root table).
234    pub fn new_npt<M: TableMemory>(memory: &mut M) -> Result<Self, MmuError> {
235        Self::with_format(memory, Format::Npt)
236    }
237
238    /// Creates an empty translation in the given entry format.
239    pub fn with_format<M: TableMemory>(memory: &mut M, format: Format) -> Result<Self, MmuError> {
240        let root = memory.alloc_table().ok_or(MmuError::OutOfMemory)?;
241        Ok(Self { root, format })
242    }
243
244    /// Entry format of this translation.
245    pub const fn format(&self) -> Format {
246        self.format
247    }
248
249    /// Physical address of the root.
250    pub const fn root_phys(&self) -> u64 {
251        self.root
252    }
253
254    /// Frees the root (the sub-tables must have been freed by
255    /// [`Self::unmap`] or by the caller).
256    pub fn release<M: TableMemory>(&self, memory: &mut M) {
257        memory.free_table(self.root);
258    }
259
260    /// Maps a range of `len` bytes (multiple of 4 KiB) in 4 KiB pages.
261    ///
262    /// `gpa` and `hpa` must be 4 KiB aligned.
263    pub fn map_4k<M: TableMemory>(
264        &self,
265        memory: &mut M,
266        gpa: u64,
267        hpa: u64,
268        len: u64,
269        perms: Perms,
270    ) -> Result<(), MmuError> {
271        if len == 0 || gpa % PAGE_SIZE != 0 || hpa % PAGE_SIZE != 0 || len % PAGE_SIZE != 0 {
272            return Err(MmuError::InvalidRange);
273        }
274        if gpa.checked_add(len).map_or(true, |end| end > MAX_GPA) {
275            return Err(MmuError::InvalidRange);
276        }
277        let leaf = self.format.leaf(perms)?;
278        let pages = len / PAGE_SIZE;
279        for index in 0..pages {
280            let offset = index * PAGE_SIZE;
281            let table = self.ensure_table(memory, gpa + offset, SHIFT_PT)?;
282            let slot = index_of(gpa + offset, SHIFT_PT);
283            let existing = memory.read_entry(table, slot);
284            if existing & entry::PRESENT != 0 && existing & entry::LARGE_PAGE == 0 {
285                return Err(MmuError::Conflict);
286            }
287            memory.write_entry(table, slot, (hpa + offset) | leaf);
288        }
289        Ok(())
290    }
291
292    /// Maps a range of `len` bytes in 2 MiB pages.
293    ///
294    /// `gpa`, `hpa`, and `len` must be 2 MiB aligned.
295    pub fn map_2m<M: TableMemory>(
296        &self,
297        memory: &mut M,
298        gpa: u64,
299        hpa: u64,
300        len: u64,
301        perms: Perms,
302    ) -> Result<(), MmuError> {
303        let align = entry::LARGE_2MB;
304        if len == 0 || gpa % align != 0 || hpa % align != 0 || len % align != 0 {
305            return Err(MmuError::Misaligned);
306        }
307        if gpa.checked_add(len).map_or(true, |end| end > MAX_GPA) {
308            return Err(MmuError::InvalidRange);
309        }
310        let mut offset = 0u64;
311        while offset < len {
312            self.map_2m_leaf(memory, gpa + offset, hpa + offset, perms)?;
313            offset += align;
314        }
315        Ok(())
316    }
317
318    /// Installs one 2 MiB leaf for the 2 MiB-aligned GPA `gpa`.
319    ///
320    /// Additive helper for callers that build their own mapping plan (for
321    /// example a large guest range split into 2 MiB leaves with 4 KiB
322    /// head/tail pages). The GPA and HPA must be 2 MiB aligned; the range must
323    /// fit below [`MAX_GPA`].
324    ///
325    /// Returns [`MmuError::Conflict`] when the destination PD slot is already
326    /// present. That covers both an existing 2 MiB leaf and a 4 KiB page-table
327    /// subtree: granularities are never silently mixed inside one 2 MiB
328    /// region. Callers that need to replace an existing 4 KiB mapping must
329    /// unmap it first (after unmapping every 4 KiB page of the region).
330    pub fn map_2m_leaf<M: TableMemory>(
331        &self,
332        memory: &mut M,
333        gpa: u64,
334        hpa: u64,
335        perms: Perms,
336    ) -> Result<(), MmuError> {
337        let align = entry::LARGE_2MB;
338        if gpa % align != 0 || hpa % align != 0 {
339            return Err(MmuError::Misaligned);
340        }
341        if gpa.checked_add(align).map_or(true, |end| end > MAX_GPA) {
342            return Err(MmuError::InvalidRange);
343        }
344        let table = self.ensure_table(memory, gpa, SHIFT_PD)?;
345        let slot = index_of(gpa, SHIFT_PD);
346        if memory.read_entry(table, slot) & entry::PRESENT != 0 {
347            return Err(MmuError::Conflict);
348        }
349        let leaf = self.format.leaf(perms)? | entry::LARGE_PAGE;
350        memory.write_entry(table, slot, hpa | leaf);
351        Ok(())
352    }
353
354    /// Translates a GPA to an HPA, if a leaf exists.
355    pub fn translate<M: TableMemory>(&self, memory: &M, gpa: u64) -> Option<u64> {
356        if gpa >= MAX_GPA {
357            return None;
358        }
359        let pml4 = memory.read_entry(self.root, index_of(gpa, SHIFT_PML4));
360        if pml4 & entry::PRESENT == 0 {
361            return None;
362        }
363        let pdpt_table = pml4 & entry::ADDR_MASK;
364        let pdpt = memory.read_entry(pdpt_table, index_of(gpa, SHIFT_PDPT));
365        if pdpt & entry::PRESENT == 0 {
366            return None;
367        }
368        if pdpt & entry::LARGE_PAGE != 0 {
369            // 1 GiB pages: supported only if the provider has
370            // placed them; they are accepted for reading.
371            let base = pdpt & entry::ADDR_MASK & !(entry::LARGE_1GB - 1);
372            return Some(base | (gpa & (entry::LARGE_1GB - 1)));
373        }
374        let pd_table = pdpt & entry::ADDR_MASK;
375        let pd = memory.read_entry(pd_table, index_of(gpa, SHIFT_PD));
376        if pd & entry::PRESENT == 0 {
377            return None;
378        }
379        if pd & entry::LARGE_PAGE != 0 {
380            let base = pd & entry::ADDR_MASK & !(entry::LARGE_2MB - 1);
381            return Some(base | (gpa & (entry::LARGE_2MB - 1)));
382        }
383        let pt_table = pd & entry::ADDR_MASK;
384        let pt = memory.read_entry(pt_table, index_of(gpa, SHIFT_PT));
385        if pt & entry::PRESENT == 0 {
386            return None;
387        }
388        Some((pt & entry::ADDR_MASK) | (gpa & (PAGE_SIZE - 1)))
389    }
390
391    /// Removes a 4 KiB mapping. Returns `true` if a leaf existed.
392    ///
393    /// Intermediate tables that become empty are not freed (they
394    /// can be reused by a later mapping); use
395    /// [`Self::release`] after [`Self::release_all`] or let the
396    /// provider owner reclaim them.
397    pub fn unmap_4k<M: TableMemory>(&self, memory: &mut M, gpa: u64) -> bool {
398        let Some(pt_table) = self.leaf_table(memory, gpa, SHIFT_PT) else {
399            return false;
400        };
401        let slot = index_of(gpa, SHIFT_PT);
402        let existing = memory.read_entry(pt_table, slot);
403        if existing & entry::PRESENT == 0 || existing & entry::LARGE_PAGE != 0 {
404            return false;
405        }
406        memory.write_entry(pt_table, slot, 0);
407        true
408    }
409
410    /// Removes a 2 MiB mapping. Returns `true` if a leaf existed.
411    pub fn unmap_2m<M: TableMemory>(&self, memory: &mut M, gpa: u64) -> bool {
412        let Some(pd_table) = self.leaf_table(memory, gpa, SHIFT_PD) else {
413            return false;
414        };
415        let slot = index_of(gpa, SHIFT_PD);
416        let existing = memory.read_entry(pd_table, slot);
417        if existing & entry::PRESENT == 0 || existing & entry::LARGE_PAGE == 0 {
418            return false;
419        }
420        memory.write_entry(pd_table, slot, 0);
421        true
422    }
423
424    /// Walks the tables down to the table containing the leaf of the requested
425    /// level (`SHIFT_PT` for 4 KiB, `SHIFT_PD` for 2 MiB).
426    fn leaf_table<M: TableMemory>(&self, memory: &M, gpa: u64, leaf_shift: u32) -> Option<u64> {
427        if gpa >= MAX_GPA {
428            return None;
429        }
430        let pml4 = memory.read_entry(self.root, index_of(gpa, SHIFT_PML4));
431        if pml4 & entry::PRESENT == 0 {
432            return None;
433        }
434        let pdpt = memory.read_entry(pml4 & entry::ADDR_MASK, index_of(gpa, SHIFT_PDPT));
435        if pdpt & entry::PRESENT == 0 || pdpt & entry::LARGE_PAGE != 0 {
436            return None;
437        }
438        let pd = memory.read_entry(pdpt & entry::ADDR_MASK, index_of(gpa, SHIFT_PD));
439        if pd & entry::PRESENT == 0 {
440            return None;
441        }
442        if leaf_shift == SHIFT_PD {
443            return Some(pdpt & entry::ADDR_MASK);
444        }
445        if pd & entry::LARGE_PAGE != 0 {
446            return None;
447        }
448        Some(pd & entry::ADDR_MASK)
449    }
450
451    /// Creates (if necessary) the table of level `shift` for the given GPA and
452    /// returns its handle. Allocates the missing levels.
453    ///
454    /// A large leaf met while walking down (a 1 GiB leaf at the PDPT level or a
455    /// 2 MiB leaf at the PD level) is reported as [`MmuError::Conflict`]: it
456    /// must never be mistaken for a table pointer, which would silently write
457    /// page-table entries into guest memory.
458    fn ensure_table<M: TableMemory>(
459        &self,
460        memory: &mut M,
461        gpa: u64,
462        shift: u32,
463    ) -> Result<u64, MmuError> {
464        debug_assert!(shift >= SHIFT_PT);
465        let pml4_slot = index_of(gpa, SHIFT_PML4);
466        let pml4 = memory.read_entry(self.root, pml4_slot);
467        let pdpt_table = if pml4 & entry::PRESENT != 0 {
468            pml4 & entry::ADDR_MASK
469        } else {
470            let table = memory.alloc_table().ok_or(MmuError::OutOfMemory)?;
471            memory.write_entry(self.root, pml4_slot, table | self.format.intermediate());
472            table
473        };
474        if shift == SHIFT_PDPT {
475            return Ok(pdpt_table);
476        }
477        let pdpt_slot = index_of(gpa, SHIFT_PDPT);
478        let pdpt = memory.read_entry(pdpt_table, pdpt_slot);
479        let pd_table = if pdpt & entry::PRESENT != 0 {
480            if pdpt & entry::LARGE_PAGE != 0 {
481                // 1 GiB leaf, not a PD table.
482                return Err(MmuError::Conflict);
483            }
484            pdpt & entry::ADDR_MASK
485        } else {
486            let table = memory.alloc_table().ok_or(MmuError::OutOfMemory)?;
487            memory.write_entry(pdpt_table, pdpt_slot, table | self.format.intermediate());
488            table
489        };
490        if shift == SHIFT_PD {
491            return Ok(pd_table);
492        }
493        let pd_slot = index_of(gpa, SHIFT_PD);
494        let pd = memory.read_entry(pd_table, pd_slot);
495        let pt_table = if pd & entry::PRESENT != 0 {
496            if pd & entry::LARGE_PAGE != 0 {
497                // 2 MiB leaf, not a PT table.
498                return Err(MmuError::Conflict);
499            }
500            pd & entry::ADDR_MASK
501        } else {
502            let table = memory.alloc_table().ok_or(MmuError::OutOfMemory)?;
503            memory.write_entry(pd_table, pd_slot, table | self.format.intermediate());
504            table
505        };
506        Ok(pt_table)
507    }
508}
509
510/// Index of an address in the table of level `shift`.
511const fn index_of(addr: u64, shift: u32) -> usize {
512    ((addr >> shift) & 0x1FF) as usize
513}
514
515/// Encodes the activation value of second-level translation (`EPTP`).
516///
517/// Format (SDM): bits 2:0 = memory type (6 = WB), bits 5:3 = walk
518/// length minus 1 (3 for 4 levels), bit 6 = A/D, bits 51:12 = root.
519pub const fn encode_second_level_pointer(
520    root_phys: u64,
521    memory_type: u8,
522    four_levels: bool,
523    accessed_dirty: bool,
524) -> u64 {
525    let mut value = (memory_type as u64) & 0x7;
526    if four_levels {
527        value |= 3 << 3;
528    }
529    if accessed_dirty {
530        value |= 1 << 6;
531    }
532    value | (root_phys & entry::ADDR_MASK)
533}