1 // 进程的用户空间内存管理 2 3 use core::{ 4 cmp, 5 hash::Hasher, 6 intrinsics::unlikely, 7 ops::Add, 8 sync::atomic::{compiler_fence, Ordering}, 9 }; 10 11 use alloc::{ 12 collections::BTreeMap, 13 sync::{Arc, Weak}, 14 vec::Vec, 15 }; 16 use hashbrown::HashSet; 17 use system_error::SystemError; 18 19 use crate::{ 20 arch::{mm::PageMapper, CurrentIrqArch, MMArch}, 21 exception::InterruptArch, 22 libs::{ 23 align::page_align_up, 24 rwlock::{RwLock, RwLockWriteGuard}, 25 spinlock::{SpinLock, SpinLockGuard}, 26 }, 27 process::ProcessManager, 28 syscall::user_access::{UserBufferReader, UserBufferWriter}, 29 }; 30 31 use super::{ 32 allocator::page_frame::{ 33 deallocate_page_frames, PageFrameCount, PhysPageFrame, VirtPageFrame, VirtPageFrameIter, 34 }, 35 page::{Flusher, InactiveFlusher, PageFlags, PageFlushAll}, 36 syscall::{MapFlags, MremapFlags, ProtFlags}, 37 MemoryManagementArch, PageTableKind, VirtAddr, VirtRegion, VmFlags, 38 }; 39 40 /// MMAP_MIN_ADDR的默认值 41 /// 以下内容来自linux-5.19: 42 /// This is the portion of low virtual memory which should be protected 43 // from userspace allocation. Keeping a user from writing to low pages 44 // can help reduce the impact of kernel NULL pointer bugs. 45 // For most ia64, ppc64 and x86 users with lots of address space 46 // a value of 65536 is reasonable and should cause no problems. 47 // On arm and other archs it should not be higher than 32768. 48 // Programs which use vm86 functionality or have some need to map 49 // this low address space will need CAP_SYS_RAWIO or disable this 50 // protection by setting the value to 0. 51 pub const DEFAULT_MMAP_MIN_ADDR: usize = 65536; 52 53 #[derive(Debug)] 54 pub struct AddressSpace { 55 inner: RwLock<InnerAddressSpace>, 56 } 57 58 impl AddressSpace { 59 pub fn new(create_stack: bool) -> Result<Arc<Self>, SystemError> { 60 let inner = InnerAddressSpace::new(create_stack)?; 61 let result = Self { 62 inner: RwLock::new(inner), 63 }; 64 return Ok(Arc::new(result)); 65 } 66 67 /// 从pcb中获取当前进程的地址空间结构体的Arc指针 68 pub fn current() -> Result<Arc<AddressSpace>, SystemError> { 69 let vm = ProcessManager::current_pcb() 70 .basic() 71 .user_vm() 72 .expect("Current process has no address space"); 73 74 return Ok(vm); 75 } 76 77 /// 判断某个地址空间是否为当前进程的地址空间 78 pub fn is_current(self: &Arc<Self>) -> bool { 79 let current = Self::current(); 80 if let Ok(current) = current { 81 return Arc::ptr_eq(¤t, self); 82 } 83 return false; 84 } 85 } 86 87 impl core::ops::Deref for AddressSpace { 88 type Target = RwLock<InnerAddressSpace>; 89 90 fn deref(&self) -> &Self::Target { 91 &self.inner 92 } 93 } 94 95 impl core::ops::DerefMut for AddressSpace { 96 fn deref_mut(&mut self) -> &mut Self::Target { 97 &mut self.inner 98 } 99 } 100 101 /// @brief 用户地址空间结构体(每个进程都有一个) 102 #[derive(Debug)] 103 pub struct InnerAddressSpace { 104 pub user_mapper: UserMapper, 105 pub mappings: UserMappings, 106 pub mmap_min: VirtAddr, 107 /// 用户栈信息结构体 108 pub user_stack: Option<UserStack>, 109 110 pub elf_brk_start: VirtAddr, 111 pub elf_brk: VirtAddr, 112 113 /// 当前进程的堆空间的起始地址 114 pub brk_start: VirtAddr, 115 /// 当前进程的堆空间的结束地址(不包含) 116 pub brk: VirtAddr, 117 118 pub start_code: VirtAddr, 119 pub end_code: VirtAddr, 120 pub start_data: VirtAddr, 121 pub end_data: VirtAddr, 122 } 123 124 impl InnerAddressSpace { 125 pub fn new(create_stack: bool) -> Result<Self, SystemError> { 126 let mut result = Self { 127 user_mapper: MMArch::setup_new_usermapper()?, 128 mappings: UserMappings::new(), 129 mmap_min: VirtAddr(DEFAULT_MMAP_MIN_ADDR), 130 elf_brk_start: VirtAddr::new(0), 131 elf_brk: VirtAddr::new(0), 132 brk_start: MMArch::USER_BRK_START, 133 brk: MMArch::USER_BRK_START, 134 user_stack: None, 135 start_code: VirtAddr(0), 136 end_code: VirtAddr(0), 137 start_data: VirtAddr(0), 138 end_data: VirtAddr(0), 139 }; 140 if create_stack { 141 // kdebug!("to create user stack."); 142 result.new_user_stack(UserStack::DEFAULT_USER_STACK_SIZE)?; 143 } 144 145 return Ok(result); 146 } 147 148 /// 尝试克隆当前进程的地址空间,包括这些映射都会被克隆 149 /// 150 /// # Returns 151 /// 152 /// 返回克隆后的,新的地址空间的Arc指针 153 #[inline(never)] 154 pub fn try_clone(&mut self) -> Result<Arc<AddressSpace>, SystemError> { 155 let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; 156 let new_addr_space = AddressSpace::new(false)?; 157 let mut new_guard = new_addr_space.write(); 158 159 // 拷贝用户栈的结构体信息,但是不拷贝用户栈的内容(因为后面VMA的拷贝会拷贝用户栈的内容) 160 unsafe { 161 new_guard.user_stack = Some(self.user_stack.as_ref().unwrap().clone_info_only()); 162 } 163 let _current_stack_size = self.user_stack.as_ref().unwrap().stack_size(); 164 165 let current_mapper = &mut self.user_mapper.utable; 166 167 // 拷贝空洞 168 new_guard.mappings.vm_holes = self.mappings.vm_holes.clone(); 169 170 for vma in self.mappings.vmas.iter() { 171 // TODO: 增加对VMA是否为文件映射的判断,如果是的话,就跳过 172 173 let vma_guard: SpinLockGuard<'_, VMA> = vma.lock(); 174 let old_flags = vma_guard.flags(); 175 let tmp_flags: PageFlags<MMArch> = PageFlags::new().set_write(true); 176 177 // 分配内存页并创建新的VMA 178 let new_vma = VMA::zeroed( 179 VirtPageFrame::new(vma_guard.region.start()), 180 PageFrameCount::new(vma_guard.region.size() / MMArch::PAGE_SIZE), 181 vma_guard.vm_flags().clone(), 182 tmp_flags, 183 &mut new_guard.user_mapper.utable, 184 (), 185 )?; 186 new_guard.mappings.vmas.insert(new_vma.clone()); 187 // kdebug!("new vma: {:x?}", new_vma); 188 let mut new_vma_guard = new_vma.lock(); 189 for page in new_vma_guard.pages().map(|p| p.virt_address()) { 190 // kdebug!("page: {:x?}", page); 191 let current_frame = unsafe { 192 MMArch::phys_2_virt( 193 current_mapper 194 .translate(page) 195 .expect("VMA page not mapped") 196 .0, 197 ) 198 } 199 .expect("Phys2Virt: vaddr overflow.") 200 .data() as *mut u8; 201 202 let new_frame = unsafe { 203 MMArch::phys_2_virt( 204 new_guard 205 .user_mapper 206 .utable 207 .translate(page) 208 .expect("VMA page not mapped") 209 .0, 210 ) 211 } 212 .expect("Phys2Virt: vaddr overflow.") 213 .data() as *mut u8; 214 215 unsafe { 216 // 拷贝数据 217 new_frame.copy_from_nonoverlapping(current_frame, MMArch::PAGE_SIZE); 218 } 219 } 220 drop(vma_guard); 221 222 new_vma_guard.remap(old_flags, &mut new_guard.user_mapper.utable, ())?; 223 drop(new_vma_guard); 224 } 225 drop(new_guard); 226 drop(irq_guard); 227 return Ok(new_addr_space); 228 } 229 230 /// 判断当前的地址空间是否是当前进程的地址空间 231 #[inline] 232 pub fn is_current(&self) -> bool { 233 return self.user_mapper.utable.is_current(); 234 } 235 236 /// 进行匿名页映射 237 /// 238 /// ## 参数 239 /// 240 /// - `start_vaddr`:映射的起始地址 241 /// - `len`:映射的长度 242 /// - `prot_flags`:保护标志 243 /// - `map_flags`:映射标志 244 /// - `round_to_min`:是否将`start_vaddr`对齐到`mmap_min`,如果为`true`,则当`start_vaddr`不为0时,会对齐到`mmap_min`,否则仅向下对齐到页边界 245 /// 246 /// ## 返回 247 /// 248 /// 返回映射的起始虚拟页帧 249 pub fn map_anonymous( 250 &mut self, 251 start_vaddr: VirtAddr, 252 len: usize, 253 prot_flags: ProtFlags, 254 map_flags: MapFlags, 255 round_to_min: bool, 256 ) -> Result<VirtPageFrame, SystemError> { 257 // 用于对齐hint的函数 258 let round_hint_to_min = |hint: VirtAddr| { 259 // 先把hint向下对齐到页边界 260 let addr = hint.data() & (!MMArch::PAGE_OFFSET_MASK); 261 // kdebug!("map_anonymous: hint = {:?}, addr = {addr:#x}", hint); 262 // 如果hint不是0,且hint小于DEFAULT_MMAP_MIN_ADDR,则对齐到DEFAULT_MMAP_MIN_ADDR 263 if (addr != 0) && round_to_min && (addr < DEFAULT_MMAP_MIN_ADDR) { 264 Some(VirtAddr::new(page_align_up(DEFAULT_MMAP_MIN_ADDR))) 265 } else if addr == 0 { 266 None 267 } else { 268 Some(VirtAddr::new(addr)) 269 } 270 }; 271 // kdebug!("map_anonymous: start_vaddr = {:?}", start_vaddr); 272 // kdebug!("map_anonymous: len(no align) = {}", len); 273 274 let len = page_align_up(len); 275 276 let vm_flags = VmFlags::from(prot_flags) 277 | VmFlags::from(map_flags) 278 | VmFlags::VM_MAYREAD 279 | VmFlags::VM_MAYWRITE 280 | VmFlags::VM_MAYEXEC; 281 282 // kdebug!("map_anonymous: len = {}", len); 283 284 let start_page: VirtPageFrame = self.mmap( 285 round_hint_to_min(start_vaddr), 286 PageFrameCount::from_bytes(len).unwrap(), 287 prot_flags, 288 map_flags, 289 move |page, count, flags, mapper, flusher| { 290 Ok(VMA::zeroed(page, count, vm_flags, flags, mapper, flusher)?) 291 }, 292 )?; 293 294 return Ok(start_page); 295 } 296 297 /// 向进程的地址空间映射页面 298 /// 299 /// # 参数 300 /// 301 /// - `addr`:映射的起始地址,如果为`None`,则由内核自动分配 302 /// - `page_count`:映射的页面数量 303 /// - `prot_flags`:保护标志 304 /// - `map_flags`:映射标志 305 /// - `map_func`:映射函数,用于创建VMA 306 /// 307 /// # Returns 308 /// 309 /// 返回映射的起始虚拟页帧 310 /// 311 /// # Errors 312 /// 313 /// - `EINVAL`:参数错误 314 pub fn mmap< 315 F: FnOnce( 316 VirtPageFrame, 317 PageFrameCount, 318 PageFlags<MMArch>, 319 &mut PageMapper, 320 &mut dyn Flusher<MMArch>, 321 ) -> Result<Arc<LockedVMA>, SystemError>, 322 >( 323 &mut self, 324 addr: Option<VirtAddr>, 325 page_count: PageFrameCount, 326 prot_flags: ProtFlags, 327 map_flags: MapFlags, 328 map_func: F, 329 ) -> Result<VirtPageFrame, SystemError> { 330 if page_count == PageFrameCount::new(0) { 331 return Err(SystemError::EINVAL); 332 } 333 // kdebug!("mmap: addr: {addr:?}, page_count: {page_count:?}, prot_flags: {prot_flags:?}, map_flags: {map_flags:?}"); 334 335 // 找到未使用的区域 336 let region = match addr { 337 Some(vaddr) => { 338 self.mappings 339 .find_free_at(self.mmap_min, vaddr, page_count.bytes(), map_flags)? 340 } 341 None => self 342 .mappings 343 .find_free(self.mmap_min, page_count.bytes()) 344 .ok_or(SystemError::ENOMEM)?, 345 }; 346 347 let page = VirtPageFrame::new(region.start()); 348 349 // kdebug!("mmap: page: {:?}, region={region:?}", page.virt_address()); 350 351 compiler_fence(Ordering::SeqCst); 352 let (mut active, mut inactive); 353 let flusher = if self.is_current() { 354 active = PageFlushAll::new(); 355 &mut active as &mut dyn Flusher<MMArch> 356 } else { 357 inactive = InactiveFlusher::new(); 358 &mut inactive as &mut dyn Flusher<MMArch> 359 }; 360 compiler_fence(Ordering::SeqCst); 361 // 映射页面,并将VMA插入到地址空间的VMA列表中 362 self.mappings.insert_vma(map_func( 363 page, 364 page_count, 365 PageFlags::from_prot_flags(prot_flags, true), 366 &mut self.user_mapper.utable, 367 flusher, 368 )?); 369 370 return Ok(page); 371 } 372 373 /// 重映射内存区域 374 /// 375 /// # 参数 376 /// 377 /// - `old_vaddr`:原映射的起始地址 378 /// - `old_len`:原映射的长度 379 /// - `new_len`:重新映射的长度 380 /// - `mremap_flags`:重映射标志 381 /// - `new_vaddr`:重新映射的起始地址 382 /// - `vm_flags`:旧内存区域标志 383 /// 384 /// # Returns 385 /// 386 /// 返回重映射的起始虚拟页帧地址 387 /// 388 /// # Errors 389 /// 390 /// - `EINVAL`:参数错误 391 pub fn mremap( 392 &mut self, 393 old_vaddr: VirtAddr, 394 old_len: usize, 395 new_len: usize, 396 mremap_flags: MremapFlags, 397 new_vaddr: VirtAddr, 398 vm_flags: VmFlags, 399 ) -> Result<VirtAddr, SystemError> { 400 // 检查新内存地址是否对齐 401 if !new_vaddr.check_aligned(MMArch::PAGE_SIZE) { 402 return Err(SystemError::EINVAL); 403 } 404 405 // 检查新、旧内存区域是否冲突 406 let old_region = VirtRegion::new(old_vaddr, old_len); 407 let new_region = VirtRegion::new(new_vaddr, new_len); 408 if old_region.collide(&new_region) { 409 return Err(SystemError::EINVAL); 410 } 411 412 // 取消新内存区域的原映射 413 if mremap_flags.contains(MremapFlags::MREMAP_FIXED) { 414 let start_page = VirtPageFrame::new(new_vaddr); 415 let page_count = PageFrameCount::from_bytes(new_len).unwrap(); 416 self.munmap(start_page, page_count)?; 417 } 418 419 // 初始化映射标志 420 let map_flags: MapFlags = vm_flags.into(); 421 // 初始化内存区域保护标志 422 let prot_flags: ProtFlags = vm_flags.into(); 423 424 // 获取映射后的新内存页面 425 let new_page = self.map_anonymous(new_vaddr, new_len, prot_flags, map_flags, true)?; 426 let new_page_vaddr = new_page.virt_address(); 427 428 // 拷贝旧内存区域内容到新内存区域 429 let old_buffer_reader = 430 UserBufferReader::new(old_vaddr.data() as *const u8, old_len, true)?; 431 let old_buf: &[u8] = old_buffer_reader.read_from_user(0)?; 432 let mut new_buffer_writer = 433 UserBufferWriter::new(new_page_vaddr.data() as *mut u8, new_len, true)?; 434 let new_buf: &mut [u8] = new_buffer_writer.buffer(0)?; 435 let len = old_buf.len().min(new_buf.len()); 436 for i in 0..len { 437 new_buf[i] = old_buf[i]; 438 } 439 440 return Ok(new_page_vaddr); 441 } 442 443 /// 取消进程的地址空间中的映射 444 /// 445 /// # 参数 446 /// 447 /// - `start_page`:起始页帧 448 /// - `page_count`:取消映射的页帧数量 449 /// 450 /// # Errors 451 /// 452 /// - `EINVAL`:参数错误 453 /// - `ENOMEM`:内存不足 454 pub fn munmap( 455 &mut self, 456 start_page: VirtPageFrame, 457 page_count: PageFrameCount, 458 ) -> Result<(), SystemError> { 459 let to_unmap = VirtRegion::new(start_page.virt_address(), page_count.bytes()); 460 let mut flusher: PageFlushAll<MMArch> = PageFlushAll::new(); 461 462 let regions: Vec<Arc<LockedVMA>> = self.mappings.conflicts(to_unmap).collect::<Vec<_>>(); 463 464 for r in regions { 465 let r = r.lock().region; 466 let r = self.mappings.remove_vma(&r).unwrap(); 467 let intersection = r.lock().region().intersect(&to_unmap).unwrap(); 468 let (before, r, after) = r.extract(intersection).unwrap(); 469 470 // TODO: 当引入后备页映射后,这里需要增加通知文件的逻辑 471 472 if let Some(before) = before { 473 // 如果前面有VMA,则需要将前面的VMA重新插入到地址空间的VMA列表中 474 self.mappings.insert_vma(before); 475 } 476 477 if let Some(after) = after { 478 // 如果后面有VMA,则需要将后面的VMA重新插入到地址空间的VMA列表中 479 self.mappings.insert_vma(after); 480 } 481 482 r.unmap(&mut self.user_mapper.utable, &mut flusher); 483 } 484 485 // TODO: 当引入后备页映射后,这里需要增加通知文件的逻辑 486 487 return Ok(()); 488 } 489 490 pub fn mprotect( 491 &mut self, 492 start_page: VirtPageFrame, 493 page_count: PageFrameCount, 494 prot_flags: ProtFlags, 495 ) -> Result<(), SystemError> { 496 // kdebug!( 497 // "mprotect: start_page: {:?}, page_count: {:?}, prot_flags:{prot_flags:?}", 498 // start_page, 499 // page_count 500 // ); 501 let (mut active, mut inactive); 502 let mut flusher = if self.is_current() { 503 active = PageFlushAll::new(); 504 &mut active as &mut dyn Flusher<MMArch> 505 } else { 506 inactive = InactiveFlusher::new(); 507 &mut inactive as &mut dyn Flusher<MMArch> 508 }; 509 510 let mapper = &mut self.user_mapper.utable; 511 let region = VirtRegion::new(start_page.virt_address(), page_count.bytes()); 512 // kdebug!("mprotect: region: {:?}", region); 513 514 let regions = self.mappings.conflicts(region).collect::<Vec<_>>(); 515 // kdebug!("mprotect: regions: {:?}", regions); 516 517 for r in regions { 518 // kdebug!("mprotect: r: {:?}", r); 519 let r = r.lock().region().clone(); 520 let r = self.mappings.remove_vma(&r).unwrap(); 521 522 let intersection = r.lock().region().intersect(®ion).unwrap(); 523 let (before, r, after) = r.extract(intersection).expect("Failed to extract VMA"); 524 525 if let Some(before) = before { 526 self.mappings.insert_vma(before); 527 } 528 if let Some(after) = after { 529 self.mappings.insert_vma(after); 530 } 531 532 let mut r_guard = r.lock(); 533 // 如果VMA的保护标志不允许指定的修改,则返回错误 534 if !r_guard.can_have_flags(prot_flags) { 535 drop(r_guard); 536 self.mappings.insert_vma(r.clone()); 537 return Err(SystemError::EACCES); 538 } 539 540 let new_flags: PageFlags<MMArch> = r_guard 541 .flags() 542 .set_execute(prot_flags.contains(ProtFlags::PROT_EXEC)) 543 .set_write(prot_flags.contains(ProtFlags::PROT_WRITE)); 544 545 r_guard.remap(new_flags, mapper, &mut flusher)?; 546 drop(r_guard); 547 self.mappings.insert_vma(r); 548 } 549 550 return Ok(()); 551 } 552 553 /// 创建新的用户栈 554 /// 555 /// ## 参数 556 /// 557 /// - `size`:栈的大小 558 pub fn new_user_stack(&mut self, size: usize) -> Result<(), SystemError> { 559 assert!(self.user_stack.is_none(), "User stack already exists"); 560 let stack = UserStack::new(self, None, size)?; 561 self.user_stack = Some(stack); 562 return Ok(()); 563 } 564 565 #[inline(always)] 566 pub fn user_stack_mut(&mut self) -> Option<&mut UserStack> { 567 return self.user_stack.as_mut(); 568 } 569 570 /// 取消用户空间内的所有映射 571 pub unsafe fn unmap_all(&mut self) { 572 let mut flusher: PageFlushAll<MMArch> = PageFlushAll::new(); 573 for vma in self.mappings.iter_vmas() { 574 vma.unmap(&mut self.user_mapper.utable, &mut flusher); 575 } 576 } 577 578 /// 设置进程的堆的内存空间 579 /// 580 /// ## 参数 581 /// 582 /// - `new_brk`:新的堆的结束地址。需要满足页对齐要求,并且是用户空间地址,且大于等于当前的堆的起始地址 583 /// 584 /// ## 返回值 585 /// 586 /// 返回旧的堆的结束地址 587 pub unsafe fn set_brk(&mut self, new_brk: VirtAddr) -> Result<VirtAddr, SystemError> { 588 assert!(new_brk.check_aligned(MMArch::PAGE_SIZE)); 589 590 if !new_brk.check_user() || new_brk < self.brk_start { 591 return Err(SystemError::EFAULT); 592 } 593 594 let old_brk = self.brk; 595 596 if new_brk > self.brk { 597 let len = new_brk - self.brk; 598 let prot_flags = ProtFlags::PROT_READ | ProtFlags::PROT_WRITE | ProtFlags::PROT_EXEC; 599 let map_flags = MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS | MapFlags::MAP_FIXED; 600 self.map_anonymous(old_brk, len, prot_flags, map_flags, true)?; 601 602 self.brk = new_brk; 603 return Ok(old_brk); 604 } else { 605 let unmap_len = self.brk - new_brk; 606 let unmap_start = new_brk; 607 if unmap_len == 0 { 608 return Ok(old_brk); 609 } 610 self.munmap( 611 VirtPageFrame::new(unmap_start), 612 PageFrameCount::from_bytes(unmap_len).unwrap(), 613 )?; 614 self.brk = new_brk; 615 return Ok(old_brk); 616 } 617 } 618 619 pub unsafe fn sbrk(&mut self, incr: isize) -> Result<VirtAddr, SystemError> { 620 if incr == 0 { 621 return Ok(self.brk); 622 } 623 624 let new_brk = if incr > 0 { 625 self.brk + incr as usize 626 } else { 627 self.brk - (incr.abs() as usize) 628 }; 629 630 let new_brk = VirtAddr::new(page_align_up(new_brk.data())); 631 632 return self.set_brk(new_brk); 633 } 634 } 635 636 impl Drop for InnerAddressSpace { 637 fn drop(&mut self) { 638 unsafe { 639 self.unmap_all(); 640 } 641 } 642 } 643 644 #[derive(Debug, Hash)] 645 pub struct UserMapper { 646 pub utable: PageMapper, 647 } 648 649 impl UserMapper { 650 pub fn new(utable: PageMapper) -> Self { 651 return Self { utable }; 652 } 653 } 654 655 impl Drop for UserMapper { 656 fn drop(&mut self) { 657 if self.utable.is_current() { 658 // 如果当前要被销毁的用户空间的页表是当前进程的页表,那么就切换回初始内核页表 659 unsafe { MMArch::set_table(PageTableKind::User, MMArch::initial_page_table()) } 660 } 661 // 释放用户空间顶层页表占用的页帧 662 // 请注意,在释放这个页帧之前,用户页表应该已经被完全释放,否则会产生内存泄露 663 unsafe { 664 deallocate_page_frames( 665 PhysPageFrame::new(self.utable.table().phys()), 666 PageFrameCount::new(1), 667 ) 668 }; 669 } 670 } 671 672 /// 用户空间映射信息 673 #[derive(Debug)] 674 pub struct UserMappings { 675 /// 当前用户空间的虚拟内存区域 676 vmas: HashSet<Arc<LockedVMA>>, 677 /// 当前用户空间的VMA空洞 678 vm_holes: BTreeMap<VirtAddr, usize>, 679 } 680 681 impl UserMappings { 682 pub fn new() -> Self { 683 return Self { 684 vmas: HashSet::new(), 685 vm_holes: core::iter::once((VirtAddr::new(0), MMArch::USER_END_VADDR.data())) 686 .collect::<BTreeMap<_, _>>(), 687 }; 688 } 689 690 /// 判断当前进程的VMA内,是否有包含指定的虚拟地址的VMA。 691 /// 692 /// 如果有,返回包含指定虚拟地址的VMA的Arc指针,否则返回None。 693 #[allow(dead_code)] 694 pub fn contains(&self, vaddr: VirtAddr) -> Option<Arc<LockedVMA>> { 695 for v in self.vmas.iter() { 696 let guard = v.lock(); 697 if guard.region.contains(vaddr) { 698 return Some(v.clone()); 699 } 700 } 701 return None; 702 } 703 704 /// 获取当前进程的地址空间中,与给定虚拟地址范围有重叠的VMA的迭代器。 705 pub fn conflicts(&self, request: VirtRegion) -> impl Iterator<Item = Arc<LockedVMA>> + '_ { 706 let r = self 707 .vmas 708 .iter() 709 .filter(move |v| !v.lock().region.intersect(&request).is_none()) 710 .cloned(); 711 return r; 712 } 713 714 /// 在当前进程的地址空间中,寻找第一个符合条件的空闲的虚拟内存范围。 715 /// 716 /// @param min_vaddr 最小的起始地址 717 /// @param size 请求的大小 718 /// 719 /// @return 如果找到了,返回虚拟内存范围,否则返回None 720 pub fn find_free(&self, min_vaddr: VirtAddr, size: usize) -> Option<VirtRegion> { 721 let _vaddr = min_vaddr; 722 let mut iter = self 723 .vm_holes 724 .iter() 725 .skip_while(|(hole_vaddr, hole_size)| hole_vaddr.add(**hole_size) <= min_vaddr); 726 727 let (hole_vaddr, size) = iter.find(|(hole_vaddr, hole_size)| { 728 // 计算当前空洞的可用大小 729 let available_size: usize = 730 if hole_vaddr <= &&min_vaddr && min_vaddr <= hole_vaddr.add(**hole_size) { 731 **hole_size - (min_vaddr - **hole_vaddr) 732 } else { 733 **hole_size 734 }; 735 736 size <= available_size 737 })?; 738 739 // 创建一个新的虚拟内存范围。 740 let region = VirtRegion::new(cmp::max(*hole_vaddr, min_vaddr), *size); 741 742 return Some(region); 743 } 744 745 pub fn find_free_at( 746 &self, 747 min_vaddr: VirtAddr, 748 vaddr: VirtAddr, 749 size: usize, 750 flags: MapFlags, 751 ) -> Result<VirtRegion, SystemError> { 752 // 如果没有指定地址,那么就在当前进程的地址空间中寻找一个空闲的虚拟内存范围。 753 if vaddr == VirtAddr::new(0) { 754 return self.find_free(min_vaddr, size).ok_or(SystemError::ENOMEM); 755 } 756 757 // 如果指定了地址,那么就检查指定的地址是否可用。 758 759 let requested = VirtRegion::new(vaddr, size); 760 761 if requested.end() >= MMArch::USER_END_VADDR || !vaddr.check_aligned(MMArch::PAGE_SIZE) { 762 return Err(SystemError::EINVAL); 763 } 764 765 if let Some(_x) = self.conflicts(requested).next() { 766 if flags.contains(MapFlags::MAP_FIXED_NOREPLACE) { 767 // 如果指定了 MAP_FIXED_NOREPLACE 标志,由于所指定的地址无法成功建立映射,则放弃映射,不对地址做修正 768 return Err(SystemError::EEXIST); 769 } 770 771 if flags.contains(MapFlags::MAP_FIXED) { 772 // todo: 支持MAP_FIXED标志对已有的VMA进行覆盖 773 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 774 } 775 776 // 如果没有指定MAP_FIXED标志,那么就对地址做修正 777 let requested = self.find_free(min_vaddr, size).ok_or(SystemError::ENOMEM)?; 778 return Ok(requested); 779 } 780 781 return Ok(requested); 782 } 783 784 /// 在当前进程的地址空间中,保留一个指定大小的区域,使得该区域不在空洞中。 785 /// 该函数会修改vm_holes中的空洞信息。 786 /// 787 /// @param region 要保留的区域 788 /// 789 /// 请注意,在调用本函数之前,必须先确定region所在范围内没有VMA。 790 fn reserve_hole(&mut self, region: &VirtRegion) { 791 let prev_hole: Option<(&VirtAddr, &mut usize)> = 792 self.vm_holes.range_mut(..=region.start()).next_back(); 793 794 if let Some((prev_hole_vaddr, prev_hole_size)) = prev_hole { 795 let prev_hole_end = prev_hole_vaddr.add(*prev_hole_size); 796 797 if prev_hole_end > region.start() { 798 // 如果前一个空洞的结束地址大于当前空洞的起始地址,那么就需要调整前一个空洞的大小。 799 *prev_hole_size = region.start().data() - prev_hole_vaddr.data(); 800 } 801 802 if prev_hole_end > region.end() { 803 // 如果前一个空洞的结束地址大于当前空洞的结束地址,那么就需要增加一个新的空洞。 804 self.vm_holes 805 .insert(region.end(), prev_hole_end - region.end()); 806 } 807 } 808 } 809 810 /// 在当前进程的地址空间中,释放一个指定大小的区域,使得该区域成为一个空洞。 811 /// 该函数会修改vm_holes中的空洞信息。 812 fn unreserve_hole(&mut self, region: &VirtRegion) { 813 // 如果将要插入的空洞与后一个空洞相邻,那么就需要合并。 814 let next_hole_size: Option<usize> = self.vm_holes.remove(®ion.end()); 815 816 if let Some((_prev_hole_vaddr, prev_hole_size)) = self 817 .vm_holes 818 .range_mut(..region.start()) 819 .next_back() 820 .filter(|(offset, size)| offset.data() + **size == region.start().data()) 821 { 822 *prev_hole_size += region.size() + next_hole_size.unwrap_or(0); 823 } else { 824 self.vm_holes 825 .insert(region.start(), region.size() + next_hole_size.unwrap_or(0)); 826 } 827 } 828 829 /// 在当前进程的映射关系中,插入一个新的VMA。 830 pub fn insert_vma(&mut self, vma: Arc<LockedVMA>) { 831 let region = vma.lock().region.clone(); 832 // 要求插入的地址范围必须是空闲的,也就是说,当前进程的地址空间中,不能有任何与之重叠的VMA。 833 assert!(self.conflicts(region).next().is_none()); 834 self.reserve_hole(®ion); 835 836 self.vmas.insert(vma); 837 } 838 839 /// @brief 删除一个VMA,并把对应的地址空间加入空洞中。 840 /// 841 /// 这里不会取消VMA对应的地址的映射 842 /// 843 /// @param region 要删除的VMA所在的地址范围 844 /// 845 /// @return 如果成功删除了VMA,则返回被删除的VMA,否则返回None 846 /// 如果没有可以删除的VMA,则不会执行删除操作,并报告失败。 847 pub fn remove_vma(&mut self, region: &VirtRegion) -> Option<Arc<LockedVMA>> { 848 // 请注意,由于这里会对每个VMA加锁,因此性能很低 849 let vma: Arc<LockedVMA> = self 850 .vmas 851 .drain_filter(|vma| vma.lock().region == *region) 852 .next()?; 853 self.unreserve_hole(region); 854 855 return Some(vma); 856 } 857 858 /// @brief Get the iterator of all VMAs in this process. 859 pub fn iter_vmas(&self) -> hashbrown::hash_set::Iter<Arc<LockedVMA>> { 860 return self.vmas.iter(); 861 } 862 } 863 864 impl Default for UserMappings { 865 fn default() -> Self { 866 return Self::new(); 867 } 868 } 869 870 /// 加了锁的VMA 871 /// 872 /// 备注:进行性能测试,看看SpinLock和RwLock哪个更快。 873 #[derive(Debug)] 874 pub struct LockedVMA(SpinLock<VMA>); 875 876 impl core::hash::Hash for LockedVMA { 877 fn hash<H: Hasher>(&self, state: &mut H) { 878 self.0.lock().hash(state); 879 } 880 } 881 882 impl PartialEq for LockedVMA { 883 fn eq(&self, other: &Self) -> bool { 884 self.0.lock().eq(&other.0.lock()) 885 } 886 } 887 888 impl Eq for LockedVMA {} 889 890 #[allow(dead_code)] 891 impl LockedVMA { 892 pub fn new(vma: VMA) -> Arc<Self> { 893 let r = Arc::new(Self(SpinLock::new(vma))); 894 r.0.lock().self_ref = Arc::downgrade(&r); 895 return r; 896 } 897 898 pub fn lock(&self) -> SpinLockGuard<VMA> { 899 return self.0.lock(); 900 } 901 902 /// 调整当前VMA的页面的标志位 903 /// 904 /// TODO:增加调整虚拟页映射的物理地址的功能 905 /// 906 /// @param flags 新的标志位 907 /// @param mapper 页表映射器 908 /// @param flusher 页表项刷新器 909 /// 910 pub fn remap( 911 &self, 912 flags: PageFlags<MMArch>, 913 mapper: &mut PageMapper, 914 mut flusher: impl Flusher<MMArch>, 915 ) -> Result<(), SystemError> { 916 let mut guard = self.lock(); 917 assert!(guard.mapped); 918 for page in guard.region.pages() { 919 // 暂时要求所有的页帧都已经映射到页表 920 // TODO: 引入Lazy Mapping, 通过缺页中断来映射页帧,这里就不必要求所有的页帧都已经映射到页表了 921 let r = unsafe { 922 mapper 923 .remap(page.virt_address(), flags) 924 .expect("Failed to remap, beacuse of some page is not mapped") 925 }; 926 flusher.consume(r); 927 } 928 guard.flags = flags; 929 return Ok(()); 930 } 931 932 pub fn unmap(&self, mapper: &mut PageMapper, mut flusher: impl Flusher<MMArch>) { 933 // todo: 如果当前vma与文件相关,完善文件相关的逻辑 934 935 let mut guard = self.lock(); 936 assert!(guard.mapped); 937 for page in guard.region.pages() { 938 let (paddr, _, flush) = unsafe { mapper.unmap_phys(page.virt_address(), true) } 939 .expect("Failed to unmap, beacuse of some page is not mapped"); 940 941 // todo: 获取物理页的anon_vma的守卫 942 943 // todo: 从anon_vma中删除当前VMA 944 945 // todo: 如果物理页的anon_vma链表长度为0,则释放物理页. 946 947 // 目前由于还没有实现共享页,所以直接释放物理页也没问题。 948 // 但是在实现共享页之后,就不能直接释放物理页了,需要在anon_vma链表长度为0的时候才能释放物理页 949 unsafe { deallocate_page_frames(PhysPageFrame::new(paddr), PageFrameCount::new(1)) }; 950 951 flusher.consume(flush); 952 } 953 guard.mapped = false; 954 } 955 956 pub fn mapped(&self) -> bool { 957 return self.0.lock().mapped; 958 } 959 960 /// 将当前VMA进行切分,切分成3个VMA,分别是: 961 /// 962 /// 1. 前面的VMA,如果没有则为None 963 /// 2. 中间的VMA,也就是传入的Region 964 /// 3. 后面的VMA,如果没有则为None 965 pub fn extract( 966 &self, 967 region: VirtRegion, 968 ) -> Option<( 969 Option<Arc<LockedVMA>>, 970 Arc<LockedVMA>, 971 Option<Arc<LockedVMA>>, 972 )> { 973 assert!(region.start().check_aligned(MMArch::PAGE_SIZE)); 974 assert!(region.end().check_aligned(MMArch::PAGE_SIZE)); 975 976 let mut guard = self.lock(); 977 { 978 // 如果传入的region不在当前VMA的范围内,则直接返回None 979 if unlikely(region.start() < guard.region.start() || region.end() > guard.region.end()) 980 { 981 return None; 982 } 983 984 let intersect: Option<VirtRegion> = guard.region.intersect(®ion); 985 // 如果当前VMA不包含region,则直接返回None 986 if unlikely(intersect.is_none()) { 987 return None; 988 } 989 let intersect: VirtRegion = intersect.unwrap(); 990 if unlikely(intersect == guard.region) { 991 // 如果当前VMA完全包含region,则直接返回当前VMA 992 return Some((None, guard.self_ref.upgrade().unwrap(), None)); 993 } 994 } 995 996 let before: Option<Arc<LockedVMA>> = guard.region.before(®ion).map(|virt_region| { 997 let mut vma: VMA = unsafe { guard.clone() }; 998 vma.region = virt_region; 999 1000 let vma: Arc<LockedVMA> = LockedVMA::new(vma); 1001 vma 1002 }); 1003 1004 let after: Option<Arc<LockedVMA>> = guard.region.after(®ion).map(|virt_region| { 1005 let mut vma: VMA = unsafe { guard.clone() }; 1006 vma.region = virt_region; 1007 1008 let vma: Arc<LockedVMA> = LockedVMA::new(vma); 1009 vma 1010 }); 1011 1012 guard.region = region; 1013 1014 // TODO: 重新设置before、after这两个VMA里面的物理页的anon_vma 1015 1016 return Some((before, guard.self_ref.upgrade().unwrap(), after)); 1017 } 1018 } 1019 1020 /// @brief 虚拟内存区域 1021 #[derive(Debug)] 1022 pub struct VMA { 1023 /// 虚拟内存区域对应的虚拟地址范围 1024 region: VirtRegion, 1025 /// 虚拟内存区域标志 1026 vm_flags: VmFlags, 1027 /// VMA内的页帧的标志 1028 flags: PageFlags<MMArch>, 1029 /// VMA内的页帧是否已经映射到页表 1030 mapped: bool, 1031 /// VMA所属的用户地址空间 1032 user_address_space: Option<Weak<AddressSpace>>, 1033 self_ref: Weak<LockedVMA>, 1034 1035 provider: Provider, 1036 } 1037 1038 impl core::hash::Hash for VMA { 1039 fn hash<H: Hasher>(&self, state: &mut H) { 1040 self.region.hash(state); 1041 self.flags.hash(state); 1042 self.mapped.hash(state); 1043 } 1044 } 1045 1046 /// 描述不同类型的内存提供者或资源 1047 #[derive(Debug)] 1048 pub enum Provider { 1049 Allocated, // TODO:其他 1050 } 1051 1052 #[allow(dead_code)] 1053 impl VMA { 1054 pub fn new( 1055 region: VirtRegion, 1056 vm_flags: VmFlags, 1057 flags: PageFlags<MMArch>, 1058 mapped: bool, 1059 ) -> Self { 1060 VMA { 1061 region, 1062 vm_flags, 1063 flags, 1064 mapped, 1065 user_address_space: None, 1066 self_ref: Weak::default(), 1067 provider: Provider::Allocated, 1068 } 1069 } 1070 1071 pub fn region(&self) -> &VirtRegion { 1072 return &self.region; 1073 } 1074 1075 pub fn vm_flags(&self) -> &VmFlags { 1076 return &self.vm_flags; 1077 } 1078 1079 pub fn set_vm_flags(&mut self, vm_flags: VmFlags) { 1080 self.vm_flags = vm_flags; 1081 } 1082 1083 pub fn set_region_size(&mut self, new_region_size: usize) { 1084 self.region.set_size(new_region_size); 1085 } 1086 1087 /// # 拷贝当前VMA的内容 1088 /// 1089 /// ### 安全性 1090 /// 1091 /// 由于这样操作可能由于错误的拷贝,导致内存泄露、内存重复释放等问题,所以需要小心使用。 1092 pub unsafe fn clone(&self) -> Self { 1093 return Self { 1094 region: self.region, 1095 vm_flags: self.vm_flags, 1096 flags: self.flags, 1097 mapped: self.mapped, 1098 user_address_space: self.user_address_space.clone(), 1099 self_ref: self.self_ref.clone(), 1100 provider: Provider::Allocated, 1101 }; 1102 } 1103 1104 #[inline(always)] 1105 pub fn flags(&self) -> PageFlags<MMArch> { 1106 return self.flags; 1107 } 1108 1109 pub fn pages(&self) -> VirtPageFrameIter { 1110 return VirtPageFrameIter::new( 1111 VirtPageFrame::new(self.region.start()), 1112 VirtPageFrame::new(self.region.end()), 1113 ); 1114 } 1115 1116 pub fn remap( 1117 &mut self, 1118 flags: PageFlags<MMArch>, 1119 mapper: &mut PageMapper, 1120 mut flusher: impl Flusher<MMArch>, 1121 ) -> Result<(), SystemError> { 1122 assert!(self.mapped); 1123 for page in self.region.pages() { 1124 // kdebug!("remap page {:?}", page.virt_address()); 1125 // 暂时要求所有的页帧都已经映射到页表 1126 // TODO: 引入Lazy Mapping, 通过缺页中断来映射页帧,这里就不必要求所有的页帧都已经映射到页表了 1127 let r = unsafe { 1128 mapper 1129 .remap(page.virt_address(), flags) 1130 .expect("Failed to remap, beacuse of some page is not mapped") 1131 }; 1132 // kdebug!("consume page {:?}", page.virt_address()); 1133 flusher.consume(r); 1134 // kdebug!("remap page {:?} done", page.virt_address()); 1135 } 1136 self.flags = flags; 1137 return Ok(()); 1138 } 1139 1140 /// 检查当前VMA是否可以拥有指定的标志位 1141 /// 1142 /// ## 参数 1143 /// 1144 /// - `prot_flags` 要检查的标志位 1145 pub fn can_have_flags(&self, prot_flags: ProtFlags) -> bool { 1146 let is_downgrade = (self.flags.has_write() || !prot_flags.contains(ProtFlags::PROT_WRITE)) 1147 && (self.flags.has_execute() || !prot_flags.contains(ProtFlags::PROT_EXEC)); 1148 1149 match self.provider { 1150 Provider::Allocated { .. } => true, 1151 1152 #[allow(unreachable_patterns)] 1153 _ => is_downgrade, 1154 } 1155 } 1156 1157 /// 把物理地址映射到虚拟地址 1158 /// 1159 /// @param phys 要映射的物理地址 1160 /// @param destination 要映射到的虚拟地址 1161 /// @param count 要映射的页帧数量 1162 /// @param flags 页面标志位 1163 /// @param mapper 页表映射器 1164 /// @param flusher 页表项刷新器 1165 /// 1166 /// @return 返回映射后的虚拟内存区域 1167 pub fn physmap( 1168 phys: PhysPageFrame, 1169 destination: VirtPageFrame, 1170 count: PageFrameCount, 1171 vm_flags: VmFlags, 1172 flags: PageFlags<MMArch>, 1173 mapper: &mut PageMapper, 1174 mut flusher: impl Flusher<MMArch>, 1175 ) -> Result<Arc<LockedVMA>, SystemError> { 1176 { 1177 let mut cur_phy = phys; 1178 let mut cur_dest = destination; 1179 1180 for _ in 0..count.data() { 1181 // 将物理页帧映射到虚拟页帧 1182 let r = unsafe { 1183 mapper.map_phys(cur_dest.virt_address(), cur_phy.phys_address(), flags) 1184 } 1185 .expect("Failed to map phys, may be OOM error"); 1186 1187 // todo: 增加OOM处理 1188 1189 // todo: 将VMA加入到anon_vma中 1190 1191 // 刷新TLB 1192 flusher.consume(r); 1193 1194 cur_phy = cur_phy.next(); 1195 cur_dest = cur_dest.next(); 1196 } 1197 } 1198 1199 let r: Arc<LockedVMA> = LockedVMA::new(VMA { 1200 region: VirtRegion::new(destination.virt_address(), count.data() * MMArch::PAGE_SIZE), 1201 vm_flags, 1202 flags, 1203 mapped: true, 1204 user_address_space: None, 1205 self_ref: Weak::default(), 1206 provider: Provider::Allocated, 1207 }); 1208 return Ok(r); 1209 } 1210 1211 /// 从页分配器中分配一些物理页,并把它们映射到指定的虚拟地址,然后创建VMA 1212 /// 1213 /// @param destination 要映射到的虚拟地址 1214 /// @param count 要映射的页帧数量 1215 /// @param flags 页面标志位 1216 /// @param mapper 页表映射器 1217 /// @param flusher 页表项刷新器 1218 /// 1219 /// @return 返回映射后的虚拟内存区域 1220 pub fn zeroed( 1221 destination: VirtPageFrame, 1222 page_count: PageFrameCount, 1223 vm_flags: VmFlags, 1224 flags: PageFlags<MMArch>, 1225 mapper: &mut PageMapper, 1226 mut flusher: impl Flusher<MMArch>, 1227 ) -> Result<Arc<LockedVMA>, SystemError> { 1228 let mut cur_dest: VirtPageFrame = destination; 1229 // kdebug!( 1230 // "VMA::zeroed: page_count = {:?}, destination={destination:?}", 1231 // page_count 1232 // ); 1233 for _ in 0..page_count.data() { 1234 // kdebug!( 1235 // "VMA::zeroed: cur_dest={cur_dest:?}, vaddr = {:?}", 1236 // cur_dest.virt_address() 1237 // ); 1238 let r = unsafe { mapper.map(cur_dest.virt_address(), flags) } 1239 .expect("Failed to map zero, may be OOM error"); 1240 // todo: 将VMA加入到anon_vma中 1241 // todo: 增加OOM处理 1242 1243 // 稍后再刷新TLB,这里取消刷新 1244 flusher.consume(r); 1245 cur_dest = cur_dest.next(); 1246 } 1247 let r = LockedVMA::new(VMA { 1248 region: VirtRegion::new( 1249 destination.virt_address(), 1250 page_count.data() * MMArch::PAGE_SIZE, 1251 ), 1252 vm_flags, 1253 flags, 1254 mapped: true, 1255 user_address_space: None, 1256 self_ref: Weak::default(), 1257 provider: Provider::Allocated, 1258 }); 1259 drop(flusher); 1260 // kdebug!("VMA::zeroed: flusher dropped"); 1261 1262 // 清空这些内存 1263 let virt_iter: VirtPageFrameIter = 1264 VirtPageFrameIter::new(destination, destination.add(page_count)); 1265 for frame in virt_iter { 1266 let paddr = mapper.translate(frame.virt_address()).unwrap().0; 1267 1268 unsafe { 1269 let vaddr = MMArch::phys_2_virt(paddr).unwrap(); 1270 MMArch::write_bytes(vaddr, 0, MMArch::PAGE_SIZE); 1271 } 1272 } 1273 // kdebug!("VMA::zeroed: done"); 1274 return Ok(r); 1275 } 1276 } 1277 1278 impl Drop for VMA { 1279 fn drop(&mut self) { 1280 // 当VMA被释放时,需要确保它已经被从页表中解除映射 1281 assert!(!self.mapped, "VMA is still mapped"); 1282 } 1283 } 1284 1285 impl PartialEq for VMA { 1286 fn eq(&self, other: &Self) -> bool { 1287 return self.region == other.region; 1288 } 1289 } 1290 1291 impl Eq for VMA {} 1292 1293 impl PartialOrd for VMA { 1294 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { 1295 return self.region.partial_cmp(&other.region); 1296 } 1297 } 1298 1299 impl Ord for VMA { 1300 fn cmp(&self, other: &Self) -> cmp::Ordering { 1301 return self.region.cmp(&other.region); 1302 } 1303 } 1304 1305 #[derive(Debug)] 1306 pub struct UserStack { 1307 // 栈底地址 1308 stack_bottom: VirtAddr, 1309 // 当前已映射的大小 1310 mapped_size: usize, 1311 /// 栈顶地址(这个值需要仔细确定!因为它可能不会实时与用户栈的真实栈顶保持一致!要小心!) 1312 current_sp: VirtAddr, 1313 } 1314 1315 impl UserStack { 1316 /// 默认的用户栈底地址 1317 pub const DEFAULT_USER_STACK_BOTTOM: VirtAddr = MMArch::USER_STACK_START; 1318 /// 默认的用户栈大小为8MB 1319 pub const DEFAULT_USER_STACK_SIZE: usize = 8 * 1024 * 1024; 1320 /// 用户栈的保护页数量 1321 pub const GUARD_PAGES_NUM: usize = 4; 1322 1323 /// 创建一个用户栈 1324 pub fn new( 1325 vm: &mut InnerAddressSpace, 1326 stack_bottom: Option<VirtAddr>, 1327 stack_size: usize, 1328 ) -> Result<Self, SystemError> { 1329 let stack_bottom = stack_bottom.unwrap_or(Self::DEFAULT_USER_STACK_BOTTOM); 1330 assert!(stack_bottom.check_aligned(MMArch::PAGE_SIZE)); 1331 1332 // 分配用户栈的保护页 1333 let guard_size = Self::GUARD_PAGES_NUM * MMArch::PAGE_SIZE; 1334 let actual_stack_bottom = stack_bottom - guard_size; 1335 1336 let mut prot_flags = ProtFlags::PROT_READ | ProtFlags::PROT_WRITE; 1337 let map_flags = 1338 MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS | MapFlags::MAP_FIXED_NOREPLACE; 1339 // kdebug!( 1340 // "map anonymous stack: {:?} {}", 1341 // actual_stack_bottom, 1342 // guard_size 1343 // ); 1344 vm.map_anonymous( 1345 actual_stack_bottom, 1346 guard_size, 1347 prot_flags, 1348 map_flags, 1349 false, 1350 )?; 1351 // test_buddy(); 1352 // 设置保护页只读 1353 prot_flags.remove(ProtFlags::PROT_WRITE); 1354 // kdebug!( 1355 // "to mprotect stack guard pages: {:?} {}", 1356 // actual_stack_bottom, 1357 // guard_size 1358 // ); 1359 vm.mprotect( 1360 VirtPageFrame::new(actual_stack_bottom), 1361 PageFrameCount::new(Self::GUARD_PAGES_NUM), 1362 prot_flags, 1363 )?; 1364 1365 // kdebug!( 1366 // "mprotect stack guard pages done: {:?} {}", 1367 // actual_stack_bottom, 1368 // guard_size 1369 // ); 1370 1371 let mut user_stack = UserStack { 1372 stack_bottom: actual_stack_bottom, 1373 mapped_size: guard_size, 1374 current_sp: actual_stack_bottom - guard_size, 1375 }; 1376 1377 // kdebug!("extend user stack: {:?} {}", stack_bottom, stack_size); 1378 // 分配用户栈 1379 user_stack.initial_extend(vm, stack_size)?; 1380 // kdebug!("user stack created: {:?} {}", stack_bottom, stack_size); 1381 return Ok(user_stack); 1382 } 1383 1384 fn initial_extend( 1385 &mut self, 1386 vm: &mut InnerAddressSpace, 1387 mut bytes: usize, 1388 ) -> Result<(), SystemError> { 1389 let prot_flags = ProtFlags::PROT_READ | ProtFlags::PROT_WRITE | ProtFlags::PROT_EXEC; 1390 let map_flags = MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS; 1391 1392 bytes = page_align_up(bytes); 1393 self.mapped_size += bytes; 1394 1395 vm.map_anonymous( 1396 self.stack_bottom - self.mapped_size, 1397 bytes, 1398 prot_flags, 1399 map_flags, 1400 false, 1401 )?; 1402 1403 return Ok(()); 1404 } 1405 1406 /// 扩展用户栈 1407 /// 1408 /// ## 参数 1409 /// 1410 /// - `vm` 用户地址空间结构体 1411 /// - `bytes` 要扩展的字节数 1412 /// 1413 /// ## 返回值 1414 /// 1415 /// - **Ok(())** 扩展成功 1416 /// - **Err(SystemError)** 扩展失败 1417 #[allow(dead_code)] 1418 pub fn extend( 1419 &mut self, 1420 vm: &mut RwLockWriteGuard<InnerAddressSpace>, 1421 mut bytes: usize, 1422 ) -> Result<(), SystemError> { 1423 let prot_flags = ProtFlags::PROT_READ | ProtFlags::PROT_WRITE | ProtFlags::PROT_EXEC; 1424 let map_flags = MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS; 1425 1426 bytes = page_align_up(bytes); 1427 self.mapped_size += bytes; 1428 1429 vm.map_anonymous( 1430 self.stack_bottom - self.mapped_size, 1431 bytes, 1432 prot_flags, 1433 map_flags, 1434 false, 1435 )?; 1436 1437 return Ok(()); 1438 } 1439 1440 /// 获取栈顶地址 1441 /// 1442 /// 请注意,如果用户栈的栈顶地址发生变化,这个值可能不会实时更新! 1443 pub fn sp(&self) -> VirtAddr { 1444 return self.current_sp; 1445 } 1446 1447 pub unsafe fn set_sp(&mut self, sp: VirtAddr) { 1448 self.current_sp = sp; 1449 } 1450 1451 /// 仅仅克隆用户栈的信息,不会克隆用户栈的内容/映射 1452 pub unsafe fn clone_info_only(&self) -> Self { 1453 return Self { 1454 stack_bottom: self.stack_bottom, 1455 mapped_size: self.mapped_size, 1456 current_sp: self.current_sp, 1457 }; 1458 } 1459 1460 /// 获取当前用户栈的大小(不包括保护页) 1461 pub fn stack_size(&self) -> usize { 1462 return self.mapped_size - Self::GUARD_PAGES_NUM * MMArch::PAGE_SIZE; 1463 } 1464 } 1465