1d4f3de93Slogin pub mod barrier; 240fe15e0SLoGin 340fe15e0SLoGin use alloc::vec::Vec; 440fe15e0SLoGin use hashbrown::HashSet; 540fe15e0SLoGin use x86::time::rdtsc; 640fe15e0SLoGin use x86_64::registers::model_specific::EferFlags; 740fe15e0SLoGin 8b087521eSChiichen use crate::driver::uart::uart_device::c_uart_send_str; 940fe15e0SLoGin use crate::include::bindings::bindings::{ 10abe3a6eaShanjiezhou multiboot2_get_memory, multiboot2_iter, multiboot_mmap_entry_t, 1140fe15e0SLoGin }; 1240fe15e0SLoGin use crate::libs::align::page_align_up; 13abe3a6eaShanjiezhou use crate::libs::lib_ui::screen_manager::scm_disable_put_to_window; 1440fe15e0SLoGin use crate::libs::printk::PrintkWriter; 1540fe15e0SLoGin use crate::libs::spinlock::SpinLock; 1640fe15e0SLoGin 17*34e6d6c8Syuyi2439 use crate::mm::allocator::page_frame::{FrameAllocator, PageFrameCount, PageFrameUsage}; 1840fe15e0SLoGin use crate::mm::mmio_buddy::mmio_init; 1940fe15e0SLoGin use crate::{ 2040fe15e0SLoGin arch::MMArch, 2140fe15e0SLoGin mm::allocator::{buddy::BuddyAllocator, bump::BumpAllocator}, 2240fe15e0SLoGin }; 2340fe15e0SLoGin 2440fe15e0SLoGin use crate::mm::kernel_mapper::KernelMapper; 2540fe15e0SLoGin use crate::mm::page::{PageEntry, PageFlags}; 2640fe15e0SLoGin use crate::mm::{MemoryManagementArch, PageTableKind, PhysAddr, PhysMemoryArea, VirtAddr}; 2740fe15e0SLoGin use crate::syscall::SystemError; 2840fe15e0SLoGin use crate::{kdebug, kinfo}; 29d4f3de93Slogin 30d4f3de93Slogin use core::arch::asm; 3140fe15e0SLoGin use core::ffi::c_void; 3240fe15e0SLoGin use core::fmt::{Debug, Write}; 3340fe15e0SLoGin use core::mem::{self}; 34d4f3de93Slogin 3540fe15e0SLoGin use core::sync::atomic::{compiler_fence, AtomicBool, Ordering}; 36d4f3de93Slogin 3740fe15e0SLoGin pub type PageMapper = 3840fe15e0SLoGin crate::mm::page::PageMapper<crate::arch::x86_64::mm::X86_64MMArch, LockedFrameAllocator>; 3940fe15e0SLoGin 4040fe15e0SLoGin /// @brief 用于存储物理内存区域的数组 4140fe15e0SLoGin static mut PHYS_MEMORY_AREAS: [PhysMemoryArea; 512] = [PhysMemoryArea { 4240fe15e0SLoGin base: PhysAddr::new(0), 4340fe15e0SLoGin size: 0, 4440fe15e0SLoGin }; 512]; 4540fe15e0SLoGin 4640fe15e0SLoGin /// 初始的CR3寄存器的值,用于内存管理初始化时,创建的第一个内核页表的位置 4740fe15e0SLoGin static mut INITIAL_CR3_VALUE: PhysAddr = PhysAddr::new(0); 4840fe15e0SLoGin 4940fe15e0SLoGin /// 内核的第一个页表在pml4中的索引 5040fe15e0SLoGin /// 顶级页表的[256, 512)项是内核的页表 5140fe15e0SLoGin static KERNEL_PML4E_NO: usize = (X86_64MMArch::PHYS_OFFSET & ((1 << 48) - 1)) >> 39; 5240fe15e0SLoGin 5340fe15e0SLoGin static INNER_ALLOCATOR: SpinLock<Option<BuddyAllocator<MMArch>>> = SpinLock::new(None); 5440fe15e0SLoGin 5540fe15e0SLoGin #[derive(Clone, Copy)] 5640fe15e0SLoGin pub struct X86_64MMBootstrapInfo { 5740fe15e0SLoGin kernel_code_start: usize, 5840fe15e0SLoGin kernel_code_end: usize, 5940fe15e0SLoGin kernel_data_end: usize, 6040fe15e0SLoGin kernel_rodata_end: usize, 6140fe15e0SLoGin start_brk: usize, 6240fe15e0SLoGin } 6340fe15e0SLoGin 6440fe15e0SLoGin impl Debug for X86_64MMBootstrapInfo { 6540fe15e0SLoGin fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { 6640fe15e0SLoGin write!( 6740fe15e0SLoGin f, 6840fe15e0SLoGin "kernel_code_start: {:x}, kernel_code_end: {:x}, kernel_data_end: {:x}, kernel_rodata_end: {:x}, start_brk: {:x}", 6940fe15e0SLoGin self.kernel_code_start, self.kernel_code_end, self.kernel_data_end, self.kernel_rodata_end, self.start_brk) 7040fe15e0SLoGin } 7140fe15e0SLoGin } 7240fe15e0SLoGin 7340fe15e0SLoGin pub static mut BOOTSTRAP_MM_INFO: Option<X86_64MMBootstrapInfo> = None; 7440fe15e0SLoGin 7540fe15e0SLoGin /// @brief X86_64的内存管理架构结构体 7640fe15e0SLoGin #[derive(Debug, Clone, Copy, Hash)] 7740fe15e0SLoGin pub struct X86_64MMArch; 7840fe15e0SLoGin 7940fe15e0SLoGin /// XD标志位是否被保留 8040fe15e0SLoGin static XD_RESERVED: AtomicBool = AtomicBool::new(false); 8140fe15e0SLoGin 8240fe15e0SLoGin impl MemoryManagementArch for X86_64MMArch { 8340fe15e0SLoGin /// 4K页 8440fe15e0SLoGin const PAGE_SHIFT: usize = 12; 8540fe15e0SLoGin 8640fe15e0SLoGin /// 每个页表项占8字节,总共有512个页表项 8740fe15e0SLoGin const PAGE_ENTRY_SHIFT: usize = 9; 8840fe15e0SLoGin 8940fe15e0SLoGin /// 四级页表(PML4T、PDPT、PDT、PT) 9040fe15e0SLoGin const PAGE_LEVELS: usize = 4; 9140fe15e0SLoGin 9240fe15e0SLoGin /// 页表项的有效位的index。在x86_64中,页表项的第[0, 47]位表示地址和flag, 9340fe15e0SLoGin /// 第[48, 51]位表示保留。因此,有效位的index为52。 9440fe15e0SLoGin /// 请注意,第63位是XD位,表示是否允许执行。 9540fe15e0SLoGin const ENTRY_ADDRESS_SHIFT: usize = 52; 9640fe15e0SLoGin 9740fe15e0SLoGin const ENTRY_FLAG_DEFAULT_PAGE: usize = Self::ENTRY_FLAG_PRESENT; 9840fe15e0SLoGin 9940fe15e0SLoGin const ENTRY_FLAG_DEFAULT_TABLE: usize = Self::ENTRY_FLAG_PRESENT; 10040fe15e0SLoGin 10140fe15e0SLoGin const ENTRY_FLAG_PRESENT: usize = 1 << 0; 10240fe15e0SLoGin 10340fe15e0SLoGin const ENTRY_FLAG_READONLY: usize = 0; 10440fe15e0SLoGin 10540fe15e0SLoGin const ENTRY_FLAG_READWRITE: usize = 1 << 1; 10640fe15e0SLoGin 10740fe15e0SLoGin const ENTRY_FLAG_USER: usize = 1 << 2; 10840fe15e0SLoGin 10940fe15e0SLoGin const ENTRY_FLAG_WRITE_THROUGH: usize = 1 << 3; 11040fe15e0SLoGin 11140fe15e0SLoGin const ENTRY_FLAG_CACHE_DISABLE: usize = 1 << 4; 11240fe15e0SLoGin 11340fe15e0SLoGin const ENTRY_FLAG_NO_EXEC: usize = 1 << 63; 11440fe15e0SLoGin /// x86_64不存在EXEC标志位,只有NO_EXEC(XD)标志位 11540fe15e0SLoGin const ENTRY_FLAG_EXEC: usize = 0; 11640fe15e0SLoGin 11740fe15e0SLoGin /// 物理地址与虚拟地址的偏移量 11840fe15e0SLoGin /// 0xffff_8000_0000_0000 11940fe15e0SLoGin const PHYS_OFFSET: usize = Self::PAGE_NEGATIVE_MASK + (Self::PAGE_ADDRESS_SIZE >> 1); 12040fe15e0SLoGin 12140fe15e0SLoGin const USER_END_VADDR: VirtAddr = VirtAddr::new(0x0000_7eff_ffff_ffff); 12240fe15e0SLoGin const USER_BRK_START: VirtAddr = VirtAddr::new(0x700000000000); 12340fe15e0SLoGin const USER_STACK_START: VirtAddr = VirtAddr::new(0x6ffff0a00000); 12440fe15e0SLoGin 12540fe15e0SLoGin /// @brief 获取物理内存区域 12640fe15e0SLoGin unsafe fn init() -> &'static [crate::mm::PhysMemoryArea] { 12740fe15e0SLoGin extern "C" { 12840fe15e0SLoGin fn _text(); 12940fe15e0SLoGin fn _etext(); 13040fe15e0SLoGin fn _edata(); 13140fe15e0SLoGin fn _erodata(); 13240fe15e0SLoGin fn _end(); 13340fe15e0SLoGin } 13440fe15e0SLoGin 13540fe15e0SLoGin Self::init_xd_rsvd(); 13640fe15e0SLoGin 13740fe15e0SLoGin let bootstrap_info = X86_64MMBootstrapInfo { 13840fe15e0SLoGin kernel_code_start: _text as usize, 13940fe15e0SLoGin kernel_code_end: _etext as usize, 14040fe15e0SLoGin kernel_data_end: _edata as usize, 14140fe15e0SLoGin kernel_rodata_end: _erodata as usize, 14240fe15e0SLoGin start_brk: _end as usize, 14340fe15e0SLoGin }; 14440fe15e0SLoGin unsafe { 14540fe15e0SLoGin BOOTSTRAP_MM_INFO = Some(bootstrap_info); 14640fe15e0SLoGin } 14740fe15e0SLoGin 14840fe15e0SLoGin // 初始化物理内存区域(从multiboot2中获取) 14940fe15e0SLoGin let areas_count = 15040fe15e0SLoGin Self::init_memory_area_from_multiboot2().expect("init memory area failed"); 15140fe15e0SLoGin c_uart_send_str(0x3f8, "x86 64 init end\n\0".as_ptr()); 15240fe15e0SLoGin 15340fe15e0SLoGin return &PHYS_MEMORY_AREAS[0..areas_count]; 15440fe15e0SLoGin } 15540fe15e0SLoGin 15640fe15e0SLoGin /// @brief 刷新TLB中,关于指定虚拟地址的条目 15740fe15e0SLoGin unsafe fn invalidate_page(address: VirtAddr) { 15840fe15e0SLoGin compiler_fence(Ordering::SeqCst); 15940fe15e0SLoGin asm!("invlpg [{0}]", in(reg) address.data(), options(nostack, preserves_flags)); 16040fe15e0SLoGin compiler_fence(Ordering::SeqCst); 16140fe15e0SLoGin } 16240fe15e0SLoGin 16340fe15e0SLoGin /// @brief 刷新TLB中,所有的条目 16440fe15e0SLoGin unsafe fn invalidate_all() { 16540fe15e0SLoGin compiler_fence(Ordering::SeqCst); 16640fe15e0SLoGin // 通过设置cr3寄存器,来刷新整个TLB 16740fe15e0SLoGin Self::set_table(PageTableKind::User, Self::table(PageTableKind::User)); 16840fe15e0SLoGin compiler_fence(Ordering::SeqCst); 16940fe15e0SLoGin } 17040fe15e0SLoGin 17140fe15e0SLoGin /// @brief 获取顶级页表的物理地址 17240fe15e0SLoGin unsafe fn table(_table_kind: PageTableKind) -> PhysAddr { 17340fe15e0SLoGin let paddr: usize; 17440fe15e0SLoGin compiler_fence(Ordering::SeqCst); 17540fe15e0SLoGin asm!("mov {}, cr3", out(reg) paddr, options(nomem, nostack, preserves_flags)); 17640fe15e0SLoGin compiler_fence(Ordering::SeqCst); 17740fe15e0SLoGin return PhysAddr::new(paddr); 17840fe15e0SLoGin } 17940fe15e0SLoGin 18040fe15e0SLoGin /// @brief 设置顶级页表的物理地址到处理器中 18140fe15e0SLoGin unsafe fn set_table(_table_kind: PageTableKind, table: PhysAddr) { 18240fe15e0SLoGin compiler_fence(Ordering::SeqCst); 18340fe15e0SLoGin asm!("mov cr3, {}", in(reg) table.data(), options(nostack, preserves_flags)); 18440fe15e0SLoGin compiler_fence(Ordering::SeqCst); 18540fe15e0SLoGin } 18640fe15e0SLoGin 18740fe15e0SLoGin /// @brief 判断虚拟地址是否合法 18840fe15e0SLoGin fn virt_is_valid(virt: VirtAddr) -> bool { 18940fe15e0SLoGin return virt.is_canonical(); 19040fe15e0SLoGin } 19140fe15e0SLoGin 19240fe15e0SLoGin /// 获取内存管理初始化时,创建的第一个内核页表的地址 19340fe15e0SLoGin fn initial_page_table() -> PhysAddr { 19440fe15e0SLoGin unsafe { 19540fe15e0SLoGin return INITIAL_CR3_VALUE; 19640fe15e0SLoGin } 19740fe15e0SLoGin } 19840fe15e0SLoGin 19940fe15e0SLoGin /// @brief 创建新的顶层页表 200d4f3de93Slogin /// 20140fe15e0SLoGin /// 该函数会创建页表并复制内核的映射到新的页表中 202d4f3de93Slogin /// 20340fe15e0SLoGin /// @return 新的页表 20440fe15e0SLoGin fn setup_new_usermapper() -> Result<crate::mm::ucontext::UserMapper, SystemError> { 20540fe15e0SLoGin let new_umapper: crate::mm::page::PageMapper<X86_64MMArch, LockedFrameAllocator> = unsafe { 20640fe15e0SLoGin PageMapper::create(PageTableKind::User, LockedFrameAllocator) 20740fe15e0SLoGin .ok_or(SystemError::ENOMEM)? 20840fe15e0SLoGin }; 20940fe15e0SLoGin 21040fe15e0SLoGin let current_ktable: KernelMapper = KernelMapper::lock(); 21140fe15e0SLoGin let copy_mapping = |pml4_entry_no| unsafe { 21240fe15e0SLoGin let entry: PageEntry<X86_64MMArch> = current_ktable 21340fe15e0SLoGin .table() 21440fe15e0SLoGin .entry(pml4_entry_no) 21540fe15e0SLoGin .unwrap_or_else(|| panic!("entry {} not found", pml4_entry_no)); 21640fe15e0SLoGin new_umapper.table().set_entry(pml4_entry_no, entry) 21740fe15e0SLoGin }; 21840fe15e0SLoGin 21940fe15e0SLoGin // 复制内核的映射 22040fe15e0SLoGin for pml4_entry_no in KERNEL_PML4E_NO..512 { 22140fe15e0SLoGin copy_mapping(pml4_entry_no); 22240fe15e0SLoGin } 22340fe15e0SLoGin 22440fe15e0SLoGin return Ok(crate::mm::ucontext::UserMapper::new(new_umapper)); 22540fe15e0SLoGin } 22640fe15e0SLoGin } 22740fe15e0SLoGin 22840fe15e0SLoGin impl X86_64MMArch { 22940fe15e0SLoGin unsafe fn init_memory_area_from_multiboot2() -> Result<usize, SystemError> { 23040fe15e0SLoGin // 这个数组用来存放内存区域的信息(从C获取) 23140fe15e0SLoGin let mut mb2_mem_info: [multiboot_mmap_entry_t; 512] = mem::zeroed(); 23240fe15e0SLoGin c_uart_send_str(0x3f8, "init_memory_area_from_multiboot2 begin\n\0".as_ptr()); 23340fe15e0SLoGin 23440fe15e0SLoGin let mut mb2_count: u32 = 0; 23540fe15e0SLoGin multiboot2_iter( 23640fe15e0SLoGin Some(multiboot2_get_memory), 23740fe15e0SLoGin &mut mb2_mem_info as *mut [multiboot_mmap_entry_t; 512] as usize as *mut c_void, 23840fe15e0SLoGin &mut mb2_count, 23940fe15e0SLoGin ); 24040fe15e0SLoGin c_uart_send_str(0x3f8, "init_memory_area_from_multiboot2 2\n\0".as_ptr()); 24140fe15e0SLoGin 24240fe15e0SLoGin let mb2_count = mb2_count as usize; 24340fe15e0SLoGin let mut areas_count = 0usize; 24440fe15e0SLoGin let mut total_mem_size = 0usize; 24540fe15e0SLoGin for i in 0..mb2_count { 24640fe15e0SLoGin // Only use the memory area if its type is 1 (RAM) 24740fe15e0SLoGin if mb2_mem_info[i].type_ == 1 { 24840fe15e0SLoGin // Skip the memory area if its len is 0 24940fe15e0SLoGin if mb2_mem_info[i].len == 0 { 25040fe15e0SLoGin continue; 25140fe15e0SLoGin } 25240fe15e0SLoGin total_mem_size += mb2_mem_info[i].len as usize; 25340fe15e0SLoGin PHYS_MEMORY_AREAS[areas_count].base = PhysAddr::new(mb2_mem_info[i].addr as usize); 25440fe15e0SLoGin PHYS_MEMORY_AREAS[areas_count].size = mb2_mem_info[i].len as usize; 25540fe15e0SLoGin areas_count += 1; 25640fe15e0SLoGin } 25740fe15e0SLoGin } 25840fe15e0SLoGin c_uart_send_str(0x3f8, "init_memory_area_from_multiboot2 end\n\0".as_ptr()); 25940fe15e0SLoGin kinfo!("Total memory size: {} MB, total areas from multiboot2: {mb2_count}, valid areas: {areas_count}", total_mem_size / 1024 / 1024); 26040fe15e0SLoGin 26140fe15e0SLoGin return Ok(areas_count); 26240fe15e0SLoGin } 26340fe15e0SLoGin 26440fe15e0SLoGin fn init_xd_rsvd() { 26540fe15e0SLoGin // 读取ia32-EFER寄存器的值 26640fe15e0SLoGin let efer: EferFlags = x86_64::registers::model_specific::Efer::read(); 26740fe15e0SLoGin if !efer.contains(EferFlags::NO_EXECUTE_ENABLE) { 26840fe15e0SLoGin // NO_EXECUTE_ENABLE是false,那么就设置xd_reserved为true 26940fe15e0SLoGin kdebug!("NO_EXECUTE_ENABLE is false, set XD_RESERVED to true"); 27040fe15e0SLoGin XD_RESERVED.store(true, Ordering::Relaxed); 27140fe15e0SLoGin } 27240fe15e0SLoGin compiler_fence(Ordering::SeqCst); 27340fe15e0SLoGin } 27440fe15e0SLoGin 27540fe15e0SLoGin /// 判断XD标志位是否被保留 27640fe15e0SLoGin pub fn is_xd_reserved() -> bool { 27740fe15e0SLoGin return XD_RESERVED.load(Ordering::Relaxed); 27840fe15e0SLoGin } 27940fe15e0SLoGin } 28040fe15e0SLoGin 28140fe15e0SLoGin impl VirtAddr { 28240fe15e0SLoGin /// @brief 判断虚拟地址是否合法 283d4f3de93Slogin #[inline(always)] 28440fe15e0SLoGin pub fn is_canonical(self) -> bool { 28540fe15e0SLoGin let x = self.data() & X86_64MMArch::PHYS_OFFSET; 28640fe15e0SLoGin // 如果x为0,说明虚拟地址的高位为0,是合法的用户地址 28740fe15e0SLoGin // 如果x为PHYS_OFFSET,说明虚拟地址的高位全为1,是合法的内核地址 28840fe15e0SLoGin return x == 0 || x == X86_64MMArch::PHYS_OFFSET; 28940fe15e0SLoGin } 29040fe15e0SLoGin } 29140fe15e0SLoGin 29240fe15e0SLoGin /// @brief 初始化内存管理模块 29340fe15e0SLoGin pub fn mm_init() { 29440fe15e0SLoGin c_uart_send_str(0x3f8, "mm_init\n\0".as_ptr()); 29540fe15e0SLoGin PrintkWriter 29640fe15e0SLoGin .write_fmt(format_args!("mm_init() called\n")) 29740fe15e0SLoGin .unwrap(); 29840fe15e0SLoGin // printk_color!(GREEN, BLACK, "mm_init() called\n"); 29940fe15e0SLoGin static _CALL_ONCE: AtomicBool = AtomicBool::new(false); 30040fe15e0SLoGin if _CALL_ONCE 30140fe15e0SLoGin .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) 30240fe15e0SLoGin .is_err() 30340fe15e0SLoGin { 30440fe15e0SLoGin c_uart_send_str(0x3f8, "mm_init err\n\0".as_ptr()); 30540fe15e0SLoGin panic!("mm_init() can only be called once"); 30640fe15e0SLoGin } 30740fe15e0SLoGin 30840fe15e0SLoGin unsafe { X86_64MMArch::init() }; 30940fe15e0SLoGin kdebug!("bootstrap info: {:?}", unsafe { BOOTSTRAP_MM_INFO }); 31040fe15e0SLoGin kdebug!("phys[0]=virt[0x{:x}]", unsafe { 31140fe15e0SLoGin MMArch::phys_2_virt(PhysAddr::new(0)).unwrap().data() 31240fe15e0SLoGin }); 31340fe15e0SLoGin 31440fe15e0SLoGin // 初始化内存管理器 31540fe15e0SLoGin unsafe { allocator_init() }; 31640fe15e0SLoGin // enable mmio 31740fe15e0SLoGin mmio_init(); 31840fe15e0SLoGin } 31940fe15e0SLoGin 32040fe15e0SLoGin unsafe fn allocator_init() { 32140fe15e0SLoGin let virt_offset = BOOTSTRAP_MM_INFO.unwrap().start_brk; 32240fe15e0SLoGin let phy_offset = 32340fe15e0SLoGin unsafe { MMArch::virt_2_phys(VirtAddr::new(page_align_up(virt_offset))) }.unwrap(); 32440fe15e0SLoGin 32540fe15e0SLoGin kdebug!("PhysArea[0..10] = {:?}", &PHYS_MEMORY_AREAS[0..10]); 32640fe15e0SLoGin let mut bump_allocator = 32740fe15e0SLoGin BumpAllocator::<X86_64MMArch>::new(&PHYS_MEMORY_AREAS, phy_offset.data()); 32840fe15e0SLoGin kdebug!( 32940fe15e0SLoGin "BumpAllocator created, offset={:?}", 33040fe15e0SLoGin bump_allocator.offset() 33140fe15e0SLoGin ); 33240fe15e0SLoGin 33340fe15e0SLoGin // 暂存初始在head.S中指定的页表的地址,后面再考虑是否需要把它加到buddy的可用空间里面! 33440fe15e0SLoGin // 现在不加的原因是,我担心会有安全漏洞问题:这些初始的页表,位于内核的数据段。如果归还到buddy, 33540fe15e0SLoGin // 可能会产生一定的安全风险(有的代码可能根据虚拟地址来进行安全校验) 33640fe15e0SLoGin let _old_page_table = MMArch::table(PageTableKind::Kernel); 33740fe15e0SLoGin 33840fe15e0SLoGin let new_page_table: PhysAddr; 33940fe15e0SLoGin // 使用bump分配器,把所有的内存页都映射到页表 34040fe15e0SLoGin { 34140fe15e0SLoGin // 用bump allocator创建新的页表 34240fe15e0SLoGin let mut mapper: crate::mm::page::PageMapper<MMArch, &mut BumpAllocator<MMArch>> = 34340fe15e0SLoGin crate::mm::page::PageMapper::<MMArch, _>::create( 34440fe15e0SLoGin PageTableKind::Kernel, 34540fe15e0SLoGin &mut bump_allocator, 34640fe15e0SLoGin ) 34740fe15e0SLoGin .expect("Failed to create page mapper"); 34840fe15e0SLoGin new_page_table = mapper.table().phys(); 34940fe15e0SLoGin kdebug!("PageMapper created"); 35040fe15e0SLoGin 35140fe15e0SLoGin // 取消最开始时候,在head.S中指定的映射(暂时不刷新TLB) 35240fe15e0SLoGin { 35340fe15e0SLoGin let table = mapper.table(); 35440fe15e0SLoGin let empty_entry = PageEntry::<MMArch>::new(0); 35540fe15e0SLoGin for i in 0..MMArch::PAGE_ENTRY_NUM { 35640fe15e0SLoGin table 35740fe15e0SLoGin .set_entry(i, empty_entry) 35840fe15e0SLoGin .expect("Failed to empty page table entry"); 35940fe15e0SLoGin } 36040fe15e0SLoGin } 36140fe15e0SLoGin kdebug!("Successfully emptied page table"); 36240fe15e0SLoGin 36340fe15e0SLoGin for area in PHYS_MEMORY_AREAS.iter() { 36440fe15e0SLoGin // kdebug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size); 36540fe15e0SLoGin for i in 0..((area.size + MMArch::PAGE_SIZE - 1) / MMArch::PAGE_SIZE) { 36640fe15e0SLoGin let paddr = area.base.add(i * MMArch::PAGE_SIZE); 36740fe15e0SLoGin let vaddr = unsafe { MMArch::phys_2_virt(paddr) }.unwrap(); 36840fe15e0SLoGin let flags = kernel_page_flags::<MMArch>(vaddr); 36940fe15e0SLoGin 37040fe15e0SLoGin let flusher = mapper 37140fe15e0SLoGin .map_phys(vaddr, paddr, flags) 37240fe15e0SLoGin .expect("Failed to map frame"); 37340fe15e0SLoGin // 暂时不刷新TLB 37440fe15e0SLoGin flusher.ignore(); 37540fe15e0SLoGin } 37640fe15e0SLoGin } 37740fe15e0SLoGin 37840fe15e0SLoGin // 添加低地址的映射(在smp完成初始化之前,需要使用低地址的映射.初始化之后需要取消这一段映射) 37940fe15e0SLoGin LowAddressRemapping::remap_at_low_address(&mut mapper); 38040fe15e0SLoGin } 381d4f3de93Slogin 382d4f3de93Slogin unsafe { 38340fe15e0SLoGin INITIAL_CR3_VALUE = new_page_table; 384d4f3de93Slogin } 38540fe15e0SLoGin kdebug!( 38640fe15e0SLoGin "After mapping all physical memory, DragonOS used: {} KB", 38740fe15e0SLoGin bump_allocator.offset() / 1024 38840fe15e0SLoGin ); 38940fe15e0SLoGin 39040fe15e0SLoGin // 初始化buddy_allocator 39140fe15e0SLoGin let buddy_allocator = unsafe { BuddyAllocator::<X86_64MMArch>::new(bump_allocator).unwrap() }; 39240fe15e0SLoGin // 设置全局的页帧分配器 39340fe15e0SLoGin unsafe { set_inner_allocator(buddy_allocator) }; 39440fe15e0SLoGin kinfo!("Successfully initialized buddy allocator"); 39540fe15e0SLoGin // 关闭显示输出 396abe3a6eaShanjiezhou scm_disable_put_to_window(); 397abe3a6eaShanjiezhou 39840fe15e0SLoGin // make the new page table current 39940fe15e0SLoGin { 40040fe15e0SLoGin let mut binding = INNER_ALLOCATOR.lock(); 40140fe15e0SLoGin let mut allocator_guard = binding.as_mut().unwrap(); 40240fe15e0SLoGin kdebug!("To enable new page table."); 40340fe15e0SLoGin compiler_fence(Ordering::SeqCst); 40440fe15e0SLoGin let mapper = crate::mm::page::PageMapper::<MMArch, _>::new( 40540fe15e0SLoGin PageTableKind::Kernel, 40640fe15e0SLoGin new_page_table, 40740fe15e0SLoGin &mut allocator_guard, 40840fe15e0SLoGin ); 40940fe15e0SLoGin compiler_fence(Ordering::SeqCst); 41040fe15e0SLoGin mapper.make_current(); 41140fe15e0SLoGin compiler_fence(Ordering::SeqCst); 41240fe15e0SLoGin kdebug!("New page table enabled"); 41340fe15e0SLoGin } 41440fe15e0SLoGin kdebug!("Successfully enabled new page table"); 41540fe15e0SLoGin } 41640fe15e0SLoGin 41740fe15e0SLoGin #[no_mangle] 41840fe15e0SLoGin pub extern "C" fn rs_test_buddy() { 41940fe15e0SLoGin test_buddy(); 42040fe15e0SLoGin } 42140fe15e0SLoGin pub fn test_buddy() { 42240fe15e0SLoGin // 申请内存然后写入数据然后free掉 42340fe15e0SLoGin // 总共申请200MB内存 42440fe15e0SLoGin const TOTAL_SIZE: usize = 200 * 1024 * 1024; 42540fe15e0SLoGin 42640fe15e0SLoGin for i in 0..10 { 42740fe15e0SLoGin kdebug!("Test buddy, round: {i}"); 42840fe15e0SLoGin // 存放申请的内存块 42940fe15e0SLoGin let mut v: Vec<(PhysAddr, PageFrameCount)> = Vec::with_capacity(60 * 1024); 43040fe15e0SLoGin // 存放已经申请的内存块的地址(用于检查重复) 43140fe15e0SLoGin let mut addr_set: HashSet<PhysAddr> = HashSet::new(); 43240fe15e0SLoGin 43340fe15e0SLoGin let mut allocated = 0usize; 43440fe15e0SLoGin 43540fe15e0SLoGin let mut free_count = 0usize; 43640fe15e0SLoGin 43740fe15e0SLoGin while allocated < TOTAL_SIZE { 43840fe15e0SLoGin let mut random_size = 0u64; 43940fe15e0SLoGin unsafe { x86::random::rdrand64(&mut random_size) }; 44040fe15e0SLoGin // 一次最多申请4M 44140fe15e0SLoGin random_size = random_size % (1024 * 4096); 44240fe15e0SLoGin if random_size == 0 { 44340fe15e0SLoGin continue; 44440fe15e0SLoGin } 44540fe15e0SLoGin let random_size = 44640fe15e0SLoGin core::cmp::min(page_align_up(random_size as usize), TOTAL_SIZE - allocated); 44740fe15e0SLoGin let random_size = PageFrameCount::from_bytes(random_size.next_power_of_two()).unwrap(); 44840fe15e0SLoGin // 获取帧 44940fe15e0SLoGin let (paddr, allocated_frame_count) = 45040fe15e0SLoGin unsafe { LockedFrameAllocator.allocate(random_size).unwrap() }; 45140fe15e0SLoGin assert!(allocated_frame_count.data().is_power_of_two()); 45240fe15e0SLoGin assert!(paddr.data() % MMArch::PAGE_SIZE == 0); 45340fe15e0SLoGin unsafe { 45440fe15e0SLoGin assert!(MMArch::phys_2_virt(paddr) 45540fe15e0SLoGin .as_ref() 45640fe15e0SLoGin .unwrap() 45740fe15e0SLoGin .check_aligned(allocated_frame_count.data() * MMArch::PAGE_SIZE)); 45840fe15e0SLoGin } 45940fe15e0SLoGin allocated += allocated_frame_count.data() * MMArch::PAGE_SIZE; 46040fe15e0SLoGin v.push((paddr, allocated_frame_count)); 46140fe15e0SLoGin assert!(addr_set.insert(paddr), "duplicate address: {:?}", paddr); 46240fe15e0SLoGin 46340fe15e0SLoGin // 写入数据 46440fe15e0SLoGin let vaddr = unsafe { MMArch::phys_2_virt(paddr).unwrap() }; 46540fe15e0SLoGin let slice = unsafe { 46640fe15e0SLoGin core::slice::from_raw_parts_mut( 46740fe15e0SLoGin vaddr.data() as *mut u8, 46840fe15e0SLoGin allocated_frame_count.data() * MMArch::PAGE_SIZE, 46940fe15e0SLoGin ) 47040fe15e0SLoGin }; 47140fe15e0SLoGin for i in 0..slice.len() { 47240fe15e0SLoGin slice[i] = ((i + unsafe { rdtsc() } as usize) % 256) as u8; 47340fe15e0SLoGin } 47440fe15e0SLoGin 47540fe15e0SLoGin // 随机释放一个内存块 47640fe15e0SLoGin if v.len() > 0 { 47740fe15e0SLoGin let mut random_index = 0u64; 47840fe15e0SLoGin unsafe { x86::random::rdrand64(&mut random_index) }; 47940fe15e0SLoGin // 70%概率释放 48040fe15e0SLoGin if random_index % 10 > 7 { 48140fe15e0SLoGin continue; 48240fe15e0SLoGin } 48340fe15e0SLoGin random_index = random_index % v.len() as u64; 48440fe15e0SLoGin let random_index = random_index as usize; 48540fe15e0SLoGin let (paddr, allocated_frame_count) = v.remove(random_index); 48640fe15e0SLoGin assert!(addr_set.remove(&paddr)); 48740fe15e0SLoGin unsafe { LockedFrameAllocator.free(paddr, allocated_frame_count) }; 48840fe15e0SLoGin free_count += allocated_frame_count.data() * MMArch::PAGE_SIZE; 48940fe15e0SLoGin } 49040fe15e0SLoGin } 49140fe15e0SLoGin 49240fe15e0SLoGin kdebug!( 49340fe15e0SLoGin "Allocated {} MB memory, release: {} MB, no release: {} bytes", 49440fe15e0SLoGin allocated / 1024 / 1024, 49540fe15e0SLoGin free_count / 1024 / 1024, 49640fe15e0SLoGin (allocated - free_count) 49740fe15e0SLoGin ); 49840fe15e0SLoGin 49940fe15e0SLoGin kdebug!("Now, to release buddy memory"); 50040fe15e0SLoGin // 释放所有的内存 50140fe15e0SLoGin for (paddr, allocated_frame_count) in v { 50240fe15e0SLoGin unsafe { LockedFrameAllocator.free(paddr, allocated_frame_count) }; 50340fe15e0SLoGin assert!(addr_set.remove(&paddr)); 50440fe15e0SLoGin free_count += allocated_frame_count.data() * MMArch::PAGE_SIZE; 50540fe15e0SLoGin } 50640fe15e0SLoGin 50740fe15e0SLoGin kdebug!("release done!, allocated: {allocated}, free_count: {free_count}"); 50840fe15e0SLoGin } 50940fe15e0SLoGin } 51040fe15e0SLoGin /// 全局的页帧分配器 51140fe15e0SLoGin #[derive(Debug, Clone, Copy, Hash)] 51240fe15e0SLoGin pub struct LockedFrameAllocator; 51340fe15e0SLoGin 51440fe15e0SLoGin impl FrameAllocator for LockedFrameAllocator { 515*34e6d6c8Syuyi2439 unsafe fn allocate(&mut self, count: PageFrameCount) -> Option<(PhysAddr, PageFrameCount)> { 51640fe15e0SLoGin if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() { 51740fe15e0SLoGin return allocator.allocate(count); 51840fe15e0SLoGin } else { 51940fe15e0SLoGin return None; 52040fe15e0SLoGin } 52140fe15e0SLoGin } 52240fe15e0SLoGin 523*34e6d6c8Syuyi2439 unsafe fn free(&mut self, address: crate::mm::PhysAddr, count: PageFrameCount) { 52440fe15e0SLoGin assert!(count.data().is_power_of_two()); 52540fe15e0SLoGin if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() { 52640fe15e0SLoGin return allocator.free(address, count); 52740fe15e0SLoGin } 52840fe15e0SLoGin } 52940fe15e0SLoGin 530*34e6d6c8Syuyi2439 unsafe fn usage(&self) -> PageFrameUsage { 531*34e6d6c8Syuyi2439 if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() { 532*34e6d6c8Syuyi2439 return allocator.usage(); 533*34e6d6c8Syuyi2439 } else { 534*34e6d6c8Syuyi2439 panic!("usage error"); 535*34e6d6c8Syuyi2439 } 536*34e6d6c8Syuyi2439 } 537*34e6d6c8Syuyi2439 } 538*34e6d6c8Syuyi2439 539*34e6d6c8Syuyi2439 impl LockedFrameAllocator { 540*34e6d6c8Syuyi2439 pub fn get_usage(&self) -> PageFrameUsage { 541*34e6d6c8Syuyi2439 unsafe { self.usage() } 54240fe15e0SLoGin } 54340fe15e0SLoGin } 54440fe15e0SLoGin 54540fe15e0SLoGin /// 获取内核地址默认的页面标志 54640fe15e0SLoGin pub unsafe fn kernel_page_flags<A: MemoryManagementArch>(virt: VirtAddr) -> PageFlags<A> { 54740fe15e0SLoGin let info: X86_64MMBootstrapInfo = BOOTSTRAP_MM_INFO.clone().unwrap(); 54840fe15e0SLoGin 54940fe15e0SLoGin if virt.data() >= info.kernel_code_start && virt.data() < info.kernel_code_end { 55040fe15e0SLoGin // Remap kernel code execute 55140fe15e0SLoGin return PageFlags::new().set_execute(true).set_write(true); 55240fe15e0SLoGin } else if virt.data() >= info.kernel_data_end && virt.data() < info.kernel_rodata_end { 55340fe15e0SLoGin // Remap kernel rodata read only 55440fe15e0SLoGin return PageFlags::new().set_execute(true); 55540fe15e0SLoGin } else { 55640fe15e0SLoGin return PageFlags::new().set_write(true).set_execute(true); 55740fe15e0SLoGin } 55840fe15e0SLoGin } 55940fe15e0SLoGin 56040fe15e0SLoGin unsafe fn set_inner_allocator(allocator: BuddyAllocator<MMArch>) { 56140fe15e0SLoGin static FLAG: AtomicBool = AtomicBool::new(false); 56240fe15e0SLoGin if FLAG 56340fe15e0SLoGin .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) 56440fe15e0SLoGin .is_err() 56540fe15e0SLoGin { 56640fe15e0SLoGin panic!("Cannot set inner allocator twice!"); 56740fe15e0SLoGin } 56840fe15e0SLoGin *INNER_ALLOCATOR.lock() = Some(allocator); 56940fe15e0SLoGin } 57040fe15e0SLoGin 57140fe15e0SLoGin /// 低地址重映射的管理器 57240fe15e0SLoGin /// 57340fe15e0SLoGin /// 低地址重映射的管理器,在smp初始化完成之前,需要使用低地址的映射,因此需要在smp初始化完成之后,取消这一段映射 57440fe15e0SLoGin pub struct LowAddressRemapping; 57540fe15e0SLoGin 57640fe15e0SLoGin impl LowAddressRemapping { 57740fe15e0SLoGin // 映射32M 57840fe15e0SLoGin const REMAP_SIZE: usize = 32 * 1024 * 1024; 57940fe15e0SLoGin 58040fe15e0SLoGin pub unsafe fn remap_at_low_address( 58140fe15e0SLoGin mapper: &mut crate::mm::page::PageMapper<MMArch, &mut BumpAllocator<MMArch>>, 58240fe15e0SLoGin ) { 58340fe15e0SLoGin for i in 0..(Self::REMAP_SIZE / MMArch::PAGE_SIZE) { 58440fe15e0SLoGin let paddr = PhysAddr::new(i * MMArch::PAGE_SIZE); 58540fe15e0SLoGin let vaddr = VirtAddr::new(i * MMArch::PAGE_SIZE); 58640fe15e0SLoGin let flags = kernel_page_flags::<MMArch>(vaddr); 58740fe15e0SLoGin 58840fe15e0SLoGin let flusher = mapper 58940fe15e0SLoGin .map_phys(vaddr, paddr, flags) 59040fe15e0SLoGin .expect("Failed to map frame"); 59140fe15e0SLoGin // 暂时不刷新TLB 59240fe15e0SLoGin flusher.ignore(); 59340fe15e0SLoGin } 59440fe15e0SLoGin } 59540fe15e0SLoGin 59640fe15e0SLoGin /// 取消低地址的映射 59740fe15e0SLoGin pub unsafe fn unmap_at_low_address(flush: bool) { 59840fe15e0SLoGin let mut mapper = KernelMapper::lock(); 59940fe15e0SLoGin assert!(mapper.as_mut().is_some()); 60040fe15e0SLoGin for i in 0..(Self::REMAP_SIZE / MMArch::PAGE_SIZE) { 60140fe15e0SLoGin let vaddr = VirtAddr::new(i * MMArch::PAGE_SIZE); 60226887c63SLoGin let (_, _, flusher) = mapper 60340fe15e0SLoGin .as_mut() 60440fe15e0SLoGin .unwrap() 60526887c63SLoGin .unmap_phys(vaddr, true) 60640fe15e0SLoGin .expect("Failed to unmap frame"); 60740fe15e0SLoGin if flush == false { 60840fe15e0SLoGin flusher.ignore(); 60940fe15e0SLoGin } 61040fe15e0SLoGin } 61140fe15e0SLoGin } 61240fe15e0SLoGin } 61340fe15e0SLoGin #[no_mangle] 61440fe15e0SLoGin pub extern "C" fn rs_mm_init() { 61540fe15e0SLoGin mm_init(); 616d4f3de93Slogin } 617