mod.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. pub mod barrier;
  2. pub mod bump;
  3. pub mod fault;
  4. pub mod pkru;
  5. use alloc::sync::Arc;
  6. use alloc::vec::Vec;
  7. use log::{debug, info};
  8. use x86_64::registers::model_specific::EferFlags;
  9. use crate::driver::serial::serial8250::send_to_default_serial8250_port;
  10. use crate::init::boot::boot_callbacks;
  11. use crate::libs::align::page_align_up;
  12. use crate::libs::lib_ui::screen_manager::scm_disable_put_to_window;
  13. use crate::libs::spinlock::SpinLock;
  14. use crate::mm::allocator::page_frame::{FrameAllocator, PageFrameCount, PageFrameUsage};
  15. use crate::mm::memblock::mem_block_manager;
  16. use crate::mm::ucontext::LockedVMA;
  17. use crate::{
  18. arch::MMArch,
  19. mm::allocator::{buddy::BuddyAllocator, bump::BumpAllocator},
  20. };
  21. use crate::mm::kernel_mapper::KernelMapper;
  22. use crate::mm::page::{EntryFlags, PageEntry, PAGE_1G_SHIFT};
  23. use crate::mm::{MemoryManagementArch, PageTableKind, PhysAddr, VirtAddr, VmFlags};
  24. use system_error::SystemError;
  25. use core::arch::asm;
  26. use core::fmt::Debug;
  27. use core::sync::atomic::{compiler_fence, AtomicBool, Ordering};
  28. pub type PageMapper =
  29. crate::mm::page::PageMapper<crate::arch::x86_64::mm::X86_64MMArch, LockedFrameAllocator>;
  30. /// 初始的CR3寄存器的值,用于内存管理初始化时,创建的第一个内核页表的位置
  31. static mut INITIAL_CR3_VALUE: PhysAddr = PhysAddr::new(0);
  32. static INNER_ALLOCATOR: SpinLock<Option<BuddyAllocator<MMArch>>> = SpinLock::new(None);
  33. #[derive(Clone, Copy, Debug)]
  34. pub struct X86_64MMBootstrapInfo {
  35. kernel_load_base_paddr: usize,
  36. kernel_code_start: usize,
  37. kernel_code_end: usize,
  38. kernel_data_end: usize,
  39. kernel_rodata_end: usize,
  40. start_brk: usize,
  41. }
  42. pub(super) static mut BOOTSTRAP_MM_INFO: Option<X86_64MMBootstrapInfo> = None;
  43. pub(super) fn x86_64_set_kernel_load_base_paddr(paddr: PhysAddr) {
  44. unsafe {
  45. BOOTSTRAP_MM_INFO.as_mut().unwrap().kernel_load_base_paddr = paddr.data();
  46. }
  47. }
  48. /// @brief X86_64的内存管理架构结构体
  49. #[derive(Debug, Clone, Copy, Hash)]
  50. pub struct X86_64MMArch;
  51. /// XD标志位是否被保留
  52. static XD_RESERVED: AtomicBool = AtomicBool::new(false);
  53. impl MemoryManagementArch for X86_64MMArch {
  54. /// X86目前支持缺页中断
  55. const PAGE_FAULT_ENABLED: bool = true;
  56. /// 4K页
  57. const PAGE_SHIFT: usize = 12;
  58. /// 每个页表项占8字节,总共有512个页表项
  59. const PAGE_ENTRY_SHIFT: usize = 9;
  60. /// 四级页表(PML4T、PDPT、PDT、PT)
  61. const PAGE_LEVELS: usize = 4;
  62. /// 页表项的有效位的index。在x86_64中,页表项的第[0, 47]位表示地址和flag,
  63. /// 第[48, 51]位表示保留。因此,有效位的index为52。
  64. /// 请注意,第63位是XD位,表示是否允许执行。
  65. const ENTRY_ADDRESS_SHIFT: usize = 52;
  66. const ENTRY_FLAG_DEFAULT_PAGE: usize = Self::ENTRY_FLAG_PRESENT;
  67. const ENTRY_FLAG_DEFAULT_TABLE: usize = Self::ENTRY_FLAG_PRESENT;
  68. const ENTRY_FLAG_PRESENT: usize = 1 << 0;
  69. const ENTRY_FLAG_READONLY: usize = 0;
  70. const ENTRY_FLAG_WRITEABLE: usize = 1 << 1;
  71. const ENTRY_FLAG_READWRITE: usize = 1 << 1;
  72. const ENTRY_FLAG_USER: usize = 1 << 2;
  73. const ENTRY_FLAG_WRITE_THROUGH: usize = 1 << 3;
  74. const ENTRY_FLAG_CACHE_DISABLE: usize = 1 << 4;
  75. const ENTRY_FLAG_NO_EXEC: usize = 1 << 63;
  76. /// x86_64不存在EXEC标志位,只有NO_EXEC(XD)标志位
  77. const ENTRY_FLAG_EXEC: usize = 0;
  78. const ENTRY_FLAG_ACCESSED: usize = 1 << 5;
  79. const ENTRY_FLAG_DIRTY: usize = 1 << 6;
  80. const ENTRY_FLAG_HUGE_PAGE: usize = 1 << 7;
  81. const ENTRY_FLAG_GLOBAL: usize = 1 << 8;
  82. /// 物理地址与虚拟地址的偏移量
  83. /// 0xffff_8000_0000_0000
  84. const PHYS_OFFSET: usize = Self::PAGE_NEGATIVE_MASK + (Self::PAGE_ADDRESS_SIZE >> 1);
  85. const KERNEL_LINK_OFFSET: usize = 0x100000;
  86. // 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/arch/x86/include/asm/page_64_types.h#75
  87. const USER_END_VADDR: VirtAddr =
  88. VirtAddr::new((Self::PAGE_ADDRESS_SIZE >> 1) - Self::PAGE_SIZE);
  89. const USER_BRK_START: VirtAddr = VirtAddr::new(0x700000000000);
  90. const USER_STACK_START: VirtAddr = VirtAddr::new(0x6ffff0a00000);
  91. const FIXMAP_START_VADDR: VirtAddr = VirtAddr::new(0xffffb00000000000);
  92. /// 设置FIXMAP区域大小为16M
  93. const FIXMAP_SIZE: usize = 256 * 4096 * 16;
  94. const MMIO_BASE: VirtAddr = VirtAddr::new(0xffffa10000000000);
  95. const MMIO_SIZE: usize = 1 << PAGE_1G_SHIFT;
  96. /// @brief 获取物理内存区域
  97. unsafe fn init() {
  98. extern "C" {
  99. fn _text();
  100. fn _etext();
  101. fn _edata();
  102. fn _erodata();
  103. fn _end();
  104. fn _default_kernel_load_base();
  105. }
  106. Self::init_xd_rsvd();
  107. let bootstrap_info = X86_64MMBootstrapInfo {
  108. kernel_load_base_paddr: _default_kernel_load_base as usize,
  109. kernel_code_start: _text as usize,
  110. kernel_code_end: _etext as usize,
  111. kernel_data_end: _edata as usize,
  112. kernel_rodata_end: _erodata as usize,
  113. start_brk: _end as usize,
  114. };
  115. unsafe {
  116. BOOTSTRAP_MM_INFO = Some(bootstrap_info);
  117. }
  118. // 初始化物理内存区域
  119. boot_callbacks()
  120. .early_init_memory_blocks()
  121. .expect("init memory area failed");
  122. debug!("bootstrap info: {:?}", unsafe { BOOTSTRAP_MM_INFO });
  123. debug!("phys[0]=virt[0x{:x}]", unsafe {
  124. MMArch::phys_2_virt(PhysAddr::new(0)).unwrap().data()
  125. });
  126. // 初始化内存管理器
  127. unsafe { allocator_init() };
  128. send_to_default_serial8250_port("x86 64 mm init done\n\0".as_bytes());
  129. }
  130. /// @brief 刷新TLB中,关于指定虚拟地址的条目
  131. unsafe fn invalidate_page(address: VirtAddr) {
  132. compiler_fence(Ordering::SeqCst);
  133. asm!("invlpg [{0}]", in(reg) address.data(), options(nostack, preserves_flags));
  134. compiler_fence(Ordering::SeqCst);
  135. }
  136. /// @brief 刷新TLB中,所有的条目
  137. unsafe fn invalidate_all() {
  138. compiler_fence(Ordering::SeqCst);
  139. // 通过设置cr3寄存器,来刷新整个TLB
  140. Self::set_table(PageTableKind::User, Self::table(PageTableKind::User));
  141. compiler_fence(Ordering::SeqCst);
  142. }
  143. /// @brief 获取顶级页表的物理地址
  144. unsafe fn table(table_kind: PageTableKind) -> PhysAddr {
  145. match table_kind {
  146. PageTableKind::Kernel | PageTableKind::User => {
  147. compiler_fence(Ordering::SeqCst);
  148. let cr3 = x86::controlregs::cr3() as usize;
  149. compiler_fence(Ordering::SeqCst);
  150. return PhysAddr::new(cr3);
  151. }
  152. _ => {
  153. todo!("Unsupported table kind: {:?}", table_kind);
  154. }
  155. }
  156. }
  157. /// @brief 设置顶级页表的物理地址到处理器中
  158. unsafe fn set_table(_table_kind: PageTableKind, table: PhysAddr) {
  159. compiler_fence(Ordering::SeqCst);
  160. asm!("mov cr3, {}", in(reg) table.data(), options(nostack, preserves_flags));
  161. compiler_fence(Ordering::SeqCst);
  162. }
  163. /// @brief 判断虚拟地址是否合法
  164. fn virt_is_valid(virt: VirtAddr) -> bool {
  165. return virt.is_canonical();
  166. }
  167. /// 获取内存管理初始化时,创建的第一个内核页表的地址
  168. fn initial_page_table() -> PhysAddr {
  169. unsafe {
  170. return INITIAL_CR3_VALUE;
  171. }
  172. }
  173. /// @brief 创建新的顶层页表
  174. ///
  175. /// 该函数会创建页表并复制内核的映射到新的页表中
  176. ///
  177. /// @return 新的页表
  178. fn setup_new_usermapper() -> Result<crate::mm::ucontext::UserMapper, SystemError> {
  179. let new_umapper: crate::mm::page::PageMapper<X86_64MMArch, LockedFrameAllocator> = unsafe {
  180. PageMapper::create(PageTableKind::User, LockedFrameAllocator)
  181. .ok_or(SystemError::ENOMEM)?
  182. };
  183. let current_ktable: KernelMapper = KernelMapper::lock();
  184. let copy_mapping = |pml4_entry_no| unsafe {
  185. let entry: PageEntry<X86_64MMArch> = current_ktable
  186. .table()
  187. .entry(pml4_entry_no)
  188. .unwrap_or_else(|| panic!("entry {} not found", pml4_entry_no));
  189. new_umapper.table().set_entry(pml4_entry_no, entry)
  190. };
  191. // 复制内核的映射
  192. for pml4_entry_no in MMArch::PAGE_KERNEL_INDEX..MMArch::PAGE_ENTRY_NUM {
  193. copy_mapping(pml4_entry_no);
  194. }
  195. return Ok(crate::mm::ucontext::UserMapper::new(new_umapper));
  196. }
  197. const PAGE_SIZE: usize = 1 << Self::PAGE_SHIFT;
  198. const PAGE_OFFSET_MASK: usize = Self::PAGE_SIZE - 1;
  199. const PAGE_MASK: usize = !(Self::PAGE_OFFSET_MASK);
  200. const PAGE_ADDRESS_SHIFT: usize = Self::PAGE_LEVELS * Self::PAGE_ENTRY_SHIFT + Self::PAGE_SHIFT;
  201. const PAGE_ADDRESS_SIZE: usize = 1 << Self::PAGE_ADDRESS_SHIFT;
  202. const PAGE_ADDRESS_MASK: usize = Self::PAGE_ADDRESS_SIZE - Self::PAGE_SIZE;
  203. const PAGE_ENTRY_SIZE: usize = 1 << (Self::PAGE_SHIFT - Self::PAGE_ENTRY_SHIFT);
  204. const PAGE_ENTRY_NUM: usize = 1 << Self::PAGE_ENTRY_SHIFT;
  205. const PAGE_ENTRY_MASK: usize = Self::PAGE_ENTRY_NUM - 1;
  206. const PAGE_KERNEL_INDEX: usize = (Self::PHYS_OFFSET & Self::PAGE_ADDRESS_MASK)
  207. >> (Self::PAGE_ADDRESS_SHIFT - Self::PAGE_ENTRY_SHIFT);
  208. const PAGE_NEGATIVE_MASK: usize = !((Self::PAGE_ADDRESS_SIZE) - 1);
  209. const ENTRY_ADDRESS_SIZE: usize = 1 << Self::ENTRY_ADDRESS_SHIFT;
  210. const ENTRY_ADDRESS_MASK: usize = Self::ENTRY_ADDRESS_SIZE - Self::PAGE_SIZE;
  211. const ENTRY_FLAGS_MASK: usize = !Self::ENTRY_ADDRESS_MASK;
  212. unsafe fn read<T>(address: VirtAddr) -> T {
  213. return core::ptr::read(address.data() as *const T);
  214. }
  215. unsafe fn write<T>(address: VirtAddr, value: T) {
  216. core::ptr::write(address.data() as *mut T, value);
  217. }
  218. unsafe fn write_bytes(address: VirtAddr, value: u8, count: usize) {
  219. core::ptr::write_bytes(address.data() as *mut u8, value, count);
  220. }
  221. unsafe fn phys_2_virt(phys: PhysAddr) -> Option<VirtAddr> {
  222. if let Some(vaddr) = phys.data().checked_add(Self::PHYS_OFFSET) {
  223. return Some(VirtAddr::new(vaddr));
  224. } else {
  225. return None;
  226. }
  227. }
  228. unsafe fn virt_2_phys(virt: VirtAddr) -> Option<PhysAddr> {
  229. if let Some(paddr) = virt.data().checked_sub(Self::PHYS_OFFSET) {
  230. return Some(PhysAddr::new(paddr));
  231. } else {
  232. return None;
  233. }
  234. }
  235. #[inline(always)]
  236. fn make_entry(paddr: PhysAddr, page_flags: usize) -> usize {
  237. return paddr.data() | page_flags;
  238. }
  239. fn vma_access_permitted(
  240. vma: Arc<LockedVMA>,
  241. write: bool,
  242. execute: bool,
  243. foreign: bool,
  244. ) -> bool {
  245. if execute {
  246. return true;
  247. }
  248. if foreign | vma.is_foreign() {
  249. return true;
  250. }
  251. pkru::pkru_allows_pkey(pkru::vma_pkey(vma), write)
  252. }
  253. const PROTECTION_MAP: [EntryFlags<MMArch>; 16] = protection_map();
  254. const PAGE_NONE: usize =
  255. Self::ENTRY_FLAG_PRESENT | Self::ENTRY_FLAG_ACCESSED | Self::ENTRY_FLAG_GLOBAL;
  256. const PAGE_SHARED: usize = Self::ENTRY_FLAG_PRESENT
  257. | Self::ENTRY_FLAG_READWRITE
  258. | Self::ENTRY_FLAG_USER
  259. | Self::ENTRY_FLAG_ACCESSED
  260. | Self::ENTRY_FLAG_NO_EXEC;
  261. const PAGE_SHARED_EXEC: usize = Self::ENTRY_FLAG_PRESENT
  262. | Self::ENTRY_FLAG_READWRITE
  263. | Self::ENTRY_FLAG_USER
  264. | Self::ENTRY_FLAG_ACCESSED;
  265. const PAGE_COPY_NOEXEC: usize = Self::ENTRY_FLAG_PRESENT
  266. | Self::ENTRY_FLAG_USER
  267. | Self::ENTRY_FLAG_ACCESSED
  268. | Self::ENTRY_FLAG_NO_EXEC;
  269. const PAGE_COPY_EXEC: usize =
  270. Self::ENTRY_FLAG_PRESENT | Self::ENTRY_FLAG_USER | Self::ENTRY_FLAG_ACCESSED;
  271. const PAGE_COPY: usize = Self::ENTRY_FLAG_PRESENT
  272. | Self::ENTRY_FLAG_USER
  273. | Self::ENTRY_FLAG_ACCESSED
  274. | Self::ENTRY_FLAG_NO_EXEC;
  275. const PAGE_READONLY: usize = Self::ENTRY_FLAG_PRESENT
  276. | Self::ENTRY_FLAG_USER
  277. | Self::ENTRY_FLAG_ACCESSED
  278. | Self::ENTRY_FLAG_NO_EXEC;
  279. const PAGE_READONLY_EXEC: usize =
  280. Self::ENTRY_FLAG_PRESENT | Self::ENTRY_FLAG_USER | Self::ENTRY_FLAG_ACCESSED;
  281. const PAGE_READ: usize = 0;
  282. const PAGE_READ_EXEC: usize = 0;
  283. const PAGE_WRITE: usize = 0;
  284. const PAGE_WRITE_EXEC: usize = 0;
  285. const PAGE_EXEC: usize = 0;
  286. }
  287. /// 获取保护标志的映射表
  288. ///
  289. ///
  290. /// ## 返回值
  291. /// - `[usize; 16]`: 长度为16的映射表
  292. const fn protection_map() -> [EntryFlags<MMArch>; 16] {
  293. let mut map = [unsafe { EntryFlags::from_data(0) }; 16];
  294. unsafe {
  295. map[VmFlags::VM_NONE.bits()] = EntryFlags::from_data(MMArch::PAGE_NONE);
  296. map[VmFlags::VM_READ.bits()] = EntryFlags::from_data(MMArch::PAGE_READONLY);
  297. map[VmFlags::VM_WRITE.bits()] = EntryFlags::from_data(MMArch::PAGE_COPY);
  298. map[VmFlags::VM_WRITE.bits() | VmFlags::VM_READ.bits()] =
  299. EntryFlags::from_data(MMArch::PAGE_COPY);
  300. map[VmFlags::VM_EXEC.bits()] = EntryFlags::from_data(MMArch::PAGE_READONLY_EXEC);
  301. map[VmFlags::VM_EXEC.bits() | VmFlags::VM_READ.bits()] =
  302. EntryFlags::from_data(MMArch::PAGE_READONLY_EXEC);
  303. map[VmFlags::VM_EXEC.bits() | VmFlags::VM_WRITE.bits()] =
  304. EntryFlags::from_data(MMArch::PAGE_COPY_EXEC);
  305. map[VmFlags::VM_EXEC.bits() | VmFlags::VM_WRITE.bits() | VmFlags::VM_READ.bits()] =
  306. EntryFlags::from_data(MMArch::PAGE_COPY_EXEC);
  307. map[VmFlags::VM_SHARED.bits()] = EntryFlags::from_data(MMArch::PAGE_NONE);
  308. map[VmFlags::VM_SHARED.bits() | VmFlags::VM_READ.bits()] =
  309. EntryFlags::from_data(MMArch::PAGE_READONLY);
  310. map[VmFlags::VM_SHARED.bits() | VmFlags::VM_WRITE.bits()] =
  311. EntryFlags::from_data(MMArch::PAGE_SHARED);
  312. map[VmFlags::VM_SHARED.bits() | VmFlags::VM_WRITE.bits() | VmFlags::VM_READ.bits()] =
  313. EntryFlags::from_data(MMArch::PAGE_SHARED);
  314. map[VmFlags::VM_SHARED.bits() | VmFlags::VM_EXEC.bits()] =
  315. EntryFlags::from_data(MMArch::PAGE_READONLY_EXEC);
  316. map[VmFlags::VM_SHARED.bits() | VmFlags::VM_EXEC.bits() | VmFlags::VM_READ.bits()] =
  317. EntryFlags::from_data(MMArch::PAGE_READONLY_EXEC);
  318. map[VmFlags::VM_SHARED.bits() | VmFlags::VM_EXEC.bits() | VmFlags::VM_WRITE.bits()] =
  319. EntryFlags::from_data(MMArch::PAGE_SHARED_EXEC);
  320. map[VmFlags::VM_SHARED.bits()
  321. | VmFlags::VM_EXEC.bits()
  322. | VmFlags::VM_WRITE.bits()
  323. | VmFlags::VM_READ.bits()] = EntryFlags::from_data(MMArch::PAGE_SHARED_EXEC);
  324. }
  325. // if X86_64MMArch::is_xd_reserved() {
  326. // map.iter_mut().for_each(|x| *x &= !Self::ENTRY_FLAG_NO_EXEC)
  327. // }
  328. map
  329. }
  330. impl X86_64MMArch {
  331. fn init_xd_rsvd() {
  332. // 读取ia32-EFER寄存器的值
  333. let efer: EferFlags = x86_64::registers::model_specific::Efer::read();
  334. if !efer.contains(EferFlags::NO_EXECUTE_ENABLE) {
  335. // NO_EXECUTE_ENABLE是false,那么就设置xd_reserved为true
  336. debug!("NO_EXECUTE_ENABLE is false, set XD_RESERVED to true");
  337. XD_RESERVED.store(true, Ordering::Relaxed);
  338. }
  339. compiler_fence(Ordering::SeqCst);
  340. }
  341. /// 判断XD标志位是否被保留
  342. pub fn is_xd_reserved() -> bool {
  343. // return XD_RESERVED.load(Ordering::Relaxed);
  344. // 由于暂时不支持execute disable,因此直接返回true
  345. // 不支持的原因是,目前好像没有能正确的设置page-level的xd位,会触发page fault
  346. return true;
  347. }
  348. pub unsafe fn read_array<T>(addr: VirtAddr, count: usize) -> Vec<T> {
  349. // 实现读取数组逻辑
  350. let mut vec = Vec::with_capacity(count);
  351. for i in 0..count {
  352. vec.push(Self::read(addr + i * core::mem::size_of::<T>()));
  353. }
  354. vec
  355. }
  356. }
  357. impl VirtAddr {
  358. /// @brief 判断虚拟地址是否合法
  359. #[inline(always)]
  360. pub fn is_canonical(self) -> bool {
  361. let x = self.data() & X86_64MMArch::PHYS_OFFSET;
  362. // 如果x为0,说明虚拟地址的高位为0,是合法的用户地址
  363. // 如果x为PHYS_OFFSET,说明虚拟地址的高位全为1,是合法的内核地址
  364. return x == 0 || x == X86_64MMArch::PHYS_OFFSET;
  365. }
  366. }
  367. unsafe fn allocator_init() {
  368. let virt_offset = VirtAddr::new(page_align_up(BOOTSTRAP_MM_INFO.unwrap().start_brk));
  369. let phy_offset = unsafe { MMArch::virt_2_phys(virt_offset) }.unwrap();
  370. mem_block_manager()
  371. .reserve_block(PhysAddr::new(0), phy_offset.data())
  372. .expect("Failed to reserve block");
  373. let mut bump_allocator = BumpAllocator::<X86_64MMArch>::new(phy_offset.data());
  374. debug!(
  375. "BumpAllocator created, offset={:?}",
  376. bump_allocator.offset()
  377. );
  378. // 暂存初始在head.S中指定的页表的地址,后面再考虑是否需要把它加到buddy的可用空间里面!
  379. // 现在不加的原因是,我担心会有安全漏洞问题:这些初始的页表,位于内核的数据段。如果归还到buddy,
  380. // 可能会产生一定的安全风险(有的代码可能根据虚拟地址来进行安全校验)
  381. let _old_page_table = MMArch::table(PageTableKind::Kernel);
  382. let new_page_table: PhysAddr;
  383. // 使用bump分配器,把所有的内存页都映射到页表
  384. {
  385. // 用bump allocator创建新的页表
  386. let mut mapper: crate::mm::page::PageMapper<MMArch, &mut BumpAllocator<MMArch>> =
  387. crate::mm::page::PageMapper::<MMArch, _>::create(
  388. PageTableKind::Kernel,
  389. &mut bump_allocator,
  390. )
  391. .expect("Failed to create page mapper");
  392. new_page_table = mapper.table().phys();
  393. debug!("PageMapper created");
  394. // 取消最开始时候,在head.S中指定的映射(暂时不刷新TLB)
  395. {
  396. let table = mapper.table();
  397. let empty_entry = PageEntry::<MMArch>::from_usize(0);
  398. for i in 0..MMArch::PAGE_ENTRY_NUM {
  399. table
  400. .set_entry(i, empty_entry)
  401. .expect("Failed to empty page table entry");
  402. }
  403. }
  404. debug!("Successfully emptied page table");
  405. let total_num = mem_block_manager().total_initial_memory_regions();
  406. for i in 0..total_num {
  407. let area = mem_block_manager().get_initial_memory_region(i).unwrap();
  408. // debug!("area: base={:?}, size={:#x}, end={:?}", area.base, area.size, area.base + area.size);
  409. for i in 0..area.size.div_ceil(MMArch::PAGE_SIZE) {
  410. let paddr = area.base.add(i * MMArch::PAGE_SIZE);
  411. let vaddr = unsafe { MMArch::phys_2_virt(paddr) }.unwrap();
  412. let flags = kernel_page_flags::<MMArch>(vaddr);
  413. let flusher = mapper
  414. .map_phys(vaddr, paddr, flags)
  415. .expect("Failed to map frame");
  416. // 暂时不刷新TLB
  417. flusher.ignore();
  418. }
  419. }
  420. }
  421. unsafe {
  422. INITIAL_CR3_VALUE = new_page_table;
  423. }
  424. debug!(
  425. "After mapping all physical memory, DragonOS used: {} KB",
  426. bump_allocator.offset() / 1024
  427. );
  428. // 初始化buddy_allocator
  429. let buddy_allocator = unsafe { BuddyAllocator::<X86_64MMArch>::new(bump_allocator).unwrap() };
  430. // 设置全局的页帧分配器
  431. unsafe { set_inner_allocator(buddy_allocator) };
  432. info!("Successfully initialized buddy allocator");
  433. // 关闭显示输出
  434. scm_disable_put_to_window();
  435. // make the new page table current
  436. {
  437. let mut binding = INNER_ALLOCATOR.lock();
  438. let mut allocator_guard = binding.as_mut().unwrap();
  439. debug!("To enable new page table.");
  440. compiler_fence(Ordering::SeqCst);
  441. let mapper = crate::mm::page::PageMapper::<MMArch, _>::new(
  442. PageTableKind::Kernel,
  443. new_page_table,
  444. &mut allocator_guard,
  445. );
  446. compiler_fence(Ordering::SeqCst);
  447. mapper.make_current();
  448. compiler_fence(Ordering::SeqCst);
  449. //debug!("New page table enabled");
  450. }
  451. debug!("Successfully enabled new page table");
  452. }
  453. #[cfg(test)]
  454. pub fn test_buddy() {
  455. use hashbrown::HashSet;
  456. use x86::time::rdtsc;
  457. // 申请内存然后写入数据然后free掉
  458. // 总共申请200MB内存
  459. const TOTAL_SIZE: usize = 200 * 1024 * 1024;
  460. for i in 0..10 {
  461. debug!("Test buddy, round: {i}");
  462. // 存放申请的内存块
  463. let mut v: Vec<(PhysAddr, PageFrameCount)> = Vec::with_capacity(60 * 1024);
  464. // 存放已经申请的内存块的地址(用于检查重复)
  465. let mut addr_set: HashSet<PhysAddr> = HashSet::new();
  466. let mut allocated = 0usize;
  467. let mut free_count = 0usize;
  468. while allocated < TOTAL_SIZE {
  469. let mut random_size = 0u64;
  470. unsafe { x86::random::rdrand64(&mut random_size) };
  471. // 一次最多申请4M
  472. random_size %= 1024 * 4096;
  473. if random_size == 0 {
  474. continue;
  475. }
  476. let random_size =
  477. core::cmp::min(page_align_up(random_size as usize), TOTAL_SIZE - allocated);
  478. let random_size = PageFrameCount::from_bytes(random_size.next_power_of_two()).unwrap();
  479. // 获取帧
  480. let (paddr, allocated_frame_count) =
  481. unsafe { LockedFrameAllocator.allocate(random_size).unwrap() };
  482. assert!(allocated_frame_count.data().is_power_of_two());
  483. assert!(paddr.data() % MMArch::PAGE_SIZE == 0);
  484. unsafe {
  485. assert!(MMArch::phys_2_virt(paddr)
  486. .as_ref()
  487. .unwrap()
  488. .check_aligned(allocated_frame_count.data() * MMArch::PAGE_SIZE));
  489. }
  490. allocated += allocated_frame_count.data() * MMArch::PAGE_SIZE;
  491. v.push((paddr, allocated_frame_count));
  492. assert!(addr_set.insert(paddr), "duplicate address: {:?}", paddr);
  493. // 写入数据
  494. let vaddr = unsafe { MMArch::phys_2_virt(paddr).unwrap() };
  495. let slice = unsafe {
  496. core::slice::from_raw_parts_mut(
  497. vaddr.data() as *mut u8,
  498. allocated_frame_count.data() * MMArch::PAGE_SIZE,
  499. )
  500. };
  501. for (i, item) in slice.iter_mut().enumerate() {
  502. *item = ((i + unsafe { rdtsc() } as usize) % 256) as u8;
  503. }
  504. // 随机释放一个内存块
  505. if !v.is_empty() {
  506. let mut random_index = 0u64;
  507. unsafe { x86::random::rdrand64(&mut random_index) };
  508. // 70%概率释放
  509. if random_index % 10 > 7 {
  510. continue;
  511. }
  512. random_index %= v.len() as u64;
  513. let random_index = random_index as usize;
  514. let (paddr, allocated_frame_count) = v.remove(random_index);
  515. assert!(addr_set.remove(&paddr));
  516. unsafe { LockedFrameAllocator.free(paddr, allocated_frame_count) };
  517. free_count += allocated_frame_count.data() * MMArch::PAGE_SIZE;
  518. }
  519. }
  520. debug!(
  521. "Allocated {} MB memory, release: {} MB, no release: {} bytes",
  522. allocated / 1024 / 1024,
  523. free_count / 1024 / 1024,
  524. (allocated - free_count)
  525. );
  526. debug!("Now, to release buddy memory");
  527. // 释放所有的内存
  528. for (paddr, allocated_frame_count) in v {
  529. unsafe { LockedFrameAllocator.free(paddr, allocated_frame_count) };
  530. assert!(addr_set.remove(&paddr));
  531. free_count += allocated_frame_count.data() * MMArch::PAGE_SIZE;
  532. }
  533. debug!("release done!, allocated: {allocated}, free_count: {free_count}");
  534. }
  535. }
  536. /// 全局的页帧分配器
  537. #[derive(Debug, Clone, Copy, Hash)]
  538. pub struct LockedFrameAllocator;
  539. impl FrameAllocator for LockedFrameAllocator {
  540. unsafe fn allocate(&mut self, mut count: PageFrameCount) -> Option<(PhysAddr, PageFrameCount)> {
  541. count = count.next_power_of_two();
  542. if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() {
  543. return allocator.allocate(count);
  544. } else {
  545. return None;
  546. }
  547. }
  548. unsafe fn free(&mut self, address: crate::mm::PhysAddr, count: PageFrameCount) {
  549. assert!(count.data().is_power_of_two());
  550. if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() {
  551. return allocator.free(address, count);
  552. }
  553. }
  554. unsafe fn usage(&self) -> PageFrameUsage {
  555. if let Some(ref mut allocator) = *INNER_ALLOCATOR.lock_irqsave() {
  556. return allocator.usage();
  557. } else {
  558. panic!("usage error");
  559. }
  560. }
  561. }
  562. /// 获取内核地址默认的页面标志
  563. pub unsafe fn kernel_page_flags<A: MemoryManagementArch>(virt: VirtAddr) -> EntryFlags<A> {
  564. let info: X86_64MMBootstrapInfo = BOOTSTRAP_MM_INFO.unwrap();
  565. if virt.data() >= info.kernel_code_start && virt.data() < info.kernel_code_end {
  566. // Remap kernel code execute
  567. return EntryFlags::new().set_execute(true).set_write(true);
  568. } else if virt.data() >= info.kernel_data_end && virt.data() < info.kernel_rodata_end {
  569. // Remap kernel rodata read only
  570. return EntryFlags::new().set_execute(true);
  571. } else {
  572. return EntryFlags::new().set_write(true).set_execute(true);
  573. }
  574. }
  575. unsafe fn set_inner_allocator(allocator: BuddyAllocator<MMArch>) {
  576. static FLAG: AtomicBool = AtomicBool::new(false);
  577. if FLAG
  578. .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
  579. .is_err()
  580. {
  581. panic!("Cannot set inner allocator twice!");
  582. }
  583. *INNER_ALLOCATOR.lock() = Some(allocator);
  584. }
  585. /// 低地址重映射的管理器
  586. ///
  587. /// 低地址重映射的管理器,在smp初始化完成之前,需要使用低地址的映射,因此需要在smp初始化完成之后,取消这一段映射
  588. pub struct LowAddressRemapping;
  589. impl LowAddressRemapping {
  590. // 映射64M
  591. const REMAP_SIZE: usize = 64 * 1024 * 1024;
  592. pub unsafe fn remap_at_low_address(mapper: &mut PageMapper) {
  593. for i in 0..(Self::REMAP_SIZE / MMArch::PAGE_SIZE) {
  594. let paddr = PhysAddr::new(i * MMArch::PAGE_SIZE);
  595. let vaddr = VirtAddr::new(i * MMArch::PAGE_SIZE);
  596. let flags = kernel_page_flags::<MMArch>(vaddr);
  597. let flusher = mapper
  598. .map_phys(vaddr, paddr, flags)
  599. .expect("Failed to map frame");
  600. // 暂时不刷新TLB
  601. flusher.ignore();
  602. }
  603. }
  604. /// 取消低地址的映射
  605. pub unsafe fn unmap_at_low_address(mapper: &mut PageMapper, flush: bool) {
  606. for i in 0..(Self::REMAP_SIZE / MMArch::PAGE_SIZE) {
  607. let vaddr = VirtAddr::new(i * MMArch::PAGE_SIZE);
  608. let (_, _, flusher) = mapper
  609. .unmap_phys(vaddr, true)
  610. .expect("Failed to unmap frame");
  611. if !flush {
  612. flusher.ignore();
  613. }
  614. }
  615. }
  616. }