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