page.rs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  1. use core::{
  2. fmt::{self, Debug, Error, Formatter},
  3. marker::PhantomData,
  4. mem,
  5. ops::Add,
  6. sync::atomic::{compiler_fence, Ordering},
  7. };
  8. use alloc::sync::Arc;
  9. use hashbrown::HashSet;
  10. use log::{error, info};
  11. use lru::LruCache;
  12. use crate::{
  13. arch::{interrupt::ipi::send_ipi, MMArch},
  14. exception::ipi::{IpiKind, IpiTarget},
  15. filesystem::vfs::file::PageCache,
  16. ipc::shm::ShmId,
  17. libs::{
  18. rwlock::RwLock,
  19. spinlock::{SpinLock, SpinLockGuard},
  20. },
  21. };
  22. use super::{
  23. allocator::page_frame::{FrameAllocator, PageFrameCount},
  24. syscall::ProtFlags,
  25. ucontext::LockedVMA,
  26. MemoryManagementArch, PageTableKind, PhysAddr, VirtAddr,
  27. };
  28. pub const PAGE_4K_SHIFT: usize = 12;
  29. #[allow(dead_code)]
  30. pub const PAGE_2M_SHIFT: usize = 21;
  31. pub const PAGE_1G_SHIFT: usize = 30;
  32. pub const PAGE_4K_SIZE: usize = 1 << PAGE_4K_SHIFT;
  33. pub const PAGE_2M_SIZE: usize = 1 << PAGE_2M_SHIFT;
  34. /// 全局物理页信息管理器
  35. pub static mut PAGE_MANAGER: Option<SpinLock<PageManager>> = None;
  36. /// 初始化PAGE_MANAGER
  37. pub fn page_manager_init() {
  38. info!("page_manager_init");
  39. let page_manager = SpinLock::new(PageManager::new());
  40. compiler_fence(Ordering::SeqCst);
  41. unsafe { PAGE_MANAGER = Some(page_manager) };
  42. compiler_fence(Ordering::SeqCst);
  43. info!("page_manager_init done");
  44. }
  45. pub fn page_manager_lock_irqsave() -> SpinLockGuard<'static, PageManager> {
  46. unsafe { PAGE_MANAGER.as_ref().unwrap().lock_irqsave() }
  47. }
  48. // 物理页管理器
  49. pub struct PageManager {
  50. phys2page: LruCache<PhysAddr, Arc<Page>>,
  51. }
  52. impl PageManager {
  53. pub fn new() -> Self {
  54. Self {
  55. phys2page: LruCache::unbounded(),
  56. }
  57. }
  58. pub fn contains(&self, paddr: &PhysAddr) -> bool {
  59. self.phys2page.peek(paddr).is_some()
  60. }
  61. pub fn get(&mut self, paddr: &PhysAddr) -> Option<Arc<Page>> {
  62. self.phys2page.get(paddr).cloned()
  63. }
  64. pub fn get_unwrap(&mut self, paddr: &PhysAddr) -> Arc<Page> {
  65. self.phys2page
  66. .get(paddr)
  67. .unwrap_or_else(|| panic!("Phys Page not found, {:?}", paddr))
  68. .clone()
  69. }
  70. pub fn insert(&mut self, paddr: PhysAddr, page: &Arc<Page>) {
  71. self.phys2page.put(paddr, page.clone());
  72. }
  73. pub fn remove_page(&mut self, paddr: &PhysAddr) {
  74. self.phys2page.pop(paddr);
  75. }
  76. pub fn shrink_list(&mut self) {
  77. let entry = self.phys2page.peek_lru().unwrap();
  78. let page = entry.1.clone();
  79. let phys = *entry.0;
  80. let page_cache = page.read().page_cache().unwrap();
  81. for vma in page.read().anon_vma() {
  82. let address_space = vma.lock().address_space().unwrap();
  83. let address_space = address_space.upgrade().unwrap();
  84. let mut guard = address_space.write();
  85. let mapper = &mut guard.user_mapper.utable;
  86. let virt = vma.lock().page_address(&page).unwrap();
  87. unsafe {
  88. mapper.unmap(virt, false).unwrap().flush();
  89. }
  90. }
  91. self.phys2page.pop(&phys);
  92. page_cache.remove_page(page.read().index().unwrap());
  93. }
  94. }
  95. bitflags! {
  96. pub struct PageFlags: u64 {
  97. const PG_LOCKED = 1 << 0;
  98. const PG_WRITEBACK = 1 << 1;
  99. const PG_REFERENCED = 1 << 2;
  100. const PG_UPTODATE = 1 << 3;
  101. const PG_DIRTY = 1 << 4;
  102. const PG_LRU = 1 << 5;
  103. const PG_HEAD = 1 << 6;
  104. const PG_WAITERS = 1 << 7;
  105. const PG_ACTIVE = 1 << 8;
  106. const PG_WORKINGSET = 1 << 9;
  107. const PG_ERROR = 1 << 10;
  108. const PG_SLAB = 1 << 11;
  109. const PG_RESERVED = 1 << 14;
  110. const PG_PRIVATE = 1 << 15;
  111. const PG_RECLAIM = 1 << 18;
  112. const PG_SWAPBACKED = 1 << 19;
  113. }
  114. }
  115. #[derive(Debug)]
  116. pub struct Page {
  117. inner: RwLock<InnerPage>,
  118. }
  119. impl core::ops::Deref for Page {
  120. type Target = RwLock<InnerPage>;
  121. fn deref(&self) -> &Self::Target {
  122. &self.inner
  123. }
  124. }
  125. impl core::ops::DerefMut for Page {
  126. fn deref_mut(&mut self) -> &mut Self::Target {
  127. &mut self.inner
  128. }
  129. }
  130. impl Page {
  131. pub fn new(shared: bool, phys_addr: PhysAddr) -> Self {
  132. let inner = InnerPage::new(shared, phys_addr);
  133. Self {
  134. inner: RwLock::new(inner),
  135. }
  136. }
  137. }
  138. #[derive(Debug)]
  139. /// 物理页面信息
  140. pub struct InnerPage {
  141. /// 映射计数
  142. map_count: usize,
  143. /// 是否为共享页
  144. shared: bool,
  145. /// 映射计数为0时,是否可回收
  146. free_when_zero: bool,
  147. /// 共享页id(如果是共享页)
  148. shm_id: Option<ShmId>,
  149. /// 映射到当前page的VMA
  150. anon_vma: HashSet<Arc<LockedVMA>>,
  151. /// 标志
  152. flags: PageFlags,
  153. /// 页所在的物理页帧号
  154. phys_addr: PhysAddr,
  155. /// 在pagecache中的偏移
  156. index: Option<usize>,
  157. page_cache: Option<Arc<PageCache>>,
  158. }
  159. impl InnerPage {
  160. pub fn new(shared: bool, phys_addr: PhysAddr) -> Self {
  161. let dealloc_when_zero = !shared;
  162. Self {
  163. map_count: 0,
  164. shared,
  165. free_when_zero: dealloc_when_zero,
  166. shm_id: None,
  167. anon_vma: HashSet::new(),
  168. flags: PageFlags::empty(),
  169. phys_addr,
  170. index: None,
  171. page_cache: None,
  172. }
  173. }
  174. /// 将vma加入anon_vma
  175. pub fn insert_vma(&mut self, vma: Arc<LockedVMA>) {
  176. self.anon_vma.insert(vma);
  177. self.map_count += 1;
  178. }
  179. /// 将vma从anon_vma中删去
  180. pub fn remove_vma(&mut self, vma: &LockedVMA) {
  181. self.anon_vma.remove(vma);
  182. self.map_count -= 1;
  183. }
  184. /// 判断当前物理页是否能被回
  185. pub fn can_deallocate(&self) -> bool {
  186. self.map_count == 0 && self.free_when_zero
  187. }
  188. pub fn shared(&self) -> bool {
  189. self.shared
  190. }
  191. pub fn shm_id(&self) -> Option<ShmId> {
  192. self.shm_id
  193. }
  194. pub fn index(&self) -> Option<usize> {
  195. self.index
  196. }
  197. pub fn page_cache(&self) -> Option<Arc<PageCache>> {
  198. self.page_cache.clone()
  199. }
  200. pub fn set_page_cache(&mut self, page_cache: Option<Arc<PageCache>>) {
  201. self.page_cache = page_cache;
  202. }
  203. pub fn set_index(&mut self, index: Option<usize>) {
  204. self.index = index;
  205. }
  206. pub fn set_page_cache_index(
  207. &mut self,
  208. page_cache: Option<Arc<PageCache>>,
  209. index: Option<usize>,
  210. ) {
  211. self.page_cache = page_cache;
  212. self.index = index;
  213. }
  214. pub fn set_shm_id(&mut self, shm_id: ShmId) {
  215. self.shm_id = Some(shm_id);
  216. }
  217. pub fn set_dealloc_when_zero(&mut self, dealloc_when_zero: bool) {
  218. self.free_when_zero = dealloc_when_zero;
  219. }
  220. #[inline(always)]
  221. pub fn anon_vma(&self) -> &HashSet<Arc<LockedVMA>> {
  222. &self.anon_vma
  223. }
  224. #[inline(always)]
  225. pub fn map_count(&self) -> usize {
  226. self.map_count
  227. }
  228. #[inline(always)]
  229. pub fn flags(&self) -> &PageFlags {
  230. &self.flags
  231. }
  232. #[inline(always)]
  233. pub fn phys_address(&self) -> PhysAddr {
  234. self.phys_addr
  235. }
  236. }
  237. #[derive(Debug)]
  238. pub struct PageTable<Arch> {
  239. /// 当前页表表示的虚拟地址空间的起始地址
  240. base: VirtAddr,
  241. /// 当前页表所在的物理地址
  242. phys: PhysAddr,
  243. /// 当前页表的层级(请注意,最顶级页表的level为[Arch::PAGE_LEVELS - 1])
  244. level: usize,
  245. phantom: PhantomData<Arch>,
  246. }
  247. #[allow(dead_code)]
  248. impl<Arch: MemoryManagementArch> PageTable<Arch> {
  249. pub unsafe fn new(base: VirtAddr, phys: PhysAddr, level: usize) -> Self {
  250. Self {
  251. base,
  252. phys,
  253. level,
  254. phantom: PhantomData,
  255. }
  256. }
  257. /// 获取顶级页表
  258. ///
  259. /// ## 参数
  260. ///
  261. /// - table_kind 页表类型
  262. ///
  263. /// ## 返回值
  264. ///
  265. /// 返回顶级页表
  266. pub unsafe fn top_level_table(table_kind: PageTableKind) -> Self {
  267. return Self::new(
  268. VirtAddr::new(0),
  269. Arch::table(table_kind),
  270. Arch::PAGE_LEVELS - 1,
  271. );
  272. }
  273. /// 获取当前页表的物理地址
  274. #[inline(always)]
  275. pub fn phys(&self) -> PhysAddr {
  276. self.phys
  277. }
  278. /// 当前页表表示的虚拟地址空间的起始地址
  279. #[inline(always)]
  280. pub fn base(&self) -> VirtAddr {
  281. self.base
  282. }
  283. /// 获取当前页表的层级
  284. #[inline(always)]
  285. pub fn level(&self) -> usize {
  286. self.level
  287. }
  288. /// 获取当前页表自身所在的虚拟地址
  289. #[inline(always)]
  290. pub unsafe fn virt(&self) -> VirtAddr {
  291. return Arch::phys_2_virt(self.phys).unwrap();
  292. }
  293. /// 获取第i个页表项所表示的虚拟内存空间的起始地址
  294. pub fn entry_base(&self, i: usize) -> Option<VirtAddr> {
  295. if i < Arch::PAGE_ENTRY_NUM {
  296. let shift = self.level * Arch::PAGE_ENTRY_SHIFT + Arch::PAGE_SHIFT;
  297. return Some(self.base.add(i << shift));
  298. } else {
  299. return None;
  300. }
  301. }
  302. /// 获取当前页表的第i个页表项所在的虚拟地址(注意与entry_base进行区分)
  303. pub unsafe fn entry_virt(&self, i: usize) -> Option<VirtAddr> {
  304. if i < Arch::PAGE_ENTRY_NUM {
  305. return Some(self.virt().add(i * Arch::PAGE_ENTRY_SIZE));
  306. } else {
  307. return None;
  308. }
  309. }
  310. /// 获取当前页表的第i个页表项
  311. pub unsafe fn entry(&self, i: usize) -> Option<PageEntry<Arch>> {
  312. let entry_virt = self.entry_virt(i)?;
  313. return Some(PageEntry::from_usize(Arch::read::<usize>(entry_virt)));
  314. }
  315. /// 设置当前页表的第i个页表项
  316. pub unsafe fn set_entry(&self, i: usize, entry: PageEntry<Arch>) -> Option<()> {
  317. let entry_virt = self.entry_virt(i)?;
  318. Arch::write::<usize>(entry_virt, entry.data());
  319. return Some(());
  320. }
  321. /// 判断当前页表的第i个页表项是否已经填写了值
  322. ///
  323. /// ## 参数
  324. /// - Some(true) 如果已经填写了值
  325. /// - Some(false) 如果未填写值
  326. /// - None 如果i超出了页表项的范围
  327. pub fn entry_mapped(&self, i: usize) -> Option<bool> {
  328. let etv = unsafe { self.entry_virt(i) }?;
  329. if unsafe { Arch::read::<usize>(etv) } != 0 {
  330. return Some(true);
  331. } else {
  332. return Some(false);
  333. }
  334. }
  335. /// 根据虚拟地址,获取对应的页表项在页表中的下标
  336. ///
  337. /// ## 参数
  338. ///
  339. /// - addr: 虚拟地址
  340. ///
  341. /// ## 返回值
  342. ///
  343. /// 页表项在页表中的下标。如果addr不在当前页表所表示的虚拟地址空间中,则返回None
  344. pub fn index_of(&self, addr: VirtAddr) -> Option<usize> {
  345. let addr = VirtAddr::new(addr.data() & Arch::PAGE_ADDRESS_MASK);
  346. let shift = self.level * Arch::PAGE_ENTRY_SHIFT + Arch::PAGE_SHIFT;
  347. let mask = (MMArch::PAGE_ENTRY_NUM << shift) - 1;
  348. if addr < self.base || addr >= self.base.add(mask) {
  349. return None;
  350. } else {
  351. return Some((addr.data() >> shift) & MMArch::PAGE_ENTRY_MASK);
  352. }
  353. }
  354. /// 获取第i个页表项指向的下一级页表
  355. pub unsafe fn next_level_table(&self, index: usize) -> Option<Self> {
  356. if self.level == 0 {
  357. return None;
  358. }
  359. // 返回下一级页表
  360. return Some(PageTable::new(
  361. self.entry_base(index)?,
  362. self.entry(index)?.address().ok()?,
  363. self.level - 1,
  364. ));
  365. }
  366. /// 拷贝页表
  367. /// ## 参数
  368. ///
  369. /// - `allocator`: 物理页框分配器
  370. /// - `copy_on_write`: 是否写时复制
  371. pub unsafe fn clone(
  372. &self,
  373. allocator: &mut impl FrameAllocator,
  374. copy_on_write: bool,
  375. ) -> Option<PageTable<Arch>> {
  376. // 分配新页面作为新的页表
  377. let phys = allocator.allocate_one()?;
  378. let frame = MMArch::phys_2_virt(phys).unwrap();
  379. MMArch::write_bytes(frame, 0, MMArch::PAGE_SIZE);
  380. let new_table = PageTable::new(self.base, phys, self.level);
  381. if self.level == 0 {
  382. for i in 0..Arch::PAGE_ENTRY_NUM {
  383. if let Some(mut entry) = self.entry(i) {
  384. if entry.present() {
  385. if copy_on_write {
  386. let mut new_flags = entry.flags().set_write(false);
  387. entry.set_flags(new_flags);
  388. self.set_entry(i, entry);
  389. new_flags = new_flags.set_dirty(false);
  390. entry.set_flags(new_flags);
  391. new_table.set_entry(i, entry);
  392. } else {
  393. let phys = allocator.allocate_one()?;
  394. let mut page_manager_guard = page_manager_lock_irqsave();
  395. let old_phys = entry.address().unwrap();
  396. let old_page = page_manager_guard.get_unwrap(&old_phys);
  397. let new_page = Arc::new(Page::new(old_page.read().shared(), phys));
  398. if let Some(ref page_cache) = old_page.read().page_cache() {
  399. new_page.write().set_page_cache_index(
  400. Some(page_cache.clone()),
  401. old_page.read().index(),
  402. );
  403. }
  404. page_manager_guard.insert(phys, &new_page);
  405. let old_phys = entry.address().unwrap();
  406. let frame = MMArch::phys_2_virt(phys).unwrap().data() as *mut u8;
  407. frame.copy_from_nonoverlapping(
  408. MMArch::phys_2_virt(old_phys).unwrap().data() as *mut u8,
  409. MMArch::PAGE_SIZE,
  410. );
  411. new_table.set_entry(i, PageEntry::new(phys, entry.flags()));
  412. }
  413. }
  414. }
  415. }
  416. } else {
  417. // 非一级页表拷贝时,对每个页表项对应的页表都进行拷贝
  418. for i in 0..MMArch::PAGE_ENTRY_NUM {
  419. if let Some(next_table) = self.next_level_table(i) {
  420. let table = next_table.clone(allocator, copy_on_write)?;
  421. let old_entry = self.entry(i).unwrap();
  422. let entry = PageEntry::new(table.phys(), old_entry.flags());
  423. new_table.set_entry(i, entry);
  424. }
  425. }
  426. }
  427. Some(new_table)
  428. }
  429. }
  430. /// 页表项
  431. #[derive(Copy, Clone)]
  432. pub struct PageEntry<Arch> {
  433. data: usize,
  434. phantom: PhantomData<Arch>,
  435. }
  436. impl<Arch> Debug for PageEntry<Arch> {
  437. fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
  438. f.write_fmt(format_args!("PageEntry({:#x})", self.data))
  439. }
  440. }
  441. impl<Arch: MemoryManagementArch> PageEntry<Arch> {
  442. #[inline(always)]
  443. pub fn new(paddr: PhysAddr, flags: EntryFlags<Arch>) -> Self {
  444. Self {
  445. data: MMArch::make_entry(paddr, flags.data()),
  446. phantom: PhantomData,
  447. }
  448. }
  449. #[inline(always)]
  450. pub fn from_usize(data: usize) -> Self {
  451. Self {
  452. data,
  453. phantom: PhantomData,
  454. }
  455. }
  456. #[inline(always)]
  457. pub fn data(&self) -> usize {
  458. self.data
  459. }
  460. /// 获取当前页表项指向的物理地址
  461. ///
  462. /// ## 返回值
  463. ///
  464. /// - Ok(PhysAddr) 如果当前页面存在于物理内存中, 返回物理地址
  465. /// - Err(PhysAddr) 如果当前页表项不存在, 返回物理地址
  466. #[inline(always)]
  467. pub fn address(&self) -> Result<PhysAddr, PhysAddr> {
  468. let paddr: PhysAddr = {
  469. #[cfg(target_arch = "x86_64")]
  470. {
  471. PhysAddr::new(self.data & Arch::PAGE_ADDRESS_MASK)
  472. }
  473. #[cfg(target_arch = "riscv64")]
  474. {
  475. let ppn = ((self.data & (!((1 << 10) - 1))) >> 10) & ((1 << 54) - 1);
  476. super::allocator::page_frame::PhysPageFrame::from_ppn(ppn).phys_address()
  477. }
  478. };
  479. if self.present() {
  480. Ok(paddr)
  481. } else {
  482. Err(paddr)
  483. }
  484. }
  485. #[inline(always)]
  486. pub fn flags(&self) -> EntryFlags<Arch> {
  487. unsafe { EntryFlags::from_data(self.data & Arch::ENTRY_FLAGS_MASK) }
  488. }
  489. #[inline(always)]
  490. pub fn set_flags(&mut self, flags: EntryFlags<Arch>) {
  491. self.data = (self.data & !Arch::ENTRY_FLAGS_MASK) | flags.data();
  492. }
  493. #[inline(always)]
  494. pub fn present(&self) -> bool {
  495. return self.data & Arch::ENTRY_FLAG_PRESENT != 0;
  496. }
  497. #[inline(always)]
  498. pub fn empty(&self) -> bool {
  499. self.data & !(Arch::ENTRY_FLAG_DIRTY & Arch::ENTRY_FLAG_ACCESSED) == 0
  500. }
  501. #[inline(always)]
  502. pub fn protnone(&self) -> bool {
  503. return self.data & (Arch::ENTRY_FLAG_PRESENT | Arch::ENTRY_FLAG_GLOBAL)
  504. == Arch::ENTRY_FLAG_GLOBAL;
  505. }
  506. #[inline(always)]
  507. pub fn write(&self) -> bool {
  508. return self.data & Arch::ENTRY_FLAG_READWRITE != 0;
  509. }
  510. }
  511. /// 页表项的标志位
  512. #[derive(Copy, Clone, Hash)]
  513. pub struct EntryFlags<Arch> {
  514. data: usize,
  515. phantom: PhantomData<Arch>,
  516. }
  517. impl<Arch: MemoryManagementArch> Default for EntryFlags<Arch> {
  518. fn default() -> Self {
  519. Self::new()
  520. }
  521. }
  522. #[allow(dead_code)]
  523. impl<Arch: MemoryManagementArch> EntryFlags<Arch> {
  524. #[inline(always)]
  525. pub fn new() -> Self {
  526. let mut r = unsafe {
  527. Self::from_data(
  528. Arch::ENTRY_FLAG_DEFAULT_PAGE
  529. | Arch::ENTRY_FLAG_READONLY
  530. | Arch::ENTRY_FLAG_NO_EXEC,
  531. )
  532. };
  533. #[cfg(target_arch = "x86_64")]
  534. {
  535. if crate::arch::mm::X86_64MMArch::is_xd_reserved() {
  536. r = r.set_execute(true);
  537. }
  538. }
  539. return r;
  540. }
  541. /// 根据ProtFlags生成EntryFlags
  542. ///
  543. /// ## 参数
  544. ///
  545. /// - prot_flags: 页的保护标志
  546. /// - user: 用户空间是否可访问
  547. pub fn from_prot_flags(prot_flags: ProtFlags, user: bool) -> EntryFlags<Arch> {
  548. let vm_flags = super::VmFlags::from(prot_flags);
  549. // let flags: EntryFlags<Arch> = EntryFlags::new()
  550. // .set_user(user)
  551. // .set_execute(prot_flags.contains(ProtFlags::PROT_EXEC))
  552. // .set_write(prot_flags.contains(ProtFlags::PROT_WRITE));
  553. let flags = Arch::vm_get_page_prot(vm_flags).set_user(user);
  554. return flags;
  555. }
  556. #[inline(always)]
  557. pub fn data(&self) -> usize {
  558. self.data
  559. }
  560. #[inline(always)]
  561. pub const unsafe fn from_data(data: usize) -> Self {
  562. return Self {
  563. data,
  564. phantom: PhantomData,
  565. };
  566. }
  567. /// 为新页表的页表项设置默认值
  568. ///
  569. /// 默认值为:
  570. /// - present
  571. /// - read only
  572. /// - kernel space
  573. /// - no exec
  574. #[inline(always)]
  575. pub fn new_page_table(user: bool) -> Self {
  576. return unsafe {
  577. let r = {
  578. #[cfg(target_arch = "x86_64")]
  579. {
  580. Self::from_data(Arch::ENTRY_FLAG_DEFAULT_TABLE | Arch::ENTRY_FLAG_READWRITE)
  581. }
  582. #[cfg(target_arch = "riscv64")]
  583. {
  584. // riscv64指向下一级页表的页表项,不应设置R/W/X权限位
  585. Self::from_data(Arch::ENTRY_FLAG_DEFAULT_TABLE)
  586. }
  587. };
  588. #[cfg(target_arch = "x86_64")]
  589. {
  590. if user {
  591. r.set_user(true)
  592. } else {
  593. r
  594. }
  595. }
  596. #[cfg(target_arch = "riscv64")]
  597. {
  598. r
  599. }
  600. };
  601. }
  602. /// 取得当前页表项的所有权,更新当前页表项的标志位,并返回更新后的页表项。
  603. ///
  604. /// ## 参数
  605. /// - flag 要更新的标志位的值
  606. /// - value 如果为true,那么将flag对应的位设置为1,否则设置为0
  607. ///
  608. /// ## 返回值
  609. ///
  610. /// 更新后的页表项
  611. #[inline(always)]
  612. #[must_use]
  613. pub fn update_flags(mut self, flag: usize, value: bool) -> Self {
  614. if value {
  615. self.data |= flag;
  616. } else {
  617. self.data &= !flag;
  618. }
  619. return self;
  620. }
  621. /// 判断当前页表项是否存在指定的flag(只有全部flag都存在才返回true)
  622. #[inline(always)]
  623. pub fn has_flag(&self, flag: usize) -> bool {
  624. return self.data & flag == flag;
  625. }
  626. #[inline(always)]
  627. pub fn present(&self) -> bool {
  628. return self.has_flag(Arch::ENTRY_FLAG_PRESENT);
  629. }
  630. /// 设置当前页表项的权限
  631. ///
  632. /// @param value 如果为true,那么将当前页表项的权限设置为用户态可访问
  633. #[must_use]
  634. #[inline(always)]
  635. pub fn set_user(self, value: bool) -> Self {
  636. return self.update_flags(Arch::ENTRY_FLAG_USER, value);
  637. }
  638. /// 用户态是否可以访问当前页表项
  639. #[inline(always)]
  640. pub fn has_user(&self) -> bool {
  641. return self.has_flag(Arch::ENTRY_FLAG_USER);
  642. }
  643. /// 设置当前页表项的可写性, 如果为true,那么将当前页表项的权限设置为可写, 否则设置为只读
  644. ///
  645. /// ## 返回值
  646. ///
  647. /// 更新后的页表项.
  648. ///
  649. /// **请注意,**本函数会取得当前页表项的所有权,因此返回的页表项不是原来的页表项
  650. #[must_use]
  651. #[inline(always)]
  652. pub fn set_write(self, value: bool) -> Self {
  653. #[cfg(target_arch = "x86_64")]
  654. {
  655. // 有的架构同时具有可写和不可写的标志位,因此需要同时更新
  656. return self
  657. .update_flags(Arch::ENTRY_FLAG_READONLY, !value)
  658. .update_flags(Arch::ENTRY_FLAG_READWRITE, value);
  659. }
  660. #[cfg(target_arch = "riscv64")]
  661. {
  662. if value {
  663. return self.update_flags(Arch::ENTRY_FLAG_READWRITE, true);
  664. } else {
  665. return self
  666. .update_flags(Arch::ENTRY_FLAG_READONLY, true)
  667. .update_flags(Arch::ENTRY_FLAG_WRITEABLE, false);
  668. }
  669. }
  670. }
  671. /// 当前页表项是否可写
  672. #[inline(always)]
  673. pub fn has_write(&self) -> bool {
  674. // 有的架构同时具有可写和不可写的标志位,因此需要同时判断
  675. return self.data & (Arch::ENTRY_FLAG_READWRITE | Arch::ENTRY_FLAG_READONLY)
  676. == Arch::ENTRY_FLAG_READWRITE;
  677. }
  678. /// 设置当前页表项的可执行性, 如果为true,那么将当前页表项的权限设置为可执行, 否则设置为不可执行
  679. #[must_use]
  680. #[inline(always)]
  681. pub fn set_execute(self, mut value: bool) -> Self {
  682. #[cfg(target_arch = "x86_64")]
  683. {
  684. // 如果xd位被保留,那么将可执行性设置为true
  685. if crate::arch::mm::X86_64MMArch::is_xd_reserved() {
  686. value = true;
  687. }
  688. }
  689. // 有的架构同时具有可执行和不可执行的标志位,因此需要同时更新
  690. return self
  691. .update_flags(Arch::ENTRY_FLAG_NO_EXEC, !value)
  692. .update_flags(Arch::ENTRY_FLAG_EXEC, value);
  693. }
  694. /// 当前页表项是否可执行
  695. #[inline(always)]
  696. pub fn has_execute(&self) -> bool {
  697. // 有的架构同时具有可执行和不可执行的标志位,因此需要同时判断
  698. return self.data & (Arch::ENTRY_FLAG_EXEC | Arch::ENTRY_FLAG_NO_EXEC)
  699. == Arch::ENTRY_FLAG_EXEC;
  700. }
  701. /// 设置当前页表项的缓存策略
  702. ///
  703. /// ## 参数
  704. ///
  705. /// - value: 如果为true,那么将当前页表项的缓存策略设置为不缓存。
  706. #[inline(always)]
  707. pub fn set_page_cache_disable(self, value: bool) -> Self {
  708. return self.update_flags(Arch::ENTRY_FLAG_CACHE_DISABLE, value);
  709. }
  710. /// 获取当前页表项的缓存策略
  711. ///
  712. /// ## 返回值
  713. ///
  714. /// 如果当前页表项的缓存策略为不缓存,那么返回true,否则返回false。
  715. #[inline(always)]
  716. pub fn has_page_cache_disable(&self) -> bool {
  717. return self.has_flag(Arch::ENTRY_FLAG_CACHE_DISABLE);
  718. }
  719. /// 设置当前页表项的写穿策略
  720. ///
  721. /// ## 参数
  722. ///
  723. /// - value: 如果为true,那么将当前页表项的写穿策略设置为写穿。
  724. #[inline(always)]
  725. pub fn set_page_write_through(self, value: bool) -> Self {
  726. return self.update_flags(Arch::ENTRY_FLAG_WRITE_THROUGH, value);
  727. }
  728. #[inline(always)]
  729. pub fn set_page_global(self, value: bool) -> Self {
  730. return self.update_flags(MMArch::ENTRY_FLAG_GLOBAL, value);
  731. }
  732. /// 获取当前页表项的写穿策略
  733. ///
  734. /// ## 返回值
  735. ///
  736. /// 如果当前页表项的写穿策略为写穿,那么返回true,否则返回false。
  737. #[inline(always)]
  738. pub fn has_page_write_through(&self) -> bool {
  739. return self.has_flag(Arch::ENTRY_FLAG_WRITE_THROUGH);
  740. }
  741. /// 设置当前页表是否为脏页
  742. ///
  743. /// ## 参数
  744. ///
  745. /// - value: 如果为true,那么将当前页表项的写穿策略设置为写穿。
  746. #[inline(always)]
  747. pub fn set_dirty(self, value: bool) -> Self {
  748. return self.update_flags(Arch::ENTRY_FLAG_DIRTY, value);
  749. }
  750. /// 设置当前页表被访问
  751. ///
  752. /// ## 参数
  753. ///
  754. /// - value: 如果为true,那么将当前页表项的访问标志设置为已访问。
  755. #[inline(always)]
  756. pub fn set_access(self, value: bool) -> Self {
  757. return self.update_flags(Arch::ENTRY_FLAG_ACCESSED, value);
  758. }
  759. /// 设置指向的页是否为大页
  760. ///
  761. /// ## 参数
  762. ///
  763. /// - value: 如果为true,那么将当前页表项的访问标志设置为已访问。
  764. #[inline(always)]
  765. pub fn set_huge_page(self, value: bool) -> Self {
  766. return self.update_flags(Arch::ENTRY_FLAG_HUGE_PAGE, value);
  767. }
  768. /// MMIO内存的页表项标志
  769. #[inline(always)]
  770. pub fn mmio_flags() -> Self {
  771. #[cfg(target_arch = "x86_64")]
  772. {
  773. Self::new()
  774. .set_user(false)
  775. .set_write(true)
  776. .set_execute(true)
  777. .set_page_cache_disable(true)
  778. .set_page_write_through(true)
  779. .set_page_global(true)
  780. }
  781. #[cfg(target_arch = "riscv64")]
  782. {
  783. Self::new()
  784. .set_user(false)
  785. .set_write(true)
  786. .set_execute(true)
  787. .set_page_global(true)
  788. }
  789. }
  790. }
  791. impl<Arch: MemoryManagementArch> fmt::Debug for EntryFlags<Arch> {
  792. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  793. f.debug_struct("EntryFlags")
  794. .field("bits", &format_args!("{:#0x}", self.data))
  795. .field("present", &self.present())
  796. .field("has_write", &self.has_write())
  797. .field("has_execute", &self.has_execute())
  798. .field("has_user", &self.has_user())
  799. .finish()
  800. }
  801. }
  802. /// 页表映射器
  803. #[derive(Hash)]
  804. pub struct PageMapper<Arch, F> {
  805. /// 页表类型
  806. table_kind: PageTableKind,
  807. /// 根页表物理地址
  808. table_paddr: PhysAddr,
  809. /// 页分配器
  810. frame_allocator: F,
  811. phantom: PhantomData<fn() -> Arch>,
  812. }
  813. impl<Arch: MemoryManagementArch, F: FrameAllocator> PageMapper<Arch, F> {
  814. /// 创建新的页面映射器
  815. ///
  816. /// ## 参数
  817. /// - table_kind 页表类型
  818. /// - table_paddr 根页表物理地址
  819. /// - allocator 页分配器
  820. ///
  821. /// ## 返回值
  822. ///
  823. /// 页面映射器
  824. pub unsafe fn new(table_kind: PageTableKind, table_paddr: PhysAddr, allocator: F) -> Self {
  825. return Self {
  826. table_kind,
  827. table_paddr,
  828. frame_allocator: allocator,
  829. phantom: PhantomData,
  830. };
  831. }
  832. /// 创建页表,并为这个页表创建页面映射器
  833. pub unsafe fn create(table_kind: PageTableKind, mut allocator: F) -> Option<Self> {
  834. let table_paddr = allocator.allocate_one()?;
  835. // 清空页表
  836. let table_vaddr = Arch::phys_2_virt(table_paddr)?;
  837. Arch::write_bytes(table_vaddr, 0, Arch::PAGE_SIZE);
  838. return Some(Self::new(table_kind, table_paddr, allocator));
  839. }
  840. /// 获取当前页表的页面映射器
  841. #[inline(always)]
  842. pub unsafe fn current(table_kind: PageTableKind, allocator: F) -> Self {
  843. let table_paddr = Arch::table(table_kind);
  844. return Self::new(table_kind, table_paddr, allocator);
  845. }
  846. /// 判断当前页表分配器所属的页表是否是当前页表
  847. #[inline(always)]
  848. pub fn is_current(&self) -> bool {
  849. return unsafe { self.table().phys() == Arch::table(self.table_kind) };
  850. }
  851. /// 将当前页表分配器所属的页表设置为当前页表
  852. #[inline(always)]
  853. pub unsafe fn make_current(&self) {
  854. Arch::set_table(self.table_kind, self.table_paddr);
  855. }
  856. /// 获取当前页表分配器所属的根页表的结构体
  857. #[inline(always)]
  858. pub fn table(&self) -> PageTable<Arch> {
  859. // 由于只能通过new方法创建PageMapper,因此这里假定table_paddr是有效的
  860. return unsafe {
  861. PageTable::new(VirtAddr::new(0), self.table_paddr, Arch::PAGE_LEVELS - 1)
  862. };
  863. }
  864. /// 获取当前PageMapper所对应的页分配器实例的引用
  865. #[inline(always)]
  866. #[allow(dead_code)]
  867. pub fn allocator_ref(&self) -> &F {
  868. return &self.frame_allocator;
  869. }
  870. /// 获取当前PageMapper所对应的页分配器实例的可变引用
  871. #[inline(always)]
  872. pub fn allocator_mut(&mut self) -> &mut F {
  873. return &mut self.frame_allocator;
  874. }
  875. /// 从当前PageMapper的页分配器中分配一个物理页,并将其映射到指定的虚拟地址
  876. pub unsafe fn map(
  877. &mut self,
  878. virt: VirtAddr,
  879. flags: EntryFlags<Arch>,
  880. ) -> Option<PageFlush<Arch>> {
  881. compiler_fence(Ordering::SeqCst);
  882. let phys: PhysAddr = self.frame_allocator.allocate_one()?;
  883. compiler_fence(Ordering::SeqCst);
  884. unsafe {
  885. let vaddr = MMArch::phys_2_virt(phys).unwrap();
  886. MMArch::write_bytes(vaddr, 0, MMArch::PAGE_SIZE);
  887. }
  888. let mut page_manager_guard: SpinLockGuard<'static, PageManager> =
  889. page_manager_lock_irqsave();
  890. if !page_manager_guard.contains(&phys) {
  891. page_manager_guard.insert(phys, &Arc::new(Page::new(false, phys)))
  892. }
  893. return self.map_phys(virt, phys, flags);
  894. }
  895. /// 映射一个物理页到指定的虚拟地址
  896. pub unsafe fn map_phys(
  897. &mut self,
  898. virt: VirtAddr,
  899. phys: PhysAddr,
  900. flags: EntryFlags<Arch>,
  901. ) -> Option<PageFlush<Arch>> {
  902. // 验证虚拟地址和物理地址是否对齐
  903. if !(virt.check_aligned(Arch::PAGE_SIZE) && phys.check_aligned(Arch::PAGE_SIZE)) {
  904. error!(
  905. "Try to map unaligned page: virt={:?}, phys={:?}",
  906. virt, phys
  907. );
  908. return None;
  909. }
  910. let virt = VirtAddr::new(virt.data() & (!Arch::PAGE_NEGATIVE_MASK));
  911. // TODO: 验证flags是否合法
  912. // 创建页表项
  913. let entry = PageEntry::new(phys, flags);
  914. let mut table = self.table();
  915. loop {
  916. let i = table.index_of(virt)?;
  917. assert!(i < Arch::PAGE_ENTRY_NUM);
  918. if table.level() == 0 {
  919. compiler_fence(Ordering::SeqCst);
  920. table.set_entry(i, entry);
  921. compiler_fence(Ordering::SeqCst);
  922. return Some(PageFlush::new(virt));
  923. } else {
  924. let next_table = table.next_level_table(i);
  925. if let Some(next_table) = next_table {
  926. table = next_table;
  927. // debug!("Mapping {:?} to next level table...", virt);
  928. } else {
  929. // 分配下一级页表
  930. let frame = self.frame_allocator.allocate_one()?;
  931. // 清空这个页帧
  932. MMArch::write_bytes(MMArch::phys_2_virt(frame).unwrap(), 0, MMArch::PAGE_SIZE);
  933. // 设置页表项的flags
  934. let flags: EntryFlags<Arch> =
  935. EntryFlags::new_page_table(virt.kind() == PageTableKind::User);
  936. // 把新分配的页表映射到当前页表
  937. table.set_entry(i, PageEntry::new(frame, flags));
  938. // 获取新分配的页表
  939. table = table.next_level_table(i)?;
  940. }
  941. }
  942. }
  943. }
  944. /// 进行大页映射
  945. pub unsafe fn map_huge_page(
  946. &mut self,
  947. virt: VirtAddr,
  948. flags: EntryFlags<Arch>,
  949. ) -> Option<PageFlush<Arch>> {
  950. // 验证虚拟地址是否对齐
  951. if !(virt.check_aligned(Arch::PAGE_SIZE)) {
  952. error!("Try to map unaligned page: virt={:?}", virt);
  953. return None;
  954. }
  955. let virt = VirtAddr::new(virt.data() & (!Arch::PAGE_NEGATIVE_MASK));
  956. let mut table = self.table();
  957. loop {
  958. let i = table.index_of(virt)?;
  959. assert!(i < Arch::PAGE_ENTRY_NUM);
  960. let next_table = table.next_level_table(i);
  961. if let Some(next_table) = next_table {
  962. table = next_table;
  963. } else {
  964. break;
  965. }
  966. }
  967. // 支持2M、1G大页,即页表层级为1、2级的页表可以映射大页
  968. if table.level == 0 || table.level > 2 {
  969. return None;
  970. }
  971. let (phys, count) = self.frame_allocator.allocate(PageFrameCount::new(
  972. Arch::PAGE_ENTRY_NUM.pow(table.level as u32),
  973. ))?;
  974. MMArch::write_bytes(
  975. MMArch::phys_2_virt(phys).unwrap(),
  976. 0,
  977. MMArch::PAGE_SIZE * count.data(),
  978. );
  979. table.set_entry(
  980. table.index_of(virt)?,
  981. PageEntry::new(phys, flags.set_huge_page(true)),
  982. )?;
  983. Some(PageFlush::new(virt))
  984. }
  985. /// 为虚拟地址分配指定层级的页表
  986. /// ## 参数
  987. ///
  988. /// - `virt`: 虚拟地址
  989. /// - `level`: 指定页表层级
  990. ///
  991. /// ## 返回值
  992. /// - Some(PageTable<Arch>): 虚拟地址对应层级的页表
  993. /// - None: 对应页表不存在
  994. pub unsafe fn allocate_table(
  995. &mut self,
  996. virt: VirtAddr,
  997. level: usize,
  998. ) -> Option<PageTable<Arch>> {
  999. let table = self.get_table(virt, level + 1)?;
  1000. let i = table.index_of(virt)?;
  1001. let frame = self.frame_allocator.allocate_one()?;
  1002. // 清空这个页帧
  1003. MMArch::write_bytes(MMArch::phys_2_virt(frame).unwrap(), 0, MMArch::PAGE_SIZE);
  1004. // 设置页表项的flags
  1005. let flags: EntryFlags<Arch> =
  1006. EntryFlags::new_page_table(virt.kind() == PageTableKind::User);
  1007. table.set_entry(i, PageEntry::new(frame, flags));
  1008. table.next_level_table(i)
  1009. }
  1010. /// 获取虚拟地址的指定层级页表
  1011. /// ## 参数
  1012. ///
  1013. /// - `virt`: 虚拟地址
  1014. /// - `level`: 指定页表层级
  1015. ///
  1016. /// ## 返回值
  1017. /// - Some(PageTable<Arch>): 虚拟地址对应层级的页表
  1018. /// - None: 对应页表不存在
  1019. pub fn get_table(&self, virt: VirtAddr, level: usize) -> Option<PageTable<Arch>> {
  1020. let mut table = self.table();
  1021. if level > Arch::PAGE_LEVELS - 1 {
  1022. return None;
  1023. }
  1024. unsafe {
  1025. loop {
  1026. if table.level == level {
  1027. return Some(table);
  1028. }
  1029. let i = table.index_of(virt)?;
  1030. assert!(i < Arch::PAGE_ENTRY_NUM);
  1031. table = table.next_level_table(i)?;
  1032. }
  1033. }
  1034. }
  1035. /// 获取虚拟地址在指定层级页表的PageEntry
  1036. /// ## 参数
  1037. ///
  1038. /// - `virt`: 虚拟地址
  1039. /// - `level`: 指定页表层级
  1040. ///
  1041. /// ## 返回值
  1042. /// - Some(PageEntry<Arch>): 虚拟地址在指定层级的页表的有效PageEntry
  1043. /// - None: 无对应的有效PageEntry
  1044. pub fn get_entry(&self, virt: VirtAddr, level: usize) -> Option<PageEntry<Arch>> {
  1045. let table = self.get_table(virt, level)?;
  1046. let i = table.index_of(virt)?;
  1047. let entry = unsafe { table.entry(i) }?;
  1048. if !entry.empty() {
  1049. Some(entry)
  1050. } else {
  1051. None
  1052. }
  1053. // let mut table = self.table();
  1054. // if level > Arch::PAGE_LEVELS - 1 {
  1055. // return None;
  1056. // }
  1057. // unsafe {
  1058. // loop {
  1059. // let i = table.index_of(virt)?;
  1060. // assert!(i < Arch::PAGE_ENTRY_NUM);
  1061. // if table.level == level {
  1062. // let entry = table.entry(i)?;
  1063. // if !entry.empty() {
  1064. // return Some(entry);
  1065. // } else {
  1066. // return None;
  1067. // }
  1068. // }
  1069. // table = table.next_level_table(i)?;
  1070. // }
  1071. // }
  1072. }
  1073. /// 拷贝用户空间映射
  1074. /// ## 参数
  1075. ///
  1076. /// - `umapper`: 要拷贝的用户空间
  1077. /// - `copy_on_write`: 是否写时复制
  1078. pub unsafe fn clone_user_mapping(&mut self, umapper: &mut Self, copy_on_write: bool) {
  1079. let old_table = umapper.table();
  1080. let new_table = self.table();
  1081. let allocator = self.allocator_mut();
  1082. // 顶级页表的[0, PAGE_KERNEL_INDEX)项为用户空间映射
  1083. for entry_index in 0..Arch::PAGE_KERNEL_INDEX {
  1084. if let Some(next_table) = old_table.next_level_table(entry_index) {
  1085. let table = next_table.clone(allocator, copy_on_write).unwrap();
  1086. let old_entry = old_table.entry(entry_index).unwrap();
  1087. let entry = PageEntry::new(table.phys(), old_entry.flags());
  1088. new_table.set_entry(entry_index, entry);
  1089. }
  1090. }
  1091. }
  1092. /// 将物理地址映射到具有线性偏移量的虚拟地址
  1093. #[allow(dead_code)]
  1094. pub unsafe fn map_linearly(
  1095. &mut self,
  1096. phys: PhysAddr,
  1097. flags: EntryFlags<Arch>,
  1098. ) -> Option<(VirtAddr, PageFlush<Arch>)> {
  1099. let virt: VirtAddr = Arch::phys_2_virt(phys)?;
  1100. return self.map_phys(virt, phys, flags).map(|flush| (virt, flush));
  1101. }
  1102. /// 修改虚拟地址的页表项的flags,并返回页表项刷新器
  1103. ///
  1104. /// 请注意,需要在修改完flags后,调用刷新器的flush方法,才能使修改生效
  1105. ///
  1106. /// ## 参数
  1107. /// - virt 虚拟地址
  1108. /// - flags 新的页表项的flags
  1109. ///
  1110. /// ## 返回值
  1111. ///
  1112. /// 如果修改成功,返回刷新器,否则返回None
  1113. pub unsafe fn remap(
  1114. &mut self,
  1115. virt: VirtAddr,
  1116. flags: EntryFlags<Arch>,
  1117. ) -> Option<PageFlush<Arch>> {
  1118. return self
  1119. .visit(virt, |p1, i| {
  1120. let mut entry = p1.entry(i)?;
  1121. entry.set_flags(flags);
  1122. p1.set_entry(i, entry);
  1123. Some(PageFlush::new(virt))
  1124. })
  1125. .flatten();
  1126. }
  1127. /// 根据虚拟地址,查找页表,获取对应的物理地址和页表项的flags
  1128. ///
  1129. /// ## 参数
  1130. ///
  1131. /// - virt 虚拟地址
  1132. ///
  1133. /// ## 返回值
  1134. ///
  1135. /// 如果查找成功,返回物理地址和页表项的flags,否则返回None
  1136. pub fn translate(&self, virt: VirtAddr) -> Option<(PhysAddr, EntryFlags<Arch>)> {
  1137. let entry: PageEntry<Arch> = self.visit(virt, |p1, i| unsafe { p1.entry(i) })??;
  1138. let paddr = entry.address().ok()?;
  1139. let flags = entry.flags();
  1140. return Some((paddr, flags));
  1141. }
  1142. /// 取消虚拟地址的映射,释放页面,并返回页表项刷新器
  1143. ///
  1144. /// 请注意,需要在取消映射后,调用刷新器的flush方法,才能使修改生效
  1145. ///
  1146. /// ## 参数
  1147. ///
  1148. /// - virt 虚拟地址
  1149. /// - unmap_parents 是否在父页表内,取消空闲子页表的映射
  1150. ///
  1151. /// ## 返回值
  1152. /// 如果取消成功,返回刷新器,否则返回None
  1153. #[allow(dead_code)]
  1154. pub unsafe fn unmap(&mut self, virt: VirtAddr, unmap_parents: bool) -> Option<PageFlush<Arch>> {
  1155. let (paddr, _, flusher) = self.unmap_phys(virt, unmap_parents)?;
  1156. self.frame_allocator.free_one(paddr);
  1157. return Some(flusher);
  1158. }
  1159. /// 取消虚拟地址的映射,并返回物理地址和页表项的flags
  1160. ///
  1161. /// ## 参数
  1162. ///
  1163. /// - vaddr 虚拟地址
  1164. /// - unmap_parents 是否在父页表内,取消空闲子页表的映射
  1165. ///
  1166. /// ## 返回值
  1167. ///
  1168. /// 如果取消成功,返回物理地址和页表项的flags,否则返回None
  1169. pub unsafe fn unmap_phys(
  1170. &mut self,
  1171. virt: VirtAddr,
  1172. unmap_parents: bool,
  1173. ) -> Option<(PhysAddr, EntryFlags<Arch>, PageFlush<Arch>)> {
  1174. if !virt.check_aligned(Arch::PAGE_SIZE) {
  1175. error!("Try to unmap unaligned page: virt={:?}", virt);
  1176. return None;
  1177. }
  1178. let table = self.table();
  1179. return unmap_phys_inner(virt, &table, unmap_parents, self.allocator_mut())
  1180. .map(|(paddr, flags)| (paddr, flags, PageFlush::<Arch>::new(virt)));
  1181. }
  1182. /// 在页表中,访问虚拟地址对应的页表项,并调用传入的函数F
  1183. fn visit<T>(
  1184. &self,
  1185. virt: VirtAddr,
  1186. f: impl FnOnce(&mut PageTable<Arch>, usize) -> T,
  1187. ) -> Option<T> {
  1188. let mut table = self.table();
  1189. unsafe {
  1190. loop {
  1191. let i = table.index_of(virt)?;
  1192. if table.level() == 0 {
  1193. return Some(f(&mut table, i));
  1194. } else {
  1195. table = table.next_level_table(i)?;
  1196. }
  1197. }
  1198. }
  1199. }
  1200. }
  1201. /// 取消页面映射,返回被取消映射的页表项的:【物理地址】和【flags】
  1202. ///
  1203. /// ## 参数
  1204. ///
  1205. /// - vaddr 虚拟地址
  1206. /// - table 页表
  1207. /// - unmap_parents 是否在父页表内,取消空闲子页表的映射
  1208. /// - allocator 页面分配器(如果页表从这个分配器分配,那么在取消映射时,也需要归还到这个分配器内)
  1209. ///
  1210. /// ## 返回值
  1211. ///
  1212. /// 如果取消成功,返回被取消映射的页表项的:【物理地址】和【flags】,否则返回None
  1213. unsafe fn unmap_phys_inner<Arch: MemoryManagementArch>(
  1214. vaddr: VirtAddr,
  1215. table: &PageTable<Arch>,
  1216. unmap_parents: bool,
  1217. allocator: &mut impl FrameAllocator,
  1218. ) -> Option<(PhysAddr, EntryFlags<Arch>)> {
  1219. // 获取页表项的索引
  1220. let i = table.index_of(vaddr)?;
  1221. // 如果当前是最后一级页表,直接取消页面映射
  1222. if table.level() == 0 {
  1223. let entry = table.entry(i)?;
  1224. table.set_entry(i, PageEntry::from_usize(0));
  1225. return Some((entry.address().ok()?, entry.flags()));
  1226. }
  1227. let subtable = table.next_level_table(i)?;
  1228. // 递归地取消映射
  1229. let result = unmap_phys_inner(vaddr, &subtable, unmap_parents, allocator)?;
  1230. // TODO: This is a bad idea for architectures where the kernel mappings are done in the process tables,
  1231. // as these mappings may become out of sync
  1232. if unmap_parents {
  1233. // 如果子页表已经没有映射的页面了,就取消子页表的映射
  1234. // 检查子页表中是否还有映射的页面
  1235. let x = (0..Arch::PAGE_ENTRY_NUM)
  1236. .map(|k| subtable.entry(k).expect("invalid page entry"))
  1237. .any(|e| e.present());
  1238. if !x {
  1239. // 如果没有,就取消子页表的映射
  1240. table.set_entry(i, PageEntry::from_usize(0));
  1241. // 释放子页表
  1242. allocator.free_one(subtable.phys());
  1243. }
  1244. }
  1245. return Some(result);
  1246. }
  1247. impl<Arch, F: Debug> Debug for PageMapper<Arch, F> {
  1248. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  1249. f.debug_struct("PageMapper")
  1250. .field("table_paddr", &self.table_paddr)
  1251. .field("frame_allocator", &self.frame_allocator)
  1252. .finish()
  1253. }
  1254. }
  1255. /// 页表刷新器的trait
  1256. pub trait Flusher<Arch: MemoryManagementArch> {
  1257. /// 取消对指定的page flusher的刷新
  1258. fn consume(&mut self, flush: PageFlush<Arch>);
  1259. }
  1260. /// 用于刷新某个虚拟地址的刷新器。这个刷新器一经产生,就必须调用flush()方法,
  1261. /// 否则会造成对页表的更改被忽略,这是不安全的
  1262. #[must_use = "The flusher must call the 'flush()', or the changes to page table will be unsafely ignored."]
  1263. pub struct PageFlush<Arch: MemoryManagementArch> {
  1264. virt: VirtAddr,
  1265. phantom: PhantomData<Arch>,
  1266. }
  1267. impl<Arch: MemoryManagementArch> PageFlush<Arch> {
  1268. pub fn new(virt: VirtAddr) -> Self {
  1269. return Self {
  1270. virt,
  1271. phantom: PhantomData,
  1272. };
  1273. }
  1274. pub fn flush(self) {
  1275. unsafe { Arch::invalidate_page(self.virt) };
  1276. }
  1277. /// 忽略掉这个刷新器
  1278. pub unsafe fn ignore(self) {
  1279. mem::forget(self);
  1280. }
  1281. }
  1282. impl<Arch: MemoryManagementArch> Drop for PageFlush<Arch> {
  1283. fn drop(&mut self) {
  1284. unsafe {
  1285. MMArch::invalidate_page(self.virt);
  1286. }
  1287. }
  1288. }
  1289. /// 用于刷新整个页表的刷新器。这个刷新器一经产生,就必须调用flush()方法,
  1290. /// 否则会造成对页表的更改被忽略,这是不安全的
  1291. #[must_use = "The flusher must call the 'flush()', or the changes to page table will be unsafely ignored."]
  1292. pub struct PageFlushAll<Arch: MemoryManagementArch> {
  1293. phantom: PhantomData<fn() -> Arch>,
  1294. }
  1295. #[allow(dead_code)]
  1296. impl<Arch: MemoryManagementArch> PageFlushAll<Arch> {
  1297. pub fn new() -> Self {
  1298. return Self {
  1299. phantom: PhantomData,
  1300. };
  1301. }
  1302. pub fn flush(self) {
  1303. unsafe { Arch::invalidate_all() };
  1304. }
  1305. /// 忽略掉这个刷新器
  1306. pub unsafe fn ignore(self) {
  1307. mem::forget(self);
  1308. }
  1309. }
  1310. impl<Arch: MemoryManagementArch> Flusher<Arch> for PageFlushAll<Arch> {
  1311. /// 为page flush all 实现consume,消除对单个页面的刷新。(刷新整个页表了就不需要刷新单个页面了)
  1312. fn consume(&mut self, flush: PageFlush<Arch>) {
  1313. unsafe { flush.ignore() };
  1314. }
  1315. }
  1316. impl<Arch: MemoryManagementArch, T: Flusher<Arch> + ?Sized> Flusher<Arch> for &mut T {
  1317. /// 允许一个flusher consume掉另一个flusher
  1318. fn consume(&mut self, flush: PageFlush<Arch>) {
  1319. <T as Flusher<Arch>>::consume(self, flush);
  1320. }
  1321. }
  1322. impl<Arch: MemoryManagementArch> Flusher<Arch> for () {
  1323. fn consume(&mut self, _flush: PageFlush<Arch>) {}
  1324. }
  1325. impl<Arch: MemoryManagementArch> Drop for PageFlushAll<Arch> {
  1326. fn drop(&mut self) {
  1327. unsafe {
  1328. Arch::invalidate_all();
  1329. }
  1330. }
  1331. }
  1332. /// 未在当前CPU上激活的页表的刷新器
  1333. ///
  1334. /// 如果页表没有在当前cpu上激活,那么需要发送ipi到其他核心,尝试在其他核心上刷新页表
  1335. ///
  1336. /// TODO: 这个方式很暴力,也许把它改成在指定的核心上刷新页表会更好。(可以测试一下开销)
  1337. #[derive(Debug)]
  1338. pub struct InactiveFlusher;
  1339. impl InactiveFlusher {
  1340. pub fn new() -> Self {
  1341. return Self {};
  1342. }
  1343. }
  1344. impl Flusher<MMArch> for InactiveFlusher {
  1345. fn consume(&mut self, flush: PageFlush<MMArch>) {
  1346. unsafe {
  1347. flush.ignore();
  1348. }
  1349. }
  1350. }
  1351. impl Drop for InactiveFlusher {
  1352. fn drop(&mut self) {
  1353. // 发送刷新页表的IPI
  1354. send_ipi(IpiKind::FlushTLB, IpiTarget::Other);
  1355. }
  1356. }
  1357. /// # 把一个地址向下对齐到页大小
  1358. pub fn round_down_to_page_size(addr: usize) -> usize {
  1359. addr & !(MMArch::PAGE_SIZE - 1)
  1360. }
  1361. /// # 把一个地址向上对齐到页大小
  1362. pub fn round_up_to_page_size(addr: usize) -> usize {
  1363. round_down_to_page_size(addr + MMArch::PAGE_SIZE - 1)
  1364. }