ostd/mm/page_table/node/mod.rs
1// SPDX-License-Identifier: MPL-2.0
2//! This module defines page table node abstractions and the handle.
3//!
4//! The page table node is also frequently referred to as a page table in many architectural
5//! documentations. It is essentially a page that contains page table entries (PTEs) that map
6//! to child page tables nodes or mapped pages.
7//!
8//! This module leverages the page metadata to manage the page table pages, which makes it
9//! easier to provide the following guarantees:
10//!
11//! The page table node is not freed when it is still in use by:
12//! - a parent page table node,
13//! - or a handle to a page table node,
14//! - or a processor.
15//!
16//! This is implemented by using a reference counter in the page metadata. If the above
17//! conditions are not met, the page table node is ensured to be freed upon dropping the last
18//! reference.
19//!
20//! One can acquire exclusive access to a page table node using merely the physical address of
21//! the page table node. This is implemented by a lock in the page metadata. Here the
22//! exclusiveness is only ensured for kernel code, and the processor's MMU is able to access the
23//! page table node while a lock is held. So the modification to the PTEs should be done after
24//! the initialization of the entity that the PTE points to. This is taken care in this module.
25//!
26mod child;
27mod entry;
28
29#[path = "../../../../specs/mm/page_table/node/child.rs"]
30mod child_specs;
31#[path = "../../../../specs/mm/page_table/node/entry.rs"]
32mod entry_specs;
33
34pub use crate::specs::mm::page_table::node::{entry_owners::*, owners::*};
35pub use child::*;
36pub use entry::*;
37
38use vstd::cell::pcell_maybe_uninit;
39use vstd::prelude::*;
40
41use vstd::atomic::PAtomicU8;
42use vstd::simple_pptr::{self, PPtr};
43
44use vstd_extra::array_ptr;
45use vstd_extra::cast_ptr::*;
46use vstd_extra::ghost_tree::*;
47use vstd_extra::ownership::*;
48
49use crate::mm::frame::allocator::FrameAllocOptions;
50use crate::mm::frame::meta::MetaSlot;
51use crate::mm::frame::{frame_to_index, AnyFrameMeta, Frame};
52use crate::mm::kspace::VMALLOC_BASE_VADDR;
53use crate::mm::page_table::*;
54use crate::mm::{kspace::LINEAR_MAPPING_BASE_VADDR, paddr_to_vaddr, Paddr, Vaddr};
55use crate::specs::arch::kspace::FRAME_METADATA_RANGE;
56use crate::specs::mm::frame::mapping::{meta_to_frame, META_SLOT_SIZE};
57use crate::specs::mm::frame::meta_owners::{
58 MetaSlotOwner, MetaSlotStorage, Metadata, REF_COUNT_UNUSED,
59};
60use crate::specs::mm::frame::meta_region_owners::MetaRegionOwners;
61use crate::specs::mm::page_table::node::owners::*;
62
63use core::{marker::PhantomData, ops::Deref, sync::atomic::Ordering};
64
65use super::nr_subpage_per_huge;
66
67use crate::{
68 mm::{
69 page_table::{load_pte, store_pte},
70 // FrameAllocOptions, Infallible,
71 // VmReader,
72 },
73 specs::task::InAtomicMode,
74};
75
76verus! {
77
78/// The metadata of any kinds of page table pages.
79/// Make sure the the generic parameters don't effect the memory layout.
80pub struct PageTablePageMeta<C: PageTableConfig> {
81 /// The number of valid PTEs. It is mutable if the lock is held.
82 pub nr_children: pcell_maybe_uninit::PCell<u16>,
83 /// If the page table is detached from its parent.
84 ///
85 /// A page table can be detached from its parent while still being accessed,
86 /// since we use a RCU scheme to recycle page tables. If this flag is set,
87 /// it means that the parent is recycling the page table.
88 pub stray: pcell_maybe_uninit::PCell<bool>,
89 /// The level of the page table page. A page table page cannot be
90 /// referenced by page tables of different levels.
91 pub level: PagingLevel,
92 /// The lock for the page table page.
93 pub lock: PAtomicU8,
94 pub _phantom: core::marker::PhantomData<C>,
95}
96
97/// A smart pointer to a page table node.
98///
99/// This smart pointer is an owner of a page table node. Thus creating and
100/// dropping it will affect the reference count of the page table node. If
101/// dropped it as the last reference, the page table node and subsequent
102/// children will be freed.
103///
104/// [`PageTableNode`] is read-only. To modify the page table node, lock and use
105/// [`PageTableGuard`].
106pub type PageTableNode<C> = Frame<PageTablePageMeta<C>>;
107
108impl<C: PageTableConfig> AnyFrameMeta for PageTablePageMeta<C> {
109 fn on_drop(&mut self) {
110 }
111
112 fn is_untyped(&self) -> bool {
113 false
114 }
115
116 uninterp spec fn vtable_ptr(&self) -> usize;
117}
118
119#[verus_verify]
120impl<C: PageTableConfig> PageTableNode<C> {
121 /// Gets the level of a page table node.
122 /// # Verified Properties
123 /// ## Preconditions
124 /// - The node must be well-formed, and the caller must provide a permission token for its metadata.
125 /// ## Postconditions
126 /// - Returns the level of the node.
127 /// ## Safety
128 /// - We require the caller to provide a permission token to ensure that this function is only called on a valid page table node.
129 #[verus_spec(
130 with Tracked(perm) : Tracked<&PointsTo<MetaSlot, Metadata<PageTablePageMeta<C>>>>
131 )]
132 pub(super) fn level(&self) -> PagingLevel
133 requires
134 self.ptr.addr() == perm.addr(),
135 self.ptr.addr() == perm.points_to.addr(),
136 perm.is_init(),
137 perm.wf(&perm.inner_perms),
138 returns
139 perm.value().metadata.level,
140 {
141 #[verus_spec(with Tracked(perm))]
142 let meta = self.meta();
143 meta.level
144 }
145
146 /// Allocates a new empty page table node.
147 #[verus_spec(res =>
148 with Tracked(parent_owner): Tracked<&mut NodeOwner<C>>,
149 Tracked(regions): Tracked<&mut MetaRegionOwners>,
150 Tracked(guards): Tracked<&Guards<'rcu, C>>,
151 Ghost(idx): Ghost<usize>,
152 -> owner: Tracked<OwnerSubtree<C>>
153 requires
154 1 <= level < NR_LEVELS,
155 idx < NR_ENTRIES,
156 old(regions).inv(),
157 old(parent_owner).inv(),
158 ensures
159 regions.inv(),
160 parent_owner.inv(),
161 allocated_empty_node_owner(owner@, level),
162 res.ptr.addr() == owner@.value.node.unwrap().meta_perm.addr(),
163 guards.unlocked(owner@.value.node.unwrap().meta_perm.addr()),
164 MetaSlot::get_from_unused_spec(meta_to_frame(owner@.value.node.unwrap().meta_perm.addr()), false, *old(regions), *regions),
165 owner@.value.relate_region(*regions),
166 owner@.value.in_scope,
167 owner@.value.match_pte(C::E::new_pt_spec(meta_to_frame(owner@.value.node.unwrap().meta_perm.addr())), level as PagingLevel),
168 *parent_owner == old(parent_owner).set_children_perm(idx, C::E::new_pt_spec(meta_to_frame(owner@.value.node.unwrap().meta_perm.addr()))),
169 )]
170 #[verifier::external_body]
171 pub fn alloc<'rcu>(level: PagingLevel) -> Self {
172 let tracked entry_owner = EntryOwner::new_absent(TreePath::new(Seq::empty()), level);
173
174 let tracked mut owner = OwnerSubtree::<C>::new_val_tracked(entry_owner, level as nat);
175 let meta = PageTablePageMeta::new(level);
176 let mut frame = FrameAllocOptions::new();
177 frame.zeroed(true);
178 let allocated_frame = frame.alloc_frame_with(meta).expect(
179 "Failed to allocate a page table node",
180 );
181 // The allocated frame is zeroed. Make sure zero is absent PTE.
182 //debug_assert_eq!(C::E::new_absent().as_usize(), 0);
183
184 proof_with!(|= Tracked(owner));
185
186 allocated_frame
187 }/*
188 /// Activates the page table assuming it is a root page table.
189 ///
190 /// Here we ensure not dropping an active page table by making a
191 /// processor a page table owner. When activating a page table, the
192 /// reference count of the last activated page table is decremented.
193 /// And that of the current page table is incremented.
194 ///
195 /// # Safety
196 ///
197 /// The caller must ensure that the page table to be activated has
198 /// proper mappings for the kernel and has the correct const parameters
199 /// matching the current CPU.
200 ///
201 /// # Panics
202 ///
203 /// Only top-level page tables can be activated using this function.
204 pub(crate) unsafe fn activate(&self) {
205 use crate::{
206 arch::mm::{activate_page_table, current_page_table_paddr},
207 mm::page_prop::CachePolicy,
208 };
209
210 assert_eq!(self.level(), C::NR_LEVELS());
211
212 let last_activated_paddr = current_page_table_paddr();
213 if last_activated_paddr == self.start_paddr() {
214 return;
215 }
216
217 // SAFETY: The safety is upheld by the caller.
218 unsafe { activate_page_table(self.clone().into_raw(), CachePolicy::Writeback) };
219
220 // Restore and drop the last activated page table.
221 // SAFETY: The physical address is valid and points to a forgotten page table node.
222 drop(unsafe { Self::from_raw(last_activated_paddr) });
223 }
224
225 /// Activates the (root) page table assuming it is the first activation.
226 ///
227 /// It will not try dropping the last activate page table. It is the same
228 /// with [`Self::activate()`] in other senses.
229 pub(super) unsafe fn first_activate(&self) {
230 use crate::{arch::mm::activate_page_table, mm::page_prop::CachePolicy};
231
232 // SAFETY: The safety is upheld by the caller.
233 unsafe { activate_page_table(self.clone().into_raw(), CachePolicy::Writeback) };
234 }*/
235
236}
237
238#[verus_verify]
239impl<'a, C: PageTableConfig> PageTableNodeRef<'a, C> {
240 pub open spec fn locks_preserved_except<'rcu>(
241 addr: usize,
242 guards0: Guards<'rcu, C>,
243 guards1: Guards<'rcu, C>,
244 ) -> bool {
245 &&& OwnerSubtree::implies(
246 CursorOwner::node_unlocked(guards0),
247 CursorOwner::node_unlocked_except(guards1, addr),
248 )
249 &&& forall|i: usize| guards0.lock_held(i) ==> guards1.lock_held(i)
250 &&& forall|i: usize| guards0.unlocked(i) && i != addr ==> guards1.unlocked(i)
251 }
252
253 /// Locks the page table node.
254 ///
255 /// An atomic mode guard is required to
256 /// 1. prevent deadlocks;
257 /// 2. provide a lifetime (`'rcu`) that the nodes are guaranteed to outlive.
258 /// # Verification Design
259 /// As of when we verified this library, we didn't have a spin lock implementation, so we axiomatize
260 /// what happens when it's successful.
261 #[verifier::external_body]
262 #[verus_spec(res =>
263 with Tracked(owner): Tracked<&NodeOwner<C>>,
264 Tracked(guards): Tracked<&mut Guards<'rcu, C>>
265 -> guard_perm: Tracked<GuardPerm<'rcu, C>>
266 requires
267 self.inner@.invariants(*owner),
268 old(guards).unlocked(owner.meta_perm.addr()),
269 ensures
270 guards.lock_held(owner.meta_perm.addr()),
271 Self::locks_preserved_except(owner.meta_perm.addr(), *old(guards), *guards),
272 res.addr() == guard_perm@.addr(),
273 owner.relate_guard_perm(guard_perm@),
274 )]
275 pub fn lock<'rcu, A: InAtomicMode>(self, _guard: &'rcu A) -> PPtr<
276 PageTableGuard<'rcu, C>,
277 > where 'a: 'rcu {
278 unimplemented!()
279 }
280
281 /// Creates a new [`PageTableGuard`] without checking if the page table lock is held.
282 ///
283 /// # Safety
284 ///
285 /// This function must be called if this task logically holds the lock.
286 ///
287 /// Calling this function when a guard is already created is undefined behavior
288 /// unless that guard was already forgotten.
289 #[verus_spec(res =>
290 with Tracked(owner): Tracked<&NodeOwner<C>>,
291 Tracked(guards): Tracked<&mut Guards<'rcu, C>>
292 -> guard_perm: Tracked<GuardPerm<'rcu, C>>
293 requires
294 self.inner@.invariants(*owner),
295 old(guards).unlocked(owner.meta_perm.addr()),
296 ensures
297 guards.lock_held(owner.meta_perm.addr()),
298 Self::locks_preserved_except(owner.meta_perm.addr(), *old(guards), *guards),
299 res.addr() == guard_perm@.addr(),
300 owner.relate_guard_perm(guard_perm@),
301 )]
302 pub fn make_guard_unchecked<'rcu, A: InAtomicMode>(self, _guard: &'rcu A) -> PPtr<
303 PageTableGuard<'rcu, C>,
304 > where 'a: 'rcu {
305 let guard = PageTableGuard { inner: self };
306 let (ptr, guard_perm) = PPtr::<PageTableGuard<C>>::new(guard);
307
308 proof {
309 let ghost guards0 = *guards;
310 guards.guards.tracked_insert(owner.meta_perm.addr(), None);
311 assert(owner.relate_guard_perm(guard_perm@));
312
313 assert(forall|other: EntryOwner<C>, path: TreePath<NR_ENTRIES>|
314 owner.inv() && CursorOwner::node_unlocked(guards0)(other, path)
315 ==> #[trigger] CursorOwner::node_unlocked_except(
316 *guards,
317 owner.meta_perm.addr(),
318 )(other, path));
319 }
320
321 proof_with!{|= guard_perm}
322 ptr
323 }
324}
325
326//}
327impl<'rcu, C: PageTableConfig> PageTableGuard<'rcu, C> {
328 /// Borrows an entry in the node at a given index.
329 ///
330 /// # Panics
331 ///
332 /// Panics if the index is not within the bound of
333 /// [`nr_subpage_per_huge<C>`].
334 #[verus_spec(res =>
335 with Tracked(owner): Tracked<&NodeOwner<C>>,
336 Tracked(child_owner): Tracked<&EntryOwner<C>>,
337 Tracked(guard_perm): Tracked<&GuardPerm<'rcu, C>>,
338 )]
339 pub fn entry(guard: PPtr<Self>, idx: usize) -> (res: Entry<'rcu, C>)
340 requires
341 owner.inv(),
342 !child_owner.in_scope,
343 child_owner.inv(),
344 owner.relate_guard_perm(*guard_perm),
345 guard_perm.addr() == guard.addr(),
346 child_owner.match_pte(
347 owner.children_perm.value()[idx as int],
348 child_owner.parent_level,
349 ),
350 // Panic condition
351 idx < NR_ENTRIES,
352 ensures
353 res.wf(*child_owner),
354 res.node.addr() == guard_perm.addr(),
355 res.idx == idx,
356 {
357 // assert!(idx < nr_subpage_per_huge::<C>());
358 // SAFETY: The index is within the bound.
359 #[verus_spec(with Tracked(child_owner), Tracked(owner), Tracked(guard_perm))]
360 Entry::new_at(guard, idx);
361 }
362
363 /// Gets the number of valid PTEs in a page table node.
364 /// # Verified Properties
365 /// ## Preconditions
366 /// - The node must be well-formed.
367 /// ## Postconditions
368 /// - Returns the number of valid PTEs in the node.
369 /// ## Safety
370 /// - We require the caller to provide a permission token to ensure that this function is only called on a valid page table node.
371 #[verus_spec(
372 with Tracked(owner) : Tracked<&NodeOwner<C>>
373 )]
374 pub fn nr_children(&self) -> (nr: u16)
375 requires
376 // Node invariants: owner well-formedness and node-owner consistency
377
378 self.inner.inner@.invariants(*owner),
379 returns
380 owner.meta_own.nr_children.value(),
381 {
382 // SAFETY: The lock is held so we have an exclusive access.
383 #[verus_spec(with Tracked(&owner.meta_perm))]
384 let meta = self.meta();
385
386 *meta.nr_children.borrow(Tracked(&owner.meta_own.nr_children))
387 }
388
389 /// Returns if the page table node is detached from its parent.
390 #[verus_spec(
391 with Tracked(meta_perm): Tracked<&'a PointsTo<MetaSlot, Metadata<PageTablePageMeta<C>>>>
392 )]
393 pub(super) fn stray_mut<'a>(&'a mut self) -> (res: &'a pcell_maybe_uninit::PCell<bool>)
394 requires
395 old(self).inner.inner@.ptr.addr() == meta_perm.addr(),
396 old(self).inner.inner@.ptr.addr() == meta_perm.points_to.addr(),
397 meta_perm.is_init(),
398 meta_perm.wf(&meta_perm.inner_perms),
399 ensures
400 res.id() == meta_perm.value().metadata.stray.id(),
401 *self == *old(self),
402 {
403 // SAFETY: The lock is held so we have an exclusive access.
404 #[verus_spec(with Tracked(meta_perm))]
405 let meta = self.meta();
406 &meta.stray
407 }
408
409 /// Reads a non-owning PTE at the given index.
410 ///
411 /// A non-owning PTE means that it does not account for a reference count
412 /// of the a page if the PTE points to a page. The original PTE still owns
413 /// the child page.
414 ///
415 /// # Safety
416 ///
417 /// The caller must ensure that the index is within the bound.
418 #[verus_spec(
419 with Tracked(owner): Tracked<&NodeOwner<C>>
420 )]
421 pub fn read_pte(&self, idx: usize) -> (pte: C::E)
422 requires
423 self.inner.inner@.invariants(*owner),
424 idx < NR_ENTRIES,
425 ensures
426 pte == owner.children_perm.value()[idx as int],
427 {
428 // debug_assert!(idx < nr_subpage_per_huge::<C>());
429 let ptr = vstd_extra::array_ptr::ArrayPtr::<C::E, NR_ENTRIES>::from_addr(
430 paddr_to_vaddr(
431 #[verus_spec(with Tracked(&owner.meta_perm.points_to))]
432 self.start_paddr(),
433 ),
434 );
435
436 // SAFETY:
437 // - The page table node is alive. The index is inside the bound, so the page table entry is valid.
438 // - All page table entries are aligned and accessed with atomic operations only.
439 #[verus_spec(with Tracked(&owner.children_perm))]
440 load_pte(ptr.add(idx), Ordering::Relaxed)
441 }
442
443 /// Writes a page table entry at a given index.
444 ///
445 /// This operation will leak the old child if the old PTE is present.
446 ///
447 /// # Safety
448 ///
449 /// The caller must ensure that:
450 /// 1. The index must be within the bound;
451 /// 2. The PTE must represent a valid [`Child`] whose level is compatible
452 /// with the page table node.
453 /// 3. The page table node will have the ownership of the [`Child`]
454 /// after this method.
455 #[verus_spec(
456 with Tracked(owner): Tracked<&mut NodeOwner<C>>
457 )]
458 pub fn write_pte(&mut self, idx: usize, pte: C::E)
459 requires
460 old(self).inner.inner@.invariants(*old(owner)),
461 idx < NR_ENTRIES,
462 ensures
463 owner.inv(),
464 owner.meta_perm.addr() == old(owner).meta_perm.addr(),
465 owner.level == old(owner).level,
466 owner.meta_own == old(owner).meta_own,
467 owner.meta_perm.points_to == old(owner).meta_perm.points_to,
468 owner.children_perm.value() == old(owner).children_perm.value().update(idx as int, pte),
469 *self == *old(self),
470 {
471 // debug_assert!(idx < nr_subpage_per_huge::<C>());
472 #[verusfmt::skip]
473 let ptr = vstd_extra::array_ptr::ArrayPtr::<C::E, NR_ENTRIES>::from_addr(
474 paddr_to_vaddr(
475 #[verus_spec(with Tracked(&owner.meta_perm.points_to))]
476 self.start_paddr()
477 ),
478 );
479
480 // SAFETY:
481 // - The page table node is alive. The index is inside the bound, so the page table entry is valid.
482 // - All page table entries are aligned and accessed with atomic operations only.
483 #[verus_spec(with Tracked(&mut owner.children_perm))]
484 store_pte(ptr.add(idx), pte, Ordering::Release)
485 }
486
487 /// Gets the mutable reference to the number of valid PTEs in the node.
488 #[verus_spec(
489 with Tracked(meta_perm): Tracked<&'a PointsTo<MetaSlot, Metadata<PageTablePageMeta<C>>>>
490 )]
491 fn nr_children_mut<'a>(&'a mut self) -> (res: &'a pcell_maybe_uninit::PCell<u16>)
492 requires
493 old(self).inner.inner@.ptr.addr() == meta_perm.addr(),
494 old(self).inner.inner@.ptr.addr() == meta_perm.points_to.addr(),
495 meta_perm.is_init(),
496 meta_perm.wf(&meta_perm.inner_perms),
497 ensures
498 res.id() == meta_perm.value().metadata.nr_children.id(),
499 *self == *old(self),
500 {
501 // SAFETY: The lock is held so we have an exclusive access.
502 #[verus_spec(with Tracked(meta_perm))]
503 let meta = self.meta();
504 &meta.nr_children
505 }
506}
507
508/*impl<C: PageTableConfig> Drop for PageTableGuard<'_, C> {
509 fn drop(&mut self) {
510 self.inner.meta().lock.store(0, Ordering::Release);
511 }
512}*/
513
514impl<C: PageTableConfig> PageTablePageMeta<C> {
515 pub fn new(level: PagingLevel) -> Self {
516 Self {
517 nr_children: pcell_maybe_uninit::PCell::new(0).0,
518 stray: pcell_maybe_uninit::PCell::new(false).0,
519 level,
520 lock: PAtomicU8::new(0).0,
521 _phantom: PhantomData,
522 }
523 }
524}
525
526} // verus!
527/* TODO: Come back after VMReader
528// FIXME: The safe APIs in the `page_table/node` module allow `Child::Frame`s with
529// arbitrary addresses to be stored in the page table nodes. Therefore, they may not
530// be valid `C::Item`s. The soundness of the following `on_drop` implementation must
531// be reasoned in conjunction with the `page_table/cursor` implementation.
532unsafe impl<C: PageTableConfig> AnyFrameMeta for PageTablePageMeta<C> {
533 fn on_drop(&mut self, reader: &mut VmReader<Infallible>) {
534 let nr_children = self.nr_children.get_mut();
535 if *nr_children == 0 {
536 return;
537 }
538
539 let level = self.level;
540 let range = if level == C::NR_LEVELS() {
541 C::TOP_LEVEL_INDEX_RANGE.clone()
542 } else {
543 0..nr_subpage_per_huge::<C>()
544 };
545
546 // Drop the children.
547 reader.skip(range.start * size_of::<C::E>());
548 for _ in range {
549 // Non-atomic read is OK because we have mutable access.
550 let pte = reader.read_once::<C::E>().unwrap();
551 if pte.is_present() {
552 let paddr = pte.paddr();
553 // As a fast path, we can ensure that the type of the child frame
554 // is `Self` if the PTE points to a child page table. Then we don't
555 // need to check the vtable for the drop method.
556 if !pte.is_last(level) {
557 // SAFETY: The PTE points to a page table node. The ownership
558 // of the child is transferred to the child then dropped.
559 drop(unsafe { Frame::<Self>::from_raw(paddr) });
560 } else {
561 // SAFETY: The PTE points to a mapped item. The ownership
562 // of the item is transferred here then dropped.
563 drop(unsafe { C::item_from_raw(paddr, level, pte.prop()) });
564 }
565 }
566 }
567 }
568}*/