1d4f3de93Slogin pub mod barrier; 299dbf38dSLoGin pub mod bump; 3a17651b1SMemoryShore pub mod fault; 4a17651b1SMemoryShore pub mod pkru; 540fe15e0SLoGin 6a17651b1SMemoryShore use alloc::sync::Arc; 740fe15e0SLoGin use alloc::vec::Vec; 840fe15e0SLoGin use hashbrown::HashSet; 940fe15e0SLoGin use x86::time::rdtsc; 1040fe15e0SLoGin use x86_64::registers::model_specific::EferFlags; 1140fe15e0SLoGin 1252da9a59SGnoCiYeH use crate::driver::serial::serial8250::send_to_default_serial8250_port; 1340fe15e0SLoGin use crate::include::bindings::bindings::{ 1499dbf38dSLoGin multiboot2_get_load_base, multiboot2_get_memory, multiboot2_iter, multiboot_mmap_entry_t, 1599dbf38dSLoGin multiboot_tag_load_base_addr_t, 1640fe15e0SLoGin }; 1740fe15e0SLoGin use crate::libs::align::page_align_up; 18abe3a6eaShanjiezhou use crate::libs::lib_ui::screen_manager::scm_disable_put_to_window; 1940fe15e0SLoGin use crate::libs::spinlock::SpinLock; 2040fe15e0SLoGin 2134e6d6c8Syuyi2439 use crate::mm::allocator::page_frame::{FrameAllocator, PageFrameCount, PageFrameUsage}; 2245626c85SLoGin use crate::mm::memblock::mem_block_manager; 23a17651b1SMemoryShore use crate::mm::ucontext::LockedVMA; 2440fe15e0SLoGin use crate::{ 2540fe15e0SLoGin arch::MMArch, 2640fe15e0SLoGin mm::allocator::{buddy::BuddyAllocator, bump::BumpAllocator}, 2740fe15e0SLoGin }; 2840fe15e0SLoGin 2940fe15e0SLoGin use crate::mm::kernel_mapper::KernelMapper; 3023ef2b33SLoGin use crate::mm::page::{PageEntry, PageFlags, PAGE_1G_SHIFT}; 3145626c85SLoGin use crate::mm::{MemoryManagementArch, PageTableKind, PhysAddr, VirtAddr}; 3245626c85SLoGin use crate::{kdebug, kinfo, kwarn}; 3391e9d4abSLoGin use system_error::SystemError; 34d4f3de93Slogin 35d4f3de93Slogin use core::arch::asm; 3640fe15e0SLoGin use core::ffi::c_void; 37453452ccSLoGin use core::fmt::Debug; 3840fe15e0SLoGin use core::mem::{self}; 39d4f3de93Slogin 4040fe15e0SLoGin use core::sync::atomic::{compiler_fence, AtomicBool, Ordering}; 41d4f3de93Slogin 4240314b30SXiaoye Zheng use super::kvm::vmx::vmcs::VmcsFields; 4340314b30SXiaoye Zheng use super::kvm::vmx::vmx_asm_wrapper::vmx_vmread; 4440314b30SXiaoye Zheng 4540fe15e0SLoGin pub type PageMapper = 4640fe15e0SLoGin crate::mm::page::PageMapper<crate::arch::x86_64::mm::X86_64MMArch, LockedFrameAllocator>; 4740fe15e0SLoGin 4840fe15e0SLoGin /// 初始的CR3寄存器的值,用于内存管理初始化时,创建的第一个内核页表的位置 4940fe15e0SLoGin static mut INITIAL_CR3_VALUE: PhysAddr = PhysAddr::new(0); 5040fe15e0SLoGin 5140fe15e0SLoGin static INNER_ALLOCATOR: SpinLock<Option<BuddyAllocator<MMArch>>> = SpinLock::new(None); 5240fe15e0SLoGin 5399dbf38dSLoGin #[derive(Clone, Copy, Debug)] 5440fe15e0SLoGin pub struct X86_64MMBootstrapInfo { 5599dbf38dSLoGin kernel_load_base_paddr: usize, 5640fe15e0SLoGin kernel_code_start: usize, 5740fe15e0SLoGin kernel_code_end: usize, 5840fe15e0SLoGin kernel_data_end: usize, 5940fe15e0SLoGin kernel_rodata_end: usize, 6040fe15e0SLoGin start_brk: usize, 6140fe15e0SLoGin } 6240fe15e0SLoGin 6399dbf38dSLoGin pub(super) static mut BOOTSTRAP_MM_INFO: Option<X86_64MMBootstrapInfo> = None; 6440fe15e0SLoGin 6540fe15e0SLoGin /// @brief X86_64的内存管理架构结构体 6640fe15e0SLoGin #[derive(Debug, Clone, Copy, Hash)] 6740fe15e0SLoGin pub struct X86_64MMArch; 6840fe15e0SLoGin 6940fe15e0SLoGin /// XD标志位是否被保留 7040fe15e0SLoGin static XD_RESERVED: AtomicBool = AtomicBool::new(false); 7140fe15e0SLoGin 7240fe15e0SLoGin impl MemoryManagementArch for X86_64MMArch { 73a17651b1SMemoryShore /// X86目前支持缺页中断 74a17651b1SMemoryShore const PAGE_FAULT_ENABLED: bool = true; 7540fe15e0SLoGin /// 4K页 7640fe15e0SLoGin const PAGE_SHIFT: usize = 12; 7740fe15e0SLoGin 7840fe15e0SLoGin /// 每个页表项占8字节,总共有512个页表项 7940fe15e0SLoGin const PAGE_ENTRY_SHIFT: usize = 9; 8040fe15e0SLoGin 8140fe15e0SLoGin /// 四级页表(PML4T、PDPT、PDT、PT) 8240fe15e0SLoGin const PAGE_LEVELS: usize = 4; 8340fe15e0SLoGin 8440fe15e0SLoGin /// 页表项的有效位的index。在x86_64中,页表项的第[0, 47]位表示地址和flag, 8540fe15e0SLoGin /// 第[48, 51]位表示保留。因此,有效位的index为52。 8640fe15e0SLoGin /// 请注意,第63位是XD位,表示是否允许执行。 8740fe15e0SLoGin const ENTRY_ADDRESS_SHIFT: usize = 52; 8840fe15e0SLoGin 8940fe15e0SLoGin const ENTRY_FLAG_DEFAULT_PAGE: usize = Self::ENTRY_FLAG_PRESENT; 9040fe15e0SLoGin 9140fe15e0SLoGin const ENTRY_FLAG_DEFAULT_TABLE: usize = Self::ENTRY_FLAG_PRESENT; 9240fe15e0SLoGin 9340fe15e0SLoGin const ENTRY_FLAG_PRESENT: usize = 1 << 0; 9440fe15e0SLoGin 9540fe15e0SLoGin const ENTRY_FLAG_READONLY: usize = 0; 9640fe15e0SLoGin 97*471d65cfSLoGin const ENTRY_FLAG_WRITEABLE: usize = 1 << 1; 9840fe15e0SLoGin const ENTRY_FLAG_READWRITE: usize = 1 << 1; 9940fe15e0SLoGin 10040fe15e0SLoGin const ENTRY_FLAG_USER: usize = 1 << 2; 10140fe15e0SLoGin 10240fe15e0SLoGin const ENTRY_FLAG_WRITE_THROUGH: usize = 1 << 3; 10340fe15e0SLoGin 10440fe15e0SLoGin const ENTRY_FLAG_CACHE_DISABLE: usize = 1 << 4; 10540fe15e0SLoGin 10640fe15e0SLoGin const ENTRY_FLAG_NO_EXEC: usize = 1 << 63; 10740fe15e0SLoGin /// x86_64不存在EXEC标志位,只有NO_EXEC(XD)标志位 10840fe15e0SLoGin const ENTRY_FLAG_EXEC: usize = 0; 10940fe15e0SLoGin 110a17651b1SMemoryShore const ENTRY_FLAG_ACCESSED: usize = 1 << 5; 111a17651b1SMemoryShore const ENTRY_FLAG_DIRTY: usize = 1 << 6; 112a17651b1SMemoryShore const ENTRY_FLAG_HUGE_PAGE: usize = 1 << 7; 113a17651b1SMemoryShore const ENTRY_FLAG_GLOBAL: usize = 1 << 8; 11492849878SLoGin 11540fe15e0SLoGin /// 物理地址与虚拟地址的偏移量 11640fe15e0SLoGin /// 0xffff_8000_0000_0000 11740fe15e0SLoGin const PHYS_OFFSET: usize = Self::PAGE_NEGATIVE_MASK + (Self::PAGE_ADDRESS_SIZE >> 1); 118453452ccSLoGin const KERNEL_LINK_OFFSET: usize = 0x100000; 11940fe15e0SLoGin 1205d549a76SChiichen // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/arch/x86/include/asm/page_64_types.h#75 1215d549a76SChiichen const USER_END_VADDR: VirtAddr = 1225d549a76SChiichen VirtAddr::new((Self::PAGE_ADDRESS_SIZE >> 1) - Self::PAGE_SIZE); 12340fe15e0SLoGin const USER_BRK_START: VirtAddr = VirtAddr::new(0x700000000000); 12440fe15e0SLoGin const USER_STACK_START: VirtAddr = VirtAddr::new(0x6ffff0a00000); 12540fe15e0SLoGin 12674ffde66SLoGin const FIXMAP_START_VADDR: VirtAddr = VirtAddr::new(0xffffb00000000000); 12774ffde66SLoGin /// 设置FIXMAP区域大小为1M 12874ffde66SLoGin const FIXMAP_SIZE: usize = 256 * 4096; 12974ffde66SLoGin 13023ef2b33SLoGin const MMIO_BASE: VirtAddr = VirtAddr::new(0xffffa10000000000); 13123ef2b33SLoGin const MMIO_SIZE: usize = 1 << PAGE_1G_SHIFT; 13223ef2b33SLoGin 13340fe15e0SLoGin /// @brief 获取物理内存区域 13445626c85SLoGin unsafe fn init() { 13540fe15e0SLoGin extern "C" { 13640fe15e0SLoGin fn _text(); 13740fe15e0SLoGin fn _etext(); 13840fe15e0SLoGin fn _edata(); 13940fe15e0SLoGin fn _erodata(); 14040fe15e0SLoGin fn _end(); 14140fe15e0SLoGin } 14240fe15e0SLoGin 14340fe15e0SLoGin Self::init_xd_rsvd(); 14499dbf38dSLoGin let load_base_paddr = Self::get_load_base_paddr(); 14540fe15e0SLoGin 14640fe15e0SLoGin let bootstrap_info = X86_64MMBootstrapInfo { 14799dbf38dSLoGin kernel_load_base_paddr: load_base_paddr.data(), 14840fe15e0SLoGin kernel_code_start: _text as usize, 14940fe15e0SLoGin kernel_code_end: _etext as usize, 15040fe15e0SLoGin kernel_data_end: _edata as usize, 15140fe15e0SLoGin kernel_rodata_end: _erodata as usize, 15240fe15e0SLoGin start_brk: _end as usize, 15340fe15e0SLoGin }; 15499dbf38dSLoGin 15540fe15e0SLoGin unsafe { 15640fe15e0SLoGin BOOTSTRAP_MM_INFO = Some(bootstrap_info); 15740fe15e0SLoGin } 15840fe15e0SLoGin 15940fe15e0SLoGin // 初始化物理内存区域(从multiboot2中获取) 16040fe15e0SLoGin Self::init_memory_area_from_multiboot2().expect("init memory area failed"); 16199dbf38dSLoGin 162453452ccSLoGin kdebug!("bootstrap info: {:?}", unsafe { BOOTSTRAP_MM_INFO }); 163453452ccSLoGin kdebug!("phys[0]=virt[0x{:x}]", unsafe { 164453452ccSLoGin MMArch::phys_2_virt(PhysAddr::new(0)).unwrap().data() 165453452ccSLoGin }); 166453452ccSLoGin 167453452ccSLoGin // 初始化内存管理器 168453452ccSLoGin unsafe { allocator_init() }; 1698cb2e9b3SLoGin 170453452ccSLoGin send_to_default_serial8250_port("x86 64 init done\n\0".as_bytes()); 17140fe15e0SLoGin } 17240fe15e0SLoGin 17340fe15e0SLoGin /// @brief 刷新TLB中,关于指定虚拟地址的条目 17440fe15e0SLoGin unsafe fn invalidate_page(address: VirtAddr) { 17540fe15e0SLoGin compiler_fence(Ordering::SeqCst); 17640fe15e0SLoGin asm!("invlpg [{0}]", in(reg) address.data(), options(nostack, preserves_flags)); 17740fe15e0SLoGin compiler_fence(Ordering::SeqCst); 17840fe15e0SLoGin } 17940fe15e0SLoGin 18040fe15e0SLoGin /// @brief 刷新TLB中,所有的条目 18140fe15e0SLoGin unsafe fn invalidate_all() { 18240fe15e0SLoGin compiler_fence(Ordering::SeqCst); 18340fe15e0SLoGin // 通过设置cr3寄存器,来刷新整个TLB 18440fe15e0SLoGin Self::set_table(PageTableKind::User, Self::table(PageTableKind::User)); 18540fe15e0SLoGin compiler_fence(Ordering::SeqCst); 18640fe15e0SLoGin } 18740fe15e0SLoGin 18840fe15e0SLoGin /// @brief 获取顶级页表的物理地址 18940314b30SXiaoye Zheng unsafe fn table(table_kind: PageTableKind) -> PhysAddr { 19040314b30SXiaoye Zheng match table_kind { 19140314b30SXiaoye Zheng PageTableKind::Kernel | PageTableKind::User => { 19240fe15e0SLoGin compiler_fence(Ordering::SeqCst); 1938cb2e9b3SLoGin let cr3 = x86::controlregs::cr3() as usize; 19440fe15e0SLoGin compiler_fence(Ordering::SeqCst); 1958cb2e9b3SLoGin return PhysAddr::new(cr3); 19640fe15e0SLoGin } 19740314b30SXiaoye Zheng PageTableKind::EPT => { 19840314b30SXiaoye Zheng let eptp = 19940314b30SXiaoye Zheng vmx_vmread(VmcsFields::CTRL_EPTP_PTR as u32).expect("Failed to read eptp"); 20040314b30SXiaoye Zheng return PhysAddr::new(eptp as usize); 20140314b30SXiaoye Zheng } 20240314b30SXiaoye Zheng } 20340314b30SXiaoye Zheng } 20440fe15e0SLoGin 20540fe15e0SLoGin /// @brief 设置顶级页表的物理地址到处理器中 20640fe15e0SLoGin unsafe fn set_table(_table_kind: PageTableKind, table: PhysAddr) { 20740fe15e0SLoGin compiler_fence(Ordering::SeqCst); 20840fe15e0SLoGin asm!("mov cr3, {}", in(reg) table.data(), options(nostack, preserves_flags)); 20940fe15e0SLoGin compiler_fence(Ordering::SeqCst); 21040fe15e0SLoGin } 21140fe15e0SLoGin 21240fe15e0SLoGin /// @brief 判断虚拟地址是否合法 21340fe15e0SLoGin fn virt_is_valid(virt: VirtAddr) -> bool { 21440fe15e0SLoGin return virt.is_canonical(); 21540fe15e0SLoGin } 21640fe15e0SLoGin 21740fe15e0SLoGin /// 获取内存管理初始化时,创建的第一个内核页表的地址 21840fe15e0SLoGin fn initial_page_table() -> PhysAddr { 21940fe15e0SLoGin unsafe { 22040fe15e0SLoGin return INITIAL_CR3_VALUE; 22140fe15e0SLoGin } 22240fe15e0SLoGin } 22340fe15e0SLoGin 22440fe15e0SLoGin /// @brief 创建新的顶层页表 225d4f3de93Slogin /// 22640fe15e0SLoGin /// 该函数会创建页表并复制内核的映射到新的页表中 227d4f3de93Slogin /// 22840fe15e0SLoGin /// @return 新的页表 22940fe15e0SLoGin fn setup_new_usermapper() -> Result<crate::mm::ucontext::UserMapper, SystemError> { 23040fe15e0SLoGin let new_umapper: crate::mm::page::PageMapper<X86_64MMArch, LockedFrameAllocator> = unsafe { 23140fe15e0SLoGin PageMapper::create(PageTableKind::User, LockedFrameAllocator) 23240fe15e0SLoGin .ok_or(SystemError::ENOMEM)? 23340fe15e0SLoGin }; 23440fe15e0SLoGin 23540fe15e0SLoGin let current_ktable: KernelMapper = KernelMapper::lock(); 23640fe15e0SLoGin let copy_mapping = |pml4_entry_no| unsafe { 23740fe15e0SLoGin let entry: PageEntry<X86_64MMArch> = current_ktable 23840fe15e0SLoGin .table() 23940fe15e0SLoGin .entry(pml4_entry_no) 24040fe15e0SLoGin .unwrap_or_else(|| panic!("entry {} not found", pml4_entry_no)); 24140fe15e0SLoGin new_umapper.table().set_entry(pml4_entry_no, entry) 24240fe15e0SLoGin }; 24340fe15e0SLoGin 24440fe15e0SLoGin // 复制内核的映射 245a17651b1SMemoryShore for pml4_entry_no in MMArch::PAGE_KERNEL_INDEX..MMArch::PAGE_ENTRY_NUM { 24640fe15e0SLoGin copy_mapping(pml4_entry_no); 24740fe15e0SLoGin } 24840fe15e0SLoGin 24940fe15e0SLoGin return Ok(crate::mm::ucontext::UserMapper::new(new_umapper)); 25040fe15e0SLoGin } 2514fda81ceSLoGin 2524fda81ceSLoGin const PAGE_SIZE: usize = 1 << Self::PAGE_SHIFT; 2534fda81ceSLoGin 2544fda81ceSLoGin const PAGE_OFFSET_MASK: usize = Self::PAGE_SIZE - 1; 2554fda81ceSLoGin 2564fda81ceSLoGin const PAGE_MASK: usize = !(Self::PAGE_OFFSET_MASK); 2574fda81ceSLoGin 2584fda81ceSLoGin const PAGE_ADDRESS_SHIFT: usize = Self::PAGE_LEVELS * Self::PAGE_ENTRY_SHIFT + Self::PAGE_SHIFT; 2594fda81ceSLoGin 2604fda81ceSLoGin const PAGE_ADDRESS_SIZE: usize = 1 << Self::PAGE_ADDRESS_SHIFT; 2614fda81ceSLoGin 2624fda81ceSLoGin const PAGE_ADDRESS_MASK: usize = Self::PAGE_ADDRESS_SIZE - Self::PAGE_SIZE; 2634fda81ceSLoGin 2644fda81ceSLoGin const PAGE_ENTRY_SIZE: usize = 1 << (Self::PAGE_SHIFT - Self::PAGE_ENTRY_SHIFT); 2654fda81ceSLoGin 2664fda81ceSLoGin const PAGE_ENTRY_NUM: usize = 1 << Self::PAGE_ENTRY_SHIFT; 2674fda81ceSLoGin 2684fda81ceSLoGin const PAGE_ENTRY_MASK: usize = Self::PAGE_ENTRY_NUM - 1; 2694fda81ceSLoGin 270a17651b1SMemoryShore const PAGE_KERNEL_INDEX: usize = (Self::PHYS_OFFSET & Self::PAGE_ADDRESS_MASK) 271a17651b1SMemoryShore >> (Self::PAGE_ADDRESS_SHIFT - Self::PAGE_ENTRY_SHIFT); 272a17651b1SMemoryShore 2734fda81ceSLoGin const PAGE_NEGATIVE_MASK: usize = !((Self::PAGE_ADDRESS_SIZE) - 1); 2744fda81ceSLoGin 2754fda81ceSLoGin const ENTRY_ADDRESS_SIZE: usize = 1 << Self::ENTRY_ADDRESS_SHIFT; 2764fda81ceSLoGin 2774fda81ceSLoGin const ENTRY_ADDRESS_MASK: usize = Self::ENTRY_ADDRESS_SIZE - Self::PAGE_SIZE; 2784fda81ceSLoGin 2794fda81ceSLoGin const ENTRY_FLAGS_MASK: usize = !Self::ENTRY_ADDRESS_MASK; 2804fda81ceSLoGin 2814fda81ceSLoGin unsafe fn read<T>(address: VirtAddr) -> T { 2824fda81ceSLoGin return core::ptr::read(address.data() as *const T); 2834fda81ceSLoGin } 2844fda81ceSLoGin 2854fda81ceSLoGin unsafe fn write<T>(address: VirtAddr, value: T) { 2864fda81ceSLoGin core::ptr::write(address.data() as *mut T, value); 2874fda81ceSLoGin } 2884fda81ceSLoGin 2894fda81ceSLoGin unsafe fn write_bytes(address: VirtAddr, value: u8, count: usize) { 2904fda81ceSLoGin core::ptr::write_bytes(address.data() as *mut u8, value, count); 2914fda81ceSLoGin } 2924fda81ceSLoGin 2934fda81ceSLoGin unsafe fn phys_2_virt(phys: PhysAddr) -> Option<VirtAddr> { 2944fda81ceSLoGin if let Some(vaddr) = phys.data().checked_add(Self::PHYS_OFFSET) { 2954fda81ceSLoGin return Some(VirtAddr::new(vaddr)); 2964fda81ceSLoGin } else { 2974fda81ceSLoGin return None; 2984fda81ceSLoGin } 2994fda81ceSLoGin } 3004fda81ceSLoGin 3014fda81ceSLoGin unsafe fn virt_2_phys(virt: VirtAddr) -> Option<PhysAddr> { 3024fda81ceSLoGin if let Some(paddr) = virt.data().checked_sub(Self::PHYS_OFFSET) { 3034fda81ceSLoGin return Some(PhysAddr::new(paddr)); 3044fda81ceSLoGin } else { 3054fda81ceSLoGin return None; 3064fda81ceSLoGin } 3074fda81ceSLoGin } 3087a29d4fcSLoGin 3097a29d4fcSLoGin #[inline(always)] 3107a29d4fcSLoGin fn make_entry(paddr: PhysAddr, page_flags: usize) -> usize { 3117a29d4fcSLoGin return paddr.data() | page_flags; 3127a29d4fcSLoGin } 313a17651b1SMemoryShore 314a17651b1SMemoryShore fn vma_access_permitted( 315a17651b1SMemoryShore vma: Arc<LockedVMA>, 316a17651b1SMemoryShore write: bool, 317a17651b1SMemoryShore execute: bool, 318a17651b1SMemoryShore foreign: bool, 319a17651b1SMemoryShore ) -> bool { 320a17651b1SMemoryShore if execute { 321a17651b1SMemoryShore return true; 322a17651b1SMemoryShore } 323a17651b1SMemoryShore if foreign | vma.is_foreign() { 324a17651b1SMemoryShore return true; 325a17651b1SMemoryShore } 326a17651b1SMemoryShore pkru::pkru_allows_pkey(pkru::vma_pkey(vma), write) 327a17651b1SMemoryShore } 32840fe15e0SLoGin } 32940fe15e0SLoGin 33040fe15e0SLoGin impl X86_64MMArch { 33199dbf38dSLoGin unsafe fn get_load_base_paddr() -> PhysAddr { 33299dbf38dSLoGin let mut mb2_lb_info: [multiboot_tag_load_base_addr_t; 512] = mem::zeroed(); 33399dbf38dSLoGin send_to_default_serial8250_port("get_load_base_paddr begin\n\0".as_bytes()); 33499dbf38dSLoGin 33599dbf38dSLoGin let mut mb2_count: u32 = 0; 33699dbf38dSLoGin multiboot2_iter( 33799dbf38dSLoGin Some(multiboot2_get_load_base), 33899dbf38dSLoGin &mut mb2_lb_info as *mut [multiboot_tag_load_base_addr_t; 512] as usize as *mut c_void, 33999dbf38dSLoGin &mut mb2_count, 34099dbf38dSLoGin ); 34199dbf38dSLoGin 34299dbf38dSLoGin if mb2_count == 0 { 34399dbf38dSLoGin send_to_default_serial8250_port( 34499dbf38dSLoGin "get_load_base_paddr mb2_count == 0, default to 1MB\n\0".as_bytes(), 34599dbf38dSLoGin ); 34699dbf38dSLoGin return PhysAddr::new(0x100000); 34799dbf38dSLoGin } 34899dbf38dSLoGin 34999dbf38dSLoGin let phys = mb2_lb_info[0].load_base_addr as usize; 35099dbf38dSLoGin 35199dbf38dSLoGin return PhysAddr::new(phys); 35299dbf38dSLoGin } 35340fe15e0SLoGin unsafe fn init_memory_area_from_multiboot2() -> Result<usize, SystemError> { 35440fe15e0SLoGin // 这个数组用来存放内存区域的信息(从C获取) 35540fe15e0SLoGin let mut mb2_mem_info: [multiboot_mmap_entry_t; 512] = mem::zeroed(); 356a03c4f9dSLoGin send_to_default_serial8250_port("init_memory_area_from_multiboot2 begin\n\0".as_bytes()); 35740fe15e0SLoGin 35840fe15e0SLoGin let mut mb2_count: u32 = 0; 35940fe15e0SLoGin multiboot2_iter( 36040fe15e0SLoGin Some(multiboot2_get_memory), 36140fe15e0SLoGin &mut mb2_mem_info as *mut [multiboot_mmap_entry_t; 512] as usize as *mut c_void, 36240fe15e0SLoGin &mut mb2_count, 36340fe15e0SLoGin ); 364a03c4f9dSLoGin send_to_default_serial8250_port("init_memory_area_from_multiboot2 2\n\0".as_bytes()); 36540fe15e0SLoGin 36640fe15e0SLoGin let mb2_count = mb2_count as usize; 36740fe15e0SLoGin let mut areas_count = 0usize; 36840fe15e0SLoGin let mut total_mem_size = 0usize; 369b5b571e0SLoGin for info_entry in mb2_mem_info.iter().take(mb2_count) { 37040fe15e0SLoGin // Only use the memory area if its type is 1 (RAM) 371b5b571e0SLoGin if info_entry.type_ == 1 { 37240fe15e0SLoGin // Skip the memory area if its len is 0 373b5b571e0SLoGin if info_entry.len == 0 { 37440fe15e0SLoGin continue; 37540fe15e0SLoGin } 37645626c85SLoGin 377b5b571e0SLoGin total_mem_size += info_entry.len as usize; 37845626c85SLoGin 37945626c85SLoGin mem_block_manager() 38045626c85SLoGin .add_block( 381b5b571e0SLoGin PhysAddr::new(info_entry.addr as usize), 382b5b571e0SLoGin info_entry.len as usize, 38345626c85SLoGin ) 38445626c85SLoGin .unwrap_or_else(|e| { 38545626c85SLoGin kwarn!( 38645626c85SLoGin "Failed to add memory block: base={:#x}, size={:#x}, error={:?}", 387b5b571e0SLoGin info_entry.addr, 388b5b571e0SLoGin info_entry.len, 38945626c85SLoGin e 39045626c85SLoGin ); 39145626c85SLoGin }); 39240fe15e0SLoGin areas_count += 1; 39340fe15e0SLoGin } 39440fe15e0SLoGin } 395a03c4f9dSLoGin send_to_default_serial8250_port("init_memory_area_from_multiboot2 end\n\0".as_bytes()); 39640fe15e0SLoGin kinfo!("Total memory size: {} MB, total areas from multiboot2: {mb2_count}, valid areas: {areas_count}", total_mem_size / 1024 / 1024); 39740fe15e0SLoGin return Ok(areas_count); 39840fe15e0SLoGin } 39940fe15e0SLoGin 40040fe15e0SLoGin fn init_xd_rsvd() { 40140fe15e0SLoGin // 读取ia32-EFER寄存器的值 40240fe15e0SLoGin let efer: EferFlags = x86_64::registers::model_specific::Efer::read(); 40340fe15e0SLoGin if !efer.contains(EferFlags::NO_EXECUTE_ENABLE) { 40440fe15e0SLoGin // NO_EXECUTE_ENABLE是false,那么就设置xd_reserved为true 40540fe15e0SLoGin kdebug!("NO_EXECUTE_ENABLE is false, set XD_RESERVED to true"); 40640fe15e0SLoGin XD_RESERVED.store(true, Ordering::Relaxed); 40740fe15e0SLoGin } 40840fe15e0SLoGin compiler_fence(Ordering::SeqCst); 40940fe15e0SLoGin } 41040fe15e0SLoGin 41140fe15e0SLoGin /// 判断XD标志位是否被保留 41240fe15e0SLoGin pub fn is_xd_reserved() -> bool { 41399dbf38dSLoGin // return XD_RESERVED.load(Ordering::Relaxed); 41499dbf38dSLoGin 41599dbf38dSLoGin // 由于暂时不支持execute disable,因此直接返回true 41699dbf38dSLoGin // 不支持的原因是,目前好像没有能正确的设置page-level的xd位,会触发page fault 41799dbf38dSLoGin return true; 41840fe15e0SLoGin } 41940fe15e0SLoGin } 42040fe15e0SLoGin 42140fe15e0SLoGin impl VirtAddr { 42240fe15e0SLoGin /// @brief 判断虚拟地址是否合法 423d4f3de93Slogin #[inline(always)] 42440fe15e0SLoGin pub fn is_canonical(self) -> bool { 42540fe15e0SLoGin let x = self.data() & X86_64MMArch::PHYS_OFFSET; 42640fe15e0SLoGin // 如果x为0,说明虚拟地址的高位为0,是合法的用户地址 42740fe15e0SLoGin // 如果x为PHYS_OFFSET,说明虚拟地址的高位全为1,是合法的内核地址 42840fe15e0SLoGin return x == 0 || x == X86_64MMArch::PHYS_OFFSET; 42940fe15e0SLoGin } 43040fe15e0SLoGin } 43140fe15e0SLoGin 43240fe15e0SLoGin unsafe fn allocator_init() { 433da152319SLoGin let virt_offset = VirtAddr::new(page_align_up(BOOTSTRAP_MM_INFO.unwrap().start_brk)); 43440fe15e0SLoGin 435da152319SLoGin let phy_offset = unsafe { MMArch::virt_2_phys(virt_offset) }.unwrap(); 436da152319SLoGin 437da152319SLoGin mem_block_manager() 438da152319SLoGin .reserve_block(PhysAddr::new(0), phy_offset.data()) 439da152319SLoGin .expect("Failed to reserve block"); 44045626c85SLoGin let mut bump_allocator = BumpAllocator::<X86_64MMArch>::new(phy_offset.data()); 44140fe15e0SLoGin kdebug!( 44240fe15e0SLoGin "BumpAllocator created, offset={:?}", 44340fe15e0SLoGin bump_allocator.offset() 44440fe15e0SLoGin ); 44540fe15e0SLoGin 44640fe15e0SLoGin // 暂存初始在head.S中指定的页表的地址,后面再考虑是否需要把它加到buddy的可用空间里面! 44740fe15e0SLoGin // 现在不加的原因是,我担心会有安全漏洞问题:这些初始的页表,位于内核的数据段。如果归还到buddy, 44840fe15e0SLoGin // 可能会产生一定的安全风险(有的代码可能根据虚拟地址来进行安全校验) 44940fe15e0SLoGin let _old_page_table = MMArch::table(PageTableKind::Kernel); 45040fe15e0SLoGin 45140fe15e0SLoGin let new_page_table: PhysAddr; 45240fe15e0SLoGin // 使用bump分配器,把所有的内存页都映射到页表 45340fe15e0SLoGin { 45440fe15e0SLoGin // 用bump allocator创建新的页表 45540fe15e0SLoGin let mut mapper: crate::mm::page::PageMapper<MMArch, &mut BumpAllocator<MMArch>> = 45640fe15e0SLoGin crate::mm::page::PageMapper::<MMArch, _>::create( 45740fe15e0SLoGin PageTableKind::Kernel, 45840fe15e0SLoGin &mut bump_allocator, 45940fe15e0SLoGin ) 46040fe15e0SLoGin .expect("Failed to create page mapper"); 46140fe15e0SLoGin new_page_table = mapper.table().phys(); 46240fe15e0SLoGin kdebug!("PageMapper created"); 46340fe15e0SLoGin 46440fe15e0SLoGin // 取消最开始时候,在head.S中指定的映射(暂时不刷新TLB) 46540fe15e0SLoGin { 46640fe15e0SLoGin let table = mapper.table(); 4677a29d4fcSLoGin let empty_entry = PageEntry::<MMArch>::from_usize(0); 46840fe15e0SLoGin for i in 0..MMArch::PAGE_ENTRY_NUM { 46940fe15e0SLoGin table 47040fe15e0SLoGin .set_entry(i, empty_entry) 47140fe15e0SLoGin .expect("Failed to empty page table entry"); 47240fe15e0SLoGin } 47340fe15e0SLoGin } 47440fe15e0SLoGin kdebug!("Successfully emptied page table"); 47540fe15e0SLoGin 47645626c85SLoGin let total_num = mem_block_manager().total_initial_memory_regions(); 47745626c85SLoGin for i in 0..total_num { 47845626c85SLoGin let area = mem_block_manager().get_initial_memory_region(i).unwrap(); 47940fe15e0SLoGin // kdebug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size); 48040fe15e0SLoGin for i in 0..((area.size + MMArch::PAGE_SIZE - 1) / MMArch::PAGE_SIZE) { 48140fe15e0SLoGin let paddr = area.base.add(i * MMArch::PAGE_SIZE); 48240fe15e0SLoGin let vaddr = unsafe { MMArch::phys_2_virt(paddr) }.unwrap(); 48340fe15e0SLoGin let flags = kernel_page_flags::<MMArch>(vaddr); 48440fe15e0SLoGin 48540fe15e0SLoGin let flusher = mapper 48640fe15e0SLoGin .map_phys(vaddr, paddr, flags) 48740fe15e0SLoGin .expect("Failed to map frame"); 48840fe15e0SLoGin // 暂时不刷新TLB 48940fe15e0SLoGin flusher.ignore(); 49040fe15e0SLoGin } 49140fe15e0SLoGin } 49240fe15e0SLoGin } 493d4f3de93Slogin 494d4f3de93Slogin unsafe { 49540fe15e0SLoGin INITIAL_CR3_VALUE = new_page_table; 496d4f3de93Slogin } 49740fe15e0SLoGin kdebug!( 49840fe15e0SLoGin "After mapping all physical memory, DragonOS used: {} KB", 49940fe15e0SLoGin bump_allocator.offset() / 1024 50040fe15e0SLoGin ); 50140fe15e0SLoGin 50240fe15e0SLoGin // 初始化buddy_allocator 50340fe15e0SLoGin let buddy_allocator = unsafe { BuddyAllocator::<X86_64MMArch>::new(bump_allocator).unwrap() }; 50440fe15e0SLoGin // 设置全局的页帧分配器 50540fe15e0SLoGin unsafe { set_inner_allocator(buddy_allocator) }; 50640fe15e0SLoGin kinfo!("Successfully initialized buddy allocator"); 50740fe15e0SLoGin // 关闭显示输出 508abe3a6eaShanjiezhou scm_disable_put_to_window(); 509abe3a6eaShanjiezhou 51040fe15e0SLoGin // make the new page table current 51140fe15e0SLoGin { 51240fe15e0SLoGin let mut binding = INNER_ALLOCATOR.lock(); 51340fe15e0SLoGin let mut allocator_guard = binding.as_mut().unwrap(); 51440fe15e0SLoGin kdebug!("To enable new page table."); 51540fe15e0SLoGin compiler_fence(Ordering::SeqCst); 51640fe15e0SLoGin let mapper = crate::mm::page::PageMapper::<MMArch, _>::new( 51740fe15e0SLoGin PageTableKind::Kernel, 51840fe15e0SLoGin new_page_table, 51940fe15e0SLoGin &mut allocator_guard, 52040fe15e0SLoGin ); 52140fe15e0SLoGin compiler_fence(Ordering::SeqCst); 52240fe15e0SLoGin mapper.make_current(); 52340fe15e0SLoGin compiler_fence(Ordering::SeqCst); 52440fe15e0SLoGin kdebug!("New page table enabled"); 52540fe15e0SLoGin } 52640fe15e0SLoGin kdebug!("Successfully enabled new page table"); 52740fe15e0SLoGin } 52840fe15e0SLoGin 52940fe15e0SLoGin #[no_mangle] 53040fe15e0SLoGin pub extern "C" fn rs_test_buddy() { 53140fe15e0SLoGin test_buddy(); 53240fe15e0SLoGin } 53340fe15e0SLoGin pub fn test_buddy() { 53440fe15e0SLoGin // 申请内存然后写入数据然后free掉 53540fe15e0SLoGin // 总共申请200MB内存 53640fe15e0SLoGin const TOTAL_SIZE: usize = 200 * 1024 * 1024; 53740fe15e0SLoGin 53840fe15e0SLoGin for i in 0..10 { 53940fe15e0SLoGin kdebug!("Test buddy, round: {i}"); 54040fe15e0SLoGin // 存放申请的内存块 54140fe15e0SLoGin let mut v: Vec<(PhysAddr, PageFrameCount)> = Vec::with_capacity(60 * 1024); 54240fe15e0SLoGin // 存放已经申请的内存块的地址(用于检查重复) 54340fe15e0SLoGin let mut addr_set: HashSet<PhysAddr> = HashSet::new(); 54440fe15e0SLoGin 54540fe15e0SLoGin let mut allocated = 0usize; 54640fe15e0SLoGin 54740fe15e0SLoGin let mut free_count = 0usize; 54840fe15e0SLoGin 54940fe15e0SLoGin while allocated < TOTAL_SIZE { 55040fe15e0SLoGin let mut random_size = 0u64; 55140fe15e0SLoGin unsafe { x86::random::rdrand64(&mut random_size) }; 55240fe15e0SLoGin // 一次最多申请4M 553b5b571e0SLoGin random_size %= 1024 * 4096; 55440fe15e0SLoGin if random_size == 0 { 55540fe15e0SLoGin continue; 55640fe15e0SLoGin } 55740fe15e0SLoGin let random_size = 55840fe15e0SLoGin core::cmp::min(page_align_up(random_size as usize), TOTAL_SIZE - allocated); 55940fe15e0SLoGin let random_size = PageFrameCount::from_bytes(random_size.next_power_of_two()).unwrap(); 56040fe15e0SLoGin // 获取帧 56140fe15e0SLoGin let (paddr, allocated_frame_count) = 56240fe15e0SLoGin unsafe { LockedFrameAllocator.allocate(random_size).unwrap() }; 56340fe15e0SLoGin assert!(allocated_frame_count.data().is_power_of_two()); 56440fe15e0SLoGin assert!(paddr.data() % MMArch::PAGE_SIZE == 0); 56540fe15e0SLoGin unsafe { 56640fe15e0SLoGin assert!(MMArch::phys_2_virt(paddr) 56740fe15e0SLoGin .as_ref() 56840fe15e0SLoGin .unwrap() 56940fe15e0SLoGin .check_aligned(allocated_frame_count.data() * MMArch::PAGE_SIZE)); 57040fe15e0SLoGin } 57140fe15e0SLoGin allocated += allocated_frame_count.data() * MMArch::PAGE_SIZE; 57240fe15e0SLoGin v.push((paddr, allocated_frame_count)); 57340fe15e0SLoGin assert!(addr_set.insert(paddr), "duplicate address: {:?}", paddr); 57440fe15e0SLoGin 57540fe15e0SLoGin // 写入数据 57640fe15e0SLoGin let vaddr = unsafe { MMArch::phys_2_virt(paddr).unwrap() }; 57740fe15e0SLoGin let slice = unsafe { 57840fe15e0SLoGin core::slice::from_raw_parts_mut( 57940fe15e0SLoGin vaddr.data() as *mut u8, 58040fe15e0SLoGin allocated_frame_count.data() * MMArch::PAGE_SIZE, 58140fe15e0SLoGin ) 58240fe15e0SLoGin }; 583b5b571e0SLoGin for (i, item) in slice.iter_mut().enumerate() { 584b5b571e0SLoGin *item = ((i + unsafe { rdtsc() } as usize) % 256) as u8; 58540fe15e0SLoGin } 58640fe15e0SLoGin 58740fe15e0SLoGin // 随机释放一个内存块 588b5b571e0SLoGin if !v.is_empty() { 58940fe15e0SLoGin let mut random_index = 0u64; 59040fe15e0SLoGin unsafe { x86::random::rdrand64(&mut random_index) }; 59140fe15e0SLoGin // 70%概率释放 59240fe15e0SLoGin if random_index % 10 > 7 { 59340fe15e0SLoGin continue; 59440fe15e0SLoGin } 595b5b571e0SLoGin random_index %= v.len() as u64; 59640fe15e0SLoGin let random_index = random_index as usize; 59740fe15e0SLoGin let (paddr, allocated_frame_count) = v.remove(random_index); 59840fe15e0SLoGin assert!(addr_set.remove(&paddr)); 59940fe15e0SLoGin unsafe { LockedFrameAllocator.free(paddr, allocated_frame_count) }; 60040fe15e0SLoGin free_count += allocated_frame_count.data() * MMArch::PAGE_SIZE; 60140fe15e0SLoGin } 60240fe15e0SLoGin } 60340fe15e0SLoGin 60440fe15e0SLoGin kdebug!( 60540fe15e0SLoGin "Allocated {} MB memory, release: {} MB, no release: {} bytes", 60640fe15e0SLoGin allocated / 1024 / 1024, 60740fe15e0SLoGin free_count / 1024 / 1024, 60840fe15e0SLoGin (allocated - free_count) 60940fe15e0SLoGin ); 61040fe15e0SLoGin 61140fe15e0SLoGin kdebug!("Now, to release buddy memory"); 61240fe15e0SLoGin // 释放所有的内存 61340fe15e0SLoGin for (paddr, allocated_frame_count) in v { 61440fe15e0SLoGin unsafe { LockedFrameAllocator.free(paddr, allocated_frame_count) }; 61540fe15e0SLoGin assert!(addr_set.remove(&paddr)); 61640fe15e0SLoGin free_count += allocated_frame_count.data() * MMArch::PAGE_SIZE; 61740fe15e0SLoGin } 61840fe15e0SLoGin 61940fe15e0SLoGin kdebug!("release done!, allocated: {allocated}, free_count: {free_count}"); 62040fe15e0SLoGin } 62140fe15e0SLoGin } 6224fda81ceSLoGin 62340fe15e0SLoGin /// 全局的页帧分配器 62440fe15e0SLoGin #[derive(Debug, Clone, Copy, Hash)] 62540fe15e0SLoGin pub struct LockedFrameAllocator; 62640fe15e0SLoGin 62740fe15e0SLoGin impl FrameAllocator for LockedFrameAllocator { 6286fc066acSJomo unsafe fn allocate(&mut self, mut count: PageFrameCount) -> Option<(PhysAddr, PageFrameCount)> { 6296fc066acSJomo count = count.next_power_of_two(); 63040fe15e0SLoGin if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() { 63140fe15e0SLoGin return allocator.allocate(count); 63240fe15e0SLoGin } else { 63340fe15e0SLoGin return None; 63440fe15e0SLoGin } 63540fe15e0SLoGin } 63640fe15e0SLoGin 63734e6d6c8Syuyi2439 unsafe fn free(&mut self, address: crate::mm::PhysAddr, count: PageFrameCount) { 63840fe15e0SLoGin assert!(count.data().is_power_of_two()); 63940fe15e0SLoGin if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() { 64040fe15e0SLoGin return allocator.free(address, count); 64140fe15e0SLoGin } 64240fe15e0SLoGin } 64340fe15e0SLoGin 64434e6d6c8Syuyi2439 unsafe fn usage(&self) -> PageFrameUsage { 64534e6d6c8Syuyi2439 if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() { 64634e6d6c8Syuyi2439 return allocator.usage(); 64734e6d6c8Syuyi2439 } else { 64834e6d6c8Syuyi2439 panic!("usage error"); 64934e6d6c8Syuyi2439 } 65034e6d6c8Syuyi2439 } 65134e6d6c8Syuyi2439 } 65234e6d6c8Syuyi2439 65340fe15e0SLoGin /// 获取内核地址默认的页面标志 65440fe15e0SLoGin pub unsafe fn kernel_page_flags<A: MemoryManagementArch>(virt: VirtAddr) -> PageFlags<A> { 655b5b571e0SLoGin let info: X86_64MMBootstrapInfo = BOOTSTRAP_MM_INFO.unwrap(); 65640fe15e0SLoGin 65740fe15e0SLoGin if virt.data() >= info.kernel_code_start && virt.data() < info.kernel_code_end { 65840fe15e0SLoGin // Remap kernel code execute 65940fe15e0SLoGin return PageFlags::new().set_execute(true).set_write(true); 66040fe15e0SLoGin } else if virt.data() >= info.kernel_data_end && virt.data() < info.kernel_rodata_end { 66140fe15e0SLoGin // Remap kernel rodata read only 66240fe15e0SLoGin return PageFlags::new().set_execute(true); 66340fe15e0SLoGin } else { 66440fe15e0SLoGin return PageFlags::new().set_write(true).set_execute(true); 66540fe15e0SLoGin } 66640fe15e0SLoGin } 66740fe15e0SLoGin 66840fe15e0SLoGin unsafe fn set_inner_allocator(allocator: BuddyAllocator<MMArch>) { 66940fe15e0SLoGin static FLAG: AtomicBool = AtomicBool::new(false); 67040fe15e0SLoGin if FLAG 67140fe15e0SLoGin .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) 67240fe15e0SLoGin .is_err() 67340fe15e0SLoGin { 67440fe15e0SLoGin panic!("Cannot set inner allocator twice!"); 67540fe15e0SLoGin } 67640fe15e0SLoGin *INNER_ALLOCATOR.lock() = Some(allocator); 67740fe15e0SLoGin } 67840fe15e0SLoGin 67940fe15e0SLoGin /// 低地址重映射的管理器 68040fe15e0SLoGin /// 68140fe15e0SLoGin /// 低地址重映射的管理器,在smp初始化完成之前,需要使用低地址的映射,因此需要在smp初始化完成之后,取消这一段映射 68240fe15e0SLoGin pub struct LowAddressRemapping; 68340fe15e0SLoGin 68440fe15e0SLoGin impl LowAddressRemapping { 685453452ccSLoGin // 映射64M 686453452ccSLoGin const REMAP_SIZE: usize = 64 * 1024 * 1024; 68740fe15e0SLoGin 6888cb2e9b3SLoGin pub unsafe fn remap_at_low_address(mapper: &mut PageMapper) { 68940fe15e0SLoGin for i in 0..(Self::REMAP_SIZE / MMArch::PAGE_SIZE) { 69040fe15e0SLoGin let paddr = PhysAddr::new(i * MMArch::PAGE_SIZE); 69140fe15e0SLoGin let vaddr = VirtAddr::new(i * MMArch::PAGE_SIZE); 69240fe15e0SLoGin let flags = kernel_page_flags::<MMArch>(vaddr); 69340fe15e0SLoGin 69440fe15e0SLoGin let flusher = mapper 69540fe15e0SLoGin .map_phys(vaddr, paddr, flags) 69640fe15e0SLoGin .expect("Failed to map frame"); 69740fe15e0SLoGin // 暂时不刷新TLB 69840fe15e0SLoGin flusher.ignore(); 69940fe15e0SLoGin } 70040fe15e0SLoGin } 70140fe15e0SLoGin 70240fe15e0SLoGin /// 取消低地址的映射 7038cb2e9b3SLoGin pub unsafe fn unmap_at_low_address(mapper: &mut PageMapper, flush: bool) { 70440fe15e0SLoGin for i in 0..(Self::REMAP_SIZE / MMArch::PAGE_SIZE) { 70540fe15e0SLoGin let vaddr = VirtAddr::new(i * MMArch::PAGE_SIZE); 70626887c63SLoGin let (_, _, flusher) = mapper 70726887c63SLoGin .unmap_phys(vaddr, true) 70840fe15e0SLoGin .expect("Failed to unmap frame"); 709b5b571e0SLoGin if !flush { 71040fe15e0SLoGin flusher.ignore(); 71140fe15e0SLoGin } 71240fe15e0SLoGin } 71340fe15e0SLoGin } 71440fe15e0SLoGin } 715