ostd/mm/frame/meta.rs
1// SPDX-License-Identifier: MPL-2.0
2
3//! Metadata management of frames.
4//!
5//! You can picture a globally shared, static, gigantic array of metadata
6//! initialized for each frame.
7//! Each entry in this array holds the metadata for a single frame.
8//! There would be a dedicated small
9//! "heap" space in each slot for dynamic metadata. You can store anything as
10//! the metadata of a frame as long as it's [`Sync`].
11//!
12//! # Implementation
13//!
14//! The slots are placed in the metadata pages mapped to a certain virtual
15//! address in the kernel space. So finding the metadata of a frame often
16//! comes with no costs since the translation is a simple arithmetic operation.
17
18pub(crate) mod mapping {
19 //! The metadata of each physical page is linear mapped to fixed virtual addresses
20 //! in [`FRAME_METADATA_RANGE`].
21
22 use super::MetaSlot;
23 use crate::mm::{PAGE_SIZE, Paddr, PagingConstsTrait, Vaddr, kspace::FRAME_METADATA_RANGE};
24
25 /// Converts a physical address of a base frame to the virtual address of the metadata slot.
26 pub(crate) const fn frame_to_meta<C: PagingConstsTrait>(paddr: Paddr) -> Vaddr {
27 let base = FRAME_METADATA_RANGE.start;
28 let offset = paddr / PAGE_SIZE;
29 base + offset * size_of::<MetaSlot>()
30 }
31
32 /// Converts a virtual address of the metadata slot to the physical address of the frame.
33 pub(crate) const fn meta_to_frame<C: PagingConstsTrait>(vaddr: Vaddr) -> Paddr {
34 let base = FRAME_METADATA_RANGE.start;
35 let offset = (vaddr - base) / size_of::<MetaSlot>();
36 offset * PAGE_SIZE
37 }
38}
39
40use core::{
41 alloc::Layout,
42 any::Any,
43 cell::UnsafeCell,
44 fmt::Debug,
45 mem::{ManuallyDrop, MaybeUninit},
46 ops::Range,
47 sync::atomic::{AtomicU64, Ordering},
48};
49
50use align_ext::AlignExt;
51
52use crate::{
53 arch::mm::PagingConsts,
54 boot::memory_region::{MemoryRegion, MemoryRegionType},
55 const_assert, info,
56 mm::{
57 CachePolicy, Infallible, PAGE_SIZE, Paddr, PageFlags, PageProperty, PrivilegedPageFlags,
58 Segment, Vaddr, VmReader,
59 frame::allocator::{self, EarlyAllocatedFrameMeta},
60 paddr_to_vaddr, page_size,
61 page_table::boot_pt,
62 },
63 panic::abort,
64 util::ops::range_difference,
65};
66
67/// The maximum number of bytes of the metadata of a frame.
68pub const FRAME_METADATA_MAX_SIZE: usize = META_SLOT_SIZE
69 - size_of::<AtomicU64>()
70 - size_of::<FrameMetaVtablePtr>()
71 - size_of::<AtomicU64>();
72/// The maximum alignment in bytes of the metadata of a frame.
73pub const FRAME_METADATA_MAX_ALIGN: usize = META_SLOT_SIZE;
74
75const META_SLOT_SIZE: usize = 64;
76
77#[repr(C)]
78pub(in crate::mm) struct MetaSlot {
79 /// The metadata of a frame.
80 ///
81 /// It is placed at the beginning of a slot because:
82 /// - the implementation can simply cast a `*const MetaSlot`
83 /// to a `*const AnyFrameMeta` for manipulation;
84 /// - if the metadata need special alignment, we can provide
85 /// at most [`FRAME_METADATA_MAX_ALIGN`] bytes of alignment;
86 /// - the subsequent fields can utilize the padding of the
87 /// reference count to save space.
88 ///
89 /// Don't interpret this field as an array of bytes. It is a
90 /// placeholder for the metadata of a frame.
91 storage: UnsafeCell<[u8; FRAME_METADATA_MAX_SIZE]>,
92 /// The reference count of the page.
93 ///
94 /// Specifically, the reference count has the following meaning:
95 /// - `REF_COUNT_UNUSED`: The page is not in use.
96 /// - `REF_COUNT_UNIQUE`: The page is owned by a [`UniqueFrame`].
97 /// - `0`: The page is being constructed ([`Frame::from_unused`])
98 /// or destructured ([`drop_last_in_place`]).
99 /// - `1..REF_COUNT_MAX`: The page is in use.
100 /// - `REF_COUNT_MAX..REF_COUNT_UNIQUE`: Illegal values to
101 /// prevent the reference count from overflowing. Otherwise,
102 /// overflowing the reference count will cause soundness issue.
103 ///
104 /// [`Frame::from_unused`]: super::Frame::from_unused
105 /// [`UniqueFrame`]: super::unique::UniqueFrame
106 /// [`drop_last_in_place`]: Self::drop_last_in_place
107 //
108 // Other than this field the fields should be `MaybeUninit`.
109 // See initialization in `alloc_meta_frames`.
110 pub(super) ref_count: AtomicU64,
111 /// The virtual table that indicates the type of the metadata.
112 pub(super) vtable_ptr: UnsafeCell<MaybeUninit<FrameMetaVtablePtr>>,
113 /// This is only accessed by [`crate::mm::frame::linked_list`].
114 /// It stores 0 if the frame is not in any list, otherwise it stores the
115 /// ID of the list.
116 ///
117 /// It is ugly but allows us to tell if a frame is in a specific list by
118 /// one relaxed read. Otherwise, if we store it conditionally in `storage`
119 /// we would have to ensure that the type is correct before the read, which
120 /// costs a synchronization.
121 pub(super) in_list: AtomicU64,
122}
123
124pub(super) const REF_COUNT_UNUSED: u64 = u64::MAX;
125pub(super) const REF_COUNT_UNIQUE: u64 = u64::MAX - 1;
126pub(super) const REF_COUNT_MAX: u64 = i64::MAX as u64;
127
128type FrameMetaVtablePtr = core::ptr::DynMetadata<dyn AnyFrameMeta>;
129
130const_assert!(PAGE_SIZE.is_multiple_of(META_SLOT_SIZE));
131const_assert!(size_of::<MetaSlot>() == META_SLOT_SIZE);
132
133/// All frame metadata types must implement this trait.
134///
135/// If a frame type needs specific drop behavior, it should specify
136/// when implementing this trait. When we drop the last handle to
137/// this frame, the `on_drop` method will be called. The `on_drop`
138/// method is called with the physical address of the frame.
139///
140/// The implemented structure should have a size less than or equal to
141/// [`FRAME_METADATA_MAX_SIZE`] and an alignment less than or equal to
142/// [`FRAME_METADATA_MAX_ALIGN`]. Otherwise, the metadata type cannot
143/// be used because storing it will fail compile-time assertions.
144///
145/// # Safety
146///
147/// If `on_drop` reads the page using the provided `VmReader`, the
148/// implementer must ensure that the frame is safe to read.
149pub unsafe trait AnyFrameMeta: Any + Send + Sync {
150 /// Called when the last handle to the frame is dropped.
151 fn on_drop(&mut self, _reader: &mut VmReader<Infallible>) {}
152
153 /// Whether the metadata's associated frame is untyped.
154 ///
155 /// If a type implements [`AnyUFrameMeta`], this should be `true`.
156 /// Otherwise, it should be `false`.
157 ///
158 /// [`AnyUFrameMeta`]: super::untyped::AnyUFrameMeta
159 fn is_untyped(&self) -> bool {
160 false
161 }
162}
163
164/// Checks that a frame metadata type has valid size and alignment.
165#[macro_export]
166macro_rules! check_frame_meta_layout {
167 ($t:ty) => {
168 $crate::const_assert!(size_of::<$t>() <= $crate::mm::frame::meta::FRAME_METADATA_MAX_SIZE);
169 $crate::const_assert!(
170 $crate::mm::frame::meta::FRAME_METADATA_MAX_ALIGN % align_of::<$t>() == 0
171 );
172 };
173}
174
175/// Makes a structure usable as a frame metadata.
176#[macro_export]
177macro_rules! impl_frame_meta_for {
178 // Implement without specifying the drop behavior.
179 ($t:ty) => {
180 // SAFETY: `on_drop` won't read the page.
181 unsafe impl $crate::mm::frame::meta::AnyFrameMeta for $t {}
182
183 $crate::check_frame_meta_layout!($t);
184 };
185}
186
187pub use impl_frame_meta_for;
188
189/// The error type for getting the frame from a physical address.
190#[derive(Debug)]
191pub enum GetFrameError {
192 /// The frame is in use.
193 InUse,
194 /// The frame is not in use.
195 Unused,
196 /// The frame is being initialized or destructed.
197 Busy,
198 /// The frame is private to an owner of [`UniqueFrame`].
199 ///
200 /// [`UniqueFrame`]: super::unique::UniqueFrame
201 Unique,
202 /// The provided physical address is out of bound.
203 OutOfBound,
204 /// The provided physical address is not aligned.
205 NotAligned,
206}
207
208/// Gets the reference to a metadata slot.
209pub(super) fn get_slot(paddr: Paddr) -> Result<&'static MetaSlot, GetFrameError> {
210 if !paddr.is_multiple_of(PAGE_SIZE) {
211 return Err(GetFrameError::NotAligned);
212 }
213 if paddr < super::min_paddr() || paddr >= super::max_paddr() {
214 return Err(GetFrameError::OutOfBound);
215 }
216
217 let vaddr = mapping::frame_to_meta::<PagingConsts>(paddr);
218 let ptr = vaddr as *mut MetaSlot;
219
220 // SAFETY: `ptr` points to a valid `MetaSlot` that will never be
221 // mutably borrowed, so taking an immutable reference to it is safe.
222 Ok(unsafe { &*ptr })
223}
224
225impl MetaSlot {
226 /// Initializes the metadata slot of a frame assuming it is unused.
227 ///
228 /// If successful, the function returns a pointer to the metadata slot.
229 /// And the slot is initialized with the given metadata.
230 ///
231 /// The resulting reference count held by the returned pointer is
232 /// [`REF_COUNT_UNIQUE`] if `as_unique_ptr` is `true`, otherwise `1`.
233 pub(super) fn get_from_unused<M: AnyFrameMeta>(
234 paddr: Paddr,
235 metadata: M,
236 as_unique_ptr: bool,
237 ) -> Result<*const Self, GetFrameError> {
238 let slot = get_slot(paddr)?;
239
240 // `Acquire` pairs with the `Release` in `drop_last_in_place` and ensures the metadata
241 // initialization won't be reordered before this memory compare-and-exchange.
242 slot.ref_count
243 .compare_exchange(REF_COUNT_UNUSED, 0, Ordering::Acquire, Ordering::Relaxed)
244 .map_err(|val| match val {
245 REF_COUNT_UNIQUE => GetFrameError::Unique,
246 0 => GetFrameError::Busy,
247 _ => GetFrameError::InUse,
248 })?;
249
250 // SAFETY: The slot now has a reference count of `0`, other threads will
251 // not access the metadata slot so it is safe to have a mutable reference.
252 unsafe { slot.write_meta(metadata) };
253
254 if as_unique_ptr {
255 // No one can create a `Frame` instance directly from the page
256 // address, so `Relaxed` is fine here.
257 slot.ref_count.store(REF_COUNT_UNIQUE, Ordering::Relaxed);
258 } else {
259 // `Release` is used to ensure that the metadata initialization
260 // won't be reordered after this memory store.
261 slot.ref_count.store(1, Ordering::Release);
262 }
263
264 Ok(slot as *const MetaSlot)
265 }
266
267 /// Gets another owning pointer to the metadata slot from the given page.
268 pub(super) fn get_from_in_use(paddr: Paddr) -> Result<*const Self, GetFrameError> {
269 let slot = get_slot(paddr)?;
270
271 // Try to increase the reference count for an in-use frame. Otherwise fail.
272 loop {
273 match slot.ref_count.load(Ordering::Relaxed) {
274 REF_COUNT_UNUSED => return Err(GetFrameError::Unused),
275 REF_COUNT_UNIQUE => return Err(GetFrameError::Unique),
276 0 => return Err(GetFrameError::Busy),
277 last_ref_cnt => {
278 if last_ref_cnt >= REF_COUNT_MAX {
279 // See `Self::inc_ref_count` for the explanation.
280 abort();
281 }
282 // Using `Acquire` here to pair with `get_from_unused` or
283 // `<Frame<M> as From<UniqueFrame<M>>>::from` (who must be
284 // performed after writing the metadata).
285 //
286 // It ensures that the written metadata will be visible to us.
287 if slot
288 .ref_count
289 .compare_exchange_weak(
290 last_ref_cnt,
291 last_ref_cnt + 1,
292 Ordering::Acquire,
293 Ordering::Relaxed,
294 )
295 .is_ok()
296 {
297 return Ok(slot as *const MetaSlot);
298 }
299 }
300 }
301 core::hint::spin_loop();
302 }
303 }
304
305 /// Increases the frame reference count by one.
306 ///
307 /// # Safety
308 ///
309 /// The caller must have already held a reference to the frame.
310 pub(super) unsafe fn inc_ref_count(&self) {
311 let last_ref_cnt = self.ref_count.fetch_add(1, Ordering::Relaxed);
312 debug_assert!(last_ref_cnt != 0 && last_ref_cnt != REF_COUNT_UNUSED);
313
314 if last_ref_cnt >= REF_COUNT_MAX {
315 // This follows the same principle as the `Arc::clone` implementation to prevent the
316 // reference count from overflowing. See also
317 // <https://doc.rust-lang.org/std/sync/struct.Arc.html#method.clone>.
318 abort();
319 }
320 }
321
322 /// Gets the corresponding frame's physical address.
323 pub(super) fn frame_paddr(&self) -> Paddr {
324 mapping::meta_to_frame::<PagingConsts>(self as *const MetaSlot as Vaddr)
325 }
326
327 /// Gets a dynamically typed pointer to the stored metadata.
328 ///
329 /// # Safety
330 ///
331 /// The caller should ensure that:
332 /// - the stored metadata is initialized (by [`Self::write_meta`]) and valid.
333 ///
334 /// The returned pointer should not be dereferenced as mutable unless having
335 /// exclusive access to the metadata slot.
336 pub(super) unsafe fn dyn_meta_ptr(&self) -> *mut dyn AnyFrameMeta {
337 // SAFETY: The page metadata is valid to be borrowed immutably, since
338 // it will never be borrowed mutably after initialization.
339 let vtable_ptr = unsafe { *self.vtable_ptr.get() };
340
341 // SAFETY: The page metadata is initialized and valid.
342 let vtable_ptr = *unsafe { vtable_ptr.assume_init_ref() };
343
344 let meta_ptr: *mut dyn AnyFrameMeta =
345 core::ptr::from_raw_parts_mut(self as *const MetaSlot as *mut MetaSlot, vtable_ptr);
346
347 meta_ptr
348 }
349
350 /// Gets the stored metadata as type `M`.
351 ///
352 /// Calling the method should be safe, but using the returned pointer would
353 /// be unsafe. Specifically, the derefernecer should ensure that:
354 /// - the stored metadata is initialized (by [`Self::write_meta`]) and
355 /// valid;
356 /// - the initialized metadata is of type `M`;
357 /// - the returned pointer should not be dereferenced as mutable unless
358 /// having exclusive access to the metadata slot.
359 pub(super) fn as_meta_ptr<M: AnyFrameMeta>(&self) -> *mut M {
360 self.storage.get() as *mut M
361 }
362
363 /// Writes the metadata to the slot without reading or dropping the previous value.
364 ///
365 /// # Safety
366 ///
367 /// The caller should have exclusive access to the metadata slot's fields.
368 pub(super) unsafe fn write_meta<M: AnyFrameMeta>(&self, metadata: M) {
369 const { assert!(size_of::<M>() <= FRAME_METADATA_MAX_SIZE) };
370 const { assert!(align_of::<M>() <= FRAME_METADATA_MAX_ALIGN) };
371
372 // SAFETY: Caller ensures that the access to the fields are exclusive.
373 let vtable_ptr = unsafe { &mut *self.vtable_ptr.get() };
374 vtable_ptr.write(core::ptr::metadata(&metadata as &dyn AnyFrameMeta));
375
376 let ptr = self.storage.get();
377 // SAFETY:
378 // 1. `ptr` points to the metadata storage.
379 // 2. The size and the alignment of the metadata storage is large enough to hold `M`
380 // (guaranteed by the const assertions above).
381 // 3. We have exclusive access to the metadata storage (guaranteed by the caller).
382 unsafe { ptr.cast::<M>().write(metadata) };
383 }
384
385 /// Drops the metadata and deallocates the frame.
386 ///
387 /// # Safety
388 ///
389 /// The caller should ensure that:
390 /// - the reference count is `0` (so we are the sole owner of the frame);
391 /// - the metadata is initialized;
392 pub(super) unsafe fn drop_last_in_place(&self) {
393 // This should be guaranteed as a safety requirement.
394 debug_assert_eq!(self.ref_count.load(Ordering::Relaxed), 0);
395
396 // SAFETY: The caller ensures safety.
397 unsafe { self.drop_meta_in_place() };
398
399 // `Release` pairs with the `Acquire` in `Frame::from_unused` and ensures
400 // `drop_meta_in_place` won't be reordered after this memory store.
401 self.ref_count.store(REF_COUNT_UNUSED, Ordering::Release);
402 }
403
404 /// Drops the metadata of a slot in place.
405 ///
406 /// After this operation, the metadata becomes uninitialized. Any access to the
407 /// metadata is undefined behavior unless it is re-initialized by [`Self::write_meta`].
408 ///
409 /// # Safety
410 ///
411 /// The caller should ensure that:
412 /// - the reference count is `0` or [`REF_COUNT_UNIQUE`] (so we are the sole owner of the frame);
413 /// - the metadata is initialized;
414 pub(super) unsafe fn drop_meta_in_place(&self) {
415 let paddr = self.frame_paddr();
416
417 // SAFETY: We have exclusive access to the frame metadata.
418 let vtable_ptr = unsafe { &mut *self.vtable_ptr.get() };
419 // SAFETY: The frame metadata is initialized and valid.
420 let vtable_ptr = unsafe { vtable_ptr.assume_init_read() };
421
422 let meta_ptr: *mut dyn AnyFrameMeta =
423 core::ptr::from_raw_parts_mut(self.storage.get(), vtable_ptr);
424
425 // SAFETY: The implementer of the frame metadata decides that if the frame
426 // is safe to be read or not.
427 let mut reader =
428 unsafe { VmReader::from_kernel_space(paddr_to_vaddr(paddr) as *const u8, PAGE_SIZE) };
429
430 // SAFETY: `ptr` points to the metadata storage which is valid to be mutably borrowed under
431 // `vtable_ptr` because the metadata is valid, the vtable is correct, and we have the exclusive
432 // access to the frame metadata.
433 unsafe {
434 // Invoke the custom `on_drop` handler.
435 (*meta_ptr).on_drop(&mut reader);
436 // Drop the frame metadata.
437 core::ptr::drop_in_place(meta_ptr);
438 }
439 }
440}
441
442/// The metadata of frames that holds metadata of frames.
443#[derive(Debug, Default)]
444pub struct MetaPageMeta {}
445
446impl_frame_meta_for!(MetaPageMeta);
447
448/// Initializes the metadata of all physical frames.
449///
450/// The function returns a list of `Frame`s containing the metadata.
451///
452/// # Safety
453///
454/// This function should be called only once and only on the BSP,
455/// before any APs are started.
456pub(crate) unsafe fn init() -> Segment<MetaPageMeta> {
457 let paddr_range = {
458 let regions = &crate::boot::EARLY_INFO.get().unwrap().memory_regions;
459 tracked_paddr_range(regions)
460 };
461 let min_paddr = paddr_range.start;
462 let max_paddr = paddr_range.end;
463
464 info!(
465 "Initializing frame metadata for physical memory {:x?}",
466 paddr_range
467 );
468
469 // In RISC-V and AArch64, the boot page table has mapped the 512GB memory,
470 // so we don't need to add temporary linear mapping.
471 // In LoongArch, the DWM0 has mapped the whole memory,
472 // so we don't need to add temporary linear mapping.
473 #[cfg(target_arch = "x86_64")]
474 add_temp_linear_mapping(max_paddr);
475
476 let tot_nr_frames = paddr_range.len() / page_size::<PagingConsts>(1);
477 let (nr_meta_pages, meta_pages) = alloc_meta_frames(tot_nr_frames);
478
479 // Map the metadata frames.
480 boot_pt::with_borrow(|boot_pt| {
481 for i in 0..nr_meta_pages {
482 let frame_paddr = meta_pages + i * PAGE_SIZE;
483 let vaddr = mapping::frame_to_meta::<PagingConsts>(min_paddr) + i * PAGE_SIZE;
484 let prop = PageProperty {
485 flags: PageFlags::RW,
486 cache: CachePolicy::Writeback,
487 priv_flags: PrivilegedPageFlags::GLOBAL,
488 };
489 // SAFETY: we are doing the metadata mappings for the kernel.
490 unsafe { boot_pt.map_base_page(vaddr, frame_paddr, prop) };
491 }
492 })
493 .unwrap();
494
495 // Now the metadata frames are mapped, we can initialize the metadata.
496 super::MIN_PADDR.store(min_paddr, Ordering::Relaxed);
497 super::MAX_PADDR.store(max_paddr, Ordering::Relaxed);
498
499 let meta_page_range = meta_pages..meta_pages + nr_meta_pages * PAGE_SIZE;
500
501 let (range_1, range_2) = allocator::EARLY_ALLOCATOR
502 .lock()
503 .as_ref()
504 .unwrap()
505 .allocated_regions();
506 for r in range_difference(&range_1, &meta_page_range) {
507 let early_seg = Segment::from_unused(r, |_| EarlyAllocatedFrameMeta).unwrap();
508 let _ = ManuallyDrop::new(early_seg);
509 }
510 for r in range_difference(&range_2, &meta_page_range) {
511 let early_seg = Segment::from_unused(r, |_| EarlyAllocatedFrameMeta).unwrap();
512 let _ = ManuallyDrop::new(early_seg);
513 }
514
515 mark_unusable_ranges();
516
517 Segment::from_unused(meta_page_range, |_| MetaPageMeta {}).unwrap()
518}
519
520/// Returns whether the global frame allocator is initialized.
521pub(in crate::mm) fn is_initialized() -> bool {
522 // `init` sets it with relaxed ordering somewhere in the middle. But due
523 // to the safety requirement of the `init` function, we can assume that
524 // there is no race conditions.
525 super::MAX_PADDR.load(Ordering::Relaxed) != 0
526}
527
528fn tracked_paddr_range(regions: &[MemoryRegion]) -> Range<Paddr> {
529 let physical_regions = regions.iter().filter(|region| region.typ().is_physical());
530 let min_paddr = physical_regions
531 .clone()
532 .map(|region| region.base())
533 .min()
534 .unwrap();
535 let max_paddr = physical_regions.map(|region| region.end()).max().unwrap();
536
537 // This ensures that the first metadata slot starts at a page boundary.
538 const META_PAGE_COVERAGE: usize = PAGE_SIZE * (PAGE_SIZE / META_SLOT_SIZE);
539 min_paddr.align_down(META_PAGE_COVERAGE)..max_paddr
540}
541
542fn alloc_meta_frames(tot_nr_frames: usize) -> (usize, Paddr) {
543 let nr_meta_pages = tot_nr_frames
544 .checked_mul(size_of::<MetaSlot>())
545 .unwrap()
546 .div_ceil(PAGE_SIZE);
547 let paddr = allocator::early_alloc(
548 Layout::from_size_align(nr_meta_pages * PAGE_SIZE, PAGE_SIZE).unwrap(),
549 )
550 .unwrap();
551
552 let slots = paddr_to_vaddr(paddr) as *mut MetaSlot;
553
554 // Initialize the metadata slots.
555 for i in 0..tot_nr_frames {
556 // SAFETY: The memory is successfully allocated with `tot_nr_frames`
557 // slots so the index must be within the range.
558 let slot = unsafe { slots.add(i) };
559 // SAFETY: The memory is just allocated so we have exclusive access and
560 // it's valid for writing.
561 unsafe {
562 slot.write(MetaSlot {
563 storage: UnsafeCell::new([0; FRAME_METADATA_MAX_SIZE]),
564 ref_count: AtomicU64::new(REF_COUNT_UNUSED),
565 vtable_ptr: UnsafeCell::new(MaybeUninit::uninit()),
566 in_list: AtomicU64::new(0),
567 })
568 };
569 }
570
571 (nr_meta_pages, paddr)
572}
573
574/// Unusable memory metadata. Cannot be used for any purposes.
575#[derive(Debug)]
576pub struct UnusableMemoryMeta;
577impl_frame_meta_for!(UnusableMemoryMeta);
578
579/// Reserved memory metadata. Maybe later used as I/O memory.
580#[derive(Debug)]
581pub struct ReservedMemoryMeta;
582impl_frame_meta_for!(ReservedMemoryMeta);
583
584/// The metadata of physical pages that contains the kernel itself.
585#[derive(Debug, Default)]
586pub struct KernelMeta;
587impl_frame_meta_for!(KernelMeta);
588
589macro_rules! mark_ranges {
590 ($region: expr, $typ: expr) => {{
591 debug_assert!($region.base().is_multiple_of(PAGE_SIZE));
592 debug_assert!($region.len().is_multiple_of(PAGE_SIZE));
593
594 let start = $region.base().max(super::min_paddr());
595 let seg = Segment::from_unused(start..$region.end(), |_| $typ).unwrap();
596 let _ = ManuallyDrop::new(seg);
597 }};
598}
599
600fn mark_unusable_ranges() {
601 let regions = &crate::boot::EARLY_INFO.get().unwrap().memory_regions;
602
603 for region in regions
604 .iter()
605 .rev()
606 .skip_while(|r| !r.typ().is_physical())
607 .take_while(|r| r.end() > super::min_paddr())
608 {
609 match region.typ() {
610 MemoryRegionType::BadMemory => mark_ranges!(region, UnusableMemoryMeta),
611 MemoryRegionType::Unknown => mark_ranges!(region, ReservedMemoryMeta),
612 MemoryRegionType::NonVolatileSleep => mark_ranges!(region, UnusableMemoryMeta),
613 MemoryRegionType::Reserved => mark_ranges!(region, ReservedMemoryMeta),
614 MemoryRegionType::Kernel => mark_ranges!(region, KernelMeta),
615 MemoryRegionType::Module => mark_ranges!(region, UnusableMemoryMeta),
616 MemoryRegionType::Framebuffer => mark_ranges!(region, ReservedMemoryMeta),
617 MemoryRegionType::Reclaimable => mark_ranges!(region, UnusableMemoryMeta),
618 MemoryRegionType::Usable => {} // By default it is initialized as usable.
619 }
620 }
621}
622
623/// Adds a temporary linear mapping for the metadata frames.
624///
625/// We only assume boot page table to contain 4G linear mapping. Thus if the
626/// physical memory is huge we end up depleted of linear virtual memory for
627/// initializing metadata.
628#[cfg(target_arch = "x86_64")]
629fn add_temp_linear_mapping(max_paddr: Paddr) {
630 use crate::mm::kspace::LINEAR_MAPPING_BASE_VADDR;
631
632 const PADDR4G: Paddr = 0x1_0000_0000;
633
634 if max_paddr <= PADDR4G {
635 return;
636 }
637
638 // TODO: We don't know if the allocator would allocate from low to high or
639 // not. So we prepare all linear mappings in the boot page table. Hope it
640 // won't drag the boot performance much.
641 let end_paddr = max_paddr.align_up(PAGE_SIZE);
642 let prange = PADDR4G..end_paddr;
643 let prop = PageProperty {
644 flags: PageFlags::RW,
645 cache: CachePolicy::Writeback,
646 priv_flags: PrivilegedPageFlags::GLOBAL,
647 };
648
649 // SAFETY: we are doing the linear mapping for the kernel.
650 unsafe {
651 boot_pt::with_borrow(|boot_pt| {
652 for paddr in prange.step_by(PAGE_SIZE) {
653 let vaddr = LINEAR_MAPPING_BASE_VADDR + paddr;
654 boot_pt.map_base_page(vaddr, paddr, prop);
655 }
656 })
657 .unwrap();
658 }
659}