Skip to main content

hyperlight_common/
vmem.rs

1/*
2Copyright 2025  The Hyperlight Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15 */
16
17#[cfg_attr(target_arch = "x86_64", path = "arch/amd64/vmem.rs")]
18#[cfg_attr(target_arch = "x86", path = "arch/i686/vmem.rs")]
19mod arch;
20
21/// This is always the page size that the /guest/ is being compiled
22/// for, which may or may not be the same as the host page size.
23pub use arch::PAGE_SIZE;
24pub use arch::{PAGE_TABLE_SIZE, PageTableEntry, PhysAddr, VirtAddr};
25pub const PAGE_TABLE_ENTRIES_PER_TABLE: usize =
26    PAGE_TABLE_SIZE / core::mem::size_of::<PageTableEntry>();
27
28/// The read-only operations used to actually access the page table
29/// structures, used to allow the same code to be used in the host and
30/// the guest for page table setup.  This is distinct from
31/// `TableWriteOps`, since there are some implementations for which
32/// writing does not make sense, and only reading is required.
33pub trait TableReadOps {
34    /// The type of table addresses
35    type TableAddr: Copy;
36
37    /// Offset the table address by the given offset in bytes.
38    ///
39    /// # Parameters
40    /// - `addr`: The base address of the table.
41    /// - `entry_offset`: The offset in **bytes** within the page table. This is
42    ///   not an entry index; callers must multiply the entry index by the size
43    ///   of a page table entry (typically 8 bytes) to obtain the correct byte offset.
44    ///
45    /// # Returns
46    /// The address of the entry at the given byte offset from the base address.
47    fn entry_addr(addr: Self::TableAddr, entry_offset: u64) -> Self::TableAddr;
48
49    /// Read a u64 from the given address, used to read existing page
50    /// table entries
51    ///
52    /// # Safety
53    /// This reads from the given memory address, and so all the usual
54    /// Rust things about raw pointers apply. This will also be used
55    /// to update guest page tables, so especially in the guest, it is
56    /// important to ensure that the page tables updates do not break
57    /// invariants. The implementor of the trait should ensure that
58    /// nothing else will be reading/writing the address at the same
59    /// time as mapping code using the trait.
60    unsafe fn read_entry(&self, addr: Self::TableAddr) -> PageTableEntry;
61
62    /// Convert an abstract table address to a concrete physical address (u64)
63    /// which can be e.g. written into a page table entry
64    fn to_phys(addr: Self::TableAddr) -> PhysAddr;
65
66    /// Convert a concrete physical address (u64) which may have been e.g. read
67    /// from a page table entry back into an abstract table address
68    fn from_phys(addr: PhysAddr) -> Self::TableAddr;
69
70    /// Return the address of the root page table
71    fn root_table(&self) -> Self::TableAddr;
72}
73
74/// Our own version of ! until it is stable. Used to avoid needing to
75/// implement [`TableOps::update_root`] for ops that never need
76/// to move a table.
77pub enum Void {}
78
79/// A marker struct, used by an implementation of [`TableOps`] to
80/// indicate that it may need to move existing page tables
81pub struct MayMoveTable {}
82/// A marker struct, used by an implementation of [`TableOps`] to
83/// indicate that it will be able to update existing page tables
84/// in-place, without moving them.
85pub struct MayNotMoveTable {}
86
87mod sealed {
88    use super::{MayMoveTable, MayNotMoveTable, TableReadOps, Void};
89
90    /// A (purposefully-not-exposed) internal implementation detail of the
91    /// logic around whether a [`TableOps`] implementation may or may not
92    /// move page tables.
93    pub trait TableMovabilityBase<Op: TableReadOps + ?Sized> {
94        type TableMoveInfo;
95    }
96    impl<Op: TableReadOps> TableMovabilityBase<Op> for MayMoveTable {
97        type TableMoveInfo = Op::TableAddr;
98    }
99    impl<Op: TableReadOps> TableMovabilityBase<Op> for MayNotMoveTable {
100        type TableMoveInfo = Void;
101    }
102}
103use sealed::*;
104
105/// A sealed trait used to collect some information about the marker structures [`MayMoveTable`] and [`MayNotMoveTable`]
106pub trait TableMovability<Op: TableReadOps + ?Sized>:
107    TableMovabilityBase<Op>
108    + arch::TableMovability<Op, <Self as TableMovabilityBase<Op>>::TableMoveInfo>
109{
110}
111impl<
112    Op: TableReadOps,
113    T: TableMovabilityBase<Op>
114        + arch::TableMovability<Op, <Self as TableMovabilityBase<Op>>::TableMoveInfo>,
115> TableMovability<Op> for T
116{
117}
118
119/// The operations used to actually access the page table structures
120/// that involve writing to them, used to allow the same code to be
121/// used in the host and the guest for page table setup.
122pub trait TableOps: TableReadOps {
123    /// This marker should be either [`MayMoveTable`] or
124    /// [`MayNotMoveTable`], as the case may be.
125    ///
126    /// If this is [`MayMoveTable`], the return type of
127    /// [`Self::write_entry`] and the parameter type of
128    /// [`Self::update_root`] will be `<Self as
129    /// TableReadOps>::TableAddr`. If it is [`MayNotMoveTable`], those
130    /// types will be [`Void`].
131    type TableMovability: TableMovability<Self>;
132
133    /// Allocate a zeroed table
134    ///
135    /// # Safety
136    /// The current implementations of this function are not
137    /// inherently unsafe, but the guest implementation will likely
138    /// become so in the future when a real physical page allocator is
139    /// implemented.
140    ///
141    /// Currently, callers should take care not to call this on
142    /// multiple threads at the same time.
143    ///
144    /// # Panics
145    /// This function may panic if:
146    /// - The Layout creation fails
147    /// - Memory allocation fails
148    unsafe fn alloc_table(&self) -> Self::TableAddr;
149
150    /// Write a u64 to the given address, used to write updated page
151    /// table entries. In some cases,the page table in which the entry
152    /// is located may need to be relocated in order for this to
153    /// succeed; if this is the case, the base address of the new
154    /// table is returned.
155    ///
156    /// # Safety
157    /// This writes to the given memory address, and so all the usual
158    /// Rust things about raw pointers apply. This will also be used
159    /// to update guest page tables, so especially in the guest, it is
160    /// important to ensure that the page tables updates do not break
161    /// invariants. The implementor of the trait should ensure that
162    /// nothing else will be reading/writing the address at the same
163    /// time as mapping code using the trait.
164    unsafe fn write_entry(
165        &self,
166        addr: Self::TableAddr,
167        entry: PageTableEntry,
168    ) -> Option<<Self::TableMovability as TableMovabilityBase<Self>>::TableMoveInfo>;
169
170    /// Change the root page table to one at a different address
171    ///
172    /// # Safety
173    /// This function will directly result in a change to virtual
174    /// memory translation, and so is inherently unsafe w.r.t. the
175    /// Rust memory model.  All the caveats listed on [`map`] apply as
176    /// well.
177    unsafe fn update_root(
178        &self,
179        new_root: <Self::TableMovability as TableMovabilityBase<Self>>::TableMoveInfo,
180    );
181}
182
183#[derive(Debug, PartialEq, Clone, Copy)]
184pub struct BasicMapping {
185    pub readable: bool,
186    pub writable: bool,
187    pub executable: bool,
188}
189
190#[derive(Debug, PartialEq, Clone, Copy)]
191pub struct CowMapping {
192    pub readable: bool,
193    pub executable: bool,
194}
195
196#[derive(Debug, PartialEq, Clone, Copy)]
197pub enum MappingKind {
198    Basic(BasicMapping),
199    Cow(CowMapping),
200    /* TODO: What useful things other than basic mappings actually
201     * require touching the tables? */
202}
203
204#[derive(Debug)]
205pub struct Mapping {
206    pub phys_base: u64,
207    pub virt_base: u64,
208    pub len: u64,
209    pub kind: MappingKind,
210}
211
212/// Assumption: all are page-aligned
213///
214/// # Safety
215/// This function modifies pages backing a virtual memory range which
216/// is inherently unsafe w.r.t.  the Rust memory model.
217///
218/// When using this function, please note:
219/// - No locking is performed before touching page table data structures,
220///   as such do not use concurrently with any other page table operations
221/// - TLB invalidation is not performed, if previously-mapped ranges
222///   are being remapped, TLB invalidation may need to be performed
223///   afterwards.
224pub use arch::map;
225/// This function is presently used for reading the tracing data, also
226/// it is useful for debugging
227///
228/// # Safety
229/// This function traverses page table data structures, and should not
230/// be called concurrently with any other operations that modify the
231/// page table.
232pub use arch::virt_to_phys;