|
| 1 | +use core::alloc::AllocError; |
| 2 | +use core::ops::Deref; |
| 3 | + |
| 4 | +use free_list::{PageLayout, PageRange}; |
| 5 | +use memory_addresses::{PhysAddr, VirtAddr}; |
| 6 | + |
| 7 | +use crate::arch::mm::paging::{self, BasePageSize, PageSize, PageTableEntryFlags}; |
| 8 | +use crate::mm::{FrameBox, PageBox}; |
| 9 | + |
| 10 | +/// A range of pages that is mapped for as long as this box is alive. |
| 11 | +pub struct MappedPageBox { |
| 12 | + frames: Option<FrameBox>, |
| 13 | + pages: PageBox, |
| 14 | +} |
| 15 | + |
| 16 | +impl MappedPageBox { |
| 17 | + /// Allocates the pages and frames described by `layout` and maps them. |
| 18 | + pub fn new(layout: PageLayout, flags: PageTableEntryFlags) -> Result<Self, AllocError> { |
| 19 | + let frames = FrameBox::new(layout)?; |
| 20 | + let pages = PageBox::new(layout)?; |
| 21 | + map(&pages, PhysAddr::from(frames.start()), flags); |
| 22 | + Ok(Self { |
| 23 | + frames: Some(frames), |
| 24 | + pages, |
| 25 | + }) |
| 26 | + } |
| 27 | + |
| 28 | + /// Allocates the pages described by `layout` and maps them to `phys_addr`. |
| 29 | + /// |
| 30 | + /// # Safety |
| 31 | + /// |
| 32 | + /// - The frames at `phys_addr` must not be deallocated while the returned box is alive. |
| 33 | + pub unsafe fn map_phys( |
| 34 | + phys_addr: PhysAddr, |
| 35 | + layout: PageLayout, |
| 36 | + flags: PageTableEntryFlags, |
| 37 | + ) -> Result<Self, AllocError> { |
| 38 | + let pages = PageBox::new(layout)?; |
| 39 | + map(&pages, phys_addr, flags); |
| 40 | + Ok(Self { |
| 41 | + frames: None, |
| 42 | + pages, |
| 43 | + }) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +impl Drop for MappedPageBox { |
| 48 | + fn drop(&mut self) { |
| 49 | + paging::unmap::<BasePageSize>(VirtAddr::from(self.pages.start()), page_count(&self.pages)); |
| 50 | + |
| 51 | + // `paging::unmap` only flushes the TLB of this CPU. Request the flush on |
| 52 | + // all other CPUs before the frames can be reused. |
| 53 | + #[cfg(all(target_arch = "x86_64", feature = "smp"))] |
| 54 | + crate::arch::kernel::apic::ipi_tlb_flush(); |
| 55 | + |
| 56 | + drop(self.frames.take()); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +impl Deref for MappedPageBox { |
| 61 | + type Target = PageRange; |
| 62 | + |
| 63 | + fn deref(&self) -> &Self::Target { |
| 64 | + &self.pages |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +fn page_count(pages: &PageBox) -> usize { |
| 69 | + pages.len().get() / BasePageSize::SIZE as usize |
| 70 | +} |
| 71 | + |
| 72 | +fn map(pages: &PageBox, phys_addr: PhysAddr, flags: PageTableEntryFlags) { |
| 73 | + paging::map::<BasePageSize>( |
| 74 | + VirtAddr::from(pages.start()), |
| 75 | + phys_addr, |
| 76 | + page_count(pages), |
| 77 | + flags, |
| 78 | + ); |
| 79 | +} |
0 commit comments