ostd/mm/frame/allocator.rs
1// SPDX-License-Identifier: MPL-2.0
2//! The physical memory allocator.
3use vstd::prelude::*;
4use vstd_extra::{cast_ptr::Repr, ownership::Inv, prelude::*};
5
6use crate::specs::mm::frame::{meta_owners::MetaSlotStorage, meta_region_owners::MetaRegionOwners};
7
8use super::{Frame, meta::AnyFrameMeta, segment::Segment};
9use crate::{
10 boot::memory_region::MemoryRegionType,
11 error::Error,
12 // impl_frame_meta_for,
13 mm::{PAGE_SIZE, Paddr, paddr_to_vaddr},
14 // util::ops::range_difference,
15};
16use align_ext::AlignExt;
17use core::{alloc::Layout, ops::Range};
18
19verus! {
20
21/// Options for allocating physical memory frames.
22pub struct FrameAllocOptions {
23 zeroed: bool,
24}
25
26impl Default for FrameAllocOptions {
27 fn default() -> Self {
28 Self::new()
29 }
30}
31
32#[verus_verify]
33impl FrameAllocOptions {
34 /// Creates new options for allocating the specified number of frames.
35 pub fn new() -> Self {
36 Self { zeroed: true }
37 }
38
39 /// Sets whether the allocated frames should be initialized with zeros.
40 ///
41 /// If `zeroed` is `true`, the allocated frames are filled with zeros.
42 /// If not, the allocated frames will contain sensitive data and the caller
43 /// should clear them before sharing them with other components.
44 ///
45 /// By default, the frames are zero-initialized.
46 pub fn zeroed(&mut self, zeroed: bool) {
47 self.zeroed = zeroed
48 }
49
50 /* /// Allocates a single untyped frame without metadata.
51 pub fn alloc_frame(&self) -> Result<Frame<()>, Error> {
52 self.alloc_frame_with(())
53 }*/
54 /// Allocates a single frame with additional metadata.
55 ///
56 /// # Verified Properties
57 /// ## Preconditions
58 /// - The metadata region invariant holds.
59 /// ## Postconditions
60 /// - A successful allocation returns a valid frame and matching typed metadata permissions.
61 /// - Failure preserves the region.
62 #[verus_spec(res =>
63 with Tracked(regions): Tracked<&mut MetaRegionOwners>,
64 requires
65 old(regions).inv(),
66 ensures
67 final(regions).inv(),
68 res matches Ok(frame) ==> {
69 &&& frame.inv()
70 &&& frame.wf_with_region(*final(regions))
71 &&& super::meta::MetaSlot::get_from_unused_spec::<M>(
72 frame.start_paddr_spec(), metadata, false,
73 *old(regions), *final(regions),
74 vstd_extra::sum::Sum::Left(frame.frac_metadata_perm()),
75 )
76 },
77 res is Err ==> {
78 &&& *final(regions) == *old(regions)
79 }
80 )]
81 #[verifier::external_body]
82 pub fn alloc_frame_with<M: AnyFrameMeta + Repr<MetaSlotStorage>>(&self, metadata: M) -> Result<
83 Frame<M>,
84 Error,
85 > {
86 unimplemented!()/*
87 let single_layout = Layout::from_size_align(PAGE_SIZE, PAGE_SIZE).unwrap();
88 let frame = get_global_frame_allocator()
89 .alloc(single_layout)
90 .map(|paddr| Frame::from_unused(paddr, metadata).unwrap())
91 .ok_or(Error::NoMemory)?;
92
93 if self.zeroed {
94 let addr = paddr_to_vaddr(frame.start_paddr()) as *mut u8;
95 // SAFETY: The newly allocated frame is guaranteed to be valid.
96 unsafe { core::ptr::write_bytes(addr, 0, PAGE_SIZE) }
97 }
98
99 Ok(frame)
100 */
101
102 }/*
103 /// Allocates a contiguous range of untyped frames without metadata.
104 pub fn alloc_segment(&self, nframes: usize) -> Result<Segment<()>> {
105 self.alloc_segment_with(nframes, |_| ())
106 }*/
107 /*
108 /// Allocates a contiguous range of frames with additional metadata.
109 ///
110 /// The returned [`Segment`] contains at least one frame. The method returns
111 /// an error if the number of frames is zero.
112 pub fn alloc_segment_with<M: AnyFrameMeta, F>(
113 &self,
114 nframes: usize,
115 metadata_fn: F,
116 ) -> Result<Segment<M>>
117 where
118 F: FnMut(Paddr) -> M,
119 {
120 if nframes == 0 {
121 return Err(Error::InvalidArgs);
122 }
123 let layout = Layout::from_size_align(nframes * PAGE_SIZE, PAGE_SIZE).unwrap();
124 let segment = get_global_frame_allocator()
125 .alloc(layout)
126 .map(|start| {
127 Segment::from_unused(start..start + nframes * PAGE_SIZE, metadata_fn).unwrap()
128 })
129 .ok_or(Error::NoMemory)?;
130
131 if self.zeroed {
132 let addr = paddr_to_vaddr(segment.start_paddr()) as *mut u8;
133 // SAFETY: The newly allocated segment is guaranteed to be valid.
134 unsafe { core::ptr::write_bytes(addr, 0, nframes * PAGE_SIZE) }
135 }
136
137 Ok(segment)
138 }*/
139
140}
141
142} // verus!
143/*
144#[cfg(ktest)]
145#[ktest]
146fn test_alloc_dealloc() {
147 // Here we allocate and deallocate frames in random orders to test the allocator.
148 // We expect the test to fail if the underlying implementation panics.
149 let single_options = FrameAllocOptions::new();
150 let mut contiguous_options = FrameAllocOptions::new();
151 contiguous_options.zeroed(false);
152 let mut remember_vec = Vec::new();
153 for _ in 0..10 {
154 for i in 0..10 {
155 let single_frame = single_options.alloc_frame().unwrap();
156 if i % 3 == 0 {
157 remember_vec.push(single_frame);
158 }
159 }
160 let contiguous_segment = contiguous_options.alloc_segment(10).unwrap();
161 drop(contiguous_segment);
162 remember_vec.pop();
163 }
164}
165
166/// The trait for the global frame allocator.
167///
168/// OSTD allows a customized frame allocator by the [`global_frame_allocator`]
169/// attribute, which marks a static variable of this type.
170///
171/// The API mimics the standard Rust allocator API ([`GlobalAlloc`] and
172/// [`global_allocator`]). However, this trait is much safer. Double free
173/// or freeing in-use memory through this trait only messes up the allocator's
174/// state rather than causing undefined behavior.
175///
176/// Whenever OSTD or other modules need to allocate or deallocate frames via
177/// [`FrameAllocOptions`], they are forwarded to the global frame allocator.
178/// It is not encouraged to call the global allocator directly.
179///
180/// [`global_frame_allocator`]: crate::global_frame_allocator
181/// [`GlobalAlloc`]: core::alloc::GlobalAlloc
182pub trait GlobalFrameAllocator: Sync {
183 /// Allocates a contiguous range of frames.
184 ///
185 /// The caller guarantees that `layout.size()` is aligned to [`PAGE_SIZE`].
186 ///
187 /// When any of the allocated memory is not in use, OSTD returns them by
188 /// calling [`GlobalFrameAllocator::dealloc`]. If multiple frames are
189 /// allocated, they may be returned in any order with any number of calls.
190 fn alloc(&self, layout: Layout) -> Option<Paddr>;
191
192 /// Deallocates a contiguous range of frames.
193 ///
194 /// The caller guarantees that `addr` and `size` are both aligned to
195 /// [`PAGE_SIZE`]. The deallocated memory should always be allocated by
196 /// [`GlobalFrameAllocator::alloc`]. However, if
197 /// [`GlobalFrameAllocator::alloc`] returns multiple frames, it is possible
198 /// that some of them are deallocated before others. The deallocated memory
199 /// must never overlap with any memory that is already deallocated or
200 /// added, without being allocated in between.
201 ///
202 /// The deallocated memory can be uninitialized.
203 fn dealloc(&self, addr: Paddr, size: usize);
204
205 /// Adds a contiguous range of frames to the allocator.
206 ///
207 /// The memory being added must never overlap with any memory that was
208 /// added before.
209 ///
210 /// The added memory can be uninitialized.
211 fn add_free_memory(&self, addr: Paddr, size: usize);
212}
213
214extern "Rust" {
215 /// The global frame allocator's reference exported by
216 /// [`crate::global_frame_allocator`].
217 static __GLOBAL_FRAME_ALLOCATOR_REF: &'static dyn GlobalFrameAllocator;
218}
219
220pub(super) fn get_global_frame_allocator() -> &'static dyn GlobalFrameAllocator {
221 // SAFETY: The global frame allocator is set up correctly with the
222 // `global_frame_allocator` attribute. If they use safe code only, the
223 // up-call is safe.
224 unsafe { __GLOBAL_FRAME_ALLOCATOR_REF }
225}
226
227/// Initializes the global frame allocator.
228///
229/// It just does adds the frames to the global frame allocator. Calling it
230/// multiple times would be not safe.
231///
232/// # Safety
233///
234/// This function should be called only once.
235pub(crate) unsafe fn init() {
236 let regions = &crate::boot::EARLY_INFO.get().unwrap().memory_regions;
237
238 // Retire the early allocator.
239 let early_allocator = EARLY_ALLOCATOR.lock().take().unwrap();
240 let (range_1, range_2) = early_allocator.allocated_regions();
241
242 for region in regions.iter() {
243 if region.typ() == MemoryRegionType::Usable {
244 debug_assert!(region.base() % PAGE_SIZE == 0);
245 debug_assert!(region.len() % PAGE_SIZE == 0);
246
247 // Add global free pages to the frame allocator.
248 // Truncate the early allocated frames if there is an overlap.
249 for r1 in range_difference(&(region.base()..region.end()), &range_1) {
250 for r2 in range_difference(&r1, &range_2) {
251 log::info!("Adding free frames to the allocator: {:x?}", r2);
252 get_global_frame_allocator().add_free_memory(r2.start, r2.len());
253 }
254 }
255 }
256 }
257}
258
259/// An allocator in the early boot phase when frame metadata is not available.
260pub(super) struct EarlyFrameAllocator {
261 // We need to allocate from under 4G first since the linear mapping for
262 // the higher region is not constructed yet.
263 under_4g_range: Range<Paddr>,
264 under_4g_end: Paddr,
265
266 // And also sometimes 4G is not enough for early phase. This, if not `0..0`,
267 // is the largest region above 4G.
268 max_range: Range<Paddr>,
269 max_end: Paddr,
270}
271
272/// The global frame allocator in the early boot phase.
273///
274/// It is used to allocate frames before the frame metadata is initialized.
275/// The allocated frames are not tracked by the frame metadata. After the
276/// metadata is initialized with [`super::meta::init`], the frames are tracked
277/// with metadata and the early allocator is no longer used.
278///
279/// This is protected by the [`spin::Mutex`] rather than [`crate::sync::SpinLock`]
280/// since the latter uses CPU-local storage, which isn't available in the early
281/// boot phase. So we must make sure that no interrupts are enabled when using
282/// this allocator.
283pub(super) static EARLY_ALLOCATOR: spin::Mutex<Option<EarlyFrameAllocator>> =
284 spin::Mutex::new(None);
285
286impl EarlyFrameAllocator {
287 /// Creates a new early frame allocator.
288 ///
289 /// It uses at most 2 regions, the first is the maximum usable region below
290 /// 4 GiB. The other is the maximum usable region above 4 GiB and is only
291 /// usable when linear mapping is constructed.
292 pub fn new() -> Self {
293 let regions = &crate::boot::EARLY_INFO.get().unwrap().memory_regions;
294
295 let mut under_4g_range = 0..0;
296 let mut max_range = 0..0;
297 for region in regions.iter() {
298 if region.typ() != MemoryRegionType::Usable {
299 continue;
300 }
301 const PADDR4G: Paddr = 0x1_0000_0000;
302 if region.base() < PADDR4G {
303 let range = region.base()..region.end().min(PADDR4G);
304 if range.len() > under_4g_range.len() {
305 under_4g_range = range;
306 }
307 }
308 if region.end() >= PADDR4G {
309 let range = region.base().max(PADDR4G)..region.end();
310 if range.len() > max_range.len() {
311 max_range = range;
312 }
313 }
314 }
315
316 log::debug!(
317 "Early frame allocator (below 4G) at: {:#x?}",
318 under_4g_range
319 );
320 if !max_range.is_empty() {
321 log::debug!("Early frame allocator (above 4G) at: {:#x?}", max_range);
322 }
323
324 Self {
325 under_4g_range: under_4g_range.clone(),
326 under_4g_end: under_4g_range.start,
327 max_range: max_range.clone(),
328 max_end: max_range.start,
329 }
330 }
331
332 /// Allocates a contiguous range of frames.
333 pub fn alloc(&mut self, layout: Layout) -> Option<Paddr> {
334 let size = layout.size().align_up(PAGE_SIZE);
335 let align = layout.align().max(PAGE_SIZE);
336
337 for (tail, end) in [
338 (&mut self.under_4g_end, self.under_4g_range.end),
339 (&mut self.max_end, self.max_range.end),
340 ] {
341 let allocated = tail.align_up(align);
342 if let Some(allocated_end) = allocated.checked_add(size)
343 && allocated_end <= end
344 {
345 *tail = allocated_end;
346 return Some(allocated);
347 }
348 }
349
350 None
351 }
352
353 pub(super) fn allocated_regions(&self) -> (Range<Paddr>, Range<Paddr>) {
354 (
355 self.under_4g_range.start..self.under_4g_end,
356 self.max_range.start..self.max_end,
357 )
358 }
359}
360
361/// Metadata for frames allocated in the early boot phase.
362///
363/// Frames allocated with [`early_alloc`] are not immediately tracked with
364/// frame metadata. But [`super::meta::init`] will track them later.
365#[derive(Debug)]
366pub(crate) struct EarlyAllocatedFrameMeta;
367
368impl_frame_meta_for!(EarlyAllocatedFrameMeta);
369
370/// Allocates a contiguous range of frames in the early boot phase.
371///
372/// The early allocated frames will not be reclaimable, until the metadata is
373/// initialized by [`super::meta::init`]. Then we can use [`Frame::from_raw`]
374/// to free the frames.
375///
376/// # Panics
377///
378/// This function panics if:
379/// - it is called before [`init_early_allocator`],
380/// - or if is called after [`init`].
381pub(crate) fn early_alloc(layout: Layout) -> Option<Paddr> {
382 let mut early_allocator = EARLY_ALLOCATOR.lock();
383 early_allocator.as_mut().unwrap().alloc(layout)
384}
385
386/// Initializes the early frame allocator.
387///
388/// [`early_alloc`] should be used after this initialization. After [`init`], the
389/// early allocator.
390///
391/// # Safety
392///
393/// This function should be called only once after the memory regions are ready.
394pub(crate) unsafe fn init_early_allocator() {
395 let mut early_allocator = EARLY_ALLOCATOR.lock();
396 *early_allocator = Some(EarlyFrameAllocator::new());
397}
398*/