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