1 //! 该文件用于系统启动早期,内存管理器初始化之前,提供一些简单的内存映射功能 2 //! 3 //! 这里假设在内核引导文件中,已经填写了前100M的页表,其中,前50M是真实映射到内存的,后面的仅仅创建了页表,表项全部为0。 4 //! 因此这里映射内存不需要任何动态分配。 5 //! 6 //! 映射关系为: 7 //! 8 //! 虚拟地址 0-100M与虚拟地址 0x8000_0000_0000 - 0x8000_0640_0000 之间具有重映射关系。 9 //! 也就是说,他们的第二级页表在最顶级页表中,占用了第0和第256个页表项。 10 //! 11 12 use crate::mm::{MMArch, MemoryManagementArch, PhysAddr}; 13 use core::marker::PhantomData; 14 15 use super::{ 16 allocator::page_frame::{FrameAllocator, PageFrameCount, PageFrameUsage}, 17 page::PageFlags, 18 PageTableKind, VirtAddr, 19 }; 20 21 /// 伪分配器 22 struct PseudoAllocator<MMA> { 23 phantom: PhantomData<MMA>, 24 } 25 26 impl<MMA: MemoryManagementArch> PseudoAllocator<MMA> { 27 pub const fn new() -> Self { 28 Self { 29 phantom: PhantomData, 30 } 31 } 32 } 33 34 /// 为NoInitAllocator实现FrameAllocator 35 impl<MMA: MemoryManagementArch> FrameAllocator for PseudoAllocator<MMA> { 36 unsafe fn allocate(&mut self, _count: PageFrameCount) -> Option<(PhysAddr, PageFrameCount)> { 37 panic!("NoInitAllocator can't allocate page frame"); 38 } 39 40 unsafe fn free(&mut self, _address: PhysAddr, _count: PageFrameCount) { 41 panic!("NoInitAllocator can't free page frame"); 42 } 43 /// @brief: 获取内存区域页帧的使用情况 44 /// @param self 45 /// @return 页帧的使用情况 46 unsafe fn usage(&self) -> PageFrameUsage { 47 panic!("NoInitAllocator can't get page frame usage"); 48 } 49 } 50 51 /// Use pseudo mapper to map physical memory to virtual memory. 52 /// 53 /// ## Safety 54 /// 55 /// 调用该函数时,必须保证内存管理器尚未初始化。否则将导致未定义的行为 56 /// 57 /// 并且,内核引导文件必须以4K页为粒度,填写了前100M的内存映射关系。(具体以本文件开头的注释为准) 58 pub unsafe fn pseudo_map_phys(vaddr: VirtAddr, paddr: PhysAddr, count: PageFrameCount) { 59 assert!(vaddr.check_aligned(MMArch::PAGE_SIZE)); 60 assert!(paddr.check_aligned(MMArch::PAGE_SIZE)); 61 62 let mut pseudo_allocator = PseudoAllocator::<MMArch>::new(); 63 64 let mut mapper = crate::mm::page::PageMapper::<MMArch, _>::new( 65 PageTableKind::Kernel, 66 MMArch::table(PageTableKind::Kernel), 67 &mut pseudo_allocator, 68 ); 69 70 let flags: PageFlags<MMArch> = PageFlags::new().set_write(true).set_execute(true); 71 72 for i in 0..count.data() { 73 let vaddr = vaddr + i * MMArch::PAGE_SIZE; 74 let paddr = paddr + i * MMArch::PAGE_SIZE; 75 let flusher = mapper.map_phys(vaddr, paddr, flags).unwrap(); 76 flusher.ignore(); 77 } 78 79 mapper.make_current(); 80 } 81