xref: /DragonOS/kernel/src/mm/mod.rs (revision b5b571e02693d91eb6918d3b7561e088c3e7ee81)
140fe15e0SLoGin use alloc::sync::Arc;
291e9d4abSLoGin use system_error::SystemError;
340fe15e0SLoGin 
491e9d4abSLoGin use crate::{arch::MMArch, include::bindings::bindings::PAGE_OFFSET};
540fe15e0SLoGin 
640fe15e0SLoGin use core::{
740fe15e0SLoGin     cmp,
840fe15e0SLoGin     fmt::Debug,
940fe15e0SLoGin     intrinsics::unlikely,
1040fe15e0SLoGin     ops::{Add, AddAssign, Sub, SubAssign},
1140fe15e0SLoGin     ptr,
1240fe15e0SLoGin     sync::atomic::{AtomicBool, Ordering},
1340fe15e0SLoGin };
1440fe15e0SLoGin 
1540fe15e0SLoGin use self::{
1640fe15e0SLoGin     allocator::page_frame::{VirtPageFrame, VirtPageFrameIter},
1792849878SLoGin     memblock::MemoryAreaAttr,
1840fe15e0SLoGin     page::round_up_to_page_size,
1940fe15e0SLoGin     ucontext::{AddressSpace, UserMapper},
2040fe15e0SLoGin };
21004e86ffSlogin 
2282d2e446Slogin pub mod allocator;
2340fe15e0SLoGin pub mod c_adapter;
2474ffde66SLoGin pub mod early_ioremap;
25453452ccSLoGin pub mod init;
2640fe15e0SLoGin pub mod kernel_mapper;
2745626c85SLoGin pub mod memblock;
28c2481452Shoumkh pub mod mmio_buddy;
2940fe15e0SLoGin pub mod no_init;
3040fe15e0SLoGin pub mod page;
31c3dad001SLoGin pub mod percpu;
32ab5c8ca4Slogin pub mod syscall;
3340fe15e0SLoGin pub mod ucontext;
3440fe15e0SLoGin 
3540fe15e0SLoGin /// 内核INIT进程的用户地址空间结构体(仅在process_init中初始化)
368cb2e9b3SLoGin static mut __IDLE_PROCESS_ADDRESS_SPACE: Option<Arc<AddressSpace>> = None;
3740fe15e0SLoGin 
384cfa009bSJomo bitflags! {
394cfa009bSJomo     /// Virtual memory flags
40*b5b571e0SLoGin     #[allow(clippy::bad_bit_mask)]
414cfa009bSJomo     pub struct VmFlags:u32{
424cfa009bSJomo         const VM_NONE = 0x00000000;
434cfa009bSJomo 
444cfa009bSJomo         const VM_READ = 0x00000001;
454cfa009bSJomo         const VM_WRITE = 0x00000002;
464cfa009bSJomo         const VM_EXEC = 0x00000004;
474cfa009bSJomo         const VM_SHARED = 0x00000008;
484cfa009bSJomo 
494cfa009bSJomo         const VM_MAYREAD = 0x00000010;
504cfa009bSJomo         const VM_MAYWRITE = 0x00000020;
514cfa009bSJomo         const VM_MAYEXEC = 0x00000040;
524cfa009bSJomo         const VM_MAYSHARE = 0x00000080;
534cfa009bSJomo 
544cfa009bSJomo         const VM_GROWSDOWN = 0x00000100;
554cfa009bSJomo         const VM_UFFD_MISSING = 0x00000200;
564cfa009bSJomo         const VM_PFNMAP = 0x00000400;
574cfa009bSJomo         const VM_UFFD_WP = 0x00001000;
584cfa009bSJomo 
594cfa009bSJomo         const VM_LOCKED = 0x00002000;
604cfa009bSJomo         const VM_IO = 0x00004000;
614cfa009bSJomo 
624cfa009bSJomo         const VM_SEQ_READ = 0x00008000;
634cfa009bSJomo         const VM_RAND_READ = 0x00010000;
644cfa009bSJomo 
654cfa009bSJomo         const VM_DONTCOPY = 0x00020000;
664cfa009bSJomo         const VM_DONTEXPAND = 0x00040000;
674cfa009bSJomo         const VM_LOCKONFAULT = 0x00080000;
684cfa009bSJomo         const VM_ACCOUNT = 0x00100000;
694cfa009bSJomo         const VM_NORESERVE = 0x00200000;
704cfa009bSJomo         const VM_HUGETLB = 0x00400000;
714cfa009bSJomo         const VM_SYNC = 0x00800000;
724cfa009bSJomo         const VM_ARCH_1 = 0x01000000;
734cfa009bSJomo         const VM_WIPEONFORK = 0x02000000;
744cfa009bSJomo         const VM_DONTDUMP = 0x04000000;
754cfa009bSJomo     }
764cfa009bSJomo }
774cfa009bSJomo 
788cb2e9b3SLoGin /// 获取内核IDLE进程的用户地址空间结构体
7940fe15e0SLoGin #[allow(non_snake_case)]
8040fe15e0SLoGin #[inline(always)]
818cb2e9b3SLoGin pub fn IDLE_PROCESS_ADDRESS_SPACE() -> Arc<AddressSpace> {
8240fe15e0SLoGin     unsafe {
838cb2e9b3SLoGin         return __IDLE_PROCESS_ADDRESS_SPACE
8440fe15e0SLoGin             .as_ref()
858cb2e9b3SLoGin             .expect("IDLE_PROCESS_ADDRESS_SPACE is null")
8640fe15e0SLoGin             .clone();
8740fe15e0SLoGin     }
8840fe15e0SLoGin }
8940fe15e0SLoGin 
908cb2e9b3SLoGin /// 设置内核IDLE进程的用户地址空间结构体全局变量
9140fe15e0SLoGin #[allow(non_snake_case)]
928cb2e9b3SLoGin pub unsafe fn set_IDLE_PROCESS_ADDRESS_SPACE(address_space: Arc<AddressSpace>) {
9340fe15e0SLoGin     static INITIALIZED: AtomicBool = AtomicBool::new(false);
9440fe15e0SLoGin     if INITIALIZED
9540fe15e0SLoGin         .compare_exchange(false, true, Ordering::SeqCst, Ordering::Acquire)
9640fe15e0SLoGin         .is_err()
9740fe15e0SLoGin     {
988cb2e9b3SLoGin         panic!("IDLE_PROCESS_ADDRESS_SPACE is already initialized");
9940fe15e0SLoGin     }
1008cb2e9b3SLoGin     __IDLE_PROCESS_ADDRESS_SPACE = Some(address_space);
10140fe15e0SLoGin }
102004e86ffSlogin 
103004e86ffSlogin /// @brief 将内核空间的虚拟地址转换为物理地址
104004e86ffSlogin #[inline(always)]
105004e86ffSlogin pub fn virt_2_phys(addr: usize) -> usize {
106004e86ffSlogin     addr - PAGE_OFFSET as usize
107004e86ffSlogin }
108004e86ffSlogin 
109004e86ffSlogin /// @brief 将物理地址转换为内核空间的虚拟地址
110004e86ffSlogin #[inline(always)]
111004e86ffSlogin pub fn phys_2_virt(addr: usize) -> usize {
112004e86ffSlogin     addr + PAGE_OFFSET as usize
113004e86ffSlogin }
114bacd691cSlogin 
11540fe15e0SLoGin #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
11640fe15e0SLoGin pub enum PageTableKind {
11740fe15e0SLoGin     /// 用户可访问的页表
11840fe15e0SLoGin     User,
11940fe15e0SLoGin     /// 内核页表
12040fe15e0SLoGin     Kernel,
1217a29d4fcSLoGin     /// x86内存虚拟化中使用的EPT
1227a29d4fcSLoGin     #[cfg(target_arch = "x86_64")]
12340314b30SXiaoye Zheng     EPT,
12440fe15e0SLoGin }
12540fe15e0SLoGin 
12640fe15e0SLoGin /// 物理内存地址
12740fe15e0SLoGin #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Hash)]
12840fe15e0SLoGin #[repr(transparent)]
12940fe15e0SLoGin pub struct PhysAddr(usize);
13040fe15e0SLoGin 
13140fe15e0SLoGin impl PhysAddr {
13292849878SLoGin     /// 最大物理地址
13392849878SLoGin     pub const MAX: Self = PhysAddr(usize::MAX);
13492849878SLoGin 
13540fe15e0SLoGin     #[inline(always)]
13640fe15e0SLoGin     pub const fn new(address: usize) -> Self {
13740fe15e0SLoGin         Self(address)
13840fe15e0SLoGin     }
13940fe15e0SLoGin 
14040fe15e0SLoGin     /// @brief 获取物理地址的值
14140fe15e0SLoGin     #[inline(always)]
14274ffde66SLoGin     pub const fn data(&self) -> usize {
14340fe15e0SLoGin         self.0
14440fe15e0SLoGin     }
14540fe15e0SLoGin 
14640fe15e0SLoGin     /// @brief 将物理地址加上一个偏移量
14740fe15e0SLoGin     #[inline(always)]
14840fe15e0SLoGin     pub fn add(self, offset: usize) -> Self {
14940fe15e0SLoGin         Self(self.0 + offset)
15040fe15e0SLoGin     }
15140fe15e0SLoGin 
15240fe15e0SLoGin     /// @brief 判断物理地址是否按照指定要求对齐
15340fe15e0SLoGin     #[inline(always)]
15440fe15e0SLoGin     pub fn check_aligned(&self, align: usize) -> bool {
15540fe15e0SLoGin         return self.0 & (align - 1) == 0;
15640fe15e0SLoGin     }
15740fe15e0SLoGin 
15840fe15e0SLoGin     #[inline(always)]
15940fe15e0SLoGin     pub fn is_null(&self) -> bool {
16040fe15e0SLoGin         return self.0 == 0;
16140fe15e0SLoGin     }
16240fe15e0SLoGin }
16340fe15e0SLoGin 
16440fe15e0SLoGin impl Debug for PhysAddr {
16540fe15e0SLoGin     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
16640fe15e0SLoGin         write!(f, "PhysAddr({:#x})", self.0)
16740fe15e0SLoGin     }
16840fe15e0SLoGin }
16940fe15e0SLoGin 
17040fe15e0SLoGin impl core::ops::Add<usize> for PhysAddr {
17140fe15e0SLoGin     type Output = Self;
17240fe15e0SLoGin 
17340fe15e0SLoGin     #[inline(always)]
17440fe15e0SLoGin     fn add(self, rhs: usize) -> Self::Output {
17540fe15e0SLoGin         return Self(self.0 + rhs);
17640fe15e0SLoGin     }
17740fe15e0SLoGin }
17840fe15e0SLoGin 
17940fe15e0SLoGin impl core::ops::AddAssign<usize> for PhysAddr {
18040fe15e0SLoGin     #[inline(always)]
18140fe15e0SLoGin     fn add_assign(&mut self, rhs: usize) {
18240fe15e0SLoGin         self.0 += rhs;
18340fe15e0SLoGin     }
18440fe15e0SLoGin }
18540fe15e0SLoGin 
18640fe15e0SLoGin impl core::ops::Add<PhysAddr> for PhysAddr {
18740fe15e0SLoGin     type Output = Self;
18840fe15e0SLoGin 
18940fe15e0SLoGin     #[inline(always)]
19040fe15e0SLoGin     fn add(self, rhs: PhysAddr) -> Self::Output {
19140fe15e0SLoGin         return Self(self.0 + rhs.0);
19240fe15e0SLoGin     }
19340fe15e0SLoGin }
19440fe15e0SLoGin 
19540fe15e0SLoGin impl core::ops::AddAssign<PhysAddr> for PhysAddr {
19640fe15e0SLoGin     #[inline(always)]
19740fe15e0SLoGin     fn add_assign(&mut self, rhs: PhysAddr) {
19840fe15e0SLoGin         self.0 += rhs.0;
19940fe15e0SLoGin     }
20040fe15e0SLoGin }
20140fe15e0SLoGin 
2022dd9f0c7SLoGin impl core::ops::BitOrAssign<usize> for PhysAddr {
2032dd9f0c7SLoGin     #[inline(always)]
2042dd9f0c7SLoGin     fn bitor_assign(&mut self, rhs: usize) {
2052dd9f0c7SLoGin         self.0 |= rhs;
2062dd9f0c7SLoGin     }
2072dd9f0c7SLoGin }
2082dd9f0c7SLoGin 
2092dd9f0c7SLoGin impl core::ops::BitOrAssign<PhysAddr> for PhysAddr {
2102dd9f0c7SLoGin     #[inline(always)]
2112dd9f0c7SLoGin     fn bitor_assign(&mut self, rhs: PhysAddr) {
2122dd9f0c7SLoGin         self.0 |= rhs.0;
2132dd9f0c7SLoGin     }
2142dd9f0c7SLoGin }
2152dd9f0c7SLoGin 
21640fe15e0SLoGin impl core::ops::Sub<usize> for PhysAddr {
21740fe15e0SLoGin     type Output = Self;
21840fe15e0SLoGin 
21940fe15e0SLoGin     #[inline(always)]
22040fe15e0SLoGin     fn sub(self, rhs: usize) -> Self::Output {
22140fe15e0SLoGin         return Self(self.0 - rhs);
22240fe15e0SLoGin     }
22340fe15e0SLoGin }
22440fe15e0SLoGin 
22540fe15e0SLoGin impl core::ops::SubAssign<usize> for PhysAddr {
22640fe15e0SLoGin     #[inline(always)]
22740fe15e0SLoGin     fn sub_assign(&mut self, rhs: usize) {
22840fe15e0SLoGin         self.0 -= rhs;
22940fe15e0SLoGin     }
23040fe15e0SLoGin }
23140fe15e0SLoGin 
23240fe15e0SLoGin impl core::ops::Sub<PhysAddr> for PhysAddr {
23340fe15e0SLoGin     type Output = usize;
23440fe15e0SLoGin 
23540fe15e0SLoGin     #[inline(always)]
23640fe15e0SLoGin     fn sub(self, rhs: PhysAddr) -> Self::Output {
23740fe15e0SLoGin         return self.0 - rhs.0;
23840fe15e0SLoGin     }
23940fe15e0SLoGin }
24040fe15e0SLoGin 
24140fe15e0SLoGin impl core::ops::SubAssign<PhysAddr> for PhysAddr {
24240fe15e0SLoGin     #[inline(always)]
24340fe15e0SLoGin     fn sub_assign(&mut self, rhs: PhysAddr) {
24440fe15e0SLoGin         self.0 -= rhs.0;
24540fe15e0SLoGin     }
24640fe15e0SLoGin }
24740fe15e0SLoGin 
24840fe15e0SLoGin /// 虚拟内存地址
24940fe15e0SLoGin #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Hash)]
25040fe15e0SLoGin #[repr(transparent)]
25140fe15e0SLoGin pub struct VirtAddr(usize);
25240fe15e0SLoGin 
25340fe15e0SLoGin impl VirtAddr {
25440fe15e0SLoGin     #[inline(always)]
25540fe15e0SLoGin     pub const fn new(address: usize) -> Self {
25640fe15e0SLoGin         return Self(address);
25740fe15e0SLoGin     }
25840fe15e0SLoGin 
25940fe15e0SLoGin     /// @brief 获取虚拟地址的值
26040fe15e0SLoGin     #[inline(always)]
26174ffde66SLoGin     pub const fn data(&self) -> usize {
26240fe15e0SLoGin         return self.0;
26340fe15e0SLoGin     }
26440fe15e0SLoGin 
26540fe15e0SLoGin     /// @brief 判断虚拟地址的类型
26640fe15e0SLoGin     #[inline(always)]
26740fe15e0SLoGin     pub fn kind(&self) -> PageTableKind {
26840fe15e0SLoGin         if self.check_user() {
26940fe15e0SLoGin             return PageTableKind::User;
27040fe15e0SLoGin         } else {
27140fe15e0SLoGin             return PageTableKind::Kernel;
27240fe15e0SLoGin         }
27340fe15e0SLoGin     }
27440fe15e0SLoGin 
27540fe15e0SLoGin     /// @brief 判断虚拟地址是否按照指定要求对齐
27640fe15e0SLoGin     #[inline(always)]
27740fe15e0SLoGin     pub fn check_aligned(&self, align: usize) -> bool {
27840fe15e0SLoGin         return self.0 & (align - 1) == 0;
27940fe15e0SLoGin     }
28040fe15e0SLoGin 
28140fe15e0SLoGin     /// @brief 判断虚拟地址是否在用户空间
28240fe15e0SLoGin     #[inline(always)]
28340fe15e0SLoGin     pub fn check_user(&self) -> bool {
284*b5b571e0SLoGin         return self < &MMArch::USER_END_VADDR;
28540fe15e0SLoGin     }
28640fe15e0SLoGin 
28740fe15e0SLoGin     #[inline(always)]
28840fe15e0SLoGin     pub fn as_ptr<T>(self) -> *mut T {
28940fe15e0SLoGin         return self.0 as *mut T;
29040fe15e0SLoGin     }
29140fe15e0SLoGin 
29240fe15e0SLoGin     #[inline(always)]
29340fe15e0SLoGin     pub fn is_null(&self) -> bool {
29440fe15e0SLoGin         return self.0 == 0;
29540fe15e0SLoGin     }
29640fe15e0SLoGin }
29740fe15e0SLoGin 
29840fe15e0SLoGin impl Add<VirtAddr> for VirtAddr {
29940fe15e0SLoGin     type Output = Self;
30040fe15e0SLoGin 
30140fe15e0SLoGin     #[inline(always)]
30240fe15e0SLoGin     fn add(self, rhs: VirtAddr) -> Self::Output {
30340fe15e0SLoGin         return Self(self.0 + rhs.0);
30440fe15e0SLoGin     }
30540fe15e0SLoGin }
30640fe15e0SLoGin 
30740fe15e0SLoGin impl Add<usize> for VirtAddr {
30840fe15e0SLoGin     type Output = Self;
30940fe15e0SLoGin 
31040fe15e0SLoGin     #[inline(always)]
31140fe15e0SLoGin     fn add(self, rhs: usize) -> Self::Output {
31240fe15e0SLoGin         return Self(self.0 + rhs);
31340fe15e0SLoGin     }
31440fe15e0SLoGin }
31540fe15e0SLoGin 
31640fe15e0SLoGin impl Sub<VirtAddr> for VirtAddr {
31740fe15e0SLoGin     type Output = usize;
31840fe15e0SLoGin 
31940fe15e0SLoGin     #[inline(always)]
32040fe15e0SLoGin     fn sub(self, rhs: VirtAddr) -> Self::Output {
32140fe15e0SLoGin         return self.0 - rhs.0;
32240fe15e0SLoGin     }
32340fe15e0SLoGin }
32440fe15e0SLoGin 
32540fe15e0SLoGin impl Sub<usize> for VirtAddr {
32640fe15e0SLoGin     type Output = Self;
32740fe15e0SLoGin 
32840fe15e0SLoGin     #[inline(always)]
32940fe15e0SLoGin     fn sub(self, rhs: usize) -> Self::Output {
33040fe15e0SLoGin         return Self(self.0 - rhs);
33140fe15e0SLoGin     }
33240fe15e0SLoGin }
33340fe15e0SLoGin 
33440fe15e0SLoGin impl AddAssign<usize> for VirtAddr {
33540fe15e0SLoGin     #[inline(always)]
33640fe15e0SLoGin     fn add_assign(&mut self, rhs: usize) {
33740fe15e0SLoGin         self.0 += rhs;
33840fe15e0SLoGin     }
33940fe15e0SLoGin }
34040fe15e0SLoGin 
34140fe15e0SLoGin impl AddAssign<VirtAddr> for VirtAddr {
34240fe15e0SLoGin     #[inline(always)]
34340fe15e0SLoGin     fn add_assign(&mut self, rhs: VirtAddr) {
34440fe15e0SLoGin         self.0 += rhs.0;
34540fe15e0SLoGin     }
34640fe15e0SLoGin }
34740fe15e0SLoGin 
34840fe15e0SLoGin impl SubAssign<usize> for VirtAddr {
34940fe15e0SLoGin     #[inline(always)]
35040fe15e0SLoGin     fn sub_assign(&mut self, rhs: usize) {
35140fe15e0SLoGin         self.0 -= rhs;
35240fe15e0SLoGin     }
35340fe15e0SLoGin }
35440fe15e0SLoGin 
35540fe15e0SLoGin impl SubAssign<VirtAddr> for VirtAddr {
35640fe15e0SLoGin     #[inline(always)]
35740fe15e0SLoGin     fn sub_assign(&mut self, rhs: VirtAddr) {
35840fe15e0SLoGin         self.0 -= rhs.0;
35940fe15e0SLoGin     }
36040fe15e0SLoGin }
36140fe15e0SLoGin 
36240fe15e0SLoGin impl Debug for VirtAddr {
36340fe15e0SLoGin     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36440fe15e0SLoGin         write!(f, "VirtAddr({:#x})", self.0)
36540fe15e0SLoGin     }
36640fe15e0SLoGin }
36740fe15e0SLoGin 
36840fe15e0SLoGin /// @brief 物理内存区域
36940fe15e0SLoGin #[derive(Clone, Copy, Debug)]
37040fe15e0SLoGin pub struct PhysMemoryArea {
37140fe15e0SLoGin     /// 物理基地址
37240fe15e0SLoGin     pub base: PhysAddr,
37340fe15e0SLoGin     /// 该区域的物理内存大小
37440fe15e0SLoGin     pub size: usize,
37592849878SLoGin 
37692849878SLoGin     pub flags: MemoryAreaAttr,
37740fe15e0SLoGin }
37840fe15e0SLoGin 
37999dbf38dSLoGin impl PhysMemoryArea {
38045626c85SLoGin     pub const DEFAULT: Self = Self {
38145626c85SLoGin         base: PhysAddr::new(0),
38245626c85SLoGin         size: 0,
38392849878SLoGin         flags: MemoryAreaAttr::empty(),
38445626c85SLoGin     };
38545626c85SLoGin 
38692849878SLoGin     pub fn new(base: PhysAddr, size: usize, flags: MemoryAreaAttr) -> Self {
38792849878SLoGin         Self { base, size, flags }
38899dbf38dSLoGin     }
38999dbf38dSLoGin 
39099dbf38dSLoGin     /// 返回向上页面对齐的区域起始物理地址
39199dbf38dSLoGin     pub fn area_base_aligned(&self) -> PhysAddr {
39299dbf38dSLoGin         return PhysAddr::new(
39399dbf38dSLoGin             (self.base.data() + (MMArch::PAGE_SIZE - 1)) & !(MMArch::PAGE_SIZE - 1),
39499dbf38dSLoGin         );
39599dbf38dSLoGin     }
39699dbf38dSLoGin 
39799dbf38dSLoGin     /// 返回向下页面对齐的区域截止物理地址
39899dbf38dSLoGin     pub fn area_end_aligned(&self) -> PhysAddr {
39999dbf38dSLoGin         return PhysAddr::new((self.base.data() + self.size) & !(MMArch::PAGE_SIZE - 1));
40099dbf38dSLoGin     }
40199dbf38dSLoGin }
40299dbf38dSLoGin 
40399dbf38dSLoGin impl Default for PhysMemoryArea {
40499dbf38dSLoGin     fn default() -> Self {
40545626c85SLoGin         return Self::DEFAULT;
40699dbf38dSLoGin     }
40799dbf38dSLoGin }
40899dbf38dSLoGin 
40940fe15e0SLoGin pub trait MemoryManagementArch: Clone + Copy + Debug {
41040fe15e0SLoGin     /// 页面大小的shift(假如页面4K,那么这个值就是12,因为2^12=4096)
41140fe15e0SLoGin     const PAGE_SHIFT: usize;
41240fe15e0SLoGin     /// 每个页表的页表项数目。(以2^n次幂来表示)假如有512个页表项,那么这个值就是9
41340fe15e0SLoGin     const PAGE_ENTRY_SHIFT: usize;
41440fe15e0SLoGin     /// 页表层级数量
41540fe15e0SLoGin     const PAGE_LEVELS: usize;
41640fe15e0SLoGin 
41740fe15e0SLoGin     /// 页表项的有效位的index(假如页表项的第0-51位有效,那么这个值就是52)
41840fe15e0SLoGin     const ENTRY_ADDRESS_SHIFT: usize;
41940fe15e0SLoGin     /// 页面的页表项的默认值
42040fe15e0SLoGin     const ENTRY_FLAG_DEFAULT_PAGE: usize;
42140fe15e0SLoGin     /// 页表的页表项的默认值
42240fe15e0SLoGin     const ENTRY_FLAG_DEFAULT_TABLE: usize;
42340fe15e0SLoGin     /// 页表项的present位被置位之后的值
42440fe15e0SLoGin     const ENTRY_FLAG_PRESENT: usize;
42540fe15e0SLoGin     /// 页表项为read only时的值
42640fe15e0SLoGin     const ENTRY_FLAG_READONLY: usize;
42740fe15e0SLoGin     /// 页表项为可读写状态的值
42840fe15e0SLoGin     const ENTRY_FLAG_READWRITE: usize;
42940fe15e0SLoGin     /// 页面项标记页面为user page的值
43040fe15e0SLoGin     const ENTRY_FLAG_USER: usize;
43140fe15e0SLoGin     /// 页面项标记页面为write through的值
43240fe15e0SLoGin     const ENTRY_FLAG_WRITE_THROUGH: usize;
43340fe15e0SLoGin     /// 页面项标记页面为cache disable的值
43440fe15e0SLoGin     const ENTRY_FLAG_CACHE_DISABLE: usize;
43540fe15e0SLoGin     /// 标记当前页面不可执行的标志位(Execute disable)(也就是说,不能从这段内存里面获取处理器指令)
43640fe15e0SLoGin     const ENTRY_FLAG_NO_EXEC: usize;
43740fe15e0SLoGin     /// 标记当前页面可执行的标志位(Execute enable)
43840fe15e0SLoGin     const ENTRY_FLAG_EXEC: usize;
43992849878SLoGin     /// 当该位为1时,标明这是一个脏页
44092849878SLoGin     const ENTRY_FLAG_DIRTY: usize;
44192849878SLoGin     /// 当该位为1时,代表这个页面被处理器访问过
44292849878SLoGin     const ENTRY_FLAG_ACCESSED: usize;
44340fe15e0SLoGin 
44440fe15e0SLoGin     /// 虚拟地址与物理地址的偏移量
44540fe15e0SLoGin     const PHYS_OFFSET: usize;
44640fe15e0SLoGin 
447453452ccSLoGin     /// 内核在链接时被链接到的偏移量
448453452ccSLoGin     const KERNEL_LINK_OFFSET: usize;
449453452ccSLoGin 
450453452ccSLoGin     const KERNEL_VIRT_START: usize = Self::PHYS_OFFSET + Self::KERNEL_LINK_OFFSET;
451453452ccSLoGin 
45240fe15e0SLoGin     /// 每个页面的大小
45340fe15e0SLoGin     const PAGE_SIZE: usize = 1 << Self::PAGE_SHIFT;
45440fe15e0SLoGin     /// 通过这个mask,获取地址的页内偏移量
45540fe15e0SLoGin     const PAGE_OFFSET_MASK: usize = Self::PAGE_SIZE - 1;
45640314b30SXiaoye Zheng     /// 通过这个mask,获取页的首地址
45740314b30SXiaoye Zheng     const PAGE_MASK: usize = !(Self::PAGE_OFFSET_MASK);
45840fe15e0SLoGin     /// 页表项的地址、数据部分的shift。
45940fe15e0SLoGin     /// 打个比方,如果这个值为52,那么意味着页表项的[0, 52)位,用于表示地址以及其他的标志位
46040fe15e0SLoGin     const PAGE_ADDRESS_SHIFT: usize = Self::PAGE_LEVELS * Self::PAGE_ENTRY_SHIFT + Self::PAGE_SHIFT;
46140fe15e0SLoGin     /// 最大的虚拟地址(对于不同的架构,由于上述PAGE_ADDRESS_SHIFT可能包括了reserved bits, 事实上能表示的虚拟地址应该比这个值要小)
46240fe15e0SLoGin     const PAGE_ADDRESS_SIZE: usize = 1 << Self::PAGE_ADDRESS_SHIFT;
46340fe15e0SLoGin     /// 页表项的值与这个常量进行与运算,得到的结果是所填写的物理地址
46440fe15e0SLoGin     const PAGE_ADDRESS_MASK: usize = Self::PAGE_ADDRESS_SIZE - Self::PAGE_SIZE;
46540fe15e0SLoGin     /// 每个页表项的大小
46640fe15e0SLoGin     const PAGE_ENTRY_SIZE: usize = 1 << (Self::PAGE_SHIFT - Self::PAGE_ENTRY_SHIFT);
46740fe15e0SLoGin     /// 每个页表的页表项数目
46840fe15e0SLoGin     const PAGE_ENTRY_NUM: usize = 1 << Self::PAGE_ENTRY_SHIFT;
46940fe15e0SLoGin     /// 该字段用于根据虚拟地址,获取该虚拟地址在对应的页表中是第几个页表项
47040fe15e0SLoGin     const PAGE_ENTRY_MASK: usize = Self::PAGE_ENTRY_NUM - 1;
47140fe15e0SLoGin 
47240fe15e0SLoGin     const PAGE_NEGATIVE_MASK: usize = !((Self::PAGE_ADDRESS_SIZE) - 1);
47340fe15e0SLoGin 
47440fe15e0SLoGin     const ENTRY_ADDRESS_SIZE: usize = 1 << Self::ENTRY_ADDRESS_SHIFT;
47540fe15e0SLoGin     /// 该mask用于获取页表项中地址字段
47640fe15e0SLoGin     const ENTRY_ADDRESS_MASK: usize = Self::ENTRY_ADDRESS_SIZE - Self::PAGE_SIZE;
47740fe15e0SLoGin     /// 这个mask用于获取页表项中的flags
47840fe15e0SLoGin     const ENTRY_FLAGS_MASK: usize = !Self::ENTRY_ADDRESS_MASK;
47940fe15e0SLoGin 
48040fe15e0SLoGin     /// 用户空间的最高地址
48140fe15e0SLoGin     const USER_END_VADDR: VirtAddr;
48240fe15e0SLoGin     /// 用户堆的起始地址
48340fe15e0SLoGin     const USER_BRK_START: VirtAddr;
48440fe15e0SLoGin     /// 用户栈起始地址(向下生长,不包含该值)
48540fe15e0SLoGin     const USER_STACK_START: VirtAddr;
48640fe15e0SLoGin 
48774ffde66SLoGin     /// 内核的固定映射区的起始地址
48874ffde66SLoGin     const FIXMAP_START_VADDR: VirtAddr;
48974ffde66SLoGin     /// 内核的固定映射区的大小
49074ffde66SLoGin     const FIXMAP_SIZE: usize;
49174ffde66SLoGin     /// 内核的固定映射区的结束地址
49274ffde66SLoGin     const FIXMAP_END_VADDR: VirtAddr =
49374ffde66SLoGin         VirtAddr::new(Self::FIXMAP_START_VADDR.data() + Self::FIXMAP_SIZE);
49474ffde66SLoGin 
49540fe15e0SLoGin     /// @brief 用于初始化内存管理模块与架构相关的信息。
49645626c85SLoGin     /// 该函数应调用其他模块的接口,把可用内存区域添加到memblock,提供给BumpAllocator使用
49745626c85SLoGin     unsafe fn init();
49840fe15e0SLoGin 
49940fe15e0SLoGin     /// @brief 读取指定虚拟地址的值,并假设它是类型T的指针
50040fe15e0SLoGin     #[inline(always)]
50140fe15e0SLoGin     unsafe fn read<T>(address: VirtAddr) -> T {
50240fe15e0SLoGin         return ptr::read(address.data() as *const T);
50340fe15e0SLoGin     }
50440fe15e0SLoGin 
50540fe15e0SLoGin     /// @brief 将value写入到指定的虚拟地址
50640fe15e0SLoGin     #[inline(always)]
50740fe15e0SLoGin     unsafe fn write<T>(address: VirtAddr, value: T) {
50840fe15e0SLoGin         ptr::write(address.data() as *mut T, value);
50940fe15e0SLoGin     }
51040fe15e0SLoGin 
51140fe15e0SLoGin     #[inline(always)]
51240fe15e0SLoGin     unsafe fn write_bytes(address: VirtAddr, value: u8, count: usize) {
51340fe15e0SLoGin         ptr::write_bytes(address.data() as *mut u8, value, count);
51440fe15e0SLoGin     }
51540fe15e0SLoGin 
51640fe15e0SLoGin     /// @brief 刷新TLB中,关于指定虚拟地址的条目
51740fe15e0SLoGin     unsafe fn invalidate_page(address: VirtAddr);
51840fe15e0SLoGin 
51940fe15e0SLoGin     /// @brief 刷新TLB中,所有的条目
52040fe15e0SLoGin     unsafe fn invalidate_all();
52140fe15e0SLoGin 
52240fe15e0SLoGin     /// @brief 获取顶级页表的物理地址
52340fe15e0SLoGin     unsafe fn table(table_kind: PageTableKind) -> PhysAddr;
52440fe15e0SLoGin 
52540fe15e0SLoGin     /// @brief 设置顶级页表的物理地址到处理器中
52640fe15e0SLoGin     unsafe fn set_table(table_kind: PageTableKind, table: PhysAddr);
52740fe15e0SLoGin 
52840fe15e0SLoGin     /// @brief 将物理地址转换为虚拟地址.
52940fe15e0SLoGin     ///
53040fe15e0SLoGin     /// @param phys 物理地址
53140fe15e0SLoGin     ///
53240fe15e0SLoGin     /// @return 转换后的虚拟地址。如果转换失败,返回None
53340fe15e0SLoGin     #[inline(always)]
53440fe15e0SLoGin     unsafe fn phys_2_virt(phys: PhysAddr) -> Option<VirtAddr> {
53540fe15e0SLoGin         if let Some(vaddr) = phys.data().checked_add(Self::PHYS_OFFSET) {
53640fe15e0SLoGin             return Some(VirtAddr::new(vaddr));
53740fe15e0SLoGin         } else {
53840fe15e0SLoGin             return None;
53940fe15e0SLoGin         }
54040fe15e0SLoGin     }
54140fe15e0SLoGin 
54240fe15e0SLoGin     /// 将虚拟地址转换为物理地址
54340fe15e0SLoGin     ///
54440fe15e0SLoGin     /// ## 参数
54540fe15e0SLoGin     ///
54640fe15e0SLoGin     /// - `virt` 虚拟地址
54740fe15e0SLoGin     ///
54840fe15e0SLoGin     /// ## 返回值
54940fe15e0SLoGin     ///
55040fe15e0SLoGin     /// 转换后的物理地址。如果转换失败,返回None
55140fe15e0SLoGin     #[inline(always)]
55240fe15e0SLoGin     unsafe fn virt_2_phys(virt: VirtAddr) -> Option<PhysAddr> {
55340fe15e0SLoGin         if let Some(paddr) = virt.data().checked_sub(Self::PHYS_OFFSET) {
55440fe15e0SLoGin             return Some(PhysAddr::new(paddr));
55540fe15e0SLoGin         } else {
55640fe15e0SLoGin             return None;
55740fe15e0SLoGin         }
55840fe15e0SLoGin     }
55940fe15e0SLoGin 
56040fe15e0SLoGin     /// @brief 判断指定的虚拟地址是否正确(符合规范)
56140fe15e0SLoGin     fn virt_is_valid(virt: VirtAddr) -> bool;
56240fe15e0SLoGin 
56340fe15e0SLoGin     /// 获取内存管理初始化时,创建的第一个内核页表的地址
56440fe15e0SLoGin     fn initial_page_table() -> PhysAddr;
56540fe15e0SLoGin 
56640fe15e0SLoGin     /// 初始化新的usermapper,为用户进程创建页表
56740fe15e0SLoGin     fn setup_new_usermapper() -> Result<UserMapper, SystemError>;
5687a29d4fcSLoGin 
5697a29d4fcSLoGin     /// 创建页表项
5707a29d4fcSLoGin     ///
5717a29d4fcSLoGin     /// 这是一个低阶api,用于根据物理地址以及指定好的pageflags,创建页表项
5727a29d4fcSLoGin     ///
5737a29d4fcSLoGin     /// ## 参数
5747a29d4fcSLoGin     ///
5757a29d4fcSLoGin     /// - `paddr` 物理地址
5767a29d4fcSLoGin     /// - `page_flags` 页表项的flags
5777a29d4fcSLoGin     ///
5787a29d4fcSLoGin     /// ## 返回值
5797a29d4fcSLoGin     ///
5807a29d4fcSLoGin     /// 页表项的值
5817a29d4fcSLoGin     fn make_entry(paddr: PhysAddr, page_flags: usize) -> usize;
58240fe15e0SLoGin }
58340fe15e0SLoGin 
58440fe15e0SLoGin /// @brief 虚拟地址范围
58540fe15e0SLoGin /// 该结构体用于表示一个虚拟地址范围,包括起始地址与大小
58640fe15e0SLoGin ///
58740fe15e0SLoGin /// 请注意与VMA进行区分,该结构体被VMA所包含
58840fe15e0SLoGin #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58940fe15e0SLoGin pub struct VirtRegion {
59040fe15e0SLoGin     start: VirtAddr,
59140fe15e0SLoGin     size: usize,
59240fe15e0SLoGin }
59340fe15e0SLoGin 
59440fe15e0SLoGin #[allow(dead_code)]
59540fe15e0SLoGin impl VirtRegion {
59640fe15e0SLoGin     /// # 创建一个新的虚拟地址范围
59740fe15e0SLoGin     pub fn new(start: VirtAddr, size: usize) -> Self {
59840fe15e0SLoGin         VirtRegion { start, size }
59940fe15e0SLoGin     }
60040fe15e0SLoGin 
60140fe15e0SLoGin     /// 获取虚拟地址范围的起始地址
60240fe15e0SLoGin     #[inline(always)]
60340fe15e0SLoGin     pub fn start(&self) -> VirtAddr {
60440fe15e0SLoGin         self.start
60540fe15e0SLoGin     }
60640fe15e0SLoGin 
60740fe15e0SLoGin     /// 获取虚拟地址范围的截止地址(不包括返回的地址)
60840fe15e0SLoGin     #[inline(always)]
60940fe15e0SLoGin     pub fn end(&self) -> VirtAddr {
61040fe15e0SLoGin         return self.start().add(self.size);
61140fe15e0SLoGin     }
61240fe15e0SLoGin 
61340fe15e0SLoGin     /// # Create a new VirtRegion from a range [start, end)
61440fe15e0SLoGin     ///
61540fe15e0SLoGin     /// If end <= start, return None
61640fe15e0SLoGin     pub fn between(start: VirtAddr, end: VirtAddr) -> Option<Self> {
61740fe15e0SLoGin         if unlikely(end.data() <= start.data()) {
61840fe15e0SLoGin             return None;
61940fe15e0SLoGin         }
62040fe15e0SLoGin         let size = end.data() - start.data();
62140fe15e0SLoGin         return Some(VirtRegion::new(start, size));
62240fe15e0SLoGin     }
62340fe15e0SLoGin 
62440fe15e0SLoGin     /// # 取两个虚拟地址范围的交集
62540fe15e0SLoGin     ///
62640fe15e0SLoGin     /// 如果两个虚拟地址范围没有交集,返回None
62740fe15e0SLoGin     pub fn intersect(&self, other: &VirtRegion) -> Option<VirtRegion> {
62840fe15e0SLoGin         let start = self.start.max(other.start);
62940fe15e0SLoGin         let end = self.end().min(other.end());
63040fe15e0SLoGin         return VirtRegion::between(start, end);
63140fe15e0SLoGin     }
63240fe15e0SLoGin 
63340fe15e0SLoGin     /// 设置虚拟地址范围的起始地址
63440fe15e0SLoGin     #[inline(always)]
63540fe15e0SLoGin     pub fn set_start(&mut self, start: VirtAddr) {
63640fe15e0SLoGin         self.start = start;
63740fe15e0SLoGin     }
63840fe15e0SLoGin 
63940fe15e0SLoGin     #[inline(always)]
64040fe15e0SLoGin     pub fn size(&self) -> usize {
64140fe15e0SLoGin         self.size
64240fe15e0SLoGin     }
64340fe15e0SLoGin 
64440fe15e0SLoGin     /// 设置虚拟地址范围的大小
64540fe15e0SLoGin     #[inline(always)]
64640fe15e0SLoGin     pub fn set_size(&mut self, size: usize) {
64740fe15e0SLoGin         self.size = size;
64840fe15e0SLoGin     }
64940fe15e0SLoGin 
65040fe15e0SLoGin     /// 判断虚拟地址范围是否为空
65140fe15e0SLoGin     #[inline(always)]
65240fe15e0SLoGin     pub fn is_empty(&self) -> bool {
65340fe15e0SLoGin         self.size == 0
65440fe15e0SLoGin     }
65540fe15e0SLoGin 
65640fe15e0SLoGin     /// 将虚拟地址区域的大小向上对齐到页大小
65740fe15e0SLoGin     #[inline(always)]
65840fe15e0SLoGin     pub fn round_up_size_to_page(self) -> Self {
65940fe15e0SLoGin         return VirtRegion::new(self.start, round_up_to_page_size(self.size));
66040fe15e0SLoGin     }
66140fe15e0SLoGin 
66240fe15e0SLoGin     /// 判断两个虚拟地址范围是否由于具有交集而导致冲突
66340fe15e0SLoGin     #[inline(always)]
66440fe15e0SLoGin     pub fn collide(&self, other: &VirtRegion) -> bool {
66540fe15e0SLoGin         return self.intersect(other).is_some();
66640fe15e0SLoGin     }
66740fe15e0SLoGin 
66840fe15e0SLoGin     pub fn iter_pages(&self) -> VirtPageFrameIter {
66940fe15e0SLoGin         return VirtPageFrame::iter_range(
67040fe15e0SLoGin             VirtPageFrame::new(self.start),
67140fe15e0SLoGin             VirtPageFrame::new(self.end()),
67240fe15e0SLoGin         );
67340fe15e0SLoGin     }
67440fe15e0SLoGin 
67540fe15e0SLoGin     /// 获取[self.start(), region.start())的虚拟地址范围
67640fe15e0SLoGin     ///
67740fe15e0SLoGin     /// 如果self.start() >= region.start(),返回None
67840fe15e0SLoGin     pub fn before(self, region: &VirtRegion) -> Option<Self> {
67940fe15e0SLoGin         return Self::between(self.start(), region.start());
68040fe15e0SLoGin     }
68140fe15e0SLoGin 
68240fe15e0SLoGin     /// 获取[region.end(),self.end())的虚拟地址范围
68340fe15e0SLoGin     ///
68440fe15e0SLoGin     /// 如果 self.end() >= region.end() ,返回None
68540fe15e0SLoGin     pub fn after(self, region: &VirtRegion) -> Option<Self> {
68640fe15e0SLoGin         // if self.end() > region.end() none
68740fe15e0SLoGin         return Self::between(region.end(), self.end());
68840fe15e0SLoGin     }
68940fe15e0SLoGin 
69040fe15e0SLoGin     /// 把当前虚拟地址范围内的某个虚拟地址,转换为另一个虚拟地址范围内的虚拟地址
69140fe15e0SLoGin     ///
69240fe15e0SLoGin     /// 如果vaddr不在当前虚拟地址范围内,返回None
69340fe15e0SLoGin     ///
69440fe15e0SLoGin     /// 如果vaddr在当前虚拟地址范围内,返回vaddr在new_base中的虚拟地址
69540fe15e0SLoGin     pub fn rebase(self, vaddr: VirtAddr, new_base: &VirtRegion) -> Option<VirtAddr> {
69640fe15e0SLoGin         if !self.contains(vaddr) {
69740fe15e0SLoGin             return None;
69840fe15e0SLoGin         }
69940fe15e0SLoGin         let offset = vaddr.data() - self.start().data();
70040fe15e0SLoGin         let new_start = new_base.start().data() + offset;
70140fe15e0SLoGin         return Some(VirtAddr::new(new_start));
70240fe15e0SLoGin     }
70340fe15e0SLoGin 
70440fe15e0SLoGin     /// 判断虚拟地址范围是否包含指定的虚拟地址
70540fe15e0SLoGin     pub fn contains(&self, addr: VirtAddr) -> bool {
70640fe15e0SLoGin         return self.start() <= addr && addr < self.end();
70740fe15e0SLoGin     }
70840fe15e0SLoGin 
70940fe15e0SLoGin     /// 创建当前虚拟地址范围的页面迭代器
71040fe15e0SLoGin     pub fn pages(&self) -> VirtPageFrameIter {
71140fe15e0SLoGin         return VirtPageFrame::iter_range(
71240fe15e0SLoGin             VirtPageFrame::new(self.start()),
71340fe15e0SLoGin             VirtPageFrame::new(self.end()),
71440fe15e0SLoGin         );
71540fe15e0SLoGin     }
71640fe15e0SLoGin }
71740fe15e0SLoGin 
71840fe15e0SLoGin impl PartialOrd for VirtRegion {
71940fe15e0SLoGin     fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
720*b5b571e0SLoGin         Some(self.cmp(other))
72140fe15e0SLoGin     }
72240fe15e0SLoGin }
72340fe15e0SLoGin 
72440fe15e0SLoGin impl Ord for VirtRegion {
72540fe15e0SLoGin     fn cmp(&self, other: &Self) -> cmp::Ordering {
72640fe15e0SLoGin         return self.start.cmp(&other.start);
72740fe15e0SLoGin     }
72840fe15e0SLoGin }
72940fe15e0SLoGin 
73040fe15e0SLoGin /// ## 判断虚拟地址是否超出了用户空间
73140fe15e0SLoGin ///
73240fe15e0SLoGin /// 如果虚拟地址超出了用户空间,返回Err(SystemError::EFAULT).
73340fe15e0SLoGin /// 如果end < start,返回Err(SystemError::EOVERFLOW)
73440fe15e0SLoGin ///
73540fe15e0SLoGin /// 否则返回Ok(())
73640fe15e0SLoGin pub fn verify_area(addr: VirtAddr, size: usize) -> Result<(), SystemError> {
73740fe15e0SLoGin     let end = addr.add(size);
73840fe15e0SLoGin     if unlikely(end.data() < addr.data()) {
73940fe15e0SLoGin         return Err(SystemError::EOVERFLOW);
74040fe15e0SLoGin     }
74140fe15e0SLoGin 
74240fe15e0SLoGin     if !addr.check_user() || !end.check_user() {
74340fe15e0SLoGin         return Err(SystemError::EFAULT);
74440fe15e0SLoGin     }
74540fe15e0SLoGin 
74640fe15e0SLoGin     return Ok(());
74740fe15e0SLoGin }
748