]> git.proxmox.com Git - mirror_edk2.git/blame - UefiCpuPkg/CpuDxe/CpuPageTable.c
UefiCpuPkg/CpuDxe: Remove unnecessary macros
[mirror_edk2.git] / UefiCpuPkg / CpuDxe / CpuPageTable.c
CommitLineData
22292ed3
JY
1/** @file\r
2 Page table management support.\r
3\r
29355b4e 4 Copyright (c) 2017 - 2019, Intel Corporation. All rights reserved.<BR>\r
627dcba3
LD
5 Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>\r
6\r
0acd8697 7 SPDX-License-Identifier: BSD-2-Clause-Patent\r
22292ed3
JY
8\r
9**/\r
10\r
11#include <Base.h>\r
12#include <Uefi.h>\r
dcc02621
JW
13#include <Library/PeCoffGetEntryPointLib.h>\r
14#include <Library/SerialPortLib.h>\r
15#include <Library/SynchronizationLib.h>\r
16#include <Library/PrintLib.h>\r
2a1408d1 17#include <Protocol/SmmBase2.h>\r
d106cf71
JW
18#include <Register/Cpuid.h>\r
19#include <Register/Msr.h>\r
c1cab54c
JW
20\r
21#include "CpuDxe.h"\r
22292ed3
JY
22#include "CpuPageTable.h"\r
23\r
24///\r
25/// Page Table Entry\r
26///\r
27#define IA32_PG_P BIT0\r
28#define IA32_PG_RW BIT1\r
29#define IA32_PG_U BIT2\r
30#define IA32_PG_WT BIT3\r
31#define IA32_PG_CD BIT4\r
32#define IA32_PG_A BIT5\r
33#define IA32_PG_D BIT6\r
34#define IA32_PG_PS BIT7\r
35#define IA32_PG_PAT_2M BIT12\r
36#define IA32_PG_PAT_4K IA32_PG_PS\r
37#define IA32_PG_PMNT BIT62\r
38#define IA32_PG_NX BIT63\r
39\r
40#define PAGE_ATTRIBUTE_BITS (IA32_PG_D | IA32_PG_A | IA32_PG_U | IA32_PG_RW | IA32_PG_P)\r
41//\r
42// Bits 1, 2, 5, 6 are reserved in the IA32 PAE PDPTE\r
43// X64 PAE PDPTE does not have such restriction\r
44//\r
45#define IA32_PAE_PDPTE_ATTRIBUTE_BITS (IA32_PG_P)\r
46\r
47#define PAGE_PROGATE_BITS (IA32_PG_NX | PAGE_ATTRIBUTE_BITS)\r
48\r
49#define PAGING_4K_MASK 0xFFF\r
50#define PAGING_2M_MASK 0x1FFFFF\r
51#define PAGING_1G_MASK 0x3FFFFFFF\r
52\r
53#define PAGING_PAE_INDEX_MASK 0x1FF\r
54\r
55#define PAGING_4K_ADDRESS_MASK_64 0x000FFFFFFFFFF000ull\r
56#define PAGING_2M_ADDRESS_MASK_64 0x000FFFFFFFE00000ull\r
57#define PAGING_1G_ADDRESS_MASK_64 0x000FFFFFC0000000ull\r
58\r
dcc02621
JW
59#define MAX_PF_ENTRY_COUNT 10\r
60#define MAX_DEBUG_MESSAGE_LENGTH 0x100\r
61#define IA32_PF_EC_ID BIT4\r
62\r
22292ed3
JY
63typedef enum {\r
64 PageNone,\r
65 Page4K,\r
66 Page2M,\r
67 Page1G,\r
68} PAGE_ATTRIBUTE;\r
69\r
70typedef struct {\r
71 PAGE_ATTRIBUTE Attribute;\r
72 UINT64 Length;\r
73 UINT64 AddressMask;\r
74} PAGE_ATTRIBUTE_TABLE;\r
75\r
76typedef enum {\r
77 PageActionAssign,\r
78 PageActionSet,\r
79 PageActionClear,\r
80} PAGE_ACTION;\r
81\r
82PAGE_ATTRIBUTE_TABLE mPageAttributeTable[] = {\r
83 {Page4K, SIZE_4KB, PAGING_4K_ADDRESS_MASK_64},\r
84 {Page2M, SIZE_2MB, PAGING_2M_ADDRESS_MASK_64},\r
85 {Page1G, SIZE_1GB, PAGING_1G_ADDRESS_MASK_64},\r
86};\r
87\r
2a1408d1 88PAGE_TABLE_POOL *mPageTablePool = NULL;\r
54efcfea 89BOOLEAN mPageTablePoolLock = FALSE;\r
2a1408d1
JW
90PAGE_TABLE_LIB_PAGING_CONTEXT mPagingContext;\r
91EFI_SMM_BASE2_PROTOCOL *mSmmBase2 = NULL;\r
92\r
dcc02621
JW
93//\r
94// Record the page fault exception count for one instruction execution.\r
95//\r
96UINTN *mPFEntryCount;\r
97UINT64 *(*mLastPFEntryPointer)[MAX_PF_ENTRY_COUNT];\r
98\r
2a1408d1
JW
99/**\r
100 Check if current execution environment is in SMM mode or not, via\r
101 EFI_SMM_BASE2_PROTOCOL.\r
102\r
103 This is necessary because of the fact that MdePkg\Library\SmmMemoryAllocationLib\r
104 supports to free memory outside SMRAM. The library will call gBS->FreePool() or\r
105 gBS->FreePages() and then SetMemorySpaceAttributes interface in turn to change\r
106 memory paging attributes during free operation, if some memory related features\r
107 are enabled (like Heap Guard).\r
108\r
109 This means that SetMemorySpaceAttributes() has chance to run in SMM mode. This\r
110 will cause incorrect result because SMM mode always loads its own page tables,\r
111 which are usually different from DXE. This function can be used to detect such\r
112 situation and help to avoid further misoperations.\r
113\r
114 @retval TRUE In SMM mode.\r
115 @retval FALSE Not in SMM mode.\r
116**/\r
117BOOLEAN\r
118IsInSmm (\r
119 VOID\r
120 )\r
121{\r
122 BOOLEAN InSmm;\r
123\r
124 InSmm = FALSE;\r
125 if (mSmmBase2 == NULL) {\r
126 gBS->LocateProtocol (&gEfiSmmBase2ProtocolGuid, NULL, (VOID **)&mSmmBase2);\r
127 }\r
128\r
129 if (mSmmBase2 != NULL) {\r
130 mSmmBase2->InSmm (mSmmBase2, &InSmm);\r
131 }\r
132\r
b72f4873
JW
133 //\r
134 // mSmmBase2->InSmm() can only detect if the caller is running in SMRAM\r
135 // or from SMM driver. It cannot tell if the caller is running in SMM mode.\r
136 // Check page table base address to guarantee that because SMM mode willl\r
137 // load its own page table.\r
138 //\r
139 return (InSmm &&\r
140 mPagingContext.ContextData.X64.PageTableBase != (UINT64)AsmReadCr3());\r
2a1408d1 141}\r
147fd35c 142\r
22292ed3
JY
143/**\r
144 Return current paging context.\r
145\r
146 @param[in,out] PagingContext The paging context.\r
147**/\r
148VOID\r
149GetCurrentPagingContext (\r
150 IN OUT PAGE_TABLE_LIB_PAGING_CONTEXT *PagingContext\r
151 )\r
152{\r
d106cf71
JW
153 UINT32 RegEax;\r
154 CPUID_EXTENDED_CPU_SIG_EDX RegEdx;\r
155 MSR_IA32_EFER_REGISTER MsrEfer;\r
29355b4e
RN
156 IA32_CR4 Cr4;\r
157 IA32_CR0 Cr0;\r
22292ed3 158\r
2a1408d1
JW
159 //\r
160 // Don't retrieve current paging context from processor if in SMM mode.\r
161 //\r
162 if (!IsInSmm ()) {\r
163 ZeroMem (&mPagingContext, sizeof(mPagingContext));\r
164 if (sizeof(UINTN) == sizeof(UINT64)) {\r
165 mPagingContext.MachineType = IMAGE_FILE_MACHINE_X64;\r
166 } else {\r
167 mPagingContext.MachineType = IMAGE_FILE_MACHINE_I386;\r
168 }\r
29355b4e
RN
169\r
170 Cr0.UintN = AsmReadCr0 ();\r
171 Cr4.UintN = AsmReadCr4 ();\r
172\r
173 if (Cr0.Bits.PG != 0) {\r
2a1408d1
JW
174 mPagingContext.ContextData.X64.PageTableBase = (AsmReadCr3 () & PAGING_4K_ADDRESS_MASK_64);\r
175 } else {\r
176 mPagingContext.ContextData.X64.PageTableBase = 0;\r
177 }\r
29355b4e
RN
178 if (Cr0.Bits.WP != 0) {\r
179 mPagingContext.ContextData.Ia32.Attributes |= PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_WP_ENABLE;\r
180 }\r
181 if (Cr4.Bits.PSE != 0) {\r
2a1408d1
JW
182 mPagingContext.ContextData.Ia32.Attributes |= PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PSE;\r
183 }\r
29355b4e 184 if (Cr4.Bits.PAE != 0) {\r
2a1408d1
JW
185 mPagingContext.ContextData.Ia32.Attributes |= PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAE;\r
186 }\r
22292ed3 187\r
d106cf71
JW
188 AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL);\r
189 if (RegEax >= CPUID_EXTENDED_CPU_SIG) {\r
190 AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &RegEdx.Uint32);\r
191\r
192 if (RegEdx.Bits.NX != 0) {\r
2a1408d1 193 // XD supported\r
d106cf71
JW
194 MsrEfer.Uint64 = AsmReadMsr64(MSR_CORE_IA32_EFER);\r
195 if (MsrEfer.Bits.NXE != 0) {\r
2a1408d1
JW
196 // XD activated\r
197 mPagingContext.ContextData.Ia32.Attributes |= PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_XD_ACTIVATED;\r
198 }\r
199 }\r
d106cf71
JW
200\r
201 if (RegEdx.Bits.Page1GB != 0) {\r
2a1408d1 202 mPagingContext.ContextData.Ia32.Attributes |= PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAGE_1G_SUPPORT;\r
22292ed3 203 }\r
22292ed3
JY
204 }\r
205 }\r
2a1408d1
JW
206\r
207 //\r
208 // This can avoid getting SMM paging context if in SMM mode. We cannot assume\r
209 // SMM mode shares the same paging context as DXE.\r
210 //\r
211 CopyMem (PagingContext, &mPagingContext, sizeof (mPagingContext));\r
22292ed3
JY
212}\r
213\r
214/**\r
215 Return length according to page attributes.\r
216\r
217 @param[in] PageAttributes The page attribute of the page entry.\r
218\r
219 @return The length of page entry.\r
220**/\r
221UINTN\r
222PageAttributeToLength (\r
223 IN PAGE_ATTRIBUTE PageAttribute\r
224 )\r
225{\r
226 UINTN Index;\r
227 for (Index = 0; Index < sizeof(mPageAttributeTable)/sizeof(mPageAttributeTable[0]); Index++) {\r
228 if (PageAttribute == mPageAttributeTable[Index].Attribute) {\r
229 return (UINTN)mPageAttributeTable[Index].Length;\r
230 }\r
231 }\r
232 return 0;\r
233}\r
234\r
235/**\r
236 Return address mask according to page attributes.\r
237\r
238 @param[in] PageAttributes The page attribute of the page entry.\r
239\r
240 @return The address mask of page entry.\r
241**/\r
242UINTN\r
243PageAttributeToMask (\r
244 IN PAGE_ATTRIBUTE PageAttribute\r
245 )\r
246{\r
247 UINTN Index;\r
248 for (Index = 0; Index < sizeof(mPageAttributeTable)/sizeof(mPageAttributeTable[0]); Index++) {\r
249 if (PageAttribute == mPageAttributeTable[Index].Attribute) {\r
250 return (UINTN)mPageAttributeTable[Index].AddressMask;\r
251 }\r
252 }\r
253 return 0;\r
254}\r
255\r
256/**\r
257 Return page table entry to match the address.\r
258\r
259 @param[in] PagingContext The paging context.\r
260 @param[in] Address The address to be checked.\r
261 @param[out] PageAttributes The page attribute of the page entry.\r
262\r
263 @return The page entry.\r
264**/\r
265VOID *\r
266GetPageTableEntry (\r
267 IN PAGE_TABLE_LIB_PAGING_CONTEXT *PagingContext,\r
268 IN PHYSICAL_ADDRESS Address,\r
269 OUT PAGE_ATTRIBUTE *PageAttribute\r
270 )\r
271{\r
272 UINTN Index1;\r
273 UINTN Index2;\r
274 UINTN Index3;\r
275 UINTN Index4;\r
276 UINT64 *L1PageTable;\r
277 UINT64 *L2PageTable;\r
278 UINT64 *L3PageTable;\r
279 UINT64 *L4PageTable;\r
627dcba3 280 UINT64 AddressEncMask;\r
22292ed3
JY
281\r
282 ASSERT (PagingContext != NULL);\r
283\r
284 Index4 = ((UINTN)RShiftU64 (Address, 39)) & PAGING_PAE_INDEX_MASK;\r
285 Index3 = ((UINTN)Address >> 30) & PAGING_PAE_INDEX_MASK;\r
286 Index2 = ((UINTN)Address >> 21) & PAGING_PAE_INDEX_MASK;\r
287 Index1 = ((UINTN)Address >> 12) & PAGING_PAE_INDEX_MASK;\r
288\r
627dcba3
LD
289 // Make sure AddressEncMask is contained to smallest supported address field.\r
290 //\r
291 AddressEncMask = PcdGet64 (PcdPteMemoryEncryptionAddressOrMask) & PAGING_1G_ADDRESS_MASK_64;\r
292\r
22292ed3
JY
293 if (PagingContext->MachineType == IMAGE_FILE_MACHINE_X64) {\r
294 L4PageTable = (UINT64 *)(UINTN)PagingContext->ContextData.X64.PageTableBase;\r
295 if (L4PageTable[Index4] == 0) {\r
296 *PageAttribute = PageNone;\r
297 return NULL;\r
298 }\r
299\r
627dcba3 300 L3PageTable = (UINT64 *)(UINTN)(L4PageTable[Index4] & ~AddressEncMask & PAGING_4K_ADDRESS_MASK_64);\r
22292ed3
JY
301 } else {\r
302 ASSERT((PagingContext->ContextData.Ia32.Attributes & PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAE) != 0);\r
303 L3PageTable = (UINT64 *)(UINTN)PagingContext->ContextData.Ia32.PageTableBase;\r
304 }\r
305 if (L3PageTable[Index3] == 0) {\r
306 *PageAttribute = PageNone;\r
307 return NULL;\r
308 }\r
309 if ((L3PageTable[Index3] & IA32_PG_PS) != 0) {\r
310 // 1G\r
311 *PageAttribute = Page1G;\r
312 return &L3PageTable[Index3];\r
313 }\r
314\r
627dcba3 315 L2PageTable = (UINT64 *)(UINTN)(L3PageTable[Index3] & ~AddressEncMask & PAGING_4K_ADDRESS_MASK_64);\r
22292ed3
JY
316 if (L2PageTable[Index2] == 0) {\r
317 *PageAttribute = PageNone;\r
318 return NULL;\r
319 }\r
320 if ((L2PageTable[Index2] & IA32_PG_PS) != 0) {\r
321 // 2M\r
322 *PageAttribute = Page2M;\r
323 return &L2PageTable[Index2];\r
324 }\r
325\r
326 // 4k\r
627dcba3 327 L1PageTable = (UINT64 *)(UINTN)(L2PageTable[Index2] & ~AddressEncMask & PAGING_4K_ADDRESS_MASK_64);\r
22292ed3
JY
328 if ((L1PageTable[Index1] == 0) && (Address != 0)) {\r
329 *PageAttribute = PageNone;\r
330 return NULL;\r
331 }\r
332 *PageAttribute = Page4K;\r
333 return &L1PageTable[Index1];\r
334}\r
335\r
336/**\r
337 Return memory attributes of page entry.\r
338\r
339 @param[in] PageEntry The page entry.\r
340\r
341 @return Memory attributes of page entry.\r
342**/\r
343UINT64\r
344GetAttributesFromPageEntry (\r
345 IN UINT64 *PageEntry\r
346 )\r
347{\r
348 UINT64 Attributes;\r
349 Attributes = 0;\r
350 if ((*PageEntry & IA32_PG_P) == 0) {\r
351 Attributes |= EFI_MEMORY_RP;\r
352 }\r
353 if ((*PageEntry & IA32_PG_RW) == 0) {\r
354 Attributes |= EFI_MEMORY_RO;\r
355 }\r
356 if ((*PageEntry & IA32_PG_NX) != 0) {\r
357 Attributes |= EFI_MEMORY_XP;\r
358 }\r
359 return Attributes;\r
360}\r
361\r
362/**\r
363 Modify memory attributes of page entry.\r
364\r
365 @param[in] PagingContext The paging context.\r
366 @param[in] PageEntry The page entry.\r
367 @param[in] Attributes The bit mask of attributes to modify for the memory region.\r
368 @param[in] PageAction The page action.\r
369 @param[out] IsModified TRUE means page table modified. FALSE means page table not modified.\r
370**/\r
371VOID\r
372ConvertPageEntryAttribute (\r
373 IN PAGE_TABLE_LIB_PAGING_CONTEXT *PagingContext,\r
374 IN UINT64 *PageEntry,\r
375 IN UINT64 Attributes,\r
376 IN PAGE_ACTION PageAction,\r
377 OUT BOOLEAN *IsModified\r
378 )\r
379{\r
380 UINT64 CurrentPageEntry;\r
381 UINT64 NewPageEntry;\r
382\r
383 CurrentPageEntry = *PageEntry;\r
384 NewPageEntry = CurrentPageEntry;\r
385 if ((Attributes & EFI_MEMORY_RP) != 0) {\r
386 switch (PageAction) {\r
387 case PageActionAssign:\r
388 case PageActionSet:\r
389 NewPageEntry &= ~(UINT64)IA32_PG_P;\r
390 break;\r
391 case PageActionClear:\r
392 NewPageEntry |= IA32_PG_P;\r
393 break;\r
394 }\r
395 } else {\r
396 switch (PageAction) {\r
397 case PageActionAssign:\r
398 NewPageEntry |= IA32_PG_P;\r
399 break;\r
400 case PageActionSet:\r
401 case PageActionClear:\r
402 break;\r
403 }\r
404 }\r
405 if ((Attributes & EFI_MEMORY_RO) != 0) {\r
406 switch (PageAction) {\r
407 case PageActionAssign:\r
408 case PageActionSet:\r
409 NewPageEntry &= ~(UINT64)IA32_PG_RW;\r
410 break;\r
411 case PageActionClear:\r
412 NewPageEntry |= IA32_PG_RW;\r
413 break;\r
414 }\r
415 } else {\r
416 switch (PageAction) {\r
417 case PageActionAssign:\r
418 NewPageEntry |= IA32_PG_RW;\r
419 break;\r
420 case PageActionSet:\r
421 case PageActionClear:\r
422 break;\r
423 }\r
424 }\r
425 if ((PagingContext->ContextData.Ia32.Attributes & PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_XD_ACTIVATED) != 0) {\r
426 if ((Attributes & EFI_MEMORY_XP) != 0) {\r
427 switch (PageAction) {\r
428 case PageActionAssign:\r
429 case PageActionSet:\r
430 NewPageEntry |= IA32_PG_NX;\r
431 break;\r
432 case PageActionClear:\r
433 NewPageEntry &= ~IA32_PG_NX;\r
434 break;\r
435 }\r
436 } else {\r
437 switch (PageAction) {\r
438 case PageActionAssign:\r
439 NewPageEntry &= ~IA32_PG_NX;\r
440 break;\r
441 case PageActionSet:\r
442 case PageActionClear:\r
443 break;\r
444 }\r
445 }\r
446 }\r
447 *PageEntry = NewPageEntry;\r
448 if (CurrentPageEntry != NewPageEntry) {\r
449 *IsModified = TRUE;\r
827330cc
JW
450 DEBUG ((DEBUG_VERBOSE, "ConvertPageEntryAttribute 0x%lx", CurrentPageEntry));\r
451 DEBUG ((DEBUG_VERBOSE, "->0x%lx\n", NewPageEntry));\r
22292ed3
JY
452 } else {\r
453 *IsModified = FALSE;\r
454 }\r
455}\r
456\r
457/**\r
458 This function returns if there is need to split page entry.\r
459\r
460 @param[in] BaseAddress The base address to be checked.\r
461 @param[in] Length The length to be checked.\r
462 @param[in] PageEntry The page entry to be checked.\r
463 @param[in] PageAttribute The page attribute of the page entry.\r
464\r
465 @retval SplitAttributes on if there is need to split page entry.\r
466**/\r
467PAGE_ATTRIBUTE\r
468NeedSplitPage (\r
469 IN PHYSICAL_ADDRESS BaseAddress,\r
470 IN UINT64 Length,\r
471 IN UINT64 *PageEntry,\r
472 IN PAGE_ATTRIBUTE PageAttribute\r
473 )\r
474{\r
475 UINT64 PageEntryLength;\r
476\r
477 PageEntryLength = PageAttributeToLength (PageAttribute);\r
478\r
479 if (((BaseAddress & (PageEntryLength - 1)) == 0) && (Length >= PageEntryLength)) {\r
480 return PageNone;\r
481 }\r
482\r
483 if (((BaseAddress & PAGING_2M_MASK) != 0) || (Length < SIZE_2MB)) {\r
484 return Page4K;\r
485 }\r
486\r
487 return Page2M;\r
488}\r
489\r
490/**\r
491 This function splits one page entry to small page entries.\r
492\r
493 @param[in] PageEntry The page entry to be splitted.\r
494 @param[in] PageAttribute The page attribute of the page entry.\r
495 @param[in] SplitAttribute How to split the page entry.\r
496 @param[in] AllocatePagesFunc If page split is needed, this function is used to allocate more pages.\r
497\r
498 @retval RETURN_SUCCESS The page entry is splitted.\r
499 @retval RETURN_UNSUPPORTED The page entry does not support to be splitted.\r
500 @retval RETURN_OUT_OF_RESOURCES No resource to split page entry.\r
501**/\r
502RETURN_STATUS\r
503SplitPage (\r
504 IN UINT64 *PageEntry,\r
505 IN PAGE_ATTRIBUTE PageAttribute,\r
506 IN PAGE_ATTRIBUTE SplitAttribute,\r
507 IN PAGE_TABLE_LIB_ALLOCATE_PAGES AllocatePagesFunc\r
508 )\r
509{\r
510 UINT64 BaseAddress;\r
511 UINT64 *NewPageEntry;\r
512 UINTN Index;\r
627dcba3 513 UINT64 AddressEncMask;\r
22292ed3
JY
514\r
515 ASSERT (PageAttribute == Page2M || PageAttribute == Page1G);\r
516\r
517 ASSERT (AllocatePagesFunc != NULL);\r
518\r
627dcba3
LD
519 // Make sure AddressEncMask is contained to smallest supported address field.\r
520 //\r
521 AddressEncMask = PcdGet64 (PcdPteMemoryEncryptionAddressOrMask) & PAGING_1G_ADDRESS_MASK_64;\r
522\r
22292ed3
JY
523 if (PageAttribute == Page2M) {\r
524 //\r
525 // Split 2M to 4K\r
526 //\r
527 ASSERT (SplitAttribute == Page4K);\r
528 if (SplitAttribute == Page4K) {\r
529 NewPageEntry = AllocatePagesFunc (1);\r
7c7c8190 530 DEBUG ((DEBUG_VERBOSE, "Split - 0x%x\n", NewPageEntry));\r
22292ed3
JY
531 if (NewPageEntry == NULL) {\r
532 return RETURN_OUT_OF_RESOURCES;\r
533 }\r
627dcba3 534 BaseAddress = *PageEntry & ~AddressEncMask & PAGING_2M_ADDRESS_MASK_64;\r
22292ed3 535 for (Index = 0; Index < SIZE_4KB / sizeof(UINT64); Index++) {\r
627dcba3 536 NewPageEntry[Index] = (BaseAddress + SIZE_4KB * Index) | AddressEncMask | ((*PageEntry) & PAGE_PROGATE_BITS);\r
22292ed3 537 }\r
fbe2c4b9 538 (*PageEntry) = (UINT64)(UINTN)NewPageEntry | AddressEncMask | ((*PageEntry) & PAGE_ATTRIBUTE_BITS);\r
22292ed3
JY
539 return RETURN_SUCCESS;\r
540 } else {\r
541 return RETURN_UNSUPPORTED;\r
542 }\r
543 } else if (PageAttribute == Page1G) {\r
544 //\r
545 // Split 1G to 2M\r
546 // No need support 1G->4K directly, we should use 1G->2M, then 2M->4K to get more compact page table.\r
547 //\r
548 ASSERT (SplitAttribute == Page2M || SplitAttribute == Page4K);\r
549 if ((SplitAttribute == Page2M || SplitAttribute == Page4K)) {\r
550 NewPageEntry = AllocatePagesFunc (1);\r
7c7c8190 551 DEBUG ((DEBUG_VERBOSE, "Split - 0x%x\n", NewPageEntry));\r
22292ed3
JY
552 if (NewPageEntry == NULL) {\r
553 return RETURN_OUT_OF_RESOURCES;\r
554 }\r
627dcba3 555 BaseAddress = *PageEntry & ~AddressEncMask & PAGING_1G_ADDRESS_MASK_64;\r
22292ed3 556 for (Index = 0; Index < SIZE_4KB / sizeof(UINT64); Index++) {\r
627dcba3 557 NewPageEntry[Index] = (BaseAddress + SIZE_2MB * Index) | AddressEncMask | IA32_PG_PS | ((*PageEntry) & PAGE_PROGATE_BITS);\r
22292ed3 558 }\r
fbe2c4b9 559 (*PageEntry) = (UINT64)(UINTN)NewPageEntry | AddressEncMask | ((*PageEntry) & PAGE_ATTRIBUTE_BITS);\r
22292ed3
JY
560 return RETURN_SUCCESS;\r
561 } else {\r
562 return RETURN_UNSUPPORTED;\r
563 }\r
564 } else {\r
565 return RETURN_UNSUPPORTED;\r
566 }\r
567}\r
568\r
147fd35c
JW
569/**\r
570 Check the WP status in CR0 register. This bit is used to lock or unlock write\r
571 access to pages marked as read-only.\r
572\r
573 @retval TRUE Write protection is enabled.\r
574 @retval FALSE Write protection is disabled.\r
575**/\r
576BOOLEAN\r
577IsReadOnlyPageWriteProtected (\r
578 VOID\r
579 )\r
580{\r
29355b4e 581 IA32_CR0 Cr0;\r
2a1408d1
JW
582 //\r
583 // To avoid unforseen consequences, don't touch paging settings in SMM mode\r
584 // in this driver.\r
585 //\r
586 if (!IsInSmm ()) {\r
29355b4e
RN
587 Cr0.UintN = AsmReadCr0 ();\r
588 return (BOOLEAN) (Cr0.Bits.WP != 0);\r
2a1408d1
JW
589 }\r
590 return FALSE;\r
147fd35c
JW
591}\r
592\r
147fd35c
JW
593/**\r
594 Disable Write Protect on pages marked as read-only.\r
595**/\r
596VOID\r
597DisableReadOnlyPageWriteProtect (\r
598 VOID\r
599 )\r
600{\r
29355b4e 601 IA32_CR0 Cr0;\r
2a1408d1
JW
602 //\r
603 // To avoid unforseen consequences, don't touch paging settings in SMM mode\r
604 // in this driver.\r
605 //\r
606 if (!IsInSmm ()) {\r
29355b4e
RN
607 Cr0.UintN = AsmReadCr0 ();\r
608 Cr0.Bits.WP = 0;\r
609 AsmWriteCr0 (Cr0.UintN);\r
2a1408d1 610 }\r
147fd35c
JW
611}\r
612\r
613/**\r
614 Enable Write Protect on pages marked as read-only.\r
615**/\r
616VOID\r
617EnableReadOnlyPageWriteProtect (\r
618 VOID\r
619 )\r
620{\r
29355b4e 621 IA32_CR0 Cr0;\r
2a1408d1
JW
622 //\r
623 // To avoid unforseen consequences, don't touch paging settings in SMM mode\r
624 // in this driver.\r
625 //\r
626 if (!IsInSmm ()) {\r
29355b4e
RN
627 Cr0.UintN = AsmReadCr0 ();\r
628 Cr0.Bits.WP = 1;\r
629 AsmWriteCr0 (Cr0.UintN);\r
2a1408d1 630 }\r
147fd35c
JW
631}\r
632\r
22292ed3
JY
633/**\r
634 This function modifies the page attributes for the memory region specified by BaseAddress and\r
635 Length from their current attributes to the attributes specified by Attributes.\r
636\r
637 Caller should make sure BaseAddress and Length is at page boundary.\r
638\r
639 @param[in] PagingContext The paging context. NULL means get page table from current CPU context.\r
640 @param[in] BaseAddress The physical address that is the start address of a memory region.\r
641 @param[in] Length The size in bytes of the memory region.\r
642 @param[in] Attributes The bit mask of attributes to modify for the memory region.\r
643 @param[in] PageAction The page action.\r
644 @param[in] AllocatePagesFunc If page split is needed, this function is used to allocate more pages.\r
645 NULL mean page split is unsupported.\r
646 @param[out] IsSplitted TRUE means page table splitted. FALSE means page table not splitted.\r
647 @param[out] IsModified TRUE means page table modified. FALSE means page table not modified.\r
648\r
649 @retval RETURN_SUCCESS The attributes were modified for the memory region.\r
650 @retval RETURN_ACCESS_DENIED The attributes for the memory resource range specified by\r
651 BaseAddress and Length cannot be modified.\r
652 @retval RETURN_INVALID_PARAMETER Length is zero.\r
653 Attributes specified an illegal combination of attributes that\r
654 cannot be set together.\r
655 @retval RETURN_OUT_OF_RESOURCES There are not enough system resources to modify the attributes of\r
656 the memory resource range.\r
657 @retval RETURN_UNSUPPORTED The processor does not support one or more bytes of the memory\r
658 resource range specified by BaseAddress and Length.\r
659 The bit mask of attributes is not support for the memory resource\r
660 range specified by BaseAddress and Length.\r
661**/\r
662RETURN_STATUS\r
663ConvertMemoryPageAttributes (\r
664 IN PAGE_TABLE_LIB_PAGING_CONTEXT *PagingContext OPTIONAL,\r
665 IN PHYSICAL_ADDRESS BaseAddress,\r
666 IN UINT64 Length,\r
667 IN UINT64 Attributes,\r
668 IN PAGE_ACTION PageAction,\r
669 IN PAGE_TABLE_LIB_ALLOCATE_PAGES AllocatePagesFunc OPTIONAL,\r
670 OUT BOOLEAN *IsSplitted, OPTIONAL\r
671 OUT BOOLEAN *IsModified OPTIONAL\r
672 )\r
673{\r
674 PAGE_TABLE_LIB_PAGING_CONTEXT CurrentPagingContext;\r
675 UINT64 *PageEntry;\r
676 PAGE_ATTRIBUTE PageAttribute;\r
677 UINTN PageEntryLength;\r
678 PAGE_ATTRIBUTE SplitAttribute;\r
679 RETURN_STATUS Status;\r
680 BOOLEAN IsEntryModified;\r
147fd35c 681 BOOLEAN IsWpEnabled;\r
22292ed3
JY
682\r
683 if ((BaseAddress & (SIZE_4KB - 1)) != 0) {\r
684 DEBUG ((DEBUG_ERROR, "BaseAddress(0x%lx) is not aligned!\n", BaseAddress));\r
685 return EFI_UNSUPPORTED;\r
686 }\r
687 if ((Length & (SIZE_4KB - 1)) != 0) {\r
688 DEBUG ((DEBUG_ERROR, "Length(0x%lx) is not aligned!\n", Length));\r
689 return EFI_UNSUPPORTED;\r
690 }\r
691 if (Length == 0) {\r
692 DEBUG ((DEBUG_ERROR, "Length is 0!\n"));\r
693 return RETURN_INVALID_PARAMETER;\r
694 }\r
695\r
696 if ((Attributes & ~(EFI_MEMORY_RP | EFI_MEMORY_RO | EFI_MEMORY_XP)) != 0) {\r
697 DEBUG ((DEBUG_ERROR, "Attributes(0x%lx) has unsupported bit\n", Attributes));\r
698 return EFI_UNSUPPORTED;\r
699 }\r
700\r
701 if (PagingContext == NULL) {\r
702 GetCurrentPagingContext (&CurrentPagingContext);\r
703 } else {\r
704 CopyMem (&CurrentPagingContext, PagingContext, sizeof(CurrentPagingContext));\r
705 }\r
706 switch(CurrentPagingContext.MachineType) {\r
707 case IMAGE_FILE_MACHINE_I386:\r
708 if (CurrentPagingContext.ContextData.Ia32.PageTableBase == 0) {\r
22292ed3
JY
709 if (Attributes == 0) {\r
710 return EFI_SUCCESS;\r
711 } else {\r
c5719579 712 DEBUG ((DEBUG_ERROR, "PageTable is 0!\n"));\r
22292ed3
JY
713 return EFI_UNSUPPORTED;\r
714 }\r
715 }\r
716 if ((CurrentPagingContext.ContextData.Ia32.Attributes & PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAE) == 0) {\r
717 DEBUG ((DEBUG_ERROR, "Non-PAE Paging!\n"));\r
718 return EFI_UNSUPPORTED;\r
719 }\r
4f10654e
JW
720 if ((BaseAddress + Length) > BASE_4GB) {\r
721 DEBUG ((DEBUG_ERROR, "Beyond 4GB memory in 32-bit mode!\n"));\r
722 return EFI_UNSUPPORTED;\r
723 }\r
22292ed3
JY
724 break;\r
725 case IMAGE_FILE_MACHINE_X64:\r
726 ASSERT (CurrentPagingContext.ContextData.X64.PageTableBase != 0);\r
727 break;\r
728 default:\r
729 ASSERT(FALSE);\r
730 return EFI_UNSUPPORTED;\r
731 break;\r
732 }\r
733\r
734// DEBUG ((DEBUG_ERROR, "ConvertMemoryPageAttributes(%x) - %016lx, %016lx, %02lx\n", IsSet, BaseAddress, Length, Attributes));\r
735\r
736 if (IsSplitted != NULL) {\r
737 *IsSplitted = FALSE;\r
738 }\r
739 if (IsModified != NULL) {\r
740 *IsModified = FALSE;\r
741 }\r
147fd35c
JW
742 if (AllocatePagesFunc == NULL) {\r
743 AllocatePagesFunc = AllocatePageTableMemory;\r
744 }\r
745\r
746 //\r
747 // Make sure that the page table is changeable.\r
748 //\r
749 IsWpEnabled = IsReadOnlyPageWriteProtected ();\r
750 if (IsWpEnabled) {\r
751 DisableReadOnlyPageWriteProtect ();\r
752 }\r
22292ed3
JY
753\r
754 //\r
755 // Below logic is to check 2M/4K page to make sure we donot waist memory.\r
756 //\r
147fd35c 757 Status = EFI_SUCCESS;\r
22292ed3
JY
758 while (Length != 0) {\r
759 PageEntry = GetPageTableEntry (&CurrentPagingContext, BaseAddress, &PageAttribute);\r
760 if (PageEntry == NULL) {\r
147fd35c
JW
761 Status = RETURN_UNSUPPORTED;\r
762 goto Done;\r
22292ed3
JY
763 }\r
764 PageEntryLength = PageAttributeToLength (PageAttribute);\r
765 SplitAttribute = NeedSplitPage (BaseAddress, Length, PageEntry, PageAttribute);\r
766 if (SplitAttribute == PageNone) {\r
767 ConvertPageEntryAttribute (&CurrentPagingContext, PageEntry, Attributes, PageAction, &IsEntryModified);\r
768 if (IsEntryModified) {\r
769 if (IsModified != NULL) {\r
770 *IsModified = TRUE;\r
771 }\r
772 }\r
773 //\r
774 // Convert success, move to next\r
775 //\r
776 BaseAddress += PageEntryLength;\r
777 Length -= PageEntryLength;\r
778 } else {\r
779 if (AllocatePagesFunc == NULL) {\r
147fd35c
JW
780 Status = RETURN_UNSUPPORTED;\r
781 goto Done;\r
22292ed3
JY
782 }\r
783 Status = SplitPage (PageEntry, PageAttribute, SplitAttribute, AllocatePagesFunc);\r
784 if (RETURN_ERROR (Status)) {\r
147fd35c
JW
785 Status = RETURN_UNSUPPORTED;\r
786 goto Done;\r
22292ed3
JY
787 }\r
788 if (IsSplitted != NULL) {\r
789 *IsSplitted = TRUE;\r
790 }\r
791 if (IsModified != NULL) {\r
792 *IsModified = TRUE;\r
793 }\r
794 //\r
795 // Just split current page\r
796 // Convert success in next around\r
797 //\r
798 }\r
799 }\r
800\r
147fd35c
JW
801Done:\r
802 //\r
803 // Restore page table write protection, if any.\r
804 //\r
805 if (IsWpEnabled) {\r
806 EnableReadOnlyPageWriteProtect ();\r
807 }\r
808 return Status;\r
22292ed3
JY
809}\r
810\r
811/**\r
812 This function assigns the page attributes for the memory region specified by BaseAddress and\r
813 Length from their current attributes to the attributes specified by Attributes.\r
814\r
815 Caller should make sure BaseAddress and Length is at page boundary.\r
816\r
817 Caller need guarentee the TPL <= TPL_NOTIFY, if there is split page request.\r
818\r
819 @param[in] PagingContext The paging context. NULL means get page table from current CPU context.\r
820 @param[in] BaseAddress The physical address that is the start address of a memory region.\r
821 @param[in] Length The size in bytes of the memory region.\r
822 @param[in] Attributes The bit mask of attributes to set for the memory region.\r
823 @param[in] AllocatePagesFunc If page split is needed, this function is used to allocate more pages.\r
824 NULL mean page split is unsupported.\r
825\r
826 @retval RETURN_SUCCESS The attributes were cleared for the memory region.\r
827 @retval RETURN_ACCESS_DENIED The attributes for the memory resource range specified by\r
828 BaseAddress and Length cannot be modified.\r
829 @retval RETURN_INVALID_PARAMETER Length is zero.\r
830 Attributes specified an illegal combination of attributes that\r
831 cannot be set together.\r
832 @retval RETURN_OUT_OF_RESOURCES There are not enough system resources to modify the attributes of\r
833 the memory resource range.\r
834 @retval RETURN_UNSUPPORTED The processor does not support one or more bytes of the memory\r
835 resource range specified by BaseAddress and Length.\r
836 The bit mask of attributes is not support for the memory resource\r
837 range specified by BaseAddress and Length.\r
838**/\r
839RETURN_STATUS\r
840EFIAPI\r
841AssignMemoryPageAttributes (\r
842 IN PAGE_TABLE_LIB_PAGING_CONTEXT *PagingContext OPTIONAL,\r
843 IN PHYSICAL_ADDRESS BaseAddress,\r
844 IN UINT64 Length,\r
845 IN UINT64 Attributes,\r
846 IN PAGE_TABLE_LIB_ALLOCATE_PAGES AllocatePagesFunc OPTIONAL\r
847 )\r
848{\r
849 RETURN_STATUS Status;\r
850 BOOLEAN IsModified;\r
851 BOOLEAN IsSplitted;\r
852\r
853// DEBUG((DEBUG_INFO, "AssignMemoryPageAttributes: 0x%lx - 0x%lx (0x%lx)\n", BaseAddress, Length, Attributes));\r
854 Status = ConvertMemoryPageAttributes (PagingContext, BaseAddress, Length, Attributes, PageActionAssign, AllocatePagesFunc, &IsSplitted, &IsModified);\r
855 if (!EFI_ERROR(Status)) {\r
856 if ((PagingContext == NULL) && IsModified) {\r
857 //\r
41a9c3fd
JW
858 // Flush TLB as last step.\r
859 //\r
860 // Note: Since APs will always init CR3 register in HLT loop mode or do\r
861 // TLB flush in MWAIT loop mode, there's no need to flush TLB for them\r
862 // here.\r
22292ed3
JY
863 //\r
864 CpuFlushTlb();\r
22292ed3
JY
865 }\r
866 }\r
867\r
868 return Status;\r
869}\r
870\r
768bd967
JW
871/**\r
872 Check if Execute Disable feature is enabled or not.\r
873**/\r
874BOOLEAN\r
875IsExecuteDisableEnabled (\r
876 VOID\r
877 )\r
878{\r
879 MSR_CORE_IA32_EFER_REGISTER MsrEfer;\r
880\r
881 MsrEfer.Uint64 = AsmReadMsr64 (MSR_IA32_EFER);\r
882 return (MsrEfer.Bits.NXE == 1);\r
883}\r
884\r
c1cab54c
JW
885/**\r
886 Update GCD memory space attributes according to current page table setup.\r
887**/\r
888VOID\r
889RefreshGcdMemoryAttributesFromPaging (\r
890 VOID\r
891 )\r
892{\r
893 EFI_STATUS Status;\r
894 UINTN NumberOfDescriptors;\r
895 EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap;\r
896 PAGE_TABLE_LIB_PAGING_CONTEXT PagingContext;\r
897 PAGE_ATTRIBUTE PageAttribute;\r
898 UINT64 *PageEntry;\r
899 UINT64 PageLength;\r
900 UINT64 MemorySpaceLength;\r
901 UINT64 Length;\r
902 UINT64 BaseAddress;\r
903 UINT64 PageStartAddress;\r
904 UINT64 Attributes;\r
905 UINT64 Capabilities;\r
768bd967 906 UINT64 NewAttributes;\r
c1cab54c
JW
907 UINTN Index;\r
908\r
909 //\r
910 // Assuming that memory space map returned is sorted already; otherwise sort\r
911 // them in the order of lowest address to highest address.\r
912 //\r
913 Status = gDS->GetMemorySpaceMap (&NumberOfDescriptors, &MemorySpaceMap);\r
914 ASSERT_EFI_ERROR (Status);\r
915\r
916 GetCurrentPagingContext (&PagingContext);\r
917\r
768bd967
JW
918 Attributes = 0;\r
919 NewAttributes = 0;\r
920 BaseAddress = 0;\r
921 PageLength = 0;\r
922\r
923 if (IsExecuteDisableEnabled ()) {\r
924 Capabilities = EFI_MEMORY_RO | EFI_MEMORY_RP | EFI_MEMORY_XP;\r
925 } else {\r
926 Capabilities = EFI_MEMORY_RO | EFI_MEMORY_RP;\r
927 }\r
96207191 928\r
c1cab54c
JW
929 for (Index = 0; Index < NumberOfDescriptors; Index++) {\r
930 if (MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeNonExistent) {\r
931 continue;\r
932 }\r
933\r
768bd967
JW
934 //\r
935 // Sync the actual paging related capabilities back to GCD service first.\r
936 // As a side effect (good one), this can also help to avoid unnecessary\r
937 // memory map entries due to the different capabilities of the same type\r
938 // memory, such as multiple RT_CODE and RT_DATA entries in memory map,\r
939 // which could cause boot failure of some old Linux distro (before v4.3).\r
940 //\r
941 Status = gDS->SetMemorySpaceCapabilities (\r
942 MemorySpaceMap[Index].BaseAddress,\r
943 MemorySpaceMap[Index].Length,\r
944 MemorySpaceMap[Index].Capabilities | Capabilities\r
945 );\r
946 if (EFI_ERROR (Status)) {\r
947 //\r
948 // If we cannot udpate the capabilities, we cannot update its\r
949 // attributes either. So just simply skip current block of memory.\r
950 //\r
951 DEBUG ((\r
952 DEBUG_WARN,\r
953 "Failed to update capability: [%lu] %016lx - %016lx (%016lx -> %016lx)\r\n",\r
954 (UINT64)Index, MemorySpaceMap[Index].BaseAddress,\r
955 MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length - 1,\r
956 MemorySpaceMap[Index].Capabilities,\r
957 MemorySpaceMap[Index].Capabilities | Capabilities\r
958 ));\r
959 continue;\r
960 }\r
961\r
c1cab54c
JW
962 if (MemorySpaceMap[Index].BaseAddress >= (BaseAddress + PageLength)) {\r
963 //\r
964 // Current memory space starts at a new page. Resetting PageLength will\r
965 // trigger a retrieval of page attributes at new address.\r
966 //\r
967 PageLength = 0;\r
968 } else {\r
969 //\r
970 // In case current memory space is not adjacent to last one\r
971 //\r
972 PageLength -= (MemorySpaceMap[Index].BaseAddress - BaseAddress);\r
973 }\r
974\r
768bd967
JW
975 //\r
976 // Sync actual page attributes to GCD\r
977 //\r
c1cab54c
JW
978 BaseAddress = MemorySpaceMap[Index].BaseAddress;\r
979 MemorySpaceLength = MemorySpaceMap[Index].Length;\r
980 while (MemorySpaceLength > 0) {\r
981 if (PageLength == 0) {\r
982 PageEntry = GetPageTableEntry (&PagingContext, BaseAddress, &PageAttribute);\r
983 if (PageEntry == NULL) {\r
984 break;\r
985 }\r
986\r
987 //\r
988 // Note current memory space might start in the middle of a page\r
989 //\r
990 PageStartAddress = (*PageEntry) & (UINT64)PageAttributeToMask(PageAttribute);\r
991 PageLength = PageAttributeToLength (PageAttribute) - (BaseAddress - PageStartAddress);\r
992 Attributes = GetAttributesFromPageEntry (PageEntry);\r
c1cab54c
JW
993 }\r
994\r
995 Length = MIN (PageLength, MemorySpaceLength);\r
768bd967
JW
996 if (Attributes != (MemorySpaceMap[Index].Attributes &\r
997 EFI_MEMORY_PAGETYPE_MASK)) {\r
998 NewAttributes = (MemorySpaceMap[Index].Attributes &\r
999 ~EFI_MEMORY_PAGETYPE_MASK) | Attributes;\r
1000 Status = gDS->SetMemorySpaceAttributes (\r
1001 BaseAddress,\r
1002 Length,\r
1003 NewAttributes\r
1004 );\r
1005 ASSERT_EFI_ERROR (Status);\r
1006 DEBUG ((\r
fbe2c4b9 1007 DEBUG_VERBOSE,\r
768bd967
JW
1008 "Updated memory space attribute: [%lu] %016lx - %016lx (%016lx -> %016lx)\r\n",\r
1009 (UINT64)Index, BaseAddress, BaseAddress + Length - 1,\r
1010 MemorySpaceMap[Index].Attributes,\r
1011 NewAttributes\r
1012 ));\r
c1cab54c
JW
1013 }\r
1014\r
1015 PageLength -= Length;\r
1016 MemorySpaceLength -= Length;\r
1017 BaseAddress += Length;\r
1018 }\r
1019 }\r
1020\r
1021 FreePool (MemorySpaceMap);\r
1022}\r
1023\r
147fd35c
JW
1024/**\r
1025 Initialize a buffer pool for page table use only.\r
1026\r
1027 To reduce the potential split operation on page table, the pages reserved for\r
1028 page table should be allocated in the times of PAGE_TABLE_POOL_UNIT_PAGES and\r
1029 at the boundary of PAGE_TABLE_POOL_ALIGNMENT. So the page pool is always\r
1030 initialized with number of pages greater than or equal to the given PoolPages.\r
1031\r
1032 Once the pages in the pool are used up, this method should be called again to\r
1033 reserve at least another PAGE_TABLE_POOL_UNIT_PAGES. Usually this won't happen\r
1034 often in practice.\r
1035\r
1036 @param[in] PoolPages The least page number of the pool to be created.\r
1037\r
1038 @retval TRUE The pool is initialized successfully.\r
1039 @retval FALSE The memory is out of resource.\r
1040**/\r
1041BOOLEAN\r
1042InitializePageTablePool (\r
1043 IN UINTN PoolPages\r
1044 )\r
1045{\r
1046 VOID *Buffer;\r
1047 BOOLEAN IsModified;\r
1048\r
54efcfea
JW
1049 //\r
1050 // Do not allow re-entrance.\r
1051 //\r
1052 if (mPageTablePoolLock) {\r
1053 return FALSE;\r
1054 }\r
1055\r
1056 mPageTablePoolLock = TRUE;\r
1057 IsModified = FALSE;\r
1058\r
147fd35c
JW
1059 //\r
1060 // Always reserve at least PAGE_TABLE_POOL_UNIT_PAGES, including one page for\r
1061 // header.\r
1062 //\r
1063 PoolPages += 1; // Add one page for header.\r
1064 PoolPages = ((PoolPages - 1) / PAGE_TABLE_POOL_UNIT_PAGES + 1) *\r
1065 PAGE_TABLE_POOL_UNIT_PAGES;\r
1066 Buffer = AllocateAlignedPages (PoolPages, PAGE_TABLE_POOL_ALIGNMENT);\r
1067 if (Buffer == NULL) {\r
1068 DEBUG ((DEBUG_ERROR, "ERROR: Out of aligned pages\r\n"));\r
54efcfea 1069 goto Done;\r
147fd35c
JW
1070 }\r
1071\r
54efcfea
JW
1072 DEBUG ((\r
1073 DEBUG_INFO,\r
1074 "Paging: added %lu pages to page table pool\r\n",\r
1075 (UINT64)PoolPages\r
1076 ));\r
1077\r
147fd35c
JW
1078 //\r
1079 // Link all pools into a list for easier track later.\r
1080 //\r
1081 if (mPageTablePool == NULL) {\r
1082 mPageTablePool = Buffer;\r
1083 mPageTablePool->NextPool = mPageTablePool;\r
1084 } else {\r
1085 ((PAGE_TABLE_POOL *)Buffer)->NextPool = mPageTablePool->NextPool;\r
1086 mPageTablePool->NextPool = Buffer;\r
1087 mPageTablePool = Buffer;\r
1088 }\r
1089\r
1090 //\r
1091 // Reserve one page for pool header.\r
1092 //\r
1093 mPageTablePool->FreePages = PoolPages - 1;\r
1094 mPageTablePool->Offset = EFI_PAGES_TO_SIZE (1);\r
1095\r
1096 //\r
1097 // Mark the whole pool pages as read-only.\r
1098 //\r
1099 ConvertMemoryPageAttributes (\r
1100 NULL,\r
1101 (PHYSICAL_ADDRESS)(UINTN)Buffer,\r
1102 EFI_PAGES_TO_SIZE (PoolPages),\r
1103 EFI_MEMORY_RO,\r
1104 PageActionSet,\r
1105 AllocatePageTableMemory,\r
1106 NULL,\r
1107 &IsModified\r
1108 );\r
1109 ASSERT (IsModified == TRUE);\r
1110\r
54efcfea
JW
1111Done:\r
1112 mPageTablePoolLock = FALSE;\r
1113 return IsModified;\r
147fd35c
JW
1114}\r
1115\r
1116/**\r
1117 This API provides a way to allocate memory for page table.\r
1118\r
1119 This API can be called more than once to allocate memory for page tables.\r
1120\r
1121 Allocates the number of 4KB pages and returns a pointer to the allocated\r
1122 buffer. The buffer returned is aligned on a 4KB boundary.\r
1123\r
1124 If Pages is 0, then NULL is returned.\r
1125 If there is not enough memory remaining to satisfy the request, then NULL is\r
1126 returned.\r
1127\r
1128 @param Pages The number of 4 KB pages to allocate.\r
1129\r
1130 @return A pointer to the allocated buffer or NULL if allocation fails.\r
1131\r
1132**/\r
1133VOID *\r
1134EFIAPI\r
1135AllocatePageTableMemory (\r
1136 IN UINTN Pages\r
1137 )\r
1138{\r
1139 VOID *Buffer;\r
1140\r
1141 if (Pages == 0) {\r
1142 return NULL;\r
1143 }\r
1144\r
1145 //\r
1146 // Renew the pool if necessary.\r
1147 //\r
1148 if (mPageTablePool == NULL ||\r
1149 Pages > mPageTablePool->FreePages) {\r
1150 if (!InitializePageTablePool (Pages)) {\r
1151 return NULL;\r
1152 }\r
1153 }\r
1154\r
1155 Buffer = (UINT8 *)mPageTablePool + mPageTablePool->Offset;\r
1156\r
1157 mPageTablePool->Offset += EFI_PAGES_TO_SIZE (Pages);\r
1158 mPageTablePool->FreePages -= Pages;\r
1159\r
1160 return Buffer;\r
1161}\r
1162\r
dcc02621
JW
1163/**\r
1164 Special handler for #DB exception, which will restore the page attributes\r
1165 (not-present). It should work with #PF handler which will set pages to\r
1166 'present'.\r
1167\r
1168 @param ExceptionType Exception type.\r
1169 @param SystemContext Pointer to EFI_SYSTEM_CONTEXT.\r
1170\r
1171**/\r
1172VOID\r
1173EFIAPI\r
1174DebugExceptionHandler (\r
1175 IN EFI_EXCEPTION_TYPE ExceptionType,\r
1176 IN EFI_SYSTEM_CONTEXT SystemContext\r
1177 )\r
1178{\r
1179 UINTN CpuIndex;\r
1180 UINTN PFEntry;\r
1181 BOOLEAN IsWpEnabled;\r
1182\r
1183 MpInitLibWhoAmI (&CpuIndex);\r
1184\r
1185 //\r
1186 // Clear last PF entries\r
1187 //\r
1188 IsWpEnabled = IsReadOnlyPageWriteProtected ();\r
1189 if (IsWpEnabled) {\r
1190 DisableReadOnlyPageWriteProtect ();\r
1191 }\r
1192\r
1193 for (PFEntry = 0; PFEntry < mPFEntryCount[CpuIndex]; PFEntry++) {\r
1194 if (mLastPFEntryPointer[CpuIndex][PFEntry] != NULL) {\r
8e2018f9 1195 *mLastPFEntryPointer[CpuIndex][PFEntry] &= ~(UINT64)IA32_PG_P;\r
dcc02621
JW
1196 }\r
1197 }\r
1198\r
1199 if (IsWpEnabled) {\r
1200 EnableReadOnlyPageWriteProtect ();\r
1201 }\r
1202\r
1203 //\r
1204 // Reset page fault exception count for next page fault.\r
1205 //\r
1206 mPFEntryCount[CpuIndex] = 0;\r
1207\r
1208 //\r
1209 // Flush TLB\r
1210 //\r
1211 CpuFlushTlb ();\r
1212\r
1213 //\r
1214 // Clear TF in EFLAGS\r
1215 //\r
1216 if (mPagingContext.MachineType == IMAGE_FILE_MACHINE_I386) {\r
1217 SystemContext.SystemContextIa32->Eflags &= (UINT32)~BIT8;\r
1218 } else {\r
1219 SystemContext.SystemContextX64->Rflags &= (UINT64)~BIT8;\r
1220 }\r
1221}\r
1222\r
1223/**\r
1224 Special handler for #PF exception, which will set the pages which caused\r
1225 #PF to be 'present'. The attribute of those pages should be restored in\r
1226 the subsequent #DB handler.\r
1227\r
1228 @param ExceptionType Exception type.\r
1229 @param SystemContext Pointer to EFI_SYSTEM_CONTEXT.\r
1230\r
1231**/\r
1232VOID\r
1233EFIAPI\r
1234PageFaultExceptionHandler (\r
1235 IN EFI_EXCEPTION_TYPE ExceptionType,\r
1236 IN EFI_SYSTEM_CONTEXT SystemContext\r
1237 )\r
1238{\r
1239 EFI_STATUS Status;\r
1240 UINT64 PFAddress;\r
1241 PAGE_TABLE_LIB_PAGING_CONTEXT PagingContext;\r
1242 PAGE_ATTRIBUTE PageAttribute;\r
1243 UINT64 Attributes;\r
1244 UINT64 *PageEntry;\r
1245 UINTN Index;\r
1246 UINTN CpuIndex;\r
1247 UINTN PageNumber;\r
1248 BOOLEAN NonStopMode;\r
1249\r
1250 PFAddress = AsmReadCr2 () & ~EFI_PAGE_MASK;\r
1251 if (PFAddress < BASE_4KB) {\r
1252 NonStopMode = NULL_DETECTION_NONSTOP_MODE ? TRUE : FALSE;\r
1253 } else {\r
1254 NonStopMode = HEAP_GUARD_NONSTOP_MODE ? TRUE : FALSE;\r
1255 }\r
1256\r
1257 if (NonStopMode) {\r
1258 MpInitLibWhoAmI (&CpuIndex);\r
1259 GetCurrentPagingContext (&PagingContext);\r
1260 //\r
1261 // Memory operation cross page boundary, like "rep mov" instruction, will\r
1262 // cause infinite loop between this and Debug Trap handler. We have to make\r
1263 // sure that current page and the page followed are both in PRESENT state.\r
1264 //\r
1265 PageNumber = 2;\r
1266 while (PageNumber > 0) {\r
1267 PageEntry = GetPageTableEntry (&PagingContext, PFAddress, &PageAttribute);\r
1268 ASSERT(PageEntry != NULL);\r
1269\r
1270 if (PageEntry != NULL) {\r
1271 Attributes = GetAttributesFromPageEntry (PageEntry);\r
1272 if ((Attributes & EFI_MEMORY_RP) != 0) {\r
1273 Attributes &= ~EFI_MEMORY_RP;\r
1274 Status = AssignMemoryPageAttributes (&PagingContext, PFAddress,\r
1275 EFI_PAGE_SIZE, Attributes, NULL);\r
1276 if (!EFI_ERROR(Status)) {\r
1277 Index = mPFEntryCount[CpuIndex];\r
1278 //\r
1279 // Re-retrieve page entry because above calling might update page\r
1280 // table due to table split.\r
1281 //\r
1282 PageEntry = GetPageTableEntry (&PagingContext, PFAddress, &PageAttribute);\r
1283 mLastPFEntryPointer[CpuIndex][Index++] = PageEntry;\r
1284 mPFEntryCount[CpuIndex] = Index;\r
1285 }\r
1286 }\r
1287 }\r
1288\r
1289 PFAddress += EFI_PAGE_SIZE;\r
1290 --PageNumber;\r
1291 }\r
1292 }\r
1293\r
1294 //\r
1295 // Initialize the serial port before dumping.\r
1296 //\r
1297 SerialPortInitialize ();\r
1298 //\r
1299 // Display ExceptionType, CPU information and Image information\r
1300 //\r
1301 DumpCpuContext (ExceptionType, SystemContext);\r
2a93cccc
JW
1302 if (NonStopMode) {\r
1303 //\r
1304 // Set TF in EFLAGS\r
1305 //\r
1306 if (mPagingContext.MachineType == IMAGE_FILE_MACHINE_I386) {\r
1307 SystemContext.SystemContextIa32->Eflags |= (UINT32)BIT8;\r
1308 } else {\r
1309 SystemContext.SystemContextX64->Rflags |= (UINT64)BIT8;\r
1310 }\r
1311 } else {\r
dcc02621
JW
1312 CpuDeadLoop ();\r
1313 }\r
1314}\r
1315\r
22292ed3
JY
1316/**\r
1317 Initialize the Page Table lib.\r
1318**/\r
1319VOID\r
1320InitializePageTableLib (\r
1321 VOID\r
1322 )\r
1323{\r
1324 PAGE_TABLE_LIB_PAGING_CONTEXT CurrentPagingContext;\r
1325\r
1326 GetCurrentPagingContext (&CurrentPagingContext);\r
147fd35c
JW
1327\r
1328 //\r
1329 // Reserve memory of page tables for future uses, if paging is enabled.\r
1330 //\r
1331 if (CurrentPagingContext.ContextData.X64.PageTableBase != 0 &&\r
1332 (CurrentPagingContext.ContextData.Ia32.Attributes &\r
1333 PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAE) != 0) {\r
1334 DisableReadOnlyPageWriteProtect ();\r
1335 InitializePageTablePool (1);\r
1336 EnableReadOnlyPageWriteProtect ();\r
1337 }\r
1338\r
dcc02621
JW
1339 if (HEAP_GUARD_NONSTOP_MODE || NULL_DETECTION_NONSTOP_MODE) {\r
1340 mPFEntryCount = (UINTN *)AllocateZeroPool (sizeof (UINTN) * mNumberOfProcessors);\r
1341 ASSERT (mPFEntryCount != NULL);\r
1342\r
1343 mLastPFEntryPointer = (UINT64 *(*)[MAX_PF_ENTRY_COUNT])\r
1344 AllocateZeroPool (sizeof (mLastPFEntryPointer[0]) * mNumberOfProcessors);\r
1345 ASSERT (mLastPFEntryPointer != NULL);\r
1346 }\r
1347\r
22292ed3
JY
1348 DEBUG ((DEBUG_INFO, "CurrentPagingContext:\n", CurrentPagingContext.MachineType));\r
1349 DEBUG ((DEBUG_INFO, " MachineType - 0x%x\n", CurrentPagingContext.MachineType));\r
1350 DEBUG ((DEBUG_INFO, " PageTableBase - 0x%x\n", CurrentPagingContext.ContextData.X64.PageTableBase));\r
1351 DEBUG ((DEBUG_INFO, " Attributes - 0x%x\n", CurrentPagingContext.ContextData.X64.Attributes));\r
1352\r
1353 return ;\r
1354}\r
1355\r