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