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