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