xref: /DragonOS/kernel/src/mm/ucontext.rs (revision 1ea2daad8121b77ed704e6d7c3a09f478147441d)
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             // debug!("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             // debug!("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         // debug!("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             // debug!("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         // debug!("map_anonymous: start_vaddr = {:?}", start_vaddr);
273         // debug!("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         // debug!("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         // debug!("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         // debug!("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         // debug!(
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         // debug!("mprotect: region: {:?}", region);
530 
531         let regions = self.mappings.conflicts(region).collect::<Vec<_>>();
532         // debug!("mprotect: regions: {:?}", regions);
533 
534         for r in regions {
535             // debug!("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             r_guard.set_vm_flags(VmFlags::from(prot_flags));
560 
561             let new_flags: PageFlags<MMArch> = r_guard
562                 .flags()
563                 .set_execute(prot_flags.contains(ProtFlags::PROT_EXEC))
564                 .set_write(prot_flags.contains(ProtFlags::PROT_WRITE));
565 
566             r_guard.remap(new_flags, mapper, &mut flusher)?;
567             drop(r_guard);
568             self.mappings.insert_vma(r);
569         }
570 
571         return Ok(());
572     }
573 
574     pub fn madvise(
575         &mut self,
576         start_page: VirtPageFrame,
577         page_count: PageFrameCount,
578         behavior: MadvFlags,
579     ) -> Result<(), SystemError> {
580         let (mut active, mut inactive);
581         let mut flusher = if self.is_current() {
582             active = PageFlushAll::new();
583             &mut active as &mut dyn Flusher<MMArch>
584         } else {
585             inactive = InactiveFlusher::new();
586             &mut inactive as &mut dyn Flusher<MMArch>
587         };
588 
589         let mapper = &mut self.user_mapper.utable;
590 
591         let region = VirtRegion::new(start_page.virt_address(), page_count.bytes());
592         let regions = self.mappings.conflicts(region).collect::<Vec<_>>();
593 
594         for r in regions {
595             let r = *r.lock().region();
596             let r = self.mappings.remove_vma(&r).unwrap();
597 
598             let intersection = r.lock().region().intersect(&region).unwrap();
599             let split_result = r
600                 .extract(intersection, mapper)
601                 .expect("Failed to extract VMA");
602 
603             if let Some(before) = split_result.prev {
604                 self.mappings.insert_vma(before);
605             }
606             if let Some(after) = split_result.after {
607                 self.mappings.insert_vma(after);
608             }
609             r.do_madvise(behavior, mapper, &mut flusher)?;
610             self.mappings.insert_vma(r);
611         }
612         Ok(())
613     }
614 
615     /// 创建新的用户栈
616     ///
617     /// ## 参数
618     ///
619     /// - `size`:栈的大小
620     pub fn new_user_stack(&mut self, size: usize) -> Result<(), SystemError> {
621         assert!(self.user_stack.is_none(), "User stack already exists");
622         let stack = UserStack::new(self, None, size)?;
623         self.user_stack = Some(stack);
624         return Ok(());
625     }
626 
627     #[inline(always)]
628     pub fn user_stack_mut(&mut self) -> Option<&mut UserStack> {
629         return self.user_stack.as_mut();
630     }
631 
632     /// 取消用户空间内的所有映射
633     pub unsafe fn unmap_all(&mut self) {
634         let mut flusher: PageFlushAll<MMArch> = PageFlushAll::new();
635         for vma in self.mappings.iter_vmas() {
636             if vma.mapped() {
637                 vma.unmap(&mut self.user_mapper.utable, &mut flusher);
638             }
639         }
640     }
641 
642     /// 设置进程的堆的内存空间
643     ///
644     /// ## 参数
645     ///
646     /// - `new_brk`:新的堆的结束地址。需要满足页对齐要求,并且是用户空间地址,且大于等于当前的堆的起始地址
647     ///
648     /// ## 返回值
649     ///
650     /// 返回旧的堆的结束地址
651     pub unsafe fn set_brk(&mut self, new_brk: VirtAddr) -> Result<VirtAddr, SystemError> {
652         assert!(new_brk.check_aligned(MMArch::PAGE_SIZE));
653 
654         if !new_brk.check_user() || new_brk < self.brk_start {
655             return Err(SystemError::EFAULT);
656         }
657 
658         let old_brk = self.brk;
659 
660         if new_brk > self.brk {
661             let len = new_brk - self.brk;
662             let prot_flags = ProtFlags::PROT_READ | ProtFlags::PROT_WRITE | ProtFlags::PROT_EXEC;
663             let map_flags = MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS | MapFlags::MAP_FIXED;
664             self.map_anonymous(old_brk, len, prot_flags, map_flags, true, false)?;
665 
666             self.brk = new_brk;
667             return Ok(old_brk);
668         } else {
669             let unmap_len = self.brk - new_brk;
670             let unmap_start = new_brk;
671             if unmap_len == 0 {
672                 return Ok(old_brk);
673             }
674             self.munmap(
675                 VirtPageFrame::new(unmap_start),
676                 PageFrameCount::from_bytes(unmap_len).unwrap(),
677             )?;
678             self.brk = new_brk;
679             return Ok(old_brk);
680         }
681     }
682 
683     pub unsafe fn sbrk(&mut self, incr: isize) -> Result<VirtAddr, SystemError> {
684         if incr == 0 {
685             return Ok(self.brk);
686         }
687 
688         let new_brk = if incr > 0 {
689             self.brk + incr as usize
690         } else {
691             self.brk - incr.unsigned_abs()
692         };
693 
694         let new_brk = VirtAddr::new(page_align_up(new_brk.data()));
695 
696         return self.set_brk(new_brk);
697     }
698 }
699 
700 impl Drop for InnerAddressSpace {
701     fn drop(&mut self) {
702         unsafe {
703             self.unmap_all();
704         }
705     }
706 }
707 
708 #[derive(Debug, Hash)]
709 pub struct UserMapper {
710     pub utable: PageMapper,
711 }
712 
713 impl UserMapper {
714     pub fn new(utable: PageMapper) -> Self {
715         return Self { utable };
716     }
717 
718     /// 拷贝用户空间映射
719     /// ## 参数
720     ///
721     /// - `umapper`: 要拷贝的用户空间
722     /// - `copy_on_write`: 是否写时复制
723     pub unsafe fn clone_from(&mut self, umapper: &mut Self, copy_on_write: bool) {
724         self.utable
725             .clone_user_mapping(&mut umapper.utable, copy_on_write);
726     }
727 }
728 
729 impl Drop for UserMapper {
730     fn drop(&mut self) {
731         if self.utable.is_current() {
732             // 如果当前要被销毁的用户空间的页表是当前进程的页表,那么就切换回初始内核页表
733             unsafe { MMArch::set_table(PageTableKind::User, MMArch::initial_page_table()) }
734         }
735         // 释放用户空间顶层页表占用的页帧
736         // 请注意,在释放这个页帧之前,用户页表应该已经被完全释放,否则会产生内存泄露
737         unsafe {
738             deallocate_page_frames(
739                 PhysPageFrame::new(self.utable.table().phys()),
740                 PageFrameCount::new(1),
741                 &mut page_manager_lock_irqsave(),
742             )
743         };
744     }
745 }
746 
747 /// 用户空间映射信息
748 #[derive(Debug)]
749 pub struct UserMappings {
750     /// 当前用户空间的虚拟内存区域
751     vmas: HashSet<Arc<LockedVMA>>,
752     /// 当前用户空间的VMA空洞
753     vm_holes: BTreeMap<VirtAddr, usize>,
754 }
755 
756 impl UserMappings {
757     pub fn new() -> Self {
758         return Self {
759             vmas: HashSet::new(),
760             vm_holes: core::iter::once((VirtAddr::new(0), MMArch::USER_END_VADDR.data()))
761                 .collect::<BTreeMap<_, _>>(),
762         };
763     }
764 
765     /// 判断当前进程的VMA内,是否有包含指定的虚拟地址的VMA。
766     ///
767     /// 如果有,返回包含指定虚拟地址的VMA的Arc指针,否则返回None。
768     #[allow(dead_code)]
769     pub fn contains(&self, vaddr: VirtAddr) -> Option<Arc<LockedVMA>> {
770         for v in self.vmas.iter() {
771             let guard = v.lock();
772             if guard.region.contains(vaddr) {
773                 return Some(v.clone());
774             }
775         }
776         return None;
777     }
778 
779     /// 向下寻找距离虚拟地址最近的VMA
780     /// ## 参数
781     ///
782     /// - `vaddr`: 虚拟地址
783     ///
784     /// ## 返回值
785     /// - Some(Arc<LockedVMA>): 虚拟地址所在的或最近的下一个VMA
786     /// - None: 未找到VMA
787     #[allow(dead_code)]
788     pub fn find_nearest(&self, vaddr: VirtAddr) -> Option<Arc<LockedVMA>> {
789         let mut nearest: Option<Arc<LockedVMA>> = None;
790         for v in self.vmas.iter() {
791             let guard = v.lock();
792             if guard.region.contains(vaddr) {
793                 return Some(v.clone());
794             }
795             if guard.region.start > vaddr
796                 && if let Some(ref nearest) = nearest {
797                     guard.region.start < nearest.lock().region.start
798                 } else {
799                     true
800                 }
801             {
802                 nearest = Some(v.clone());
803             }
804         }
805         return nearest;
806     }
807 
808     /// 获取当前进程的地址空间中,与给定虚拟地址范围有重叠的VMA的迭代器。
809     pub fn conflicts(&self, request: VirtRegion) -> impl Iterator<Item = Arc<LockedVMA>> + '_ {
810         let r = self
811             .vmas
812             .iter()
813             .filter(move |v| v.lock().region.intersect(&request).is_some())
814             .cloned();
815         return r;
816     }
817 
818     /// 在当前进程的地址空间中,寻找第一个符合条件的空闲的虚拟内存范围。
819     ///
820     /// @param min_vaddr 最小的起始地址
821     /// @param size 请求的大小
822     ///
823     /// @return 如果找到了,返回虚拟内存范围,否则返回None
824     pub fn find_free(&self, min_vaddr: VirtAddr, size: usize) -> Option<VirtRegion> {
825         let _vaddr = min_vaddr;
826         let mut iter = self
827             .vm_holes
828             .iter()
829             .skip_while(|(hole_vaddr, hole_size)| hole_vaddr.add(**hole_size) <= min_vaddr);
830 
831         let (hole_vaddr, size) = iter.find(|(hole_vaddr, hole_size)| {
832             // 计算当前空洞的可用大小
833             let available_size: usize =
834                 if hole_vaddr <= &&min_vaddr && min_vaddr <= hole_vaddr.add(**hole_size) {
835                     **hole_size - (min_vaddr - **hole_vaddr)
836                 } else {
837                     **hole_size
838                 };
839 
840             size <= available_size
841         })?;
842 
843         // 创建一个新的虚拟内存范围。
844         let region = VirtRegion::new(cmp::max(*hole_vaddr, min_vaddr), *size);
845 
846         return Some(region);
847     }
848 
849     pub fn find_free_at(
850         &self,
851         min_vaddr: VirtAddr,
852         vaddr: VirtAddr,
853         size: usize,
854         flags: MapFlags,
855     ) -> Result<VirtRegion, SystemError> {
856         // 如果没有指定地址,那么就在当前进程的地址空间中寻找一个空闲的虚拟内存范围。
857         if vaddr == VirtAddr::new(0) {
858             return self.find_free(min_vaddr, size).ok_or(SystemError::ENOMEM);
859         }
860 
861         // 如果指定了地址,那么就检查指定的地址是否可用。
862 
863         let requested = VirtRegion::new(vaddr, size);
864 
865         if requested.end() >= MMArch::USER_END_VADDR || !vaddr.check_aligned(MMArch::PAGE_SIZE) {
866             return Err(SystemError::EINVAL);
867         }
868 
869         if let Some(_x) = self.conflicts(requested).next() {
870             if flags.contains(MapFlags::MAP_FIXED_NOREPLACE) {
871                 // 如果指定了 MAP_FIXED_NOREPLACE 标志,由于所指定的地址无法成功建立映射,则放弃映射,不对地址做修正
872                 return Err(SystemError::EEXIST);
873             }
874 
875             if flags.contains(MapFlags::MAP_FIXED) {
876                 // todo: 支持MAP_FIXED标志对已有的VMA进行覆盖
877                 return Err(SystemError::ENOSYS);
878             }
879 
880             // 如果没有指定MAP_FIXED标志,那么就对地址做修正
881             let requested = self.find_free(min_vaddr, size).ok_or(SystemError::ENOMEM)?;
882             return Ok(requested);
883         }
884 
885         return Ok(requested);
886     }
887 
888     /// 在当前进程的地址空间中,保留一个指定大小的区域,使得该区域不在空洞中。
889     /// 该函数会修改vm_holes中的空洞信息。
890     ///
891     /// @param region 要保留的区域
892     ///
893     /// 请注意,在调用本函数之前,必须先确定region所在范围内没有VMA。
894     fn reserve_hole(&mut self, region: &VirtRegion) {
895         let prev_hole: Option<(&VirtAddr, &mut usize)> =
896             self.vm_holes.range_mut(..=region.start()).next_back();
897 
898         if let Some((prev_hole_vaddr, prev_hole_size)) = prev_hole {
899             let prev_hole_end = prev_hole_vaddr.add(*prev_hole_size);
900 
901             if prev_hole_end > region.start() {
902                 // 如果前一个空洞的结束地址大于当前空洞的起始地址,那么就需要调整前一个空洞的大小。
903                 *prev_hole_size = region.start().data() - prev_hole_vaddr.data();
904             }
905 
906             if prev_hole_end > region.end() {
907                 // 如果前一个空洞的结束地址大于当前空洞的结束地址,那么就需要增加一个新的空洞。
908                 self.vm_holes
909                     .insert(region.end(), prev_hole_end - region.end());
910             }
911         }
912     }
913 
914     /// 在当前进程的地址空间中,释放一个指定大小的区域,使得该区域成为一个空洞。
915     /// 该函数会修改vm_holes中的空洞信息。
916     fn unreserve_hole(&mut self, region: &VirtRegion) {
917         // 如果将要插入的空洞与后一个空洞相邻,那么就需要合并。
918         let next_hole_size: Option<usize> = self.vm_holes.remove(&region.end());
919 
920         if let Some((_prev_hole_vaddr, prev_hole_size)) = self
921             .vm_holes
922             .range_mut(..region.start())
923             .next_back()
924             .filter(|(offset, size)| offset.data() + **size == region.start().data())
925         {
926             *prev_hole_size += region.size() + next_hole_size.unwrap_or(0);
927         } else {
928             self.vm_holes
929                 .insert(region.start(), region.size() + next_hole_size.unwrap_or(0));
930         }
931     }
932 
933     /// 在当前进程的映射关系中,插入一个新的VMA。
934     pub fn insert_vma(&mut self, vma: Arc<LockedVMA>) {
935         let region = vma.lock().region;
936         // 要求插入的地址范围必须是空闲的,也就是说,当前进程的地址空间中,不能有任何与之重叠的VMA。
937         assert!(self.conflicts(region).next().is_none());
938         self.reserve_hole(&region);
939 
940         self.vmas.insert(vma);
941     }
942 
943     /// @brief 删除一个VMA,并把对应的地址空间加入空洞中。
944     ///
945     /// 这里不会取消VMA对应的地址的映射
946     ///
947     /// @param region 要删除的VMA所在的地址范围
948     ///
949     /// @return 如果成功删除了VMA,则返回被删除的VMA,否则返回None
950     /// 如果没有可以删除的VMA,则不会执行删除操作,并报告失败。
951     pub fn remove_vma(&mut self, region: &VirtRegion) -> Option<Arc<LockedVMA>> {
952         // 请注意,由于这里会对每个VMA加锁,因此性能很低
953         let vma: Arc<LockedVMA> = self
954             .vmas
955             .drain_filter(|vma| vma.lock().region == *region)
956             .next()?;
957         self.unreserve_hole(region);
958 
959         return Some(vma);
960     }
961 
962     /// @brief Get the iterator of all VMAs in this process.
963     pub fn iter_vmas(&self) -> hashbrown::hash_set::Iter<Arc<LockedVMA>> {
964         return self.vmas.iter();
965     }
966 }
967 
968 impl Default for UserMappings {
969     fn default() -> Self {
970         return Self::new();
971     }
972 }
973 
974 /// 加了锁的VMA
975 ///
976 /// 备注:进行性能测试,看看SpinLock和RwLock哪个更快。
977 #[derive(Debug)]
978 pub struct LockedVMA {
979     /// 用于计算哈希值,避免总是获取vma锁来计算哈希值
980     id: usize,
981     vma: SpinLock<VMA>,
982 }
983 
984 impl core::hash::Hash for LockedVMA {
985     fn hash<H: Hasher>(&self, state: &mut H) {
986         self.id.hash(state);
987     }
988 }
989 
990 impl PartialEq for LockedVMA {
991     fn eq(&self, other: &Self) -> bool {
992         self.id.eq(&other.id)
993     }
994 }
995 
996 impl Eq for LockedVMA {}
997 
998 #[allow(dead_code)]
999 impl LockedVMA {
1000     pub fn new(vma: VMA) -> Arc<Self> {
1001         let r = Arc::new(Self {
1002             id: LOCKEDVMA_ID_ALLOCATOR.alloc().unwrap(),
1003             vma: SpinLock::new(vma),
1004         });
1005         r.vma.lock().self_ref = Arc::downgrade(&r);
1006         return r;
1007     }
1008 
1009     pub fn id(&self) -> usize {
1010         self.id
1011     }
1012 
1013     pub fn lock(&self) -> SpinLockGuard<VMA> {
1014         return self.vma.lock();
1015     }
1016 
1017     /// 调整当前VMA的页面的标志位
1018     ///
1019     /// TODO:增加调整虚拟页映射的物理地址的功能
1020     ///
1021     /// @param flags 新的标志位
1022     /// @param mapper 页表映射器
1023     /// @param flusher 页表项刷新器
1024     ///
1025     pub fn remap(
1026         &self,
1027         flags: PageFlags<MMArch>,
1028         mapper: &mut PageMapper,
1029         mut flusher: impl Flusher<MMArch>,
1030     ) -> Result<(), SystemError> {
1031         let mut guard = self.lock();
1032         for page in guard.region.pages() {
1033             // 暂时要求所有的页帧都已经映射到页表
1034             // TODO: 引入Lazy Mapping, 通过缺页中断来映射页帧,这里就不必要求所有的页帧都已经映射到页表了
1035             let r = unsafe {
1036                 mapper
1037                     .remap(page.virt_address(), flags)
1038                     .expect("Failed to remap, beacuse of some page is not mapped")
1039             };
1040             flusher.consume(r);
1041         }
1042         guard.flags = flags;
1043         return Ok(());
1044     }
1045 
1046     pub fn unmap(&self, mapper: &mut PageMapper, mut flusher: impl Flusher<MMArch>) {
1047         // todo: 如果当前vma与文件相关,完善文件相关的逻辑
1048 
1049         let mut guard = self.lock();
1050 
1051         // 获取物理页的anon_vma的守卫
1052         let mut page_manager_guard: SpinLockGuard<'_, crate::mm::page::PageManager> =
1053             page_manager_lock_irqsave();
1054         for page in guard.region.pages() {
1055             if mapper.translate(page.virt_address()).is_none() {
1056                 continue;
1057             }
1058             let (paddr, _, flush) = unsafe { mapper.unmap_phys(page.virt_address(), true) }
1059                 .expect("Failed to unmap, beacuse of some page is not mapped");
1060 
1061             // 从anon_vma中删除当前VMA
1062             let page = page_manager_guard.get_mut(&paddr);
1063             page.remove_vma(self);
1064 
1065             // 如果物理页的anon_vma链表长度为0并且不是共享页,则释放物理页.
1066             if page.can_deallocate() {
1067                 unsafe {
1068                     deallocate_page_frames(
1069                         PhysPageFrame::new(paddr),
1070                         PageFrameCount::new(1),
1071                         &mut page_manager_guard,
1072                     )
1073                 };
1074             }
1075 
1076             flusher.consume(flush);
1077         }
1078         guard.mapped = false;
1079     }
1080 
1081     pub fn mapped(&self) -> bool {
1082         return self.vma.lock().mapped;
1083     }
1084 
1085     /// 将当前VMA进行切分,切分成3个VMA,分别是:
1086     ///
1087     /// 1. 前面的VMA,如果没有则为None
1088     /// 2. 中间的VMA,也就是传入的Region
1089     /// 3. 后面的VMA,如果没有则为None
1090     pub fn extract(&self, region: VirtRegion, utable: &PageMapper) -> Option<VMASplitResult> {
1091         assert!(region.start().check_aligned(MMArch::PAGE_SIZE));
1092         assert!(region.end().check_aligned(MMArch::PAGE_SIZE));
1093 
1094         let mut guard = self.lock();
1095         {
1096             // 如果传入的region不在当前VMA的范围内,则直接返回None
1097             if unlikely(region.start() < guard.region.start() || region.end() > guard.region.end())
1098             {
1099                 return None;
1100             }
1101 
1102             let intersect: Option<VirtRegion> = guard.region.intersect(&region);
1103             // 如果当前VMA不包含region,则直接返回None
1104             if unlikely(intersect.is_none()) {
1105                 return None;
1106             }
1107             let intersect: VirtRegion = intersect.unwrap();
1108             if unlikely(intersect == guard.region) {
1109                 // 如果当前VMA完全包含region,则直接返回当前VMA
1110                 return Some(VMASplitResult::new(
1111                     None,
1112                     guard.self_ref.upgrade().unwrap(),
1113                     None,
1114                 ));
1115             }
1116         }
1117 
1118         let before: Option<Arc<LockedVMA>> = guard.region.before(&region).map(|virt_region| {
1119             let mut vma: VMA = unsafe { guard.clone() };
1120             vma.region = virt_region;
1121             vma.mapped = false;
1122             let vma: Arc<LockedVMA> = LockedVMA::new(vma);
1123             vma
1124         });
1125 
1126         let after: Option<Arc<LockedVMA>> = guard.region.after(&region).map(|virt_region| {
1127             let mut vma: VMA = unsafe { guard.clone() };
1128             vma.region = virt_region;
1129             vma.mapped = false;
1130             let vma: Arc<LockedVMA> = LockedVMA::new(vma);
1131             vma
1132         });
1133 
1134         // 重新设置before、after这两个VMA里面的物理页的anon_vma
1135         let mut page_manager_guard = page_manager_lock_irqsave();
1136         if let Some(before) = before.clone() {
1137             let virt_iter = before.lock().region.iter_pages();
1138             for frame in virt_iter {
1139                 if let Some((paddr, _)) = utable.translate(frame.virt_address()) {
1140                     let page = page_manager_guard.get_mut(&paddr);
1141                     page.insert_vma(before.clone());
1142                     page.remove_vma(self);
1143                     before.lock().mapped = true;
1144                 }
1145             }
1146         }
1147 
1148         if let Some(after) = after.clone() {
1149             let virt_iter = after.lock().region.iter_pages();
1150             for frame in virt_iter {
1151                 if let Some((paddr, _)) = utable.translate(frame.virt_address()) {
1152                     let page = page_manager_guard.get_mut(&paddr);
1153                     page.insert_vma(after.clone());
1154                     page.remove_vma(self);
1155                     after.lock().mapped = true;
1156                 }
1157             }
1158         }
1159 
1160         guard.region = region;
1161 
1162         return Some(VMASplitResult::new(
1163             before,
1164             guard.self_ref.upgrade().unwrap(),
1165             after,
1166         ));
1167     }
1168 
1169     /// 判断VMA是否为外部(非当前进程空间)的VMA
1170     pub fn is_foreign(&self) -> bool {
1171         let guard = self.lock();
1172         if let Some(space) = guard.user_address_space.clone() {
1173             if let Some(space) = space.upgrade() {
1174                 return AddressSpace::is_current(&space);
1175             } else {
1176                 return true;
1177             }
1178         } else {
1179             return true;
1180         }
1181     }
1182 
1183     /// 判断VMA是否可访问
1184     pub fn is_accessible(&self) -> bool {
1185         let guard = self.lock();
1186         let vm_access_flags: VmFlags = VmFlags::VM_READ | VmFlags::VM_WRITE | VmFlags::VM_EXEC;
1187         guard.vm_flags().intersects(vm_access_flags)
1188     }
1189 
1190     /// 判断VMA是否为匿名映射
1191     pub fn is_anonymous(&self) -> bool {
1192         //TODO: 实现匿名映射判断逻辑,目前仅支持匿名映射
1193         true
1194     }
1195 
1196     /// 判断VMA是否为大页映射
1197     pub fn is_hugepage(&self) -> bool {
1198         //TODO: 实现巨页映射判断逻辑,目前不支持巨页映射
1199         false
1200     }
1201 }
1202 
1203 impl Drop for LockedVMA {
1204     fn drop(&mut self) {
1205         LOCKEDVMA_ID_ALLOCATOR.free(self.id);
1206     }
1207 }
1208 
1209 /// VMA切分结果
1210 pub struct VMASplitResult {
1211     pub prev: Option<Arc<LockedVMA>>,
1212     pub middle: Arc<LockedVMA>,
1213     pub after: Option<Arc<LockedVMA>>,
1214 }
1215 
1216 impl VMASplitResult {
1217     pub fn new(
1218         prev: Option<Arc<LockedVMA>>,
1219         middle: Arc<LockedVMA>,
1220         post: Option<Arc<LockedVMA>>,
1221     ) -> Self {
1222         Self {
1223             prev,
1224             middle,
1225             after: post,
1226         }
1227     }
1228 }
1229 
1230 /// @brief 虚拟内存区域
1231 #[derive(Debug)]
1232 pub struct VMA {
1233     /// 虚拟内存区域对应的虚拟地址范围
1234     region: VirtRegion,
1235     /// 虚拟内存区域标志
1236     vm_flags: VmFlags,
1237     /// VMA内的页帧的标志
1238     flags: PageFlags<MMArch>,
1239     /// VMA内的页帧是否已经映射到页表
1240     mapped: bool,
1241     /// VMA所属的用户地址空间
1242     user_address_space: Option<Weak<AddressSpace>>,
1243     self_ref: Weak<LockedVMA>,
1244 
1245     provider: Provider,
1246 }
1247 
1248 impl core::hash::Hash for VMA {
1249     fn hash<H: Hasher>(&self, state: &mut H) {
1250         self.region.hash(state);
1251         self.flags.hash(state);
1252         self.mapped.hash(state);
1253     }
1254 }
1255 
1256 /// 描述不同类型的内存提供者或资源
1257 #[derive(Debug)]
1258 pub enum Provider {
1259     Allocated, // TODO:其他
1260 }
1261 
1262 #[allow(dead_code)]
1263 impl VMA {
1264     pub fn new(
1265         region: VirtRegion,
1266         vm_flags: VmFlags,
1267         flags: PageFlags<MMArch>,
1268         mapped: bool,
1269     ) -> Self {
1270         VMA {
1271             region,
1272             vm_flags,
1273             flags,
1274             mapped,
1275             user_address_space: None,
1276             self_ref: Weak::default(),
1277             provider: Provider::Allocated,
1278         }
1279     }
1280 
1281     pub fn region(&self) -> &VirtRegion {
1282         return &self.region;
1283     }
1284 
1285     pub fn vm_flags(&self) -> &VmFlags {
1286         return &self.vm_flags;
1287     }
1288 
1289     pub fn set_vm_flags(&mut self, vm_flags: VmFlags) {
1290         self.vm_flags = vm_flags;
1291     }
1292 
1293     pub fn set_region_size(&mut self, new_region_size: usize) {
1294         self.region.set_size(new_region_size);
1295     }
1296 
1297     pub fn set_mapped(&mut self, mapped: bool) {
1298         self.mapped = mapped;
1299     }
1300 
1301     /// # 拷贝当前VMA的内容
1302     ///
1303     /// ### 安全性
1304     ///
1305     /// 由于这样操作可能由于错误的拷贝,导致内存泄露、内存重复释放等问题,所以需要小心使用。
1306     pub unsafe fn clone(&self) -> Self {
1307         return Self {
1308             region: self.region,
1309             vm_flags: self.vm_flags,
1310             flags: self.flags,
1311             mapped: self.mapped,
1312             user_address_space: self.user_address_space.clone(),
1313             self_ref: self.self_ref.clone(),
1314             provider: Provider::Allocated,
1315         };
1316     }
1317 
1318     pub fn clone_info_only(&self) -> Self {
1319         return Self {
1320             region: self.region,
1321             vm_flags: self.vm_flags,
1322             flags: self.flags,
1323             mapped: self.mapped,
1324             user_address_space: None,
1325             self_ref: Weak::default(),
1326             provider: Provider::Allocated,
1327         };
1328     }
1329 
1330     #[inline(always)]
1331     pub fn flags(&self) -> PageFlags<MMArch> {
1332         return self.flags;
1333     }
1334 
1335     pub fn pages(&self) -> VirtPageFrameIter {
1336         return VirtPageFrameIter::new(
1337             VirtPageFrame::new(self.region.start()),
1338             VirtPageFrame::new(self.region.end()),
1339         );
1340     }
1341 
1342     pub fn remap(
1343         &mut self,
1344         flags: PageFlags<MMArch>,
1345         mapper: &mut PageMapper,
1346         mut flusher: impl Flusher<MMArch>,
1347     ) -> Result<(), SystemError> {
1348         for page in self.region.pages() {
1349             // debug!("remap page {:?}", page.virt_address());
1350             if mapper.translate(page.virt_address()).is_some() {
1351                 let r = unsafe {
1352                     mapper
1353                         .remap(page.virt_address(), flags)
1354                         .expect("Failed to remap")
1355                 };
1356                 flusher.consume(r);
1357             }
1358             // debug!("consume page {:?}", page.virt_address());
1359             // debug!("remap page {:?} done", page.virt_address());
1360         }
1361         self.flags = flags;
1362         return Ok(());
1363     }
1364 
1365     /// 检查当前VMA是否可以拥有指定的标志位
1366     ///
1367     /// ## 参数
1368     ///
1369     /// - `prot_flags` 要检查的标志位
1370     pub fn can_have_flags(&self, prot_flags: ProtFlags) -> bool {
1371         let is_downgrade = (self.flags.has_write() || !prot_flags.contains(ProtFlags::PROT_WRITE))
1372             && (self.flags.has_execute() || !prot_flags.contains(ProtFlags::PROT_EXEC));
1373 
1374         match self.provider {
1375             Provider::Allocated { .. } => true,
1376 
1377             #[allow(unreachable_patterns)]
1378             _ => is_downgrade,
1379         }
1380     }
1381 
1382     /// 把物理地址映射到虚拟地址
1383     ///
1384     /// @param phys 要映射的物理地址
1385     /// @param destination 要映射到的虚拟地址
1386     /// @param count 要映射的页帧数量
1387     /// @param flags 页面标志位
1388     /// @param mapper 页表映射器
1389     /// @param flusher 页表项刷新器
1390     ///
1391     /// @return 返回映射后的虚拟内存区域
1392     pub fn physmap(
1393         phys: PhysPageFrame,
1394         destination: VirtPageFrame,
1395         count: PageFrameCount,
1396         vm_flags: VmFlags,
1397         flags: PageFlags<MMArch>,
1398         mapper: &mut PageMapper,
1399         mut flusher: impl Flusher<MMArch>,
1400     ) -> Result<Arc<LockedVMA>, SystemError> {
1401         let mut cur_phy = phys;
1402         let mut cur_dest = destination;
1403 
1404         for _ in 0..count.data() {
1405             // 将物理页帧映射到虚拟页帧
1406             let r =
1407                 unsafe { mapper.map_phys(cur_dest.virt_address(), cur_phy.phys_address(), flags) }
1408                     .expect("Failed to map phys, may be OOM error");
1409 
1410             // todo: 增加OOM处理
1411 
1412             // 刷新TLB
1413             flusher.consume(r);
1414 
1415             cur_phy = cur_phy.next();
1416             cur_dest = cur_dest.next();
1417         }
1418 
1419         let r: Arc<LockedVMA> = LockedVMA::new(VMA {
1420             region: VirtRegion::new(destination.virt_address(), count.data() * MMArch::PAGE_SIZE),
1421             vm_flags,
1422             flags,
1423             mapped: true,
1424             user_address_space: None,
1425             self_ref: Weak::default(),
1426             provider: Provider::Allocated,
1427         });
1428 
1429         // 将VMA加入到anon_vma中
1430         let mut page_manager_guard = page_manager_lock_irqsave();
1431         cur_phy = phys;
1432         for _ in 0..count.data() {
1433             let paddr = cur_phy.phys_address();
1434             let page = page_manager_guard.get_mut(&paddr);
1435             page.insert_vma(r.clone());
1436             cur_phy = cur_phy.next();
1437         }
1438 
1439         return Ok(r);
1440     }
1441 
1442     /// 从页分配器中分配一些物理页,并把它们映射到指定的虚拟地址,然后创建VMA
1443     ///
1444     /// @param destination 要映射到的虚拟地址
1445     /// @param count 要映射的页帧数量
1446     /// @param flags 页面标志位
1447     /// @param mapper 页表映射器
1448     /// @param flusher 页表项刷新器
1449     ///
1450     /// @return 返回映射后的虚拟内存区域
1451     pub fn zeroed(
1452         destination: VirtPageFrame,
1453         page_count: PageFrameCount,
1454         vm_flags: VmFlags,
1455         flags: PageFlags<MMArch>,
1456         mapper: &mut PageMapper,
1457         mut flusher: impl Flusher<MMArch>,
1458     ) -> Result<Arc<LockedVMA>, SystemError> {
1459         let mut cur_dest: VirtPageFrame = destination;
1460         // debug!(
1461         //     "VMA::zeroed: page_count = {:?}, destination={destination:?}",
1462         //     page_count
1463         // );
1464         for _ in 0..page_count.data() {
1465             // debug!(
1466             //     "VMA::zeroed: cur_dest={cur_dest:?}, vaddr = {:?}",
1467             //     cur_dest.virt_address()
1468             // );
1469             let r = unsafe { mapper.map(cur_dest.virt_address(), flags) }
1470                 .expect("Failed to map zero, may be OOM error");
1471             // todo: 增加OOM处理
1472 
1473             // 稍后再刷新TLB,这里取消刷新
1474             flusher.consume(r);
1475             cur_dest = cur_dest.next();
1476         }
1477         let r = LockedVMA::new(VMA::new(
1478             VirtRegion::new(
1479                 destination.virt_address(),
1480                 page_count.data() * MMArch::PAGE_SIZE,
1481             ),
1482             vm_flags,
1483             flags,
1484             true,
1485         ));
1486         drop(flusher);
1487         // debug!("VMA::zeroed: flusher dropped");
1488 
1489         // 清空这些内存并将VMA加入到anon_vma中
1490         let mut page_manager_guard = page_manager_lock_irqsave();
1491         let virt_iter: VirtPageFrameIter =
1492             VirtPageFrameIter::new(destination, destination.add(page_count));
1493         for frame in virt_iter {
1494             let paddr = mapper.translate(frame.virt_address()).unwrap().0;
1495 
1496             // 将VMA加入到anon_vma
1497             let page = page_manager_guard.get_mut(&paddr);
1498             page.insert_vma(r.clone());
1499         }
1500         // debug!("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         // debug!(
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         // debug!(
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         // debug!(
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         // debug!("extend user stack: {:?} {}", stack_bottom, stack_size);
1608         // 分配用户栈
1609         user_stack.initial_extend(vm, stack_size)?;
1610         // debug!("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