ostd/mm/frame/mod.rs
1// SPDX-License-Identifier: MPL-2.0
2
3//! Frame (physical memory page) management.
4//!
5//! A frame is an aligned, contiguous range of bytes in physical memory. The
6//! sizes of base frames and huge frames (that are mapped as "huge pages") are
7//! architecture-dependent. A frame can be mapped to virtual address spaces
8//! using the page table.
9//!
10//! Frames can be accessed through frame handles, namely, [`Frame`]. A frame
11//! handle is a reference-counted pointer to a frame. When all handles to a
12//! frame are dropped, the frame is released and can be reused. Contiguous
13//! frames are managed with [`Segment`].
14//!
15//! There are various kinds of frames. The top-level grouping of frame kinds
16//! are "typed" frames and "untyped" frames. Typed frames host Rust objects
17//! that must follow the visibility, lifetime and borrow rules of Rust, thus
18//! not being able to be directly manipulated. Untyped frames are raw memory
19//! that can be manipulated directly. So only untyped frames can be
20//! - safely shared to external entities such as device drivers or user-space
21//! applications.
22//! - or directly manipulated with readers and writers that neglect Rust's
23//! "alias XOR mutability" rule.
24//!
25//! The kind of a frame is determined by the type of its metadata. Untyped
26//! frames have its metadata type that implements the [`AnyUFrameMeta`]
27//! trait, while typed frames don't.
28//!
29//! Frames can have dedicated metadata, which is implemented in the [`meta`]
30//! module. The reference count and usage of a frame are stored in the metadata
31//! as well, leaving the handle only a pointer to the metadata slot. Users
32//! can create custom metadata types by implementing the [`AnyFrameMeta`] trait.
33
34pub mod allocator;
35pub mod linked_list;
36pub mod meta;
37pub mod segment;
38pub mod unique;
39pub mod untyped;
40
41mod frame_ref;
42pub use frame_ref::FrameRef;
43
44#[cfg(ktest)]
45mod test;
46
47use core::{
48 marker::PhantomData,
49 mem::ManuallyDrop,
50 sync::atomic::{AtomicUsize, Ordering},
51};
52
53pub use allocator::GlobalFrameAllocator;
54use meta::{AnyFrameMeta, GetFrameError, MetaSlot, REF_COUNT_UNUSED, mapping};
55pub use segment::Segment;
56use untyped::{AnyUFrameMeta, UFrame};
57
58use crate::{
59 mm::{HasPaddr, HasSize, PAGE_SIZE, Paddr, PagingConsts, PagingLevel, Vaddr},
60 sync::RcuDrop,
61};
62
63// These bounds are set once during frame metadata initialization, before APs start.
64static MIN_PADDR: AtomicUsize = AtomicUsize::new(0);
65static MAX_PADDR: AtomicUsize = AtomicUsize::new(0);
66
67/// Returns the minimum physical address that is tracked by frame metadata.
68pub(in crate::mm) fn min_paddr() -> Paddr {
69 MIN_PADDR.load(Ordering::Relaxed)
70}
71
72/// Returns the maximum physical address that is tracked by frame metadata.
73pub(in crate::mm) fn max_paddr() -> Paddr {
74 let max_paddr = MAX_PADDR.load(Ordering::Relaxed) as Paddr;
75 debug_assert_ne!(max_paddr, 0);
76 max_paddr
77}
78
79/// A smart pointer to a frame.
80///
81/// A frame is a contiguous range of bytes in physical memory. The [`Frame`]
82/// type is a smart pointer to a frame that is reference-counted.
83///
84/// Frames are associated with metadata. The type of the metadata `M` is
85/// determines the kind of the frame. If `M` implements [`AnyUFrameMeta`], the
86/// frame is a untyped frame. Otherwise, it is a typed frame.
87#[repr(transparent)]
88pub struct Frame<M: AnyFrameMeta + ?Sized> {
89 ptr: *const MetaSlot,
90 _marker: PhantomData<M>,
91}
92
93unsafe impl<M: AnyFrameMeta + ?Sized> Send for Frame<M> {}
94
95unsafe impl<M: AnyFrameMeta + ?Sized> Sync for Frame<M> {}
96
97impl<M: AnyFrameMeta + ?Sized> core::fmt::Debug for Frame<M> {
98 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
99 write!(f, "Frame({:#x})", self.paddr())
100 }
101}
102
103impl<M: AnyFrameMeta + ?Sized> PartialEq for Frame<M> {
104 fn eq(&self, other: &Self) -> bool {
105 self.paddr() == other.paddr()
106 }
107}
108impl<M: AnyFrameMeta + ?Sized> Eq for Frame<M> {}
109
110impl<M: AnyFrameMeta> Frame<M> {
111 /// Gets a [`Frame`] with a specific usage from a raw, unused page.
112 ///
113 /// The caller should provide the initial metadata of the page.
114 ///
115 /// If the provided frame is not truly unused at the moment, it will return
116 /// an error. If wanting to acquire a frame that is already in use, use
117 /// [`Frame::from_in_use`] instead.
118 pub fn from_unused(paddr: Paddr, metadata: M) -> Result<Self, GetFrameError> {
119 Ok(Self {
120 ptr: MetaSlot::get_from_unused(paddr, metadata, false)?,
121 _marker: PhantomData,
122 })
123 }
124
125 /// Gets the metadata of this page.
126 pub fn meta(&self) -> &M {
127 // SAFETY: The type is tracked by the type system.
128 unsafe { &*self.slot().as_meta_ptr::<M>() }
129 }
130}
131
132impl Frame<dyn AnyFrameMeta> {
133 /// Gets a dynamically typed [`Frame`] from a raw, in-use page.
134 ///
135 /// If the provided frame is not in use at the moment, it will return an error.
136 ///
137 /// The returned frame will have an extra reference count to the frame.
138 pub fn from_in_use(paddr: Paddr) -> Result<Self, GetFrameError> {
139 Ok(Self {
140 ptr: MetaSlot::get_from_in_use(paddr)?,
141 _marker: PhantomData,
142 })
143 }
144}
145
146impl<M: AnyFrameMeta + ?Sized> Frame<M> {
147 /// Gets the map level of this page.
148 ///
149 /// This is the level of the page table entry that maps the frame,
150 /// which determines the size of the frame.
151 ///
152 /// Currently, the level is always 1, which means the frame is a regular
153 /// page frame.
154 pub const fn map_level(&self) -> PagingLevel {
155 1
156 }
157
158 /// Gets the dynamically-typed metadata of this frame.
159 ///
160 /// If the type is known at compile time, use [`Frame::meta`] instead.
161 pub fn dyn_meta(&self) -> &dyn AnyFrameMeta {
162 // SAFETY: The metadata is initialized and valid.
163 unsafe { &*self.slot().dyn_meta_ptr() }
164 }
165
166 /// Gets the reference count of the frame.
167 ///
168 /// It returns the number of all references to the frame, including all the
169 /// existing frame handles ([`Frame`], [`Frame<dyn AnyFrameMeta>`]), and all
170 /// the mappings in the page table that points to the frame.
171 ///
172 /// # Safety
173 ///
174 /// The function is safe to call, but using it requires extra care. The
175 /// reference count can be changed by other threads at any time including
176 /// potentially between calling this method and acting on the result.
177 pub fn reference_count(&self) -> u64 {
178 let refcnt = self.slot().ref_count.load(Ordering::Relaxed);
179 debug_assert!(refcnt < meta::REF_COUNT_MAX);
180 refcnt
181 }
182
183 /// Borrows a reference from the given frame.
184 pub fn borrow(&self) -> FrameRef<'_, M> {
185 // SAFETY: Both the lifetime and the type matches `self`.
186 unsafe { FrameRef::borrow_paddr(self.paddr()) }
187 }
188
189 /// Forgets the handle to the frame.
190 ///
191 /// This will result in the frame being leaked without calling the custom dropper.
192 ///
193 /// A physical address to the frame is returned in case the frame needs to be
194 /// restored using [`Frame::from_raw`] later. This is useful when some architectural
195 /// data structures need to hold the frame handle such as the page table.
196 pub(in crate::mm) fn into_raw(self) -> Paddr {
197 let this = ManuallyDrop::new(self);
198 this.paddr()
199 }
200
201 /// Restores a forgotten [`Frame`] from a physical address.
202 ///
203 /// # Safety
204 ///
205 /// The caller should only restore a `Frame` that was previously forgotten using
206 /// [`Frame::into_raw`].
207 ///
208 /// And the restoring operation should only be done once for a forgotten
209 /// [`Frame`]. Otherwise double-free will happen.
210 ///
211 /// Also, the caller ensures that the usage of the frame is correct. There's
212 /// no checking of the usage in this function.
213 pub(crate) unsafe fn from_raw(paddr: Paddr) -> Self {
214 debug_assert!(paddr < max_paddr());
215
216 let vaddr = mapping::frame_to_meta::<PagingConsts>(paddr);
217 let ptr = vaddr as *const MetaSlot;
218
219 Self {
220 ptr,
221 _marker: PhantomData,
222 }
223 }
224
225 fn slot(&self) -> &MetaSlot {
226 // SAFETY: `ptr` points to a valid `MetaSlot` that will never be
227 // mutably borrowed, so taking an immutable reference to it is safe.
228 unsafe { &*self.ptr }
229 }
230}
231
232impl<M: AnyFrameMeta + ?Sized> HasPaddr for Frame<M> {
233 fn paddr(&self) -> Paddr {
234 self.slot().frame_paddr()
235 }
236}
237
238impl<M: AnyFrameMeta + ?Sized> HasSize for Frame<M> {
239 fn size(&self) -> usize {
240 PAGE_SIZE
241 }
242}
243
244impl<M: AnyFrameMeta + ?Sized> Clone for Frame<M> {
245 fn clone(&self) -> Self {
246 // SAFETY: We have already held a reference to the frame.
247 unsafe { self.slot().inc_ref_count() };
248
249 Self {
250 ptr: self.ptr,
251 _marker: PhantomData,
252 }
253 }
254}
255
256impl<M: AnyFrameMeta + ?Sized> Drop for Frame<M> {
257 fn drop(&mut self) {
258 let last_ref_cnt = self.slot().ref_count.fetch_sub(1, Ordering::Release);
259 debug_assert!(last_ref_cnt != 0 && last_ref_cnt != REF_COUNT_UNUSED);
260
261 if last_ref_cnt == 1 {
262 // A fence is needed here with the same reasons stated in the implementation of
263 // `Arc::drop`: <https://doc.rust-lang.org/std/sync/struct.Arc.html#method.drop>.
264 core::sync::atomic::fence(Ordering::Acquire);
265
266 // SAFETY: this is the last reference and is about to be dropped.
267 unsafe { self.slot().drop_last_in_place() };
268
269 allocator::get_global_frame_allocator().dealloc(self.paddr(), PAGE_SIZE);
270 }
271 }
272}
273
274impl<M: AnyFrameMeta> TryFrom<Frame<dyn AnyFrameMeta>> for Frame<M> {
275 type Error = Frame<dyn AnyFrameMeta>;
276
277 /// Tries converting a [`Frame<dyn AnyFrameMeta>`] into the statically-typed [`Frame`].
278 ///
279 /// If the usage of the frame is not the same as the expected usage, it will
280 /// return the dynamic frame itself as is.
281 fn try_from(dyn_frame: Frame<dyn AnyFrameMeta>) -> Result<Self, Self::Error> {
282 if (dyn_frame.dyn_meta() as &dyn core::any::Any).is::<M>() {
283 // SAFETY: The metadata is coerceable and the struct is transmutable.
284 Ok(unsafe { core::mem::transmute::<Frame<dyn AnyFrameMeta>, Frame<M>>(dyn_frame) })
285 } else {
286 Err(dyn_frame)
287 }
288 }
289}
290
291impl Frame<dyn AnyFrameMeta> {
292 /// Converts a [`Frame`] with a specific metadata type into a
293 /// [`Frame<dyn AnyFrameMeta>`].
294 ///
295 /// This exists because:
296 ///
297 /// ```ignore
298 /// impl<M: AnyFrameMeta + ?Sized> From<Frame<M>> for Frame<dyn AnyFrameMeta>
299 /// ```
300 ///
301 /// will conflict with `impl<T> core::convert::From<T> for T` in crate `core`.
302 pub fn from_unsized<M: AnyFrameMeta + ?Sized>(frame: Frame<M>) -> Frame<dyn AnyFrameMeta> {
303 // SAFETY: The metadata is coerceable and the struct is transmutable.
304 unsafe { core::mem::transmute(frame) }
305 }
306
307 /// Converts an RCU-dropped [`Frame`] with a specific metadata type into a
308 /// RCU-dropped [`Frame<dyn AnyFrameMeta>`].
309 ///
310 /// See also [`Frame::from_unsized`] for the reason of why not implementing
311 /// [`From`] directly.
312 pub fn rcu_from_unsized<M: AnyFrameMeta + ?Sized>(frame: RcuDrop<Frame<M>>) -> RcuDrop<Self> {
313 // SAFETY: The resulting frame will be dropped after the RCU grace period.
314 let (frame, panic_guard) = unsafe { RcuDrop::into_inner(frame) };
315 let dyn_frame = Self::from_unsized(frame);
316 panic_guard.forget();
317 RcuDrop::new(dyn_frame)
318 }
319}
320
321impl<M: AnyFrameMeta> From<Frame<M>> for Frame<dyn AnyFrameMeta> {
322 fn from(frame: Frame<M>) -> Self {
323 Self::from_unsized(frame)
324 }
325}
326
327impl<M: AnyUFrameMeta> From<Frame<M>> for UFrame {
328 fn from(frame: Frame<M>) -> Self {
329 // SAFETY: The metadata is coerceable and the struct is transmutable.
330 unsafe { core::mem::transmute(frame) }
331 }
332}
333
334impl From<UFrame> for Frame<dyn AnyFrameMeta> {
335 fn from(frame: UFrame) -> Self {
336 // SAFETY: The metadata is coerceable and the struct is transmutable.
337 unsafe { core::mem::transmute(frame) }
338 }
339}
340
341impl TryFrom<Frame<dyn AnyFrameMeta>> for UFrame {
342 type Error = Frame<dyn AnyFrameMeta>;
343
344 /// Tries converting a [`Frame<dyn AnyFrameMeta>`] into [`UFrame`].
345 ///
346 /// If the usage of the frame is not the same as the expected usage, it will
347 /// return the dynamic frame itself as is.
348 fn try_from(dyn_frame: Frame<dyn AnyFrameMeta>) -> Result<Self, Self::Error> {
349 if dyn_frame.dyn_meta().is_untyped() {
350 // SAFETY: The metadata is coerceable and the struct is transmutable.
351 Ok(unsafe { core::mem::transmute::<Frame<dyn AnyFrameMeta>, UFrame>(dyn_frame) })
352 } else {
353 Err(dyn_frame)
354 }
355 }
356}
357
358/// Increases the reference count of the frame by one.
359///
360/// # Safety
361///
362/// The caller should ensure the following conditions:
363/// 1. The physical address must represent a valid frame;
364/// 2. The caller must have already held a reference to the frame.
365pub(in crate::mm) unsafe fn inc_frame_ref_count(paddr: Paddr) {
366 debug_assert!(paddr.is_multiple_of(PAGE_SIZE));
367 debug_assert!(paddr < max_paddr());
368
369 let vaddr: Vaddr = mapping::frame_to_meta::<PagingConsts>(paddr);
370 // SAFETY: `vaddr` points to a valid `MetaSlot` that will never be mutably borrowed, so taking
371 // an immutable reference to it is always safe.
372 let slot = unsafe { &*(vaddr as *const MetaSlot) };
373
374 // SAFETY: We have already held a reference to the frame.
375 unsafe { slot.inc_ref_count() };
376}