VirtualMemory.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. /** @file
  2. x64-specifc functionality for Page Table Setup.
  3. Copyright (c) 2006 - 2020, Intel Corporation. All rights reserved.<BR>
  4. SPDX-License-Identifier: BSD-2-Clause-Patent
  5. **/
  6. #include <Uefi/UefiBaseType.h>
  7. #include <Uefi/UefiSpec.h>
  8. #include <Pi/PiBootMode.h>
  9. #include <Pi/PiHob.h>
  10. #include <Library/DebugLib.h>
  11. #include <Library/BaseLib.h>
  12. #include <Library/HobLib.h>
  13. #include <Library/BaseMemoryLib.h>
  14. #include <Library/MemoryAllocationLib.h>
  15. #include <Library/PcdLib.h>
  16. #include <Guid/MemoryTypeInformation.h>
  17. #include <Guid/MemoryAllocationHob.h>
  18. #include <Register/Intel/Cpuid.h>
  19. #include <Library/PlatformInitLib.h>
  20. #include "PageTables.h"
  21. //
  22. // Global variable to keep track current available memory used as page table.
  23. //
  24. PAGE_TABLE_POOL *mPageTablePool = NULL;
  25. UINTN mLevelShift[5] = {
  26. 0,
  27. PAGING_L1_ADDRESS_SHIFT,
  28. PAGING_L2_ADDRESS_SHIFT,
  29. PAGING_L3_ADDRESS_SHIFT,
  30. PAGING_L4_ADDRESS_SHIFT
  31. };
  32. UINT64 mLevelMask[5] = {
  33. 0,
  34. PAGING_4K_ADDRESS_MASK_64,
  35. PAGING_2M_ADDRESS_MASK_64,
  36. PAGING_1G_ADDRESS_MASK_64,
  37. PAGING_1G_ADDRESS_MASK_64
  38. };
  39. UINT64 mLevelSize[5] = {
  40. 0,
  41. SIZE_4KB,
  42. SIZE_2MB,
  43. SIZE_1GB,
  44. SIZE_512GB
  45. };
  46. BOOLEAN
  47. IsSetNxForStack (
  48. VOID
  49. )
  50. {
  51. EFI_HOB_GUID_TYPE *GuidHob;
  52. EFI_HOB_PLATFORM_INFO *PlatformInfo;
  53. GuidHob = GetFirstGuidHob (&gUefiOvmfPkgPlatformInfoGuid);
  54. if (GuidHob == NULL) {
  55. ASSERT (FALSE);
  56. return FALSE;
  57. }
  58. PlatformInfo = (EFI_HOB_PLATFORM_INFO *)GET_GUID_HOB_DATA (GuidHob);
  59. return PlatformInfo->PcdSetNxForStack;
  60. }
  61. /**
  62. Clear legacy memory located at the first 4K-page, if available.
  63. This function traverses the whole HOB list to check if memory from 0 to 4095
  64. exists and has not been allocated, and then clear it if so.
  65. @param HobStart The start of HobList passed to DxeCore.
  66. **/
  67. VOID
  68. ClearFirst4KPage (
  69. IN VOID *HobStart
  70. )
  71. {
  72. EFI_PEI_HOB_POINTERS RscHob;
  73. EFI_PEI_HOB_POINTERS MemHob;
  74. BOOLEAN DoClear;
  75. RscHob.Raw = HobStart;
  76. MemHob.Raw = HobStart;
  77. DoClear = FALSE;
  78. //
  79. // Check if page 0 exists and free
  80. //
  81. while ((RscHob.Raw = GetNextHob (
  82. EFI_HOB_TYPE_RESOURCE_DESCRIPTOR,
  83. RscHob.Raw
  84. )) != NULL)
  85. {
  86. if ((RscHob.ResourceDescriptor->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) &&
  87. (RscHob.ResourceDescriptor->PhysicalStart == 0))
  88. {
  89. DoClear = TRUE;
  90. //
  91. // Make sure memory at 0-4095 has not been allocated.
  92. //
  93. while ((MemHob.Raw = GetNextHob (
  94. EFI_HOB_TYPE_MEMORY_ALLOCATION,
  95. MemHob.Raw
  96. )) != NULL)
  97. {
  98. if (MemHob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress
  99. < EFI_PAGE_SIZE)
  100. {
  101. DoClear = FALSE;
  102. break;
  103. }
  104. MemHob.Raw = GET_NEXT_HOB (MemHob);
  105. }
  106. break;
  107. }
  108. RscHob.Raw = GET_NEXT_HOB (RscHob);
  109. }
  110. if (DoClear) {
  111. DEBUG ((DEBUG_INFO, "Clearing first 4K-page!\r\n"));
  112. SetMem (NULL, EFI_PAGE_SIZE, 0);
  113. }
  114. return;
  115. }
  116. /**
  117. Return configure status of NULL pointer detection feature.
  118. @return TRUE NULL pointer detection feature is enabled
  119. @return FALSE NULL pointer detection feature is disabled
  120. **/
  121. BOOLEAN
  122. IsNullDetectionEnabled (
  123. VOID
  124. )
  125. {
  126. return ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT0) != 0);
  127. }
  128. /**
  129. The function will check if Execute Disable Bit is available.
  130. @retval TRUE Execute Disable Bit is available.
  131. @retval FALSE Execute Disable Bit is not available.
  132. **/
  133. BOOLEAN
  134. IsExecuteDisableBitAvailable (
  135. VOID
  136. )
  137. {
  138. UINT32 RegEax;
  139. UINT32 RegEdx;
  140. BOOLEAN Available;
  141. Available = FALSE;
  142. AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);
  143. if (RegEax >= 0x80000001) {
  144. AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx);
  145. if ((RegEdx & BIT20) != 0) {
  146. //
  147. // Bit 20: Execute Disable Bit available.
  148. //
  149. Available = TRUE;
  150. }
  151. }
  152. return Available;
  153. }
  154. /**
  155. Check if Execute Disable Bit (IA32_EFER.NXE) should be enabled or not.
  156. @retval TRUE IA32_EFER.NXE should be enabled.
  157. @retval FALSE IA32_EFER.NXE should not be enabled.
  158. **/
  159. BOOLEAN
  160. IsEnableNonExecNeeded (
  161. VOID
  162. )
  163. {
  164. if (!IsExecuteDisableBitAvailable ()) {
  165. return FALSE;
  166. }
  167. //
  168. // XD flag (BIT63) in page table entry is only valid if IA32_EFER.NXE is set.
  169. // Features controlled by Following PCDs need this feature to be enabled.
  170. //
  171. return (IsSetNxForStack () ||
  172. FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) != 0 ||
  173. PcdGet32 (PcdImageProtectionPolicy) != 0);
  174. }
  175. /**
  176. Enable Execute Disable Bit.
  177. **/
  178. VOID
  179. EnableExecuteDisableBit (
  180. VOID
  181. )
  182. {
  183. UINT64 MsrRegisters;
  184. MsrRegisters = AsmReadMsr64 (0xC0000080);
  185. MsrRegisters |= BIT11;
  186. AsmWriteMsr64 (0xC0000080, MsrRegisters);
  187. }
  188. /**
  189. The function will check if page table entry should be splitted to smaller
  190. granularity.
  191. @param Address Physical memory address.
  192. @param Size Size of the given physical memory.
  193. @param StackBase Base address of stack.
  194. @param StackSize Size of stack.
  195. @retval TRUE Page table should be split.
  196. @retval FALSE Page table should not be split.
  197. **/
  198. BOOLEAN
  199. ToSplitPageTable (
  200. IN EFI_PHYSICAL_ADDRESS Address,
  201. IN UINTN Size,
  202. IN EFI_PHYSICAL_ADDRESS StackBase,
  203. IN UINTN StackSize
  204. )
  205. {
  206. if (IsNullDetectionEnabled () && (Address == 0)) {
  207. return TRUE;
  208. }
  209. if (FixedPcdGetBool (PcdCpuStackGuard)) {
  210. if ((StackBase >= Address) && (StackBase < (Address + Size))) {
  211. return TRUE;
  212. }
  213. }
  214. if (IsSetNxForStack ()) {
  215. if ((Address < StackBase + StackSize) && ((Address + Size) > StackBase)) {
  216. return TRUE;
  217. }
  218. }
  219. return FALSE;
  220. }
  221. /**
  222. Initialize a buffer pool for page table use only.
  223. To reduce the potential split operation on page table, the pages reserved for
  224. page table should be allocated in the times of PAGE_TABLE_POOL_UNIT_PAGES and
  225. at the boundary of PAGE_TABLE_POOL_ALIGNMENT. So the page pool is always
  226. initialized with number of pages greater than or equal to the given PoolPages.
  227. Once the pages in the pool are used up, this method should be called again to
  228. reserve at least another PAGE_TABLE_POOL_UNIT_PAGES. But usually this won't
  229. happen in practice.
  230. @param PoolPages The least page number of the pool to be created.
  231. @retval TRUE The pool is initialized successfully.
  232. @retval FALSE The memory is out of resource.
  233. **/
  234. BOOLEAN
  235. InitializePageTablePool (
  236. IN UINTN PoolPages
  237. )
  238. {
  239. VOID *Buffer;
  240. DEBUG ((DEBUG_INFO, "InitializePageTablePool PoolPages=%d\n", PoolPages));
  241. //
  242. // Always reserve at least PAGE_TABLE_POOL_UNIT_PAGES, including one page for
  243. // header.
  244. //
  245. PoolPages += 1; // Add one page for header.
  246. PoolPages = ((PoolPages - 1) / PAGE_TABLE_POOL_UNIT_PAGES + 1) *
  247. PAGE_TABLE_POOL_UNIT_PAGES;
  248. Buffer = AllocateAlignedPages (PoolPages, PAGE_TABLE_POOL_ALIGNMENT);
  249. if (Buffer == NULL) {
  250. DEBUG ((DEBUG_ERROR, "ERROR: Out of aligned pages\r\n"));
  251. return FALSE;
  252. }
  253. //
  254. // Link all pools into a list for easier track later.
  255. //
  256. if (mPageTablePool == NULL) {
  257. mPageTablePool = Buffer;
  258. mPageTablePool->NextPool = mPageTablePool;
  259. } else {
  260. ((PAGE_TABLE_POOL *)Buffer)->NextPool = mPageTablePool->NextPool;
  261. mPageTablePool->NextPool = Buffer;
  262. mPageTablePool = Buffer;
  263. }
  264. //
  265. // Reserve one page for pool header.
  266. //
  267. mPageTablePool->FreePages = PoolPages - 1;
  268. mPageTablePool->Offset = EFI_PAGES_TO_SIZE (1);
  269. return TRUE;
  270. }
  271. /**
  272. This API provides a way to allocate memory for page table.
  273. This API can be called more than once to allocate memory for page tables.
  274. Allocates the number of 4KB pages and returns a pointer to the allocated
  275. buffer. The buffer returned is aligned on a 4KB boundary.
  276. If Pages is 0, then NULL is returned.
  277. If there is not enough memory remaining to satisfy the request, then NULL is
  278. returned.
  279. @param Pages The number of 4 KB pages to allocate.
  280. @return A pointer to the allocated buffer or NULL if allocation fails.
  281. **/
  282. VOID *
  283. AllocatePageTableMemory (
  284. IN UINTN Pages
  285. )
  286. {
  287. VOID *Buffer;
  288. if (Pages == 0) {
  289. return NULL;
  290. }
  291. DEBUG ((DEBUG_INFO, "AllocatePageTableMemory. mPageTablePool=%p, Pages=%d\n", mPageTablePool, Pages));
  292. //
  293. // Renew the pool if necessary.
  294. //
  295. if ((mPageTablePool == NULL) ||
  296. (Pages > mPageTablePool->FreePages))
  297. {
  298. if (!InitializePageTablePool (Pages)) {
  299. return NULL;
  300. }
  301. }
  302. Buffer = (UINT8 *)mPageTablePool + mPageTablePool->Offset;
  303. mPageTablePool->Offset += EFI_PAGES_TO_SIZE (Pages);
  304. mPageTablePool->FreePages -= Pages;
  305. DEBUG ((
  306. DEBUG_INFO,
  307. "%a:%a: Buffer=0x%Lx Pages=%ld\n",
  308. gEfiCallerBaseName,
  309. __FUNCTION__,
  310. Buffer,
  311. Pages
  312. ));
  313. return Buffer;
  314. }
  315. /**
  316. Split 2M page to 4K.
  317. @param[in] PhysicalAddress Start physical address the 2M page covered.
  318. @param[in, out] PageEntry2M Pointer to 2M page entry.
  319. @param[in] StackBase Stack base address.
  320. @param[in] StackSize Stack size.
  321. **/
  322. VOID
  323. Split2MPageTo4K (
  324. IN EFI_PHYSICAL_ADDRESS PhysicalAddress,
  325. IN OUT UINT64 *PageEntry2M,
  326. IN EFI_PHYSICAL_ADDRESS StackBase,
  327. IN UINTN StackSize
  328. )
  329. {
  330. EFI_PHYSICAL_ADDRESS PhysicalAddress4K;
  331. UINTN IndexOfPageTableEntries;
  332. PAGE_TABLE_4K_ENTRY *PageTableEntry;
  333. DEBUG ((DEBUG_INFO, "Split2MPageTo4K\n"));
  334. PageTableEntry = AllocatePageTableMemory (1);
  335. if (PageTableEntry == NULL) {
  336. ASSERT (FALSE);
  337. return;
  338. }
  339. //
  340. // Fill in 2M page entry.
  341. //
  342. *PageEntry2M = (UINT64)(UINTN)PageTableEntry | IA32_PG_P | IA32_PG_RW;
  343. PhysicalAddress4K = PhysicalAddress;
  344. for (IndexOfPageTableEntries = 0; IndexOfPageTableEntries < 512; IndexOfPageTableEntries++, PageTableEntry++, PhysicalAddress4K += SIZE_4KB) {
  345. //
  346. // Fill in the Page Table entries
  347. //
  348. PageTableEntry->Uint64 = (UINT64)PhysicalAddress4K;
  349. PageTableEntry->Bits.ReadWrite = 1;
  350. if ((IsNullDetectionEnabled () && (PhysicalAddress4K == 0)) ||
  351. (FixedPcdGetBool (PcdCpuStackGuard) && (PhysicalAddress4K == StackBase)))
  352. {
  353. PageTableEntry->Bits.Present = 0;
  354. } else {
  355. PageTableEntry->Bits.Present = 1;
  356. }
  357. if ( IsSetNxForStack ()
  358. && (PhysicalAddress4K >= StackBase)
  359. && (PhysicalAddress4K < StackBase + StackSize))
  360. {
  361. //
  362. // Set Nx bit for stack.
  363. //
  364. PageTableEntry->Bits.Nx = 1;
  365. }
  366. }
  367. }
  368. /**
  369. Split 1G page to 2M.
  370. @param[in] PhysicalAddress Start physical address the 1G page covered.
  371. @param[in, out] PageEntry1G Pointer to 1G page entry.
  372. @param[in] StackBase Stack base address.
  373. @param[in] StackSize Stack size.
  374. **/
  375. VOID
  376. Split1GPageTo2M (
  377. IN EFI_PHYSICAL_ADDRESS PhysicalAddress,
  378. IN OUT UINT64 *PageEntry1G,
  379. IN EFI_PHYSICAL_ADDRESS StackBase,
  380. IN UINTN StackSize
  381. )
  382. {
  383. EFI_PHYSICAL_ADDRESS PhysicalAddress2M;
  384. UINTN IndexOfPageDirectoryEntries;
  385. PAGE_TABLE_ENTRY *PageDirectoryEntry;
  386. PageDirectoryEntry = AllocatePageTableMemory (1);
  387. if (PageDirectoryEntry == NULL) {
  388. ASSERT (FALSE);
  389. return;
  390. }
  391. //
  392. // Fill in 1G page entry.
  393. //
  394. *PageEntry1G = (UINT64)(UINTN)PageDirectoryEntry | IA32_PG_P | IA32_PG_RW;
  395. PhysicalAddress2M = PhysicalAddress;
  396. for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectoryEntry++, PhysicalAddress2M += SIZE_2MB) {
  397. if (ToSplitPageTable (PhysicalAddress2M, SIZE_2MB, StackBase, StackSize)) {
  398. //
  399. // Need to split this 2M page that covers NULL or stack range.
  400. //
  401. Split2MPageTo4K (PhysicalAddress2M, (UINT64 *)PageDirectoryEntry, StackBase, StackSize);
  402. } else {
  403. //
  404. // Fill in the Page Directory entries
  405. //
  406. PageDirectoryEntry->Uint64 = (UINT64)PhysicalAddress2M;
  407. PageDirectoryEntry->Bits.ReadWrite = 1;
  408. PageDirectoryEntry->Bits.Present = 1;
  409. PageDirectoryEntry->Bits.MustBe1 = 1;
  410. }
  411. }
  412. }
  413. /**
  414. Set one page of page table pool memory to be read-only.
  415. @param[in] PageTableBase Base address of page table (CR3).
  416. @param[in] Address Start address of a page to be set as read-only.
  417. @param[in] Level4Paging Level 4 paging flag.
  418. **/
  419. VOID
  420. SetPageTablePoolReadOnly (
  421. IN UINTN PageTableBase,
  422. IN EFI_PHYSICAL_ADDRESS Address,
  423. IN BOOLEAN Level4Paging
  424. )
  425. {
  426. UINTN Index;
  427. UINTN EntryIndex;
  428. EFI_PHYSICAL_ADDRESS PhysicalAddress;
  429. UINT64 *PageTable;
  430. UINT64 *NewPageTable;
  431. UINT64 PageAttr;
  432. UINTN Level;
  433. UINT64 PoolUnitSize;
  434. if (PageTableBase == 0) {
  435. ASSERT (FALSE);
  436. return;
  437. }
  438. //
  439. // Since the page table is always from page table pool, which is always
  440. // located at the boundary of PcdPageTablePoolAlignment, we just need to
  441. // set the whole pool unit to be read-only.
  442. //
  443. Address = Address & PAGE_TABLE_POOL_ALIGN_MASK;
  444. PageTable = (UINT64 *)(UINTN)PageTableBase;
  445. PoolUnitSize = PAGE_TABLE_POOL_UNIT_SIZE;
  446. for (Level = (Level4Paging) ? 4 : 3; Level > 0; --Level) {
  447. Index = ((UINTN)RShiftU64 (Address, mLevelShift[Level]));
  448. Index &= PAGING_PAE_INDEX_MASK;
  449. PageAttr = PageTable[Index];
  450. if ((PageAttr & IA32_PG_PS) == 0) {
  451. //
  452. // Go to next level of table.
  453. //
  454. PageTable = (UINT64 *)(UINTN)(PageAttr & PAGING_4K_ADDRESS_MASK_64);
  455. continue;
  456. }
  457. if (PoolUnitSize >= mLevelSize[Level]) {
  458. //
  459. // Clear R/W bit if current page granularity is not larger than pool unit
  460. // size.
  461. //
  462. if ((PageAttr & IA32_PG_RW) != 0) {
  463. while (PoolUnitSize > 0) {
  464. //
  465. // PAGE_TABLE_POOL_UNIT_SIZE and PAGE_TABLE_POOL_ALIGNMENT are fit in
  466. // one page (2MB). Then we don't need to update attributes for pages
  467. // crossing page directory. ASSERT below is for that purpose.
  468. //
  469. ASSERT (Index < EFI_PAGE_SIZE/sizeof (UINT64));
  470. PageTable[Index] &= ~(UINT64)IA32_PG_RW;
  471. PoolUnitSize -= mLevelSize[Level];
  472. ++Index;
  473. }
  474. }
  475. break;
  476. } else {
  477. //
  478. // The smaller granularity of page must be needed.
  479. //
  480. ASSERT (Level > 1);
  481. NewPageTable = AllocatePageTableMemory (1);
  482. if (NewPageTable == NULL) {
  483. ASSERT (FALSE);
  484. return;
  485. }
  486. PhysicalAddress = PageAttr & mLevelMask[Level];
  487. for (EntryIndex = 0;
  488. EntryIndex < EFI_PAGE_SIZE/sizeof (UINT64);
  489. ++EntryIndex)
  490. {
  491. NewPageTable[EntryIndex] = PhysicalAddress |
  492. IA32_PG_P | IA32_PG_RW;
  493. if (Level > 2) {
  494. NewPageTable[EntryIndex] |= IA32_PG_PS;
  495. }
  496. PhysicalAddress += mLevelSize[Level - 1];
  497. }
  498. PageTable[Index] = (UINT64)(UINTN)NewPageTable |
  499. IA32_PG_P | IA32_PG_RW;
  500. PageTable = NewPageTable;
  501. }
  502. }
  503. }
  504. /**
  505. Prevent the memory pages used for page table from been overwritten.
  506. @param[in] PageTableBase Base address of page table (CR3).
  507. @param[in] Level4Paging Level 4 paging flag.
  508. **/
  509. VOID
  510. EnablePageTableProtection (
  511. IN UINTN PageTableBase,
  512. IN BOOLEAN Level4Paging
  513. )
  514. {
  515. PAGE_TABLE_POOL *HeadPool;
  516. PAGE_TABLE_POOL *Pool;
  517. UINT64 PoolSize;
  518. EFI_PHYSICAL_ADDRESS Address;
  519. DEBUG ((DEBUG_INFO, "EnablePageTableProtection\n"));
  520. if (mPageTablePool == NULL) {
  521. return;
  522. }
  523. //
  524. // Disable write protection, because we need to mark page table to be write
  525. // protected.
  526. //
  527. AsmWriteCr0 (AsmReadCr0 () & ~CR0_WP);
  528. //
  529. // SetPageTablePoolReadOnly might update mPageTablePool. It's safer to
  530. // remember original one in advance.
  531. //
  532. HeadPool = mPageTablePool;
  533. Pool = HeadPool;
  534. do {
  535. Address = (EFI_PHYSICAL_ADDRESS)(UINTN)Pool;
  536. PoolSize = Pool->Offset + EFI_PAGES_TO_SIZE (Pool->FreePages);
  537. //
  538. // The size of one pool must be multiple of PAGE_TABLE_POOL_UNIT_SIZE, which
  539. // is one of page size of the processor (2MB by default). Let's apply the
  540. // protection to them one by one.
  541. //
  542. while (PoolSize > 0) {
  543. SetPageTablePoolReadOnly (PageTableBase, Address, Level4Paging);
  544. Address += PAGE_TABLE_POOL_UNIT_SIZE;
  545. PoolSize -= PAGE_TABLE_POOL_UNIT_SIZE;
  546. }
  547. Pool = Pool->NextPool;
  548. } while (Pool != HeadPool);
  549. //
  550. // Enable write protection, after page table attribute updated.
  551. //
  552. AsmWriteCr0 (AsmReadCr0 () | CR0_WP);
  553. }
  554. /**
  555. Allocates and fills in the Page Directory and Page Table Entries to
  556. establish a 1:1 Virtual to Physical mapping.
  557. @param[in] StackBase Stack base address.
  558. @param[in] StackSize Stack size.
  559. @return The address of 4 level page map.
  560. **/
  561. UINTN
  562. CreateIdentityMappingPageTables (
  563. IN EFI_PHYSICAL_ADDRESS StackBase,
  564. IN UINTN StackSize
  565. )
  566. {
  567. UINT32 RegEax;
  568. UINT32 RegEdx;
  569. UINT8 PhysicalAddressBits;
  570. EFI_PHYSICAL_ADDRESS PageAddress;
  571. UINTN IndexOfPml5Entries;
  572. UINTN IndexOfPml4Entries;
  573. UINTN IndexOfPdpEntries;
  574. UINTN IndexOfPageDirectoryEntries;
  575. UINT32 NumberOfPml5EntriesNeeded;
  576. UINT32 NumberOfPml4EntriesNeeded;
  577. UINT32 NumberOfPdpEntriesNeeded;
  578. PAGE_MAP_AND_DIRECTORY_POINTER *PageMapLevel5Entry;
  579. PAGE_MAP_AND_DIRECTORY_POINTER *PageMapLevel4Entry;
  580. PAGE_MAP_AND_DIRECTORY_POINTER *PageMap;
  581. PAGE_MAP_AND_DIRECTORY_POINTER *PageDirectoryPointerEntry;
  582. PAGE_TABLE_ENTRY *PageDirectoryEntry;
  583. UINTN TotalPagesNum;
  584. UINTN BigPageAddress;
  585. VOID *Hob;
  586. BOOLEAN Page5LevelSupport;
  587. BOOLEAN Page1GSupport;
  588. PAGE_TABLE_1G_ENTRY *PageDirectory1GEntry;
  589. IA32_CR4 Cr4;
  590. //
  591. // Set PageMapLevel5Entry to suppress incorrect compiler/analyzer warnings
  592. //
  593. PageMapLevel5Entry = NULL;
  594. Page1GSupport = FALSE;
  595. if (FixedPcdGetBool (PcdUse1GPageTable)) {
  596. AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);
  597. if (RegEax >= 0x80000001) {
  598. AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx);
  599. if ((RegEdx & BIT26) != 0) {
  600. Page1GSupport = TRUE;
  601. }
  602. }
  603. }
  604. //
  605. // Get physical address bits supported.
  606. //
  607. Hob = GetFirstHob (EFI_HOB_TYPE_CPU);
  608. if (Hob == NULL) {
  609. ASSERT (FALSE);
  610. return 0;
  611. }
  612. PhysicalAddressBits = ((EFI_HOB_CPU *)Hob)->SizeOfMemorySpace;
  613. //
  614. // CPU will already have LA57 enabled so just check CR4
  615. Cr4.UintN = AsmReadCr4 ();
  616. Page5LevelSupport = (Cr4.Bits.LA57 ? TRUE : FALSE);
  617. DEBUG ((
  618. DEBUG_INFO,
  619. "AddressBits=%u 5LevelPaging=%u 1GPage=%u \n",
  620. PhysicalAddressBits,
  621. Page5LevelSupport,
  622. Page1GSupport
  623. ));
  624. //
  625. // Calculate the table entries needed.
  626. //
  627. NumberOfPml5EntriesNeeded = 1;
  628. if (PhysicalAddressBits > 48) {
  629. NumberOfPml5EntriesNeeded = (UINT32)LShiftU64 (1, PhysicalAddressBits - 48);
  630. PhysicalAddressBits = 48;
  631. }
  632. NumberOfPml4EntriesNeeded = 1;
  633. if (PhysicalAddressBits > 39) {
  634. NumberOfPml4EntriesNeeded = (UINT32)LShiftU64 (1, PhysicalAddressBits - 39);
  635. PhysicalAddressBits = 39;
  636. }
  637. NumberOfPdpEntriesNeeded = 1;
  638. ASSERT (PhysicalAddressBits > 30);
  639. NumberOfPdpEntriesNeeded = (UINT32)LShiftU64 (1, PhysicalAddressBits - 30);
  640. //
  641. // Pre-allocate big pages to avoid later allocations.
  642. //
  643. if (!Page1GSupport) {
  644. TotalPagesNum = ((NumberOfPdpEntriesNeeded + 1) * NumberOfPml4EntriesNeeded + 1) * NumberOfPml5EntriesNeeded + 1;
  645. } else {
  646. TotalPagesNum = (NumberOfPml4EntriesNeeded + 1) * NumberOfPml5EntriesNeeded + 1;
  647. }
  648. //
  649. // Substract the one page occupied by PML5 entries if 5-Level Paging is disabled.
  650. //
  651. if (!Page5LevelSupport) {
  652. TotalPagesNum--;
  653. }
  654. DEBUG ((
  655. DEBUG_INFO,
  656. "Pml5=%u Pml4=%u Pdp=%u TotalPage=%Lu\n",
  657. NumberOfPml5EntriesNeeded,
  658. NumberOfPml4EntriesNeeded,
  659. NumberOfPdpEntriesNeeded,
  660. (UINT64)TotalPagesNum
  661. ));
  662. BigPageAddress = (UINTN)AllocatePageTableMemory (TotalPagesNum);
  663. if (BigPageAddress == 0) {
  664. ASSERT (FALSE);
  665. return 0;
  666. }
  667. DEBUG ((DEBUG_INFO, "BigPageAddress = 0x%llx\n", BigPageAddress));
  668. //
  669. // By architecture only one PageMapLevel4 exists - so lets allocate storage for it.
  670. //
  671. PageMap = (VOID *)BigPageAddress;
  672. if (Page5LevelSupport) {
  673. //
  674. // By architecture only one PageMapLevel5 exists - so lets allocate storage for it.
  675. //
  676. PageMapLevel5Entry = PageMap;
  677. BigPageAddress += SIZE_4KB;
  678. }
  679. PageAddress = 0;
  680. for ( IndexOfPml5Entries = 0
  681. ; IndexOfPml5Entries < NumberOfPml5EntriesNeeded
  682. ; IndexOfPml5Entries++)
  683. {
  684. //
  685. // Each PML5 entry points to a page of PML4 entires.
  686. // So lets allocate space for them and fill them in the IndexOfPml4Entries loop.
  687. // When 5-Level Paging is disabled, below allocation happens only once.
  688. //
  689. PageMapLevel4Entry = (VOID *)BigPageAddress;
  690. BigPageAddress += SIZE_4KB;
  691. if (Page5LevelSupport) {
  692. //
  693. // Make a PML5 Entry
  694. //
  695. PageMapLevel5Entry->Uint64 = (UINT64)(UINTN)PageMapLevel4Entry;
  696. PageMapLevel5Entry->Bits.ReadWrite = 1;
  697. PageMapLevel5Entry->Bits.Present = 1;
  698. PageMapLevel5Entry++;
  699. }
  700. for ( IndexOfPml4Entries = 0
  701. ; IndexOfPml4Entries < (NumberOfPml5EntriesNeeded == 1 ? NumberOfPml4EntriesNeeded : 512)
  702. ; IndexOfPml4Entries++, PageMapLevel4Entry++)
  703. {
  704. //
  705. // Each PML4 entry points to a page of Page Directory Pointer entires.
  706. // So lets allocate space for them and fill them in the IndexOfPdpEntries loop.
  707. //
  708. PageDirectoryPointerEntry = (VOID *)BigPageAddress;
  709. BigPageAddress += SIZE_4KB;
  710. //
  711. // Make a PML4 Entry
  712. //
  713. PageMapLevel4Entry->Uint64 = (UINT64)(UINTN)PageDirectoryPointerEntry;
  714. PageMapLevel4Entry->Bits.ReadWrite = 1;
  715. PageMapLevel4Entry->Bits.Present = 1;
  716. if (Page1GSupport) {
  717. PageDirectory1GEntry = (VOID *)PageDirectoryPointerEntry;
  718. for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectory1GEntry++, PageAddress += SIZE_1GB) {
  719. if (ToSplitPageTable (PageAddress, SIZE_1GB, StackBase, StackSize)) {
  720. Split1GPageTo2M (
  721. PageAddress,
  722. (UINT64 *)PageDirectory1GEntry,
  723. StackBase,
  724. StackSize
  725. );
  726. } else {
  727. //
  728. // Fill in the Page Directory entries
  729. //
  730. PageDirectory1GEntry->Uint64 = (UINT64)PageAddress;
  731. PageDirectory1GEntry->Bits.ReadWrite = 1;
  732. PageDirectory1GEntry->Bits.Present = 1;
  733. PageDirectory1GEntry->Bits.MustBe1 = 1;
  734. }
  735. }
  736. } else {
  737. for ( IndexOfPdpEntries = 0
  738. ; IndexOfPdpEntries < (NumberOfPml4EntriesNeeded == 1 ? NumberOfPdpEntriesNeeded : 512)
  739. ; IndexOfPdpEntries++, PageDirectoryPointerEntry++)
  740. {
  741. //
  742. // Each Directory Pointer entries points to a page of Page Directory entires.
  743. // So allocate space for them and fill them in the IndexOfPageDirectoryEntries loop.
  744. //
  745. PageDirectoryEntry = (VOID *)BigPageAddress;
  746. BigPageAddress += SIZE_4KB;
  747. //
  748. // Fill in a Page Directory Pointer Entries
  749. //
  750. PageDirectoryPointerEntry->Uint64 = (UINT64)(UINTN)PageDirectoryEntry;
  751. PageDirectoryPointerEntry->Bits.ReadWrite = 1;
  752. PageDirectoryPointerEntry->Bits.Present = 1;
  753. for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectoryEntry++, PageAddress += SIZE_2MB) {
  754. if (ToSplitPageTable (PageAddress, SIZE_2MB, StackBase, StackSize)) {
  755. //
  756. // Need to split this 2M page that covers NULL or stack range.
  757. //
  758. Split2MPageTo4K (PageAddress, (UINT64 *)PageDirectoryEntry, StackBase, StackSize);
  759. } else {
  760. //
  761. // Fill in the Page Directory entries
  762. //
  763. PageDirectoryEntry->Uint64 = (UINT64)PageAddress;
  764. PageDirectoryEntry->Bits.ReadWrite = 1;
  765. PageDirectoryEntry->Bits.Present = 1;
  766. PageDirectoryEntry->Bits.MustBe1 = 1;
  767. }
  768. }
  769. }
  770. //
  771. // Fill with null entry for unused PDPTE
  772. //
  773. ZeroMem (PageDirectoryPointerEntry, (512 - IndexOfPdpEntries) * sizeof (PAGE_MAP_AND_DIRECTORY_POINTER));
  774. }
  775. }
  776. //
  777. // For the PML4 entries we are not using fill in a null entry.
  778. //
  779. ZeroMem (PageMapLevel4Entry, (512 - IndexOfPml4Entries) * sizeof (PAGE_MAP_AND_DIRECTORY_POINTER));
  780. }
  781. if (Page5LevelSupport) {
  782. //
  783. // For the PML5 entries we are not using fill in a null entry.
  784. //
  785. ZeroMem (PageMapLevel5Entry, (512 - IndexOfPml5Entries) * sizeof (PAGE_MAP_AND_DIRECTORY_POINTER));
  786. }
  787. //
  788. // Protect the page table by marking the memory used for page table to be
  789. // read-only.
  790. //
  791. EnablePageTableProtection ((UINTN)PageMap, TRUE);
  792. return (UINTN)PageMap;
  793. }