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