Skip to main content

ostd/mm/
mod.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Virtual memory (VM).
3use vstd::{
4    arithmetic::{div_mod::group_div_basics, mul::lemma_mul_left_inequality, power2::*},
5    bits::lemma_usize_shl_is_mul,
6    prelude::*,
7};
8use vstd_extra::external::ilog2::{
9    lemma_pow2_is_pow2, lemma_usize_ilog2_ordered, lemma_usize_is_pow2_is_ilog2_pow2,
10    lemma_usize_pow2_shl_is_pow2,
11};
12
13use crate::specs::mm::page_table::{
14    lemma_page_size_is_pow2_pte_index_bit_offset, nr_pte_index_bits_spec,
15};
16
17/// Virtual addresses.
18pub type Vaddr = usize;
19
20/// Physical addresses.
21pub type Paddr = usize;
22
23pub(crate) mod dma;
24pub mod frame;
25//pub mod heap;
26pub mod io;
27pub mod kspace;
28pub(crate) mod page_prop;
29pub mod page_table;
30pub mod tlb;
31pub mod vm_space;
32
33/* #[cfg(ktest)] */
34mod test;
35
36use core::{fmt::Debug, ops::Range};
37
38pub use self::{
39    dma::{Daddr, DmaCoherent, /* DmaDirection, DmaStream, DmaStreamSlice, */ HasDaddr},
40    frame::{
41        Frame,
42        allocator::FrameAllocOptions,
43        segment::{Segment, USegment},
44        unique::UniqueFrame,
45        untyped::{AnyUFrameMeta, UFrame, UntypedMem},
46    },
47    io::{
48        Fallible, FallibleVmRead, FallibleVmWrite, Infallible, PodOnce, VmIo, VmIoOnce, VmReader,
49        VmWriter,
50    },
51    page_prop::{CachePolicy, PageFlags, PageProperty},
52    vm_space::VmSpace,
53};
54pub(crate) use self::{
55    kspace::paddr_to_vaddr, page_prop::PrivilegedPageFlags, page_table::PageTable,
56};
57pub(crate) use crate::arch::mm::PagingConsts;
58pub use crate::arch::mm::{NR_ENTRIES, NR_LEVELS, PAGE_SIZE};
59
60// Re-export largest_pages from page_table
61pub(crate) use page_table::largest_pages;
62
63/// The level of a page table node or a frame.
64pub type PagingLevel = u8;
65
66verus! {
67
68/// The maximum value of `PagingConstsTrait::NR_LEVELS`.
69/* Moved from page_table/cursor/mod.rs for shared layout proofs.
70 * Origin Rust: const MAX_NR_LEVELS: usize = 4;
71 */
72pub const MAX_NR_LEVELS: usize = 4;
73
74/* Keep modeled memory bounds in mm so architecture models can share them
75 * without depending on specs::arch::x86. Paddr is an alias for usize.
76 * Origin Rust:
77 * pub const MAX_PADDR: usize = 0x8000_0000;
78 * pub const MAX_NR_PAGES: u64 = (MAX_PADDR / PAGE_SIZE) as u64;
79 */
80
81/// Current verification upper bound for tracked physical addresses.
82///
83/// This is a memory-model bound, not the architectural physical-address width.
84pub const MAX_PADDR: Paddr = 0x8000_0000;
85
86/// Maximum number of base-page frames represented by the current memory model.
87pub const MAX_NR_PAGES: u64 = (MAX_PADDR / PAGE_SIZE) as u64;
88
89/// A minimal set of constants that determines the paging system.
90/// This provides an abstraction over most paging modes in common architectures.
91///
92/// Verification requires 4 KiB pages, 8-byte PTEs, 1..=[`MAX_NR_LEVELS`] levels,
93/// and `12 + 9 * NR_LEVELS <= ADDRESS_WIDTH < usize::BITS`.
94pub trait PagingConstsTrait: Clone + Debug + Send + Sync + 'static {
95    /// The smallest page size.
96    /// This is also the page size at level 1 page tables.
97    const BASE_PAGE_SIZE: usize;
98
99    /// The number of levels in the page table.
100    /// The numbering of levels goes from deepest node to the root node. For example,
101    /// the level 1 to 5 on AMD64 corresponds to Page Tables, Page Directory Tables,
102    /// Page Directory Pointer Tables, Page-Map Level-4 Table, and Page-Map Level-5
103    /// Table, respectively.
104    const NR_LEVELS: PagingLevel;
105
106    /// The highest level that a PTE can be directly used to translate a VA.
107    /// This affects the the largest page size supported by the page table.
108    const HIGHEST_TRANSLATION_LEVEL: PagingLevel;
109
110    /// The size of a PTE.
111    const PTE_SIZE: usize;
112
113    /// The address width may be BASE_PAGE_SIZE.ilog2() + NR_LEVELS * IN_FRAME_INDEX_BITS.
114    /// If it is shorter than that, the higher bits in the highest level are ignored.
115    const ADDRESS_WIDTH: usize;
116
117    /// Whether virtual addresses are sign-extended.
118    ///
119    /// The sign bit of a [`Vaddr`] is the bit at index [`PagingConstsTrait::ADDRESS_WIDTH`] - 1.
120    /// If this constant is `true`, bits in [`Vaddr`] that are higher than the sign bit must be
121    /// equal to the sign bit. If an address violates this rule, both the hardware and OSTD
122    /// should reject it.
123    ///
124    /// Otherwise, if this constant is `false`, higher bits must be zero.
125    ///
126    /// Regardless of sign extension, [`Vaddr`] is always not signed upon calculation.
127    /// That means, `0xffff_ffff_ffff_0000 < 0xffff_ffff_ffff_0001` is `true`.
128    const VA_SIGN_EXT: bool;
129
130    /// The requirements of the paging constants so that the memory management system can work correctly.
131    ///
132    /// NOTE: The postcondition is designed to be minimal, to actually be used in proofs, call `lemma_paging_consts_properties`
133    /// instead to get all the properties that are derived from the requirements.
134    ///
135    proof fn lemma_paging_consts_requirements()
136        ensures
137            Self::BASE_PAGE_SIZE == 4096,
138            1 <= Self::NR_LEVELS <= MAX_NR_LEVELS,
139            0 < Self::BASE_PAGE_SIZE,
140            is_pow2(Self::BASE_PAGE_SIZE as int),
141            0 < Self::HIGHEST_TRANSLATION_LEVEL <= Self::NR_LEVELS < PagingLevel::MAX,
142            is_pow2(Self::PTE_SIZE as int),
143            0 < Self::PTE_SIZE <= Self::BASE_PAGE_SIZE,
144            0 < Self::ADDRESS_WIDTH < usize::BITS,
145            Self::BASE_PAGE_SIZE.ilog2() + (Self::BASE_PAGE_SIZE / Self::PTE_SIZE).ilog2()
146                * Self::NR_LEVELS <= Self::ADDRESS_WIDTH,
147            Self::PTE_SIZE == core::mem::size_of::<usize>(),
148    ;
149
150    /// The derived properties of the paging constants.
151    ///
152    /// NOTE: Implementations of `PagingConstsTrait` do not need to implement this lemma, the proof is automatically inherited from the default implementation.
153    proof fn lemma_paging_consts_properties()
154        ensures
155    // Derived properties.
156
157            Self::PTE_SIZE == 8,
158            Self::BASE_PAGE_SIZE.ilog2() + (Self::BASE_PAGE_SIZE / Self::PTE_SIZE).ilog2() * (
159            Self::NR_LEVELS - 1) <= Self::ADDRESS_WIDTH,
160            0 < Self::BASE_PAGE_SIZE / Self::PTE_SIZE <= Self::BASE_PAGE_SIZE,
161            is_pow2((Self::BASE_PAGE_SIZE / Self::PTE_SIZE) as int),
162            Self::BASE_PAGE_SIZE / Self::PTE_SIZE == NR_ENTRIES,
163            // Copied from the postcondition of `lemma_paging_consts_requirements`
164            // so that we only need to call this lemma in proofs.
165            Self::BASE_PAGE_SIZE == 4096,
166            1 <= Self::NR_LEVELS <= MAX_NR_LEVELS,
167            0 < Self::BASE_PAGE_SIZE,
168            is_pow2(Self::BASE_PAGE_SIZE as int),
169            0 < Self::HIGHEST_TRANSLATION_LEVEL <= Self::NR_LEVELS < PagingLevel::MAX,
170            is_pow2(Self::PTE_SIZE as int),
171            0 < Self::PTE_SIZE <= Self::BASE_PAGE_SIZE,
172            0 < Self::ADDRESS_WIDTH < usize::BITS,
173            Self::BASE_PAGE_SIZE.ilog2() + (Self::BASE_PAGE_SIZE / Self::PTE_SIZE).ilog2()
174                * Self::NR_LEVELS <= Self::ADDRESS_WIDTH,
175            Self::PTE_SIZE == core::mem::size_of::<usize>(),
176    {
177        Self::lemma_paging_consts_requirements();
178        broadcast use group_div_basics;
179
180        assert(Self::PTE_SIZE == 8);
181        assert(NR_ENTRIES == 512) by (compute_only);
182        assert(Self::BASE_PAGE_SIZE / Self::PTE_SIZE == NR_ENTRIES) by (nonlinear_arith)
183            requires
184                Self::BASE_PAGE_SIZE == 4096,
185                Self::PTE_SIZE == 8,
186                NR_ENTRIES == 512,
187        ;
188        let base = Self::BASE_PAGE_SIZE as int;
189        let pte = Self::PTE_SIZE as int;
190        let levels = Self::NR_LEVELS as int;
191        let base_bits = Self::BASE_PAGE_SIZE.ilog2() as int;
192        let index_bits = (Self::BASE_PAGE_SIZE / Self::PTE_SIZE).ilog2() as int;
193        assert(0 < base / pte) by {
194            vstd::arithmetic::div_mod::lemma_div_non_zero(base, pte);
195        };
196        assert(base / pte <= base) by {
197            vstd::arithmetic::div_mod::lemma_div_is_ordered(0, base, pte);
198        };
199        assert(base_bits + index_bits * (levels - 1) <= base_bits + index_bits * levels)
200            by (nonlinear_arith)
201            requires
202                0 <= index_bits,
203                1 <= levels,
204        ;
205        let page = Self::BASE_PAGE_SIZE;
206        let pte = Self::PTE_SIZE;
207        lemma_usize_is_pow2_is_ilog2_pow2(page);
208        lemma_usize_is_pow2_is_ilog2_pow2(pte);
209        lemma_usize_ilog2_ordered(pte, page);
210        lemma_pow2_subtracts(pte.ilog2() as nat, page.ilog2() as nat);
211        lemma_pow2_is_pow2((page.ilog2() - pte.ilog2()) as nat);
212    }
213}
214
215pub open spec fn page_size_spec<C: PagingConstsTrait>(level: PagingLevel) -> usize {
216    (C::BASE_PAGE_SIZE * pow2((nr_subpage_per_huge::<C>().ilog2() * (level - 1)) as nat)) as usize
217}
218
219// /// The page size
220// pub const PAGE_SIZE: usize = page_size::<PagingConsts>(1);
221/// The page size at a given level.
222#[verifier::when_used_as_spec(page_size_spec)]
223pub const fn page_size<C: PagingConstsTrait>(level: PagingLevel) -> (ret: usize)
224    requires
225        1 <= level <= C::NR_LEVELS + 1,
226    ensures
227        is_pow2(ret as int),
228        ret >= C::BASE_PAGE_SIZE,
229    returns
230        page_size_spec::<C>(level),
231{
232    proof {
233        C::lemma_paging_consts_properties();
234        lemma_page_size_is_pow2_pte_index_bit_offset::<C>(level);
235        let shift = (nr_pte_index_bits_spec::<C>() * (level - 1)) as usize;
236        lemma_usize_is_pow2_is_ilog2_pow2(C::BASE_PAGE_SIZE);
237        lemma_pow2_adds(C::BASE_PAGE_SIZE.ilog2() as nat, shift as nat);
238        lemma_usize_shl_is_mul(C::BASE_PAGE_SIZE, shift);
239        lemma_usize_pow2_shl_is_pow2(C::BASE_PAGE_SIZE, shift);
240        lemma_pow2_pos(shift as nat);
241        lemma_mul_left_inequality(C::BASE_PAGE_SIZE as int, 1, pow2(shift as nat) as int);
242    }
243    C::BASE_PAGE_SIZE << (nr_subpage_per_huge::<C>().ilog2() as usize * (level as usize - 1))
244}
245
246#[verifier::inline]
247pub open spec fn nr_subpage_per_huge_spec<C: PagingConstsTrait>() -> usize {
248    C::BASE_PAGE_SIZE / C::PTE_SIZE
249}
250
251/// The number of sub pages in a huge page.
252#[verifier::when_used_as_spec(nr_subpage_per_huge_spec)]
253pub const fn nr_subpage_per_huge<C: PagingConstsTrait>() -> usize
254    returns
255        nr_subpage_per_huge_spec::<C>(),
256{
257    proof {
258        C::lemma_paging_consts_properties();
259    }
260    C::BASE_PAGE_SIZE / C::PTE_SIZE
261}
262
263/// The maximum virtual address of user space (non inclusive).
264///
265/// Typical 64-bit systems have at least 48-bit virtual address space.
266/// A typical way to reserve half of the address space for the kernel is
267/// to use the highest 48-bit virtual address space.
268///
269/// Also, the top page is not regarded as usable since it's a workaround
270/// for some x86_64 CPUs' bugs. See
271/// <https://github.com/torvalds/linux/blob/480e035fc4c714fb5536e64ab9db04fedc89e910/arch/x86/include/asm/page_64.h#L68-L78>
272/// for the rationale.
273pub const MAX_USERSPACE_VADDR: Vaddr = 0x0000_8000_0000_0000_usize - PAGE_SIZE;
274
275/// The kernel address space.
276///
277/// There are the high canonical addresses defined in most 48-bit width
278/// architectures.
279pub const KERNEL_VADDR_RANGE: Range<Vaddr> =
280    0xffff_8000_0000_0000_usize..0xffff_ffff_ffff_0000_usize;
281
282/// Gets physical address trait
283pub trait HasPaddr {
284    /// Returns the physical address.
285    fn paddr(&self) -> Paddr;
286}
287
288/// Checks if the given address is page-aligned.
289pub const fn is_page_aligned(p: usize) -> bool {
290    (p & (PAGE_SIZE - 1)) == 0
291}
292
293} // verus!