1 use alloc::sync::Arc;
2 use system_error::SystemError;
3 
4 use crate::{arch::MMArch, include::bindings::bindings::PAGE_OFFSET};
5 
6 use core::{
7     cmp,
8     fmt::Debug,
9     intrinsics::unlikely,
10     ops::{Add, AddAssign, Sub, SubAssign},
11     ptr,
12     sync::atomic::{AtomicBool, Ordering},
13 };
14 
15 use self::{
16     allocator::page_frame::{VirtPageFrame, VirtPageFrameIter},
17     memblock::MemoryAreaAttr,
18     page::round_up_to_page_size,
19     ucontext::{AddressSpace, UserMapper},
20 };
21 
22 pub mod allocator;
23 pub mod c_adapter;
24 pub mod early_ioremap;
25 pub mod init;
26 pub mod kernel_mapper;
27 pub mod memblock;
28 pub mod mmio_buddy;
29 pub mod no_init;
30 pub mod page;
31 pub mod percpu;
32 pub mod syscall;
33 pub mod ucontext;
34 
35 /// 内核INIT进程的用户地址空间结构体(仅在process_init中初始化)
36 static mut __INITIAL_PROCESS_ADDRESS_SPACE: Option<Arc<AddressSpace>> = None;
37 
38 bitflags! {
39     /// Virtual memory flags
40     pub struct VmFlags:u32{
41         const VM_NONE = 0x00000000;
42 
43         const VM_READ = 0x00000001;
44         const VM_WRITE = 0x00000002;
45         const VM_EXEC = 0x00000004;
46         const VM_SHARED = 0x00000008;
47 
48         const VM_MAYREAD = 0x00000010;
49         const VM_MAYWRITE = 0x00000020;
50         const VM_MAYEXEC = 0x00000040;
51         const VM_MAYSHARE = 0x00000080;
52 
53         const VM_GROWSDOWN = 0x00000100;
54         const VM_UFFD_MISSING = 0x00000200;
55         const VM_PFNMAP = 0x00000400;
56         const VM_UFFD_WP = 0x00001000;
57 
58         const VM_LOCKED = 0x00002000;
59         const VM_IO = 0x00004000;
60 
61         const VM_SEQ_READ = 0x00008000;
62         const VM_RAND_READ = 0x00010000;
63 
64         const VM_DONTCOPY = 0x00020000;
65         const VM_DONTEXPAND = 0x00040000;
66         const VM_LOCKONFAULT = 0x00080000;
67         const VM_ACCOUNT = 0x00100000;
68         const VM_NORESERVE = 0x00200000;
69         const VM_HUGETLB = 0x00400000;
70         const VM_SYNC = 0x00800000;
71         const VM_ARCH_1 = 0x01000000;
72         const VM_WIPEONFORK = 0x02000000;
73         const VM_DONTDUMP = 0x04000000;
74     }
75 }
76 
77 /// 获取内核INIT进程的用户地址空间结构体
78 #[allow(non_snake_case)]
79 #[inline(always)]
INITIAL_PROCESS_ADDRESS_SPACE() -> Arc<AddressSpace>80 pub fn INITIAL_PROCESS_ADDRESS_SPACE() -> Arc<AddressSpace> {
81     unsafe {
82         return __INITIAL_PROCESS_ADDRESS_SPACE
83             .as_ref()
84             .expect("INITIAL_PROCESS_ADDRESS_SPACE is null")
85             .clone();
86     }
87 }
88 
89 /// 设置内核INIT进程的用户地址空间结构体全局变量
90 #[allow(non_snake_case)]
set_INITIAL_PROCESS_ADDRESS_SPACE(address_space: Arc<AddressSpace>)91 pub unsafe fn set_INITIAL_PROCESS_ADDRESS_SPACE(address_space: Arc<AddressSpace>) {
92     static INITIALIZED: AtomicBool = AtomicBool::new(false);
93     if INITIALIZED
94         .compare_exchange(false, true, Ordering::SeqCst, Ordering::Acquire)
95         .is_err()
96     {
97         panic!("INITIAL_PROCESS_ADDRESS_SPACE is already initialized");
98     }
99     __INITIAL_PROCESS_ADDRESS_SPACE = Some(address_space);
100 }
101 
102 /// @brief 将内核空间的虚拟地址转换为物理地址
103 #[inline(always)]
virt_2_phys(addr: usize) -> usize104 pub fn virt_2_phys(addr: usize) -> usize {
105     addr - PAGE_OFFSET as usize
106 }
107 
108 /// @brief 将物理地址转换为内核空间的虚拟地址
109 #[inline(always)]
phys_2_virt(addr: usize) -> usize110 pub fn phys_2_virt(addr: usize) -> usize {
111     addr + PAGE_OFFSET as usize
112 }
113 
114 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
115 pub enum PageTableKind {
116     /// 用户可访问的页表
117     User,
118     /// 内核页表
119     Kernel,
120     /// x86内存虚拟化中使用的EPT
121     #[cfg(target_arch = "x86_64")]
122     EPT,
123 }
124 
125 /// 物理内存地址
126 #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Hash)]
127 #[repr(transparent)]
128 pub struct PhysAddr(usize);
129 
130 impl PhysAddr {
131     /// 最大物理地址
132     pub const MAX: Self = PhysAddr(usize::MAX);
133 
134     #[inline(always)]
new(address: usize) -> Self135     pub const fn new(address: usize) -> Self {
136         Self(address)
137     }
138 
139     /// @brief 获取物理地址的值
140     #[inline(always)]
data(&self) -> usize141     pub const fn data(&self) -> usize {
142         self.0
143     }
144 
145     /// @brief 将物理地址加上一个偏移量
146     #[inline(always)]
add(self, offset: usize) -> Self147     pub fn add(self, offset: usize) -> Self {
148         Self(self.0 + offset)
149     }
150 
151     /// @brief 判断物理地址是否按照指定要求对齐
152     #[inline(always)]
check_aligned(&self, align: usize) -> bool153     pub fn check_aligned(&self, align: usize) -> bool {
154         return self.0 & (align - 1) == 0;
155     }
156 
157     #[inline(always)]
is_null(&self) -> bool158     pub fn is_null(&self) -> bool {
159         return self.0 == 0;
160     }
161 }
162 
163 impl Debug for PhysAddr {
fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result164     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
165         write!(f, "PhysAddr({:#x})", self.0)
166     }
167 }
168 
169 impl core::ops::Add<usize> for PhysAddr {
170     type Output = Self;
171 
172     #[inline(always)]
add(self, rhs: usize) -> Self::Output173     fn add(self, rhs: usize) -> Self::Output {
174         return Self(self.0 + rhs);
175     }
176 }
177 
178 impl core::ops::AddAssign<usize> for PhysAddr {
179     #[inline(always)]
add_assign(&mut self, rhs: usize)180     fn add_assign(&mut self, rhs: usize) {
181         self.0 += rhs;
182     }
183 }
184 
185 impl core::ops::Add<PhysAddr> for PhysAddr {
186     type Output = Self;
187 
188     #[inline(always)]
add(self, rhs: PhysAddr) -> Self::Output189     fn add(self, rhs: PhysAddr) -> Self::Output {
190         return Self(self.0 + rhs.0);
191     }
192 }
193 
194 impl core::ops::AddAssign<PhysAddr> for PhysAddr {
195     #[inline(always)]
add_assign(&mut self, rhs: PhysAddr)196     fn add_assign(&mut self, rhs: PhysAddr) {
197         self.0 += rhs.0;
198     }
199 }
200 
201 impl core::ops::BitOrAssign<usize> for PhysAddr {
202     #[inline(always)]
bitor_assign(&mut self, rhs: usize)203     fn bitor_assign(&mut self, rhs: usize) {
204         self.0 |= rhs;
205     }
206 }
207 
208 impl core::ops::BitOrAssign<PhysAddr> for PhysAddr {
209     #[inline(always)]
bitor_assign(&mut self, rhs: PhysAddr)210     fn bitor_assign(&mut self, rhs: PhysAddr) {
211         self.0 |= rhs.0;
212     }
213 }
214 
215 impl core::ops::Sub<usize> for PhysAddr {
216     type Output = Self;
217 
218     #[inline(always)]
sub(self, rhs: usize) -> Self::Output219     fn sub(self, rhs: usize) -> Self::Output {
220         return Self(self.0 - rhs);
221     }
222 }
223 
224 impl core::ops::SubAssign<usize> for PhysAddr {
225     #[inline(always)]
sub_assign(&mut self, rhs: usize)226     fn sub_assign(&mut self, rhs: usize) {
227         self.0 -= rhs;
228     }
229 }
230 
231 impl core::ops::Sub<PhysAddr> for PhysAddr {
232     type Output = usize;
233 
234     #[inline(always)]
sub(self, rhs: PhysAddr) -> Self::Output235     fn sub(self, rhs: PhysAddr) -> Self::Output {
236         return self.0 - rhs.0;
237     }
238 }
239 
240 impl core::ops::SubAssign<PhysAddr> for PhysAddr {
241     #[inline(always)]
sub_assign(&mut self, rhs: PhysAddr)242     fn sub_assign(&mut self, rhs: PhysAddr) {
243         self.0 -= rhs.0;
244     }
245 }
246 
247 /// 虚拟内存地址
248 #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Hash)]
249 #[repr(transparent)]
250 pub struct VirtAddr(usize);
251 
252 impl VirtAddr {
253     #[inline(always)]
new(address: usize) -> Self254     pub const fn new(address: usize) -> Self {
255         return Self(address);
256     }
257 
258     /// @brief 获取虚拟地址的值
259     #[inline(always)]
data(&self) -> usize260     pub const fn data(&self) -> usize {
261         return self.0;
262     }
263 
264     /// @brief 判断虚拟地址的类型
265     #[inline(always)]
kind(&self) -> PageTableKind266     pub fn kind(&self) -> PageTableKind {
267         if self.check_user() {
268             return PageTableKind::User;
269         } else {
270             return PageTableKind::Kernel;
271         }
272     }
273 
274     /// @brief 判断虚拟地址是否按照指定要求对齐
275     #[inline(always)]
check_aligned(&self, align: usize) -> bool276     pub fn check_aligned(&self, align: usize) -> bool {
277         return self.0 & (align - 1) == 0;
278     }
279 
280     /// @brief 判断虚拟地址是否在用户空间
281     #[inline(always)]
check_user(&self) -> bool282     pub fn check_user(&self) -> bool {
283         if self < &MMArch::USER_END_VADDR {
284             return true;
285         } else {
286             return false;
287         }
288     }
289 
290     #[inline(always)]
as_ptr<T>(self) -> *mut T291     pub fn as_ptr<T>(self) -> *mut T {
292         return self.0 as *mut T;
293     }
294 
295     #[inline(always)]
is_null(&self) -> bool296     pub fn is_null(&self) -> bool {
297         return self.0 == 0;
298     }
299 }
300 
301 impl Add<VirtAddr> for VirtAddr {
302     type Output = Self;
303 
304     #[inline(always)]
add(self, rhs: VirtAddr) -> Self::Output305     fn add(self, rhs: VirtAddr) -> Self::Output {
306         return Self(self.0 + rhs.0);
307     }
308 }
309 
310 impl Add<usize> for VirtAddr {
311     type Output = Self;
312 
313     #[inline(always)]
add(self, rhs: usize) -> Self::Output314     fn add(self, rhs: usize) -> Self::Output {
315         return Self(self.0 + rhs);
316     }
317 }
318 
319 impl Sub<VirtAddr> for VirtAddr {
320     type Output = usize;
321 
322     #[inline(always)]
sub(self, rhs: VirtAddr) -> Self::Output323     fn sub(self, rhs: VirtAddr) -> Self::Output {
324         return self.0 - rhs.0;
325     }
326 }
327 
328 impl Sub<usize> for VirtAddr {
329     type Output = Self;
330 
331     #[inline(always)]
sub(self, rhs: usize) -> Self::Output332     fn sub(self, rhs: usize) -> Self::Output {
333         return Self(self.0 - rhs);
334     }
335 }
336 
337 impl AddAssign<usize> for VirtAddr {
338     #[inline(always)]
add_assign(&mut self, rhs: usize)339     fn add_assign(&mut self, rhs: usize) {
340         self.0 += rhs;
341     }
342 }
343 
344 impl AddAssign<VirtAddr> for VirtAddr {
345     #[inline(always)]
add_assign(&mut self, rhs: VirtAddr)346     fn add_assign(&mut self, rhs: VirtAddr) {
347         self.0 += rhs.0;
348     }
349 }
350 
351 impl SubAssign<usize> for VirtAddr {
352     #[inline(always)]
sub_assign(&mut self, rhs: usize)353     fn sub_assign(&mut self, rhs: usize) {
354         self.0 -= rhs;
355     }
356 }
357 
358 impl SubAssign<VirtAddr> for VirtAddr {
359     #[inline(always)]
sub_assign(&mut self, rhs: VirtAddr)360     fn sub_assign(&mut self, rhs: VirtAddr) {
361         self.0 -= rhs.0;
362     }
363 }
364 
365 impl Debug for VirtAddr {
fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result366     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
367         write!(f, "VirtAddr({:#x})", self.0)
368     }
369 }
370 
371 /// @brief 物理内存区域
372 #[derive(Clone, Copy, Debug)]
373 pub struct PhysMemoryArea {
374     /// 物理基地址
375     pub base: PhysAddr,
376     /// 该区域的物理内存大小
377     pub size: usize,
378 
379     pub flags: MemoryAreaAttr,
380 }
381 
382 impl PhysMemoryArea {
383     pub const DEFAULT: Self = Self {
384         base: PhysAddr::new(0),
385         size: 0,
386         flags: MemoryAreaAttr::empty(),
387     };
388 
new(base: PhysAddr, size: usize, flags: MemoryAreaAttr) -> Self389     pub fn new(base: PhysAddr, size: usize, flags: MemoryAreaAttr) -> Self {
390         Self { base, size, flags }
391     }
392 
393     /// 返回向上页面对齐的区域起始物理地址
area_base_aligned(&self) -> PhysAddr394     pub fn area_base_aligned(&self) -> PhysAddr {
395         return PhysAddr::new(
396             (self.base.data() + (MMArch::PAGE_SIZE - 1)) & !(MMArch::PAGE_SIZE - 1),
397         );
398     }
399 
400     /// 返回向下页面对齐的区域截止物理地址
area_end_aligned(&self) -> PhysAddr401     pub fn area_end_aligned(&self) -> PhysAddr {
402         return PhysAddr::new((self.base.data() + self.size) & !(MMArch::PAGE_SIZE - 1));
403     }
404 }
405 
406 impl Default for PhysMemoryArea {
default() -> Self407     fn default() -> Self {
408         return Self::DEFAULT;
409     }
410 }
411 
412 pub trait MemoryManagementArch: Clone + Copy + Debug {
413     /// 页面大小的shift(假如页面4K,那么这个值就是12,因为2^12=4096)
414     const PAGE_SHIFT: usize;
415     /// 每个页表的页表项数目。(以2^n次幂来表示)假如有512个页表项,那么这个值就是9
416     const PAGE_ENTRY_SHIFT: usize;
417     /// 页表层级数量
418     const PAGE_LEVELS: usize;
419 
420     /// 页表项的有效位的index(假如页表项的第0-51位有效,那么这个值就是52)
421     const ENTRY_ADDRESS_SHIFT: usize;
422     /// 页面的页表项的默认值
423     const ENTRY_FLAG_DEFAULT_PAGE: usize;
424     /// 页表的页表项的默认值
425     const ENTRY_FLAG_DEFAULT_TABLE: usize;
426     /// 页表项的present位被置位之后的值
427     const ENTRY_FLAG_PRESENT: usize;
428     /// 页表项为read only时的值
429     const ENTRY_FLAG_READONLY: usize;
430     /// 页表项为可读写状态的值
431     const ENTRY_FLAG_READWRITE: usize;
432     /// 页面项标记页面为user page的值
433     const ENTRY_FLAG_USER: usize;
434     /// 页面项标记页面为write through的值
435     const ENTRY_FLAG_WRITE_THROUGH: usize;
436     /// 页面项标记页面为cache disable的值
437     const ENTRY_FLAG_CACHE_DISABLE: usize;
438     /// 标记当前页面不可执行的标志位(Execute disable)(也就是说,不能从这段内存里面获取处理器指令)
439     const ENTRY_FLAG_NO_EXEC: usize;
440     /// 标记当前页面可执行的标志位(Execute enable)
441     const ENTRY_FLAG_EXEC: usize;
442     /// 当该位为1时,标明这是一个脏页
443     const ENTRY_FLAG_DIRTY: usize;
444     /// 当该位为1时,代表这个页面被处理器访问过
445     const ENTRY_FLAG_ACCESSED: usize;
446 
447     /// 虚拟地址与物理地址的偏移量
448     const PHYS_OFFSET: usize;
449 
450     /// 内核在链接时被链接到的偏移量
451     const KERNEL_LINK_OFFSET: usize;
452 
453     const KERNEL_VIRT_START: usize = Self::PHYS_OFFSET + Self::KERNEL_LINK_OFFSET;
454 
455     /// 每个页面的大小
456     const PAGE_SIZE: usize = 1 << Self::PAGE_SHIFT;
457     /// 通过这个mask,获取地址的页内偏移量
458     const PAGE_OFFSET_MASK: usize = Self::PAGE_SIZE - 1;
459     /// 通过这个mask,获取页的首地址
460     const PAGE_MASK: usize = !(Self::PAGE_OFFSET_MASK);
461     /// 页表项的地址、数据部分的shift。
462     /// 打个比方,如果这个值为52,那么意味着页表项的[0, 52)位,用于表示地址以及其他的标志位
463     const PAGE_ADDRESS_SHIFT: usize = Self::PAGE_LEVELS * Self::PAGE_ENTRY_SHIFT + Self::PAGE_SHIFT;
464     /// 最大的虚拟地址(对于不同的架构,由于上述PAGE_ADDRESS_SHIFT可能包括了reserved bits, 事实上能表示的虚拟地址应该比这个值要小)
465     const PAGE_ADDRESS_SIZE: usize = 1 << Self::PAGE_ADDRESS_SHIFT;
466     /// 页表项的值与这个常量进行与运算,得到的结果是所填写的物理地址
467     const PAGE_ADDRESS_MASK: usize = Self::PAGE_ADDRESS_SIZE - Self::PAGE_SIZE;
468     /// 每个页表项的大小
469     const PAGE_ENTRY_SIZE: usize = 1 << (Self::PAGE_SHIFT - Self::PAGE_ENTRY_SHIFT);
470     /// 每个页表的页表项数目
471     const PAGE_ENTRY_NUM: usize = 1 << Self::PAGE_ENTRY_SHIFT;
472     /// 该字段用于根据虚拟地址,获取该虚拟地址在对应的页表中是第几个页表项
473     const PAGE_ENTRY_MASK: usize = Self::PAGE_ENTRY_NUM - 1;
474 
475     const PAGE_NEGATIVE_MASK: usize = !((Self::PAGE_ADDRESS_SIZE) - 1);
476 
477     const ENTRY_ADDRESS_SIZE: usize = 1 << Self::ENTRY_ADDRESS_SHIFT;
478     /// 该mask用于获取页表项中地址字段
479     const ENTRY_ADDRESS_MASK: usize = Self::ENTRY_ADDRESS_SIZE - Self::PAGE_SIZE;
480     /// 这个mask用于获取页表项中的flags
481     const ENTRY_FLAGS_MASK: usize = !Self::ENTRY_ADDRESS_MASK;
482 
483     /// 用户空间的最高地址
484     const USER_END_VADDR: VirtAddr;
485     /// 用户堆的起始地址
486     const USER_BRK_START: VirtAddr;
487     /// 用户栈起始地址(向下生长,不包含该值)
488     const USER_STACK_START: VirtAddr;
489 
490     /// 内核的固定映射区的起始地址
491     const FIXMAP_START_VADDR: VirtAddr;
492     /// 内核的固定映射区的大小
493     const FIXMAP_SIZE: usize;
494     /// 内核的固定映射区的结束地址
495     const FIXMAP_END_VADDR: VirtAddr =
496         VirtAddr::new(Self::FIXMAP_START_VADDR.data() + Self::FIXMAP_SIZE);
497 
498     /// @brief 用于初始化内存管理模块与架构相关的信息。
499     /// 该函数应调用其他模块的接口,把可用内存区域添加到memblock,提供给BumpAllocator使用
init()500     unsafe fn init();
501 
502     /// @brief 读取指定虚拟地址的值,并假设它是类型T的指针
503     #[inline(always)]
read<T>(address: VirtAddr) -> T504     unsafe fn read<T>(address: VirtAddr) -> T {
505         return ptr::read(address.data() as *const T);
506     }
507 
508     /// @brief 将value写入到指定的虚拟地址
509     #[inline(always)]
write<T>(address: VirtAddr, value: T)510     unsafe fn write<T>(address: VirtAddr, value: T) {
511         ptr::write(address.data() as *mut T, value);
512     }
513 
514     #[inline(always)]
write_bytes(address: VirtAddr, value: u8, count: usize)515     unsafe fn write_bytes(address: VirtAddr, value: u8, count: usize) {
516         ptr::write_bytes(address.data() as *mut u8, value, count);
517     }
518 
519     /// @brief 刷新TLB中,关于指定虚拟地址的条目
invalidate_page(address: VirtAddr)520     unsafe fn invalidate_page(address: VirtAddr);
521 
522     /// @brief 刷新TLB中,所有的条目
invalidate_all()523     unsafe fn invalidate_all();
524 
525     /// @brief 获取顶级页表的物理地址
table(table_kind: PageTableKind) -> PhysAddr526     unsafe fn table(table_kind: PageTableKind) -> PhysAddr;
527 
528     /// @brief 设置顶级页表的物理地址到处理器中
set_table(table_kind: PageTableKind, table: PhysAddr)529     unsafe fn set_table(table_kind: PageTableKind, table: PhysAddr);
530 
531     /// @brief 将物理地址转换为虚拟地址.
532     ///
533     /// @param phys 物理地址
534     ///
535     /// @return 转换后的虚拟地址。如果转换失败,返回None
536     #[inline(always)]
phys_2_virt(phys: PhysAddr) -> Option<VirtAddr>537     unsafe fn phys_2_virt(phys: PhysAddr) -> Option<VirtAddr> {
538         if let Some(vaddr) = phys.data().checked_add(Self::PHYS_OFFSET) {
539             return Some(VirtAddr::new(vaddr));
540         } else {
541             return None;
542         }
543     }
544 
545     /// 将虚拟地址转换为物理地址
546     ///
547     /// ## 参数
548     ///
549     /// - `virt` 虚拟地址
550     ///
551     /// ## 返回值
552     ///
553     /// 转换后的物理地址。如果转换失败,返回None
554     #[inline(always)]
virt_2_phys(virt: VirtAddr) -> Option<PhysAddr>555     unsafe fn virt_2_phys(virt: VirtAddr) -> Option<PhysAddr> {
556         if let Some(paddr) = virt.data().checked_sub(Self::PHYS_OFFSET) {
557             return Some(PhysAddr::new(paddr));
558         } else {
559             return None;
560         }
561     }
562 
563     /// @brief 判断指定的虚拟地址是否正确(符合规范)
virt_is_valid(virt: VirtAddr) -> bool564     fn virt_is_valid(virt: VirtAddr) -> bool;
565 
566     /// 获取内存管理初始化时,创建的第一个内核页表的地址
initial_page_table() -> PhysAddr567     fn initial_page_table() -> PhysAddr;
568 
569     /// 初始化新的usermapper,为用户进程创建页表
setup_new_usermapper() -> Result<UserMapper, SystemError>570     fn setup_new_usermapper() -> Result<UserMapper, SystemError>;
571 
572     /// 创建页表项
573     ///
574     /// 这是一个低阶api,用于根据物理地址以及指定好的pageflags,创建页表项
575     ///
576     /// ## 参数
577     ///
578     /// - `paddr` 物理地址
579     /// - `page_flags` 页表项的flags
580     ///
581     /// ## 返回值
582     ///
583     /// 页表项的值
make_entry(paddr: PhysAddr, page_flags: usize) -> usize584     fn make_entry(paddr: PhysAddr, page_flags: usize) -> usize;
585 }
586 
587 /// @brief 虚拟地址范围
588 /// 该结构体用于表示一个虚拟地址范围,包括起始地址与大小
589 ///
590 /// 请注意与VMA进行区分,该结构体被VMA所包含
591 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
592 pub struct VirtRegion {
593     start: VirtAddr,
594     size: usize,
595 }
596 
597 #[allow(dead_code)]
598 impl VirtRegion {
599     /// # 创建一个新的虚拟地址范围
new(start: VirtAddr, size: usize) -> Self600     pub fn new(start: VirtAddr, size: usize) -> Self {
601         VirtRegion { start, size }
602     }
603 
604     /// 获取虚拟地址范围的起始地址
605     #[inline(always)]
start(&self) -> VirtAddr606     pub fn start(&self) -> VirtAddr {
607         self.start
608     }
609 
610     /// 获取虚拟地址范围的截止地址(不包括返回的地址)
611     #[inline(always)]
end(&self) -> VirtAddr612     pub fn end(&self) -> VirtAddr {
613         return self.start().add(self.size);
614     }
615 
616     /// # Create a new VirtRegion from a range [start, end)
617     ///
618     /// If end <= start, return None
between(start: VirtAddr, end: VirtAddr) -> Option<Self>619     pub fn between(start: VirtAddr, end: VirtAddr) -> Option<Self> {
620         if unlikely(end.data() <= start.data()) {
621             return None;
622         }
623         let size = end.data() - start.data();
624         return Some(VirtRegion::new(start, size));
625     }
626 
627     /// # 取两个虚拟地址范围的交集
628     ///
629     /// 如果两个虚拟地址范围没有交集,返回None
intersect(&self, other: &VirtRegion) -> Option<VirtRegion>630     pub fn intersect(&self, other: &VirtRegion) -> Option<VirtRegion> {
631         let start = self.start.max(other.start);
632         let end = self.end().min(other.end());
633         return VirtRegion::between(start, end);
634     }
635 
636     /// 设置虚拟地址范围的起始地址
637     #[inline(always)]
set_start(&mut self, start: VirtAddr)638     pub fn set_start(&mut self, start: VirtAddr) {
639         self.start = start;
640     }
641 
642     #[inline(always)]
size(&self) -> usize643     pub fn size(&self) -> usize {
644         self.size
645     }
646 
647     /// 设置虚拟地址范围的大小
648     #[inline(always)]
set_size(&mut self, size: usize)649     pub fn set_size(&mut self, size: usize) {
650         self.size = size;
651     }
652 
653     /// 判断虚拟地址范围是否为空
654     #[inline(always)]
is_empty(&self) -> bool655     pub fn is_empty(&self) -> bool {
656         self.size == 0
657     }
658 
659     /// 将虚拟地址区域的大小向上对齐到页大小
660     #[inline(always)]
round_up_size_to_page(self) -> Self661     pub fn round_up_size_to_page(self) -> Self {
662         return VirtRegion::new(self.start, round_up_to_page_size(self.size));
663     }
664 
665     /// 判断两个虚拟地址范围是否由于具有交集而导致冲突
666     #[inline(always)]
collide(&self, other: &VirtRegion) -> bool667     pub fn collide(&self, other: &VirtRegion) -> bool {
668         return self.intersect(other).is_some();
669     }
670 
iter_pages(&self) -> VirtPageFrameIter671     pub fn iter_pages(&self) -> VirtPageFrameIter {
672         return VirtPageFrame::iter_range(
673             VirtPageFrame::new(self.start),
674             VirtPageFrame::new(self.end()),
675         );
676     }
677 
678     /// 获取[self.start(), region.start())的虚拟地址范围
679     ///
680     /// 如果self.start() >= region.start(),返回None
before(self, region: &VirtRegion) -> Option<Self>681     pub fn before(self, region: &VirtRegion) -> Option<Self> {
682         return Self::between(self.start(), region.start());
683     }
684 
685     /// 获取[region.end(),self.end())的虚拟地址范围
686     ///
687     /// 如果 self.end() >= region.end() ,返回None
after(self, region: &VirtRegion) -> Option<Self>688     pub fn after(self, region: &VirtRegion) -> Option<Self> {
689         // if self.end() > region.end() none
690         return Self::between(region.end(), self.end());
691     }
692 
693     /// 把当前虚拟地址范围内的某个虚拟地址,转换为另一个虚拟地址范围内的虚拟地址
694     ///
695     /// 如果vaddr不在当前虚拟地址范围内,返回None
696     ///
697     /// 如果vaddr在当前虚拟地址范围内,返回vaddr在new_base中的虚拟地址
rebase(self, vaddr: VirtAddr, new_base: &VirtRegion) -> Option<VirtAddr>698     pub fn rebase(self, vaddr: VirtAddr, new_base: &VirtRegion) -> Option<VirtAddr> {
699         if !self.contains(vaddr) {
700             return None;
701         }
702         let offset = vaddr.data() - self.start().data();
703         let new_start = new_base.start().data() + offset;
704         return Some(VirtAddr::new(new_start));
705     }
706 
707     /// 判断虚拟地址范围是否包含指定的虚拟地址
contains(&self, addr: VirtAddr) -> bool708     pub fn contains(&self, addr: VirtAddr) -> bool {
709         return self.start() <= addr && addr < self.end();
710     }
711 
712     /// 创建当前虚拟地址范围的页面迭代器
pages(&self) -> VirtPageFrameIter713     pub fn pages(&self) -> VirtPageFrameIter {
714         return VirtPageFrame::iter_range(
715             VirtPageFrame::new(self.start()),
716             VirtPageFrame::new(self.end()),
717         );
718     }
719 }
720 
721 impl PartialOrd for VirtRegion {
partial_cmp(&self, other: &Self) -> Option<cmp::Ordering>722     fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
723         return self.start.partial_cmp(&other.start);
724     }
725 }
726 
727 impl Ord for VirtRegion {
cmp(&self, other: &Self) -> cmp::Ordering728     fn cmp(&self, other: &Self) -> cmp::Ordering {
729         return self.start.cmp(&other.start);
730     }
731 }
732 
733 /// ## 判断虚拟地址是否超出了用户空间
734 ///
735 /// 如果虚拟地址超出了用户空间,返回Err(SystemError::EFAULT).
736 /// 如果end < start,返回Err(SystemError::EOVERFLOW)
737 ///
738 /// 否则返回Ok(())
verify_area(addr: VirtAddr, size: usize) -> Result<(), SystemError>739 pub fn verify_area(addr: VirtAddr, size: usize) -> Result<(), SystemError> {
740     let end = addr.add(size);
741     if unlikely(end.data() < addr.data()) {
742         return Err(SystemError::EOVERFLOW);
743     }
744 
745     if !addr.check_user() || !end.check_user() {
746         return Err(SystemError::EFAULT);
747     }
748 
749     return Ok(());
750 }
751