1 pub mod barrier; 2 pub mod bump; 3 mod c_adapter; 4 5 use alloc::vec::Vec; 6 use hashbrown::HashSet; 7 use x86::time::rdtsc; 8 use x86_64::registers::model_specific::EferFlags; 9 10 use crate::driver::tty::serial::serial8250::send_to_default_serial8250_port; 11 use crate::filesystem::procfs::kmsg::kmsg_init; 12 use crate::include::bindings::bindings::{ 13 multiboot2_get_load_base, multiboot2_get_memory, multiboot2_iter, multiboot_mmap_entry_t, 14 multiboot_tag_load_base_addr_t, 15 }; 16 use crate::libs::align::page_align_up; 17 use crate::libs::lib_ui::screen_manager::scm_disable_put_to_window; 18 use crate::libs::printk::PrintkWriter; 19 use crate::libs::spinlock::SpinLock; 20 21 use crate::mm::allocator::page_frame::{FrameAllocator, PageFrameCount, PageFrameUsage}; 22 use crate::mm::memblock::mem_block_manager; 23 use crate::mm::mmio_buddy::mmio_init; 24 use crate::{ 25 arch::MMArch, 26 mm::allocator::{buddy::BuddyAllocator, bump::BumpAllocator}, 27 }; 28 29 use crate::mm::kernel_mapper::KernelMapper; 30 use crate::mm::page::{PageEntry, PageFlags}; 31 use crate::mm::{MemoryManagementArch, PageTableKind, PhysAddr, VirtAddr}; 32 use crate::{kdebug, kinfo, kwarn}; 33 use system_error::SystemError; 34 35 use core::arch::asm; 36 use core::ffi::c_void; 37 use core::fmt::{Debug, Write}; 38 use core::mem::{self}; 39 40 use core::sync::atomic::{compiler_fence, AtomicBool, Ordering}; 41 42 use super::kvm::vmx::vmcs::VmcsFields; 43 use super::kvm::vmx::vmx_asm_wrapper::vmx_vmread; 44 45 pub type PageMapper = 46 crate::mm::page::PageMapper<crate::arch::x86_64::mm::X86_64MMArch, LockedFrameAllocator>; 47 48 /// 初始的CR3寄存器的值,用于内存管理初始化时,创建的第一个内核页表的位置 49 static mut INITIAL_CR3_VALUE: PhysAddr = PhysAddr::new(0); 50 51 /// 内核的第一个页表在pml4中的索引 52 /// 顶级页表的[256, 512)项是内核的页表 53 static KERNEL_PML4E_NO: usize = (X86_64MMArch::PHYS_OFFSET & ((1 << 48) - 1)) >> 39; 54 55 static INNER_ALLOCATOR: SpinLock<Option<BuddyAllocator<MMArch>>> = SpinLock::new(None); 56 57 #[derive(Clone, Copy, Debug)] 58 pub struct X86_64MMBootstrapInfo { 59 kernel_load_base_paddr: usize, 60 kernel_code_start: usize, 61 kernel_code_end: usize, 62 kernel_data_end: usize, 63 kernel_rodata_end: usize, 64 start_brk: usize, 65 } 66 67 pub(super) static mut BOOTSTRAP_MM_INFO: Option<X86_64MMBootstrapInfo> = None; 68 69 /// @brief X86_64的内存管理架构结构体 70 #[derive(Debug, Clone, Copy, Hash)] 71 pub struct X86_64MMArch; 72 73 /// XD标志位是否被保留 74 static XD_RESERVED: AtomicBool = AtomicBool::new(false); 75 76 impl MemoryManagementArch for X86_64MMArch { 77 /// 4K页 78 const PAGE_SHIFT: usize = 12; 79 80 /// 每个页表项占8字节,总共有512个页表项 81 const PAGE_ENTRY_SHIFT: usize = 9; 82 83 /// 四级页表(PML4T、PDPT、PDT、PT) 84 const PAGE_LEVELS: usize = 4; 85 86 /// 页表项的有效位的index。在x86_64中,页表项的第[0, 47]位表示地址和flag, 87 /// 第[48, 51]位表示保留。因此,有效位的index为52。 88 /// 请注意,第63位是XD位,表示是否允许执行。 89 const ENTRY_ADDRESS_SHIFT: usize = 52; 90 91 const ENTRY_FLAG_DEFAULT_PAGE: usize = Self::ENTRY_FLAG_PRESENT; 92 93 const ENTRY_FLAG_DEFAULT_TABLE: usize = Self::ENTRY_FLAG_PRESENT; 94 95 const ENTRY_FLAG_PRESENT: usize = 1 << 0; 96 97 const ENTRY_FLAG_READONLY: usize = 0; 98 99 const ENTRY_FLAG_READWRITE: usize = 1 << 1; 100 101 const ENTRY_FLAG_USER: usize = 1 << 2; 102 103 const ENTRY_FLAG_WRITE_THROUGH: usize = 1 << 3; 104 105 const ENTRY_FLAG_CACHE_DISABLE: usize = 1 << 4; 106 107 const ENTRY_FLAG_NO_EXEC: usize = 1 << 63; 108 /// x86_64不存在EXEC标志位,只有NO_EXEC(XD)标志位 109 const ENTRY_FLAG_EXEC: usize = 0; 110 111 const ENTRY_FLAG_ACCESSED: usize = 0; 112 const ENTRY_FLAG_DIRTY: usize = 0; 113 114 /// 物理地址与虚拟地址的偏移量 115 /// 0xffff_8000_0000_0000 116 const PHYS_OFFSET: usize = Self::PAGE_NEGATIVE_MASK + (Self::PAGE_ADDRESS_SIZE >> 1); 117 118 // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/arch/x86/include/asm/page_64_types.h#75 119 const USER_END_VADDR: VirtAddr = 120 VirtAddr::new((Self::PAGE_ADDRESS_SIZE >> 1) - Self::PAGE_SIZE); 121 const USER_BRK_START: VirtAddr = VirtAddr::new(0x700000000000); 122 const USER_STACK_START: VirtAddr = VirtAddr::new(0x6ffff0a00000); 123 124 const FIXMAP_START_VADDR: VirtAddr = VirtAddr::new(0xffffb00000000000); 125 /// 设置FIXMAP区域大小为1M 126 const FIXMAP_SIZE: usize = 256 * 4096; 127 128 /// @brief 获取物理内存区域 129 unsafe fn init() { 130 extern "C" { 131 fn _text(); 132 fn _etext(); 133 fn _edata(); 134 fn _erodata(); 135 fn _end(); 136 } 137 138 Self::init_xd_rsvd(); 139 let load_base_paddr = Self::get_load_base_paddr(); 140 141 let bootstrap_info = X86_64MMBootstrapInfo { 142 kernel_load_base_paddr: load_base_paddr.data(), 143 kernel_code_start: _text as usize, 144 kernel_code_end: _etext as usize, 145 kernel_data_end: _edata as usize, 146 kernel_rodata_end: _erodata as usize, 147 start_brk: _end as usize, 148 }; 149 150 unsafe { 151 BOOTSTRAP_MM_INFO = Some(bootstrap_info); 152 } 153 154 // 初始化物理内存区域(从multiboot2中获取) 155 Self::init_memory_area_from_multiboot2().expect("init memory area failed"); 156 157 send_to_default_serial8250_port("x86 64 init end\n\0".as_bytes()); 158 } 159 160 /// @brief 刷新TLB中,关于指定虚拟地址的条目 161 unsafe fn invalidate_page(address: VirtAddr) { 162 compiler_fence(Ordering::SeqCst); 163 asm!("invlpg [{0}]", in(reg) address.data(), options(nostack, preserves_flags)); 164 compiler_fence(Ordering::SeqCst); 165 } 166 167 /// @brief 刷新TLB中,所有的条目 168 unsafe fn invalidate_all() { 169 compiler_fence(Ordering::SeqCst); 170 // 通过设置cr3寄存器,来刷新整个TLB 171 Self::set_table(PageTableKind::User, Self::table(PageTableKind::User)); 172 compiler_fence(Ordering::SeqCst); 173 } 174 175 /// @brief 获取顶级页表的物理地址 176 unsafe fn table(table_kind: PageTableKind) -> PhysAddr { 177 match table_kind { 178 PageTableKind::Kernel | PageTableKind::User => { 179 let paddr: usize; 180 compiler_fence(Ordering::SeqCst); 181 asm!("mov {}, cr3", out(reg) paddr, options(nomem, nostack, preserves_flags)); 182 compiler_fence(Ordering::SeqCst); 183 return PhysAddr::new(paddr); 184 } 185 PageTableKind::EPT => { 186 let eptp = 187 vmx_vmread(VmcsFields::CTRL_EPTP_PTR as u32).expect("Failed to read eptp"); 188 return PhysAddr::new(eptp as usize); 189 } 190 } 191 } 192 193 /// @brief 设置顶级页表的物理地址到处理器中 194 unsafe fn set_table(_table_kind: PageTableKind, table: PhysAddr) { 195 compiler_fence(Ordering::SeqCst); 196 asm!("mov cr3, {}", in(reg) table.data(), options(nostack, preserves_flags)); 197 compiler_fence(Ordering::SeqCst); 198 } 199 200 /// @brief 判断虚拟地址是否合法 201 fn virt_is_valid(virt: VirtAddr) -> bool { 202 return virt.is_canonical(); 203 } 204 205 /// 获取内存管理初始化时,创建的第一个内核页表的地址 206 fn initial_page_table() -> PhysAddr { 207 unsafe { 208 return INITIAL_CR3_VALUE; 209 } 210 } 211 212 /// @brief 创建新的顶层页表 213 /// 214 /// 该函数会创建页表并复制内核的映射到新的页表中 215 /// 216 /// @return 新的页表 217 fn setup_new_usermapper() -> Result<crate::mm::ucontext::UserMapper, SystemError> { 218 let new_umapper: crate::mm::page::PageMapper<X86_64MMArch, LockedFrameAllocator> = unsafe { 219 PageMapper::create(PageTableKind::User, LockedFrameAllocator) 220 .ok_or(SystemError::ENOMEM)? 221 }; 222 223 let current_ktable: KernelMapper = KernelMapper::lock(); 224 let copy_mapping = |pml4_entry_no| unsafe { 225 let entry: PageEntry<X86_64MMArch> = current_ktable 226 .table() 227 .entry(pml4_entry_no) 228 .unwrap_or_else(|| panic!("entry {} not found", pml4_entry_no)); 229 new_umapper.table().set_entry(pml4_entry_no, entry) 230 }; 231 232 // 复制内核的映射 233 for pml4_entry_no in KERNEL_PML4E_NO..512 { 234 copy_mapping(pml4_entry_no); 235 } 236 237 return Ok(crate::mm::ucontext::UserMapper::new(new_umapper)); 238 } 239 240 const PAGE_SIZE: usize = 1 << Self::PAGE_SHIFT; 241 242 const PAGE_OFFSET_MASK: usize = Self::PAGE_SIZE - 1; 243 244 const PAGE_MASK: usize = !(Self::PAGE_OFFSET_MASK); 245 246 const PAGE_ADDRESS_SHIFT: usize = Self::PAGE_LEVELS * Self::PAGE_ENTRY_SHIFT + Self::PAGE_SHIFT; 247 248 const PAGE_ADDRESS_SIZE: usize = 1 << Self::PAGE_ADDRESS_SHIFT; 249 250 const PAGE_ADDRESS_MASK: usize = Self::PAGE_ADDRESS_SIZE - Self::PAGE_SIZE; 251 252 const PAGE_ENTRY_SIZE: usize = 1 << (Self::PAGE_SHIFT - Self::PAGE_ENTRY_SHIFT); 253 254 const PAGE_ENTRY_NUM: usize = 1 << Self::PAGE_ENTRY_SHIFT; 255 256 const PAGE_ENTRY_MASK: usize = Self::PAGE_ENTRY_NUM - 1; 257 258 const PAGE_NEGATIVE_MASK: usize = !((Self::PAGE_ADDRESS_SIZE) - 1); 259 260 const ENTRY_ADDRESS_SIZE: usize = 1 << Self::ENTRY_ADDRESS_SHIFT; 261 262 const ENTRY_ADDRESS_MASK: usize = Self::ENTRY_ADDRESS_SIZE - Self::PAGE_SIZE; 263 264 const ENTRY_FLAGS_MASK: usize = !Self::ENTRY_ADDRESS_MASK; 265 266 unsafe fn read<T>(address: VirtAddr) -> T { 267 return core::ptr::read(address.data() as *const T); 268 } 269 270 unsafe fn write<T>(address: VirtAddr, value: T) { 271 core::ptr::write(address.data() as *mut T, value); 272 } 273 274 unsafe fn write_bytes(address: VirtAddr, value: u8, count: usize) { 275 core::ptr::write_bytes(address.data() as *mut u8, value, count); 276 } 277 278 unsafe fn phys_2_virt(phys: PhysAddr) -> Option<VirtAddr> { 279 if let Some(vaddr) = phys.data().checked_add(Self::PHYS_OFFSET) { 280 return Some(VirtAddr::new(vaddr)); 281 } else { 282 return None; 283 } 284 } 285 286 unsafe fn virt_2_phys(virt: VirtAddr) -> Option<PhysAddr> { 287 if let Some(paddr) = virt.data().checked_sub(Self::PHYS_OFFSET) { 288 return Some(PhysAddr::new(paddr)); 289 } else { 290 return None; 291 } 292 } 293 294 #[inline(always)] 295 fn make_entry(paddr: PhysAddr, page_flags: usize) -> usize { 296 return paddr.data() | page_flags; 297 } 298 } 299 300 impl X86_64MMArch { 301 unsafe fn get_load_base_paddr() -> PhysAddr { 302 let mut mb2_lb_info: [multiboot_tag_load_base_addr_t; 512] = mem::zeroed(); 303 send_to_default_serial8250_port("get_load_base_paddr begin\n\0".as_bytes()); 304 305 let mut mb2_count: u32 = 0; 306 multiboot2_iter( 307 Some(multiboot2_get_load_base), 308 &mut mb2_lb_info as *mut [multiboot_tag_load_base_addr_t; 512] as usize as *mut c_void, 309 &mut mb2_count, 310 ); 311 312 if mb2_count == 0 { 313 send_to_default_serial8250_port( 314 "get_load_base_paddr mb2_count == 0, default to 1MB\n\0".as_bytes(), 315 ); 316 return PhysAddr::new(0x100000); 317 } 318 319 let phys = mb2_lb_info[0].load_base_addr as usize; 320 321 return PhysAddr::new(phys); 322 } 323 unsafe fn init_memory_area_from_multiboot2() -> Result<usize, SystemError> { 324 // 这个数组用来存放内存区域的信息(从C获取) 325 let mut mb2_mem_info: [multiboot_mmap_entry_t; 512] = mem::zeroed(); 326 send_to_default_serial8250_port("init_memory_area_from_multiboot2 begin\n\0".as_bytes()); 327 328 let mut mb2_count: u32 = 0; 329 multiboot2_iter( 330 Some(multiboot2_get_memory), 331 &mut mb2_mem_info as *mut [multiboot_mmap_entry_t; 512] as usize as *mut c_void, 332 &mut mb2_count, 333 ); 334 send_to_default_serial8250_port("init_memory_area_from_multiboot2 2\n\0".as_bytes()); 335 336 let mb2_count = mb2_count as usize; 337 let mut areas_count = 0usize; 338 let mut total_mem_size = 0usize; 339 for i in 0..mb2_count { 340 // Only use the memory area if its type is 1 (RAM) 341 if mb2_mem_info[i].type_ == 1 { 342 // Skip the memory area if its len is 0 343 if mb2_mem_info[i].len == 0 { 344 continue; 345 } 346 347 total_mem_size += mb2_mem_info[i].len as usize; 348 349 mem_block_manager() 350 .add_block( 351 PhysAddr::new(mb2_mem_info[i].addr as usize), 352 mb2_mem_info[i].len as usize, 353 ) 354 .unwrap_or_else(|e| { 355 kwarn!( 356 "Failed to add memory block: base={:#x}, size={:#x}, error={:?}", 357 mb2_mem_info[i].addr, 358 mb2_mem_info[i].len, 359 e 360 ); 361 }); 362 areas_count += 1; 363 } 364 } 365 send_to_default_serial8250_port("init_memory_area_from_multiboot2 end\n\0".as_bytes()); 366 kinfo!("Total memory size: {} MB, total areas from multiboot2: {mb2_count}, valid areas: {areas_count}", total_mem_size / 1024 / 1024); 367 return Ok(areas_count); 368 } 369 370 fn init_xd_rsvd() { 371 // 读取ia32-EFER寄存器的值 372 let efer: EferFlags = x86_64::registers::model_specific::Efer::read(); 373 if !efer.contains(EferFlags::NO_EXECUTE_ENABLE) { 374 // NO_EXECUTE_ENABLE是false,那么就设置xd_reserved为true 375 kdebug!("NO_EXECUTE_ENABLE is false, set XD_RESERVED to true"); 376 XD_RESERVED.store(true, Ordering::Relaxed); 377 } 378 compiler_fence(Ordering::SeqCst); 379 } 380 381 /// 判断XD标志位是否被保留 382 pub fn is_xd_reserved() -> bool { 383 // return XD_RESERVED.load(Ordering::Relaxed); 384 385 // 由于暂时不支持execute disable,因此直接返回true 386 // 不支持的原因是,目前好像没有能正确的设置page-level的xd位,会触发page fault 387 return true; 388 } 389 } 390 391 impl VirtAddr { 392 /// @brief 判断虚拟地址是否合法 393 #[inline(always)] 394 pub fn is_canonical(self) -> bool { 395 let x = self.data() & X86_64MMArch::PHYS_OFFSET; 396 // 如果x为0,说明虚拟地址的高位为0,是合法的用户地址 397 // 如果x为PHYS_OFFSET,说明虚拟地址的高位全为1,是合法的内核地址 398 return x == 0 || x == X86_64MMArch::PHYS_OFFSET; 399 } 400 } 401 402 /// @brief 初始化内存管理模块 403 pub fn mm_init() { 404 send_to_default_serial8250_port("mm_init\n\0".as_bytes()); 405 PrintkWriter 406 .write_fmt(format_args!("mm_init() called\n")) 407 .unwrap(); 408 // printk_color!(GREEN, BLACK, "mm_init() called\n"); 409 static _CALL_ONCE: AtomicBool = AtomicBool::new(false); 410 if _CALL_ONCE 411 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) 412 .is_err() 413 { 414 send_to_default_serial8250_port("mm_init err\n\0".as_bytes()); 415 panic!("mm_init() can only be called once"); 416 } 417 418 unsafe { X86_64MMArch::init() }; 419 kdebug!("bootstrap info: {:?}", unsafe { BOOTSTRAP_MM_INFO }); 420 kdebug!("phys[0]=virt[0x{:x}]", unsafe { 421 MMArch::phys_2_virt(PhysAddr::new(0)).unwrap().data() 422 }); 423 424 // 初始化内存管理器 425 unsafe { allocator_init() }; 426 // enable mmio 427 mmio_init(); 428 // enable KMSG 429 kmsg_init(); 430 } 431 432 unsafe fn allocator_init() { 433 let virt_offset = BOOTSTRAP_MM_INFO.unwrap().start_brk; 434 let phy_offset = 435 unsafe { MMArch::virt_2_phys(VirtAddr::new(page_align_up(virt_offset))) }.unwrap(); 436 437 let mut bump_allocator = BumpAllocator::<X86_64MMArch>::new(phy_offset.data()); 438 kdebug!( 439 "BumpAllocator created, offset={:?}", 440 bump_allocator.offset() 441 ); 442 443 // 暂存初始在head.S中指定的页表的地址,后面再考虑是否需要把它加到buddy的可用空间里面! 444 // 现在不加的原因是,我担心会有安全漏洞问题:这些初始的页表,位于内核的数据段。如果归还到buddy, 445 // 可能会产生一定的安全风险(有的代码可能根据虚拟地址来进行安全校验) 446 let _old_page_table = MMArch::table(PageTableKind::Kernel); 447 448 let new_page_table: PhysAddr; 449 // 使用bump分配器,把所有的内存页都映射到页表 450 { 451 // 用bump allocator创建新的页表 452 let mut mapper: crate::mm::page::PageMapper<MMArch, &mut BumpAllocator<MMArch>> = 453 crate::mm::page::PageMapper::<MMArch, _>::create( 454 PageTableKind::Kernel, 455 &mut bump_allocator, 456 ) 457 .expect("Failed to create page mapper"); 458 new_page_table = mapper.table().phys(); 459 kdebug!("PageMapper created"); 460 461 // 取消最开始时候,在head.S中指定的映射(暂时不刷新TLB) 462 { 463 let table = mapper.table(); 464 let empty_entry = PageEntry::<MMArch>::from_usize(0); 465 for i in 0..MMArch::PAGE_ENTRY_NUM { 466 table 467 .set_entry(i, empty_entry) 468 .expect("Failed to empty page table entry"); 469 } 470 } 471 kdebug!("Successfully emptied page table"); 472 473 let total_num = mem_block_manager().total_initial_memory_regions(); 474 for i in 0..total_num { 475 let area = mem_block_manager().get_initial_memory_region(i).unwrap(); 476 // kdebug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size); 477 for i in 0..((area.size + MMArch::PAGE_SIZE - 1) / MMArch::PAGE_SIZE) { 478 let paddr = area.base.add(i * MMArch::PAGE_SIZE); 479 let vaddr = unsafe { MMArch::phys_2_virt(paddr) }.unwrap(); 480 let flags = kernel_page_flags::<MMArch>(vaddr); 481 482 let flusher = mapper 483 .map_phys(vaddr, paddr, flags) 484 .expect("Failed to map frame"); 485 // 暂时不刷新TLB 486 flusher.ignore(); 487 } 488 } 489 490 // 添加低地址的映射(在smp完成初始化之前,需要使用低地址的映射.初始化之后需要取消这一段映射) 491 LowAddressRemapping::remap_at_low_address(&mut mapper); 492 } 493 494 unsafe { 495 INITIAL_CR3_VALUE = new_page_table; 496 } 497 kdebug!( 498 "After mapping all physical memory, DragonOS used: {} KB", 499 bump_allocator.offset() / 1024 500 ); 501 502 // 初始化buddy_allocator 503 let buddy_allocator = unsafe { BuddyAllocator::<X86_64MMArch>::new(bump_allocator).unwrap() }; 504 // 设置全局的页帧分配器 505 unsafe { set_inner_allocator(buddy_allocator) }; 506 kinfo!("Successfully initialized buddy allocator"); 507 // 关闭显示输出 508 scm_disable_put_to_window(); 509 510 // make the new page table current 511 { 512 let mut binding = INNER_ALLOCATOR.lock(); 513 let mut allocator_guard = binding.as_mut().unwrap(); 514 kdebug!("To enable new page table."); 515 compiler_fence(Ordering::SeqCst); 516 let mapper = crate::mm::page::PageMapper::<MMArch, _>::new( 517 PageTableKind::Kernel, 518 new_page_table, 519 &mut allocator_guard, 520 ); 521 compiler_fence(Ordering::SeqCst); 522 mapper.make_current(); 523 compiler_fence(Ordering::SeqCst); 524 kdebug!("New page table enabled"); 525 } 526 kdebug!("Successfully enabled new page table"); 527 } 528 529 #[no_mangle] 530 pub extern "C" fn rs_test_buddy() { 531 test_buddy(); 532 } 533 pub fn test_buddy() { 534 // 申请内存然后写入数据然后free掉 535 // 总共申请200MB内存 536 const TOTAL_SIZE: usize = 200 * 1024 * 1024; 537 538 for i in 0..10 { 539 kdebug!("Test buddy, round: {i}"); 540 // 存放申请的内存块 541 let mut v: Vec<(PhysAddr, PageFrameCount)> = Vec::with_capacity(60 * 1024); 542 // 存放已经申请的内存块的地址(用于检查重复) 543 let mut addr_set: HashSet<PhysAddr> = HashSet::new(); 544 545 let mut allocated = 0usize; 546 547 let mut free_count = 0usize; 548 549 while allocated < TOTAL_SIZE { 550 let mut random_size = 0u64; 551 unsafe { x86::random::rdrand64(&mut random_size) }; 552 // 一次最多申请4M 553 random_size = random_size % (1024 * 4096); 554 if random_size == 0 { 555 continue; 556 } 557 let random_size = 558 core::cmp::min(page_align_up(random_size as usize), TOTAL_SIZE - allocated); 559 let random_size = PageFrameCount::from_bytes(random_size.next_power_of_two()).unwrap(); 560 // 获取帧 561 let (paddr, allocated_frame_count) = 562 unsafe { LockedFrameAllocator.allocate(random_size).unwrap() }; 563 assert!(allocated_frame_count.data().is_power_of_two()); 564 assert!(paddr.data() % MMArch::PAGE_SIZE == 0); 565 unsafe { 566 assert!(MMArch::phys_2_virt(paddr) 567 .as_ref() 568 .unwrap() 569 .check_aligned(allocated_frame_count.data() * MMArch::PAGE_SIZE)); 570 } 571 allocated += allocated_frame_count.data() * MMArch::PAGE_SIZE; 572 v.push((paddr, allocated_frame_count)); 573 assert!(addr_set.insert(paddr), "duplicate address: {:?}", paddr); 574 575 // 写入数据 576 let vaddr = unsafe { MMArch::phys_2_virt(paddr).unwrap() }; 577 let slice = unsafe { 578 core::slice::from_raw_parts_mut( 579 vaddr.data() as *mut u8, 580 allocated_frame_count.data() * MMArch::PAGE_SIZE, 581 ) 582 }; 583 for i in 0..slice.len() { 584 slice[i] = ((i + unsafe { rdtsc() } as usize) % 256) as u8; 585 } 586 587 // 随机释放一个内存块 588 if v.len() > 0 { 589 let mut random_index = 0u64; 590 unsafe { x86::random::rdrand64(&mut random_index) }; 591 // 70%概率释放 592 if random_index % 10 > 7 { 593 continue; 594 } 595 random_index = random_index % v.len() as u64; 596 let random_index = random_index as usize; 597 let (paddr, allocated_frame_count) = v.remove(random_index); 598 assert!(addr_set.remove(&paddr)); 599 unsafe { LockedFrameAllocator.free(paddr, allocated_frame_count) }; 600 free_count += allocated_frame_count.data() * MMArch::PAGE_SIZE; 601 } 602 } 603 604 kdebug!( 605 "Allocated {} MB memory, release: {} MB, no release: {} bytes", 606 allocated / 1024 / 1024, 607 free_count / 1024 / 1024, 608 (allocated - free_count) 609 ); 610 611 kdebug!("Now, to release buddy memory"); 612 // 释放所有的内存 613 for (paddr, allocated_frame_count) in v { 614 unsafe { LockedFrameAllocator.free(paddr, allocated_frame_count) }; 615 assert!(addr_set.remove(&paddr)); 616 free_count += allocated_frame_count.data() * MMArch::PAGE_SIZE; 617 } 618 619 kdebug!("release done!, allocated: {allocated}, free_count: {free_count}"); 620 } 621 } 622 623 /// 全局的页帧分配器 624 #[derive(Debug, Clone, Copy, Hash)] 625 pub struct LockedFrameAllocator; 626 627 impl FrameAllocator for LockedFrameAllocator { 628 unsafe fn allocate(&mut self, count: PageFrameCount) -> Option<(PhysAddr, PageFrameCount)> { 629 if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() { 630 return allocator.allocate(count); 631 } else { 632 return None; 633 } 634 } 635 636 unsafe fn free(&mut self, address: crate::mm::PhysAddr, count: PageFrameCount) { 637 assert!(count.data().is_power_of_two()); 638 if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() { 639 return allocator.free(address, count); 640 } 641 } 642 643 unsafe fn usage(&self) -> PageFrameUsage { 644 if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() { 645 return allocator.usage(); 646 } else { 647 panic!("usage error"); 648 } 649 } 650 } 651 652 /// 获取内核地址默认的页面标志 653 pub unsafe fn kernel_page_flags<A: MemoryManagementArch>(virt: VirtAddr) -> PageFlags<A> { 654 let info: X86_64MMBootstrapInfo = BOOTSTRAP_MM_INFO.clone().unwrap(); 655 656 if virt.data() >= info.kernel_code_start && virt.data() < info.kernel_code_end { 657 // Remap kernel code execute 658 return PageFlags::new().set_execute(true).set_write(true); 659 } else if virt.data() >= info.kernel_data_end && virt.data() < info.kernel_rodata_end { 660 // Remap kernel rodata read only 661 return PageFlags::new().set_execute(true); 662 } else { 663 return PageFlags::new().set_write(true).set_execute(true); 664 } 665 } 666 667 unsafe fn set_inner_allocator(allocator: BuddyAllocator<MMArch>) { 668 static FLAG: AtomicBool = AtomicBool::new(false); 669 if FLAG 670 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) 671 .is_err() 672 { 673 panic!("Cannot set inner allocator twice!"); 674 } 675 *INNER_ALLOCATOR.lock() = Some(allocator); 676 } 677 678 /// 低地址重映射的管理器 679 /// 680 /// 低地址重映射的管理器,在smp初始化完成之前,需要使用低地址的映射,因此需要在smp初始化完成之后,取消这一段映射 681 pub struct LowAddressRemapping; 682 683 impl LowAddressRemapping { 684 // 映射32M 685 const REMAP_SIZE: usize = 32 * 1024 * 1024; 686 687 pub unsafe fn remap_at_low_address( 688 mapper: &mut crate::mm::page::PageMapper<MMArch, &mut BumpAllocator<MMArch>>, 689 ) { 690 for i in 0..(Self::REMAP_SIZE / MMArch::PAGE_SIZE) { 691 let paddr = PhysAddr::new(i * MMArch::PAGE_SIZE); 692 let vaddr = VirtAddr::new(i * MMArch::PAGE_SIZE); 693 let flags = kernel_page_flags::<MMArch>(vaddr); 694 695 let flusher = mapper 696 .map_phys(vaddr, paddr, flags) 697 .expect("Failed to map frame"); 698 // 暂时不刷新TLB 699 flusher.ignore(); 700 } 701 } 702 703 /// 取消低地址的映射 704 pub unsafe fn unmap_at_low_address(flush: bool) { 705 let mut mapper = KernelMapper::lock(); 706 assert!(mapper.as_mut().is_some()); 707 for i in 0..(Self::REMAP_SIZE / MMArch::PAGE_SIZE) { 708 let vaddr = VirtAddr::new(i * MMArch::PAGE_SIZE); 709 let (_, _, flusher) = mapper 710 .as_mut() 711 .unwrap() 712 .unmap_phys(vaddr, true) 713 .expect("Failed to unmap frame"); 714 if flush == false { 715 flusher.ignore(); 716 } 717 } 718 } 719 } 720 #[no_mangle] 721 pub extern "C" fn rs_mm_init() { 722 mm_init(); 723 } 724