2 Page table management support.
4 Copyright (c) 2017 - 2019, Intel Corporation. All rights reserved.<BR>
5 Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
7 SPDX-License-Identifier: BSD-2-Clause-Patent
13 #include <Library/PeCoffGetEntryPointLib.h>
14 #include <Library/SerialPortLib.h>
15 #include <Library/SynchronizationLib.h>
16 #include <Library/PrintLib.h>
17 #include <Protocol/SmmBase2.h>
18 #include <Register/Cpuid.h>
19 #include <Register/Msr.h>
22 #include "CpuPageTable.h"
27 #define IA32_PG_P BIT0
28 #define IA32_PG_RW BIT1
29 #define IA32_PG_U BIT2
30 #define IA32_PG_WT BIT3
31 #define IA32_PG_CD BIT4
32 #define IA32_PG_A BIT5
33 #define IA32_PG_D BIT6
34 #define IA32_PG_PS BIT7
35 #define IA32_PG_PAT_2M BIT12
36 #define IA32_PG_PAT_4K IA32_PG_PS
37 #define IA32_PG_PMNT BIT62
38 #define IA32_PG_NX BIT63
40 #define PAGE_ATTRIBUTE_BITS (IA32_PG_D | IA32_PG_A | IA32_PG_U | IA32_PG_RW | IA32_PG_P)
42 // Bits 1, 2, 5, 6 are reserved in the IA32 PAE PDPTE
43 // X64 PAE PDPTE does not have such restriction
45 #define IA32_PAE_PDPTE_ATTRIBUTE_BITS (IA32_PG_P)
47 #define PAGE_PROGATE_BITS (IA32_PG_NX | PAGE_ATTRIBUTE_BITS)
49 #define PAGING_4K_MASK 0xFFF
50 #define PAGING_2M_MASK 0x1FFFFF
51 #define PAGING_1G_MASK 0x3FFFFFFF
53 #define PAGING_PAE_INDEX_MASK 0x1FF
55 #define PAGING_4K_ADDRESS_MASK_64 0x000FFFFFFFFFF000ull
56 #define PAGING_2M_ADDRESS_MASK_64 0x000FFFFFFFE00000ull
57 #define PAGING_1G_ADDRESS_MASK_64 0x000FFFFFC0000000ull
59 #define MAX_PF_ENTRY_COUNT 10
60 #define MAX_DEBUG_MESSAGE_LENGTH 0x100
61 #define IA32_PF_EC_ID BIT4
71 PAGE_ATTRIBUTE Attribute
;
74 } PAGE_ATTRIBUTE_TABLE
;
82 PAGE_ATTRIBUTE_TABLE mPageAttributeTable
[] = {
83 {Page4K
, SIZE_4KB
, PAGING_4K_ADDRESS_MASK_64
},
84 {Page2M
, SIZE_2MB
, PAGING_2M_ADDRESS_MASK_64
},
85 {Page1G
, SIZE_1GB
, PAGING_1G_ADDRESS_MASK_64
},
88 PAGE_TABLE_POOL
*mPageTablePool
= NULL
;
89 BOOLEAN mPageTablePoolLock
= FALSE
;
90 PAGE_TABLE_LIB_PAGING_CONTEXT mPagingContext
;
91 EFI_SMM_BASE2_PROTOCOL
*mSmmBase2
= NULL
;
94 // Record the page fault exception count for one instruction execution.
97 UINT64
*(*mLastPFEntryPointer
)[MAX_PF_ENTRY_COUNT
];
100 Check if current execution environment is in SMM mode or not, via
101 EFI_SMM_BASE2_PROTOCOL.
103 This is necessary because of the fact that MdePkg\Library\SmmMemoryAllocationLib
104 supports to free memory outside SMRAM. The library will call gBS->FreePool() or
105 gBS->FreePages() and then SetMemorySpaceAttributes interface in turn to change
106 memory paging attributes during free operation, if some memory related features
107 are enabled (like Heap Guard).
109 This means that SetMemorySpaceAttributes() has chance to run in SMM mode. This
110 will cause incorrect result because SMM mode always loads its own page tables,
111 which are usually different from DXE. This function can be used to detect such
112 situation and help to avoid further misoperations.
114 @retval TRUE In SMM mode.
115 @retval FALSE Not in SMM mode.
125 if (mSmmBase2
== NULL
) {
126 gBS
->LocateProtocol (&gEfiSmmBase2ProtocolGuid
, NULL
, (VOID
**)&mSmmBase2
);
129 if (mSmmBase2
!= NULL
) {
130 mSmmBase2
->InSmm (mSmmBase2
, &InSmm
);
134 // mSmmBase2->InSmm() can only detect if the caller is running in SMRAM
135 // or from SMM driver. It cannot tell if the caller is running in SMM mode.
136 // Check page table base address to guarantee that because SMM mode willl
137 // load its own page table.
140 mPagingContext
.ContextData
.X64
.PageTableBase
!= (UINT64
)AsmReadCr3());
144 Return current paging context.
146 @param[in,out] PagingContext The paging context.
149 GetCurrentPagingContext (
150 IN OUT PAGE_TABLE_LIB_PAGING_CONTEXT
*PagingContext
154 CPUID_EXTENDED_CPU_SIG_EDX RegEdx
;
155 MSR_IA32_EFER_REGISTER MsrEfer
;
160 // Don't retrieve current paging context from processor if in SMM mode.
163 ZeroMem (&mPagingContext
, sizeof(mPagingContext
));
164 if (sizeof(UINTN
) == sizeof(UINT64
)) {
165 mPagingContext
.MachineType
= IMAGE_FILE_MACHINE_X64
;
167 mPagingContext
.MachineType
= IMAGE_FILE_MACHINE_I386
;
170 Cr0
.UintN
= AsmReadCr0 ();
171 Cr4
.UintN
= AsmReadCr4 ();
173 if (Cr0
.Bits
.PG
!= 0) {
174 mPagingContext
.ContextData
.X64
.PageTableBase
= (AsmReadCr3 () & PAGING_4K_ADDRESS_MASK_64
);
176 mPagingContext
.ContextData
.X64
.PageTableBase
= 0;
178 if (Cr0
.Bits
.WP
!= 0) {
179 mPagingContext
.ContextData
.Ia32
.Attributes
|= PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_WP_ENABLE
;
181 if (Cr4
.Bits
.PSE
!= 0) {
182 mPagingContext
.ContextData
.Ia32
.Attributes
|= PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PSE
;
184 if (Cr4
.Bits
.PAE
!= 0) {
185 mPagingContext
.ContextData
.Ia32
.Attributes
|= PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAE
;
187 if (Cr4
.Bits
.LA57
!= 0) {
188 mPagingContext
.ContextData
.Ia32
.Attributes
|= PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_5_LEVEL
;
191 AsmCpuid (CPUID_EXTENDED_FUNCTION
, &RegEax
, NULL
, NULL
, NULL
);
192 if (RegEax
>= CPUID_EXTENDED_CPU_SIG
) {
193 AsmCpuid (CPUID_EXTENDED_CPU_SIG
, NULL
, NULL
, NULL
, &RegEdx
.Uint32
);
195 if (RegEdx
.Bits
.NX
!= 0) {
197 MsrEfer
.Uint64
= AsmReadMsr64(MSR_CORE_IA32_EFER
);
198 if (MsrEfer
.Bits
.NXE
!= 0) {
200 mPagingContext
.ContextData
.Ia32
.Attributes
|= PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_XD_ACTIVATED
;
204 if (RegEdx
.Bits
.Page1GB
!= 0) {
205 mPagingContext
.ContextData
.Ia32
.Attributes
|= PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAGE_1G_SUPPORT
;
211 // This can avoid getting SMM paging context if in SMM mode. We cannot assume
212 // SMM mode shares the same paging context as DXE.
214 CopyMem (PagingContext
, &mPagingContext
, sizeof (mPagingContext
));
218 Return length according to page attributes.
220 @param[in] PageAttributes The page attribute of the page entry.
222 @return The length of page entry.
225 PageAttributeToLength (
226 IN PAGE_ATTRIBUTE PageAttribute
230 for (Index
= 0; Index
< sizeof(mPageAttributeTable
)/sizeof(mPageAttributeTable
[0]); Index
++) {
231 if (PageAttribute
== mPageAttributeTable
[Index
].Attribute
) {
232 return (UINTN
)mPageAttributeTable
[Index
].Length
;
239 Return address mask according to page attributes.
241 @param[in] PageAttributes The page attribute of the page entry.
243 @return The address mask of page entry.
246 PageAttributeToMask (
247 IN PAGE_ATTRIBUTE PageAttribute
251 for (Index
= 0; Index
< sizeof(mPageAttributeTable
)/sizeof(mPageAttributeTable
[0]); Index
++) {
252 if (PageAttribute
== mPageAttributeTable
[Index
].Attribute
) {
253 return (UINTN
)mPageAttributeTable
[Index
].AddressMask
;
260 Return page table entry to match the address.
262 @param[in] PagingContext The paging context.
263 @param[in] Address The address to be checked.
264 @param[out] PageAttributes The page attribute of the page entry.
266 @return The page entry.
270 IN PAGE_TABLE_LIB_PAGING_CONTEXT
*PagingContext
,
271 IN PHYSICAL_ADDRESS Address
,
272 OUT PAGE_ATTRIBUTE
*PageAttribute
285 UINT64 AddressEncMask
;
287 ASSERT (PagingContext
!= NULL
);
289 Index5
= ((UINTN
)RShiftU64 (Address
, 48)) & PAGING_PAE_INDEX_MASK
;
290 Index4
= ((UINTN
)RShiftU64 (Address
, 39)) & PAGING_PAE_INDEX_MASK
;
291 Index3
= ((UINTN
)Address
>> 30) & PAGING_PAE_INDEX_MASK
;
292 Index2
= ((UINTN
)Address
>> 21) & PAGING_PAE_INDEX_MASK
;
293 Index1
= ((UINTN
)Address
>> 12) & PAGING_PAE_INDEX_MASK
;
295 // Make sure AddressEncMask is contained to smallest supported address field.
297 AddressEncMask
= PcdGet64 (PcdPteMemoryEncryptionAddressOrMask
) & PAGING_1G_ADDRESS_MASK_64
;
299 if (PagingContext
->MachineType
== IMAGE_FILE_MACHINE_X64
) {
300 if ((PagingContext
->ContextData
.X64
.Attributes
& PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_5_LEVEL
) != 0) {
301 L5PageTable
= (UINT64
*)(UINTN
)PagingContext
->ContextData
.X64
.PageTableBase
;
302 if (L5PageTable
[Index5
] == 0) {
303 *PageAttribute
= PageNone
;
307 L4PageTable
= (UINT64
*)(UINTN
)(L5PageTable
[Index5
] & ~AddressEncMask
& PAGING_4K_ADDRESS_MASK_64
);
309 L4PageTable
= (UINT64
*)(UINTN
)PagingContext
->ContextData
.X64
.PageTableBase
;
311 if (L4PageTable
[Index4
] == 0) {
312 *PageAttribute
= PageNone
;
316 L3PageTable
= (UINT64
*)(UINTN
)(L4PageTable
[Index4
] & ~AddressEncMask
& PAGING_4K_ADDRESS_MASK_64
);
318 ASSERT((PagingContext
->ContextData
.Ia32
.Attributes
& PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAE
) != 0);
319 L3PageTable
= (UINT64
*)(UINTN
)PagingContext
->ContextData
.Ia32
.PageTableBase
;
321 if (L3PageTable
[Index3
] == 0) {
322 *PageAttribute
= PageNone
;
325 if ((L3PageTable
[Index3
] & IA32_PG_PS
) != 0) {
327 *PageAttribute
= Page1G
;
328 return &L3PageTable
[Index3
];
331 L2PageTable
= (UINT64
*)(UINTN
)(L3PageTable
[Index3
] & ~AddressEncMask
& PAGING_4K_ADDRESS_MASK_64
);
332 if (L2PageTable
[Index2
] == 0) {
333 *PageAttribute
= PageNone
;
336 if ((L2PageTable
[Index2
] & IA32_PG_PS
) != 0) {
338 *PageAttribute
= Page2M
;
339 return &L2PageTable
[Index2
];
343 L1PageTable
= (UINT64
*)(UINTN
)(L2PageTable
[Index2
] & ~AddressEncMask
& PAGING_4K_ADDRESS_MASK_64
);
344 if ((L1PageTable
[Index1
] == 0) && (Address
!= 0)) {
345 *PageAttribute
= PageNone
;
348 *PageAttribute
= Page4K
;
349 return &L1PageTable
[Index1
];
353 Return memory attributes of page entry.
355 @param[in] PageEntry The page entry.
357 @return Memory attributes of page entry.
360 GetAttributesFromPageEntry (
366 if ((*PageEntry
& IA32_PG_P
) == 0) {
367 Attributes
|= EFI_MEMORY_RP
;
369 if ((*PageEntry
& IA32_PG_RW
) == 0) {
370 Attributes
|= EFI_MEMORY_RO
;
372 if ((*PageEntry
& IA32_PG_NX
) != 0) {
373 Attributes
|= EFI_MEMORY_XP
;
379 Modify memory attributes of page entry.
381 @param[in] PagingContext The paging context.
382 @param[in] PageEntry The page entry.
383 @param[in] Attributes The bit mask of attributes to modify for the memory region.
384 @param[in] PageAction The page action.
385 @param[out] IsModified TRUE means page table modified. FALSE means page table not modified.
388 ConvertPageEntryAttribute (
389 IN PAGE_TABLE_LIB_PAGING_CONTEXT
*PagingContext
,
390 IN UINT64
*PageEntry
,
391 IN UINT64 Attributes
,
392 IN PAGE_ACTION PageAction
,
393 OUT BOOLEAN
*IsModified
396 UINT64 CurrentPageEntry
;
399 CurrentPageEntry
= *PageEntry
;
400 NewPageEntry
= CurrentPageEntry
;
401 if ((Attributes
& EFI_MEMORY_RP
) != 0) {
402 switch (PageAction
) {
403 case PageActionAssign
:
405 NewPageEntry
&= ~(UINT64
)IA32_PG_P
;
407 case PageActionClear
:
408 NewPageEntry
|= IA32_PG_P
;
412 switch (PageAction
) {
413 case PageActionAssign
:
414 NewPageEntry
|= IA32_PG_P
;
417 case PageActionClear
:
421 if ((Attributes
& EFI_MEMORY_RO
) != 0) {
422 switch (PageAction
) {
423 case PageActionAssign
:
425 NewPageEntry
&= ~(UINT64
)IA32_PG_RW
;
427 case PageActionClear
:
428 NewPageEntry
|= IA32_PG_RW
;
432 switch (PageAction
) {
433 case PageActionAssign
:
434 NewPageEntry
|= IA32_PG_RW
;
437 case PageActionClear
:
441 if ((PagingContext
->ContextData
.Ia32
.Attributes
& PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_XD_ACTIVATED
) != 0) {
442 if ((Attributes
& EFI_MEMORY_XP
) != 0) {
443 switch (PageAction
) {
444 case PageActionAssign
:
446 NewPageEntry
|= IA32_PG_NX
;
448 case PageActionClear
:
449 NewPageEntry
&= ~IA32_PG_NX
;
453 switch (PageAction
) {
454 case PageActionAssign
:
455 NewPageEntry
&= ~IA32_PG_NX
;
458 case PageActionClear
:
463 *PageEntry
= NewPageEntry
;
464 if (CurrentPageEntry
!= NewPageEntry
) {
466 DEBUG ((DEBUG_VERBOSE
, "ConvertPageEntryAttribute 0x%lx", CurrentPageEntry
));
467 DEBUG ((DEBUG_VERBOSE
, "->0x%lx\n", NewPageEntry
));
474 This function returns if there is need to split page entry.
476 @param[in] BaseAddress The base address to be checked.
477 @param[in] Length The length to be checked.
478 @param[in] PageEntry The page entry to be checked.
479 @param[in] PageAttribute The page attribute of the page entry.
481 @retval SplitAttributes on if there is need to split page entry.
485 IN PHYSICAL_ADDRESS BaseAddress
,
487 IN UINT64
*PageEntry
,
488 IN PAGE_ATTRIBUTE PageAttribute
491 UINT64 PageEntryLength
;
493 PageEntryLength
= PageAttributeToLength (PageAttribute
);
495 if (((BaseAddress
& (PageEntryLength
- 1)) == 0) && (Length
>= PageEntryLength
)) {
499 if (((BaseAddress
& PAGING_2M_MASK
) != 0) || (Length
< SIZE_2MB
)) {
507 This function splits one page entry to small page entries.
509 @param[in] PageEntry The page entry to be splitted.
510 @param[in] PageAttribute The page attribute of the page entry.
511 @param[in] SplitAttribute How to split the page entry.
512 @param[in] AllocatePagesFunc If page split is needed, this function is used to allocate more pages.
514 @retval RETURN_SUCCESS The page entry is splitted.
515 @retval RETURN_UNSUPPORTED The page entry does not support to be splitted.
516 @retval RETURN_OUT_OF_RESOURCES No resource to split page entry.
520 IN UINT64
*PageEntry
,
521 IN PAGE_ATTRIBUTE PageAttribute
,
522 IN PAGE_ATTRIBUTE SplitAttribute
,
523 IN PAGE_TABLE_LIB_ALLOCATE_PAGES AllocatePagesFunc
527 UINT64
*NewPageEntry
;
529 UINT64 AddressEncMask
;
531 ASSERT (PageAttribute
== Page2M
|| PageAttribute
== Page1G
);
533 ASSERT (AllocatePagesFunc
!= NULL
);
535 // Make sure AddressEncMask is contained to smallest supported address field.
537 AddressEncMask
= PcdGet64 (PcdPteMemoryEncryptionAddressOrMask
) & PAGING_1G_ADDRESS_MASK_64
;
539 if (PageAttribute
== Page2M
) {
543 ASSERT (SplitAttribute
== Page4K
);
544 if (SplitAttribute
== Page4K
) {
545 NewPageEntry
= AllocatePagesFunc (1);
546 DEBUG ((DEBUG_VERBOSE
, "Split - 0x%x\n", NewPageEntry
));
547 if (NewPageEntry
== NULL
) {
548 return RETURN_OUT_OF_RESOURCES
;
550 BaseAddress
= *PageEntry
& ~AddressEncMask
& PAGING_2M_ADDRESS_MASK_64
;
551 for (Index
= 0; Index
< SIZE_4KB
/ sizeof(UINT64
); Index
++) {
552 NewPageEntry
[Index
] = (BaseAddress
+ SIZE_4KB
* Index
) | AddressEncMask
| ((*PageEntry
) & PAGE_PROGATE_BITS
);
554 (*PageEntry
) = (UINT64
)(UINTN
)NewPageEntry
| AddressEncMask
| ((*PageEntry
) & PAGE_ATTRIBUTE_BITS
);
555 return RETURN_SUCCESS
;
557 return RETURN_UNSUPPORTED
;
559 } else if (PageAttribute
== Page1G
) {
562 // No need support 1G->4K directly, we should use 1G->2M, then 2M->4K to get more compact page table.
564 ASSERT (SplitAttribute
== Page2M
|| SplitAttribute
== Page4K
);
565 if ((SplitAttribute
== Page2M
|| SplitAttribute
== Page4K
)) {
566 NewPageEntry
= AllocatePagesFunc (1);
567 DEBUG ((DEBUG_VERBOSE
, "Split - 0x%x\n", NewPageEntry
));
568 if (NewPageEntry
== NULL
) {
569 return RETURN_OUT_OF_RESOURCES
;
571 BaseAddress
= *PageEntry
& ~AddressEncMask
& PAGING_1G_ADDRESS_MASK_64
;
572 for (Index
= 0; Index
< SIZE_4KB
/ sizeof(UINT64
); Index
++) {
573 NewPageEntry
[Index
] = (BaseAddress
+ SIZE_2MB
* Index
) | AddressEncMask
| IA32_PG_PS
| ((*PageEntry
) & PAGE_PROGATE_BITS
);
575 (*PageEntry
) = (UINT64
)(UINTN
)NewPageEntry
| AddressEncMask
| ((*PageEntry
) & PAGE_ATTRIBUTE_BITS
);
576 return RETURN_SUCCESS
;
578 return RETURN_UNSUPPORTED
;
581 return RETURN_UNSUPPORTED
;
586 Check the WP status in CR0 register. This bit is used to lock or unlock write
587 access to pages marked as read-only.
589 @retval TRUE Write protection is enabled.
590 @retval FALSE Write protection is disabled.
593 IsReadOnlyPageWriteProtected (
599 // To avoid unforseen consequences, don't touch paging settings in SMM mode
603 Cr0
.UintN
= AsmReadCr0 ();
604 return (BOOLEAN
) (Cr0
.Bits
.WP
!= 0);
610 Disable Write Protect on pages marked as read-only.
613 DisableReadOnlyPageWriteProtect (
619 // To avoid unforseen consequences, don't touch paging settings in SMM mode
623 Cr0
.UintN
= AsmReadCr0 ();
625 AsmWriteCr0 (Cr0
.UintN
);
630 Enable Write Protect on pages marked as read-only.
633 EnableReadOnlyPageWriteProtect (
639 // To avoid unforseen consequences, don't touch paging settings in SMM mode
643 Cr0
.UintN
= AsmReadCr0 ();
645 AsmWriteCr0 (Cr0
.UintN
);
650 This function modifies the page attributes for the memory region specified by BaseAddress and
651 Length from their current attributes to the attributes specified by Attributes.
653 Caller should make sure BaseAddress and Length is at page boundary.
655 @param[in] PagingContext The paging context. NULL means get page table from current CPU context.
656 @param[in] BaseAddress The physical address that is the start address of a memory region.
657 @param[in] Length The size in bytes of the memory region.
658 @param[in] Attributes The bit mask of attributes to modify for the memory region.
659 @param[in] PageAction The page action.
660 @param[in] AllocatePagesFunc If page split is needed, this function is used to allocate more pages.
661 NULL mean page split is unsupported.
662 @param[out] IsSplitted TRUE means page table splitted. FALSE means page table not splitted.
663 @param[out] IsModified TRUE means page table modified. FALSE means page table not modified.
665 @retval RETURN_SUCCESS The attributes were modified for the memory region.
666 @retval RETURN_ACCESS_DENIED The attributes for the memory resource range specified by
667 BaseAddress and Length cannot be modified.
668 @retval RETURN_INVALID_PARAMETER Length is zero.
669 Attributes specified an illegal combination of attributes that
670 cannot be set together.
671 @retval RETURN_OUT_OF_RESOURCES There are not enough system resources to modify the attributes of
672 the memory resource range.
673 @retval RETURN_UNSUPPORTED The processor does not support one or more bytes of the memory
674 resource range specified by BaseAddress and Length.
675 The bit mask of attributes is not support for the memory resource
676 range specified by BaseAddress and Length.
679 ConvertMemoryPageAttributes (
680 IN PAGE_TABLE_LIB_PAGING_CONTEXT
*PagingContext OPTIONAL
,
681 IN PHYSICAL_ADDRESS BaseAddress
,
683 IN UINT64 Attributes
,
684 IN PAGE_ACTION PageAction
,
685 IN PAGE_TABLE_LIB_ALLOCATE_PAGES AllocatePagesFunc OPTIONAL
,
686 OUT BOOLEAN
*IsSplitted
, OPTIONAL
687 OUT BOOLEAN
*IsModified OPTIONAL
690 PAGE_TABLE_LIB_PAGING_CONTEXT CurrentPagingContext
;
692 PAGE_ATTRIBUTE PageAttribute
;
693 UINTN PageEntryLength
;
694 PAGE_ATTRIBUTE SplitAttribute
;
695 RETURN_STATUS Status
;
696 BOOLEAN IsEntryModified
;
699 if ((BaseAddress
& (SIZE_4KB
- 1)) != 0) {
700 DEBUG ((DEBUG_ERROR
, "BaseAddress(0x%lx) is not aligned!\n", BaseAddress
));
701 return EFI_UNSUPPORTED
;
703 if ((Length
& (SIZE_4KB
- 1)) != 0) {
704 DEBUG ((DEBUG_ERROR
, "Length(0x%lx) is not aligned!\n", Length
));
705 return EFI_UNSUPPORTED
;
708 DEBUG ((DEBUG_ERROR
, "Length is 0!\n"));
709 return RETURN_INVALID_PARAMETER
;
712 if ((Attributes
& ~(EFI_MEMORY_RP
| EFI_MEMORY_RO
| EFI_MEMORY_XP
)) != 0) {
713 DEBUG ((DEBUG_ERROR
, "Attributes(0x%lx) has unsupported bit\n", Attributes
));
714 return EFI_UNSUPPORTED
;
717 if (PagingContext
== NULL
) {
718 GetCurrentPagingContext (&CurrentPagingContext
);
720 CopyMem (&CurrentPagingContext
, PagingContext
, sizeof(CurrentPagingContext
));
722 switch(CurrentPagingContext
.MachineType
) {
723 case IMAGE_FILE_MACHINE_I386
:
724 if (CurrentPagingContext
.ContextData
.Ia32
.PageTableBase
== 0) {
725 if (Attributes
== 0) {
728 DEBUG ((DEBUG_ERROR
, "PageTable is 0!\n"));
729 return EFI_UNSUPPORTED
;
732 if ((CurrentPagingContext
.ContextData
.Ia32
.Attributes
& PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAE
) == 0) {
733 DEBUG ((DEBUG_ERROR
, "Non-PAE Paging!\n"));
734 return EFI_UNSUPPORTED
;
736 if ((BaseAddress
+ Length
) > BASE_4GB
) {
737 DEBUG ((DEBUG_ERROR
, "Beyond 4GB memory in 32-bit mode!\n"));
738 return EFI_UNSUPPORTED
;
741 case IMAGE_FILE_MACHINE_X64
:
742 ASSERT (CurrentPagingContext
.ContextData
.X64
.PageTableBase
!= 0);
746 return EFI_UNSUPPORTED
;
750 // DEBUG ((DEBUG_ERROR, "ConvertMemoryPageAttributes(%x) - %016lx, %016lx, %02lx\n", IsSet, BaseAddress, Length, Attributes));
752 if (IsSplitted
!= NULL
) {
755 if (IsModified
!= NULL
) {
758 if (AllocatePagesFunc
== NULL
) {
759 AllocatePagesFunc
= AllocatePageTableMemory
;
763 // Make sure that the page table is changeable.
765 IsWpEnabled
= IsReadOnlyPageWriteProtected ();
767 DisableReadOnlyPageWriteProtect ();
771 // Below logic is to check 2M/4K page to make sure we donot waist memory.
773 Status
= EFI_SUCCESS
;
774 while (Length
!= 0) {
775 PageEntry
= GetPageTableEntry (&CurrentPagingContext
, BaseAddress
, &PageAttribute
);
776 if (PageEntry
== NULL
) {
777 Status
= RETURN_UNSUPPORTED
;
780 PageEntryLength
= PageAttributeToLength (PageAttribute
);
781 SplitAttribute
= NeedSplitPage (BaseAddress
, Length
, PageEntry
, PageAttribute
);
782 if (SplitAttribute
== PageNone
) {
783 ConvertPageEntryAttribute (&CurrentPagingContext
, PageEntry
, Attributes
, PageAction
, &IsEntryModified
);
784 if (IsEntryModified
) {
785 if (IsModified
!= NULL
) {
790 // Convert success, move to next
792 BaseAddress
+= PageEntryLength
;
793 Length
-= PageEntryLength
;
795 if (AllocatePagesFunc
== NULL
) {
796 Status
= RETURN_UNSUPPORTED
;
799 Status
= SplitPage (PageEntry
, PageAttribute
, SplitAttribute
, AllocatePagesFunc
);
800 if (RETURN_ERROR (Status
)) {
801 Status
= RETURN_UNSUPPORTED
;
804 if (IsSplitted
!= NULL
) {
807 if (IsModified
!= NULL
) {
811 // Just split current page
812 // Convert success in next around
819 // Restore page table write protection, if any.
822 EnableReadOnlyPageWriteProtect ();
828 This function assigns the page attributes for the memory region specified by BaseAddress and
829 Length from their current attributes to the attributes specified by Attributes.
831 Caller should make sure BaseAddress and Length is at page boundary.
833 Caller need guarentee the TPL <= TPL_NOTIFY, if there is split page request.
835 @param[in] PagingContext The paging context. NULL means get page table from current CPU context.
836 @param[in] BaseAddress The physical address that is the start address of a memory region.
837 @param[in] Length The size in bytes of the memory region.
838 @param[in] Attributes The bit mask of attributes to set for the memory region.
839 @param[in] AllocatePagesFunc If page split is needed, this function is used to allocate more pages.
840 NULL mean page split is unsupported.
842 @retval RETURN_SUCCESS The attributes were cleared for the memory region.
843 @retval RETURN_ACCESS_DENIED The attributes for the memory resource range specified by
844 BaseAddress and Length cannot be modified.
845 @retval RETURN_INVALID_PARAMETER Length is zero.
846 Attributes specified an illegal combination of attributes that
847 cannot be set together.
848 @retval RETURN_OUT_OF_RESOURCES There are not enough system resources to modify the attributes of
849 the memory resource range.
850 @retval RETURN_UNSUPPORTED The processor does not support one or more bytes of the memory
851 resource range specified by BaseAddress and Length.
852 The bit mask of attributes is not support for the memory resource
853 range specified by BaseAddress and Length.
857 AssignMemoryPageAttributes (
858 IN PAGE_TABLE_LIB_PAGING_CONTEXT
*PagingContext OPTIONAL
,
859 IN PHYSICAL_ADDRESS BaseAddress
,
861 IN UINT64 Attributes
,
862 IN PAGE_TABLE_LIB_ALLOCATE_PAGES AllocatePagesFunc OPTIONAL
865 RETURN_STATUS Status
;
869 // DEBUG((DEBUG_INFO, "AssignMemoryPageAttributes: 0x%lx - 0x%lx (0x%lx)\n", BaseAddress, Length, Attributes));
870 Status
= ConvertMemoryPageAttributes (PagingContext
, BaseAddress
, Length
, Attributes
, PageActionAssign
, AllocatePagesFunc
, &IsSplitted
, &IsModified
);
871 if (!EFI_ERROR(Status
)) {
872 if ((PagingContext
== NULL
) && IsModified
) {
874 // Flush TLB as last step.
876 // Note: Since APs will always init CR3 register in HLT loop mode or do
877 // TLB flush in MWAIT loop mode, there's no need to flush TLB for them
888 Check if Execute Disable feature is enabled or not.
891 IsExecuteDisableEnabled (
895 MSR_CORE_IA32_EFER_REGISTER MsrEfer
;
897 MsrEfer
.Uint64
= AsmReadMsr64 (MSR_IA32_EFER
);
898 return (MsrEfer
.Bits
.NXE
== 1);
902 Update GCD memory space attributes according to current page table setup.
905 RefreshGcdMemoryAttributesFromPaging (
910 UINTN NumberOfDescriptors
;
911 EFI_GCD_MEMORY_SPACE_DESCRIPTOR
*MemorySpaceMap
;
912 PAGE_TABLE_LIB_PAGING_CONTEXT PagingContext
;
913 PAGE_ATTRIBUTE PageAttribute
;
916 UINT64 MemorySpaceLength
;
919 UINT64 PageStartAddress
;
922 UINT64 NewAttributes
;
926 // Assuming that memory space map returned is sorted already; otherwise sort
927 // them in the order of lowest address to highest address.
929 Status
= gDS
->GetMemorySpaceMap (&NumberOfDescriptors
, &MemorySpaceMap
);
930 ASSERT_EFI_ERROR (Status
);
932 GetCurrentPagingContext (&PagingContext
);
939 if (IsExecuteDisableEnabled ()) {
940 Capabilities
= EFI_MEMORY_RO
| EFI_MEMORY_RP
| EFI_MEMORY_XP
;
942 Capabilities
= EFI_MEMORY_RO
| EFI_MEMORY_RP
;
945 for (Index
= 0; Index
< NumberOfDescriptors
; Index
++) {
946 if (MemorySpaceMap
[Index
].GcdMemoryType
== EfiGcdMemoryTypeNonExistent
) {
951 // Sync the actual paging related capabilities back to GCD service first.
952 // As a side effect (good one), this can also help to avoid unnecessary
953 // memory map entries due to the different capabilities of the same type
954 // memory, such as multiple RT_CODE and RT_DATA entries in memory map,
955 // which could cause boot failure of some old Linux distro (before v4.3).
957 Status
= gDS
->SetMemorySpaceCapabilities (
958 MemorySpaceMap
[Index
].BaseAddress
,
959 MemorySpaceMap
[Index
].Length
,
960 MemorySpaceMap
[Index
].Capabilities
| Capabilities
962 if (EFI_ERROR (Status
)) {
964 // If we cannot udpate the capabilities, we cannot update its
965 // attributes either. So just simply skip current block of memory.
969 "Failed to update capability: [%lu] %016lx - %016lx (%016lx -> %016lx)\r\n",
970 (UINT64
)Index
, MemorySpaceMap
[Index
].BaseAddress
,
971 MemorySpaceMap
[Index
].BaseAddress
+ MemorySpaceMap
[Index
].Length
- 1,
972 MemorySpaceMap
[Index
].Capabilities
,
973 MemorySpaceMap
[Index
].Capabilities
| Capabilities
978 if (MemorySpaceMap
[Index
].BaseAddress
>= (BaseAddress
+ PageLength
)) {
980 // Current memory space starts at a new page. Resetting PageLength will
981 // trigger a retrieval of page attributes at new address.
986 // In case current memory space is not adjacent to last one
988 PageLength
-= (MemorySpaceMap
[Index
].BaseAddress
- BaseAddress
);
992 // Sync actual page attributes to GCD
994 BaseAddress
= MemorySpaceMap
[Index
].BaseAddress
;
995 MemorySpaceLength
= MemorySpaceMap
[Index
].Length
;
996 while (MemorySpaceLength
> 0) {
997 if (PageLength
== 0) {
998 PageEntry
= GetPageTableEntry (&PagingContext
, BaseAddress
, &PageAttribute
);
999 if (PageEntry
== NULL
) {
1004 // Note current memory space might start in the middle of a page
1006 PageStartAddress
= (*PageEntry
) & (UINT64
)PageAttributeToMask(PageAttribute
);
1007 PageLength
= PageAttributeToLength (PageAttribute
) - (BaseAddress
- PageStartAddress
);
1008 Attributes
= GetAttributesFromPageEntry (PageEntry
);
1011 Length
= MIN (PageLength
, MemorySpaceLength
);
1012 if (Attributes
!= (MemorySpaceMap
[Index
].Attributes
&
1013 EFI_MEMORY_PAGETYPE_MASK
)) {
1014 NewAttributes
= (MemorySpaceMap
[Index
].Attributes
&
1015 ~EFI_MEMORY_PAGETYPE_MASK
) | Attributes
;
1016 Status
= gDS
->SetMemorySpaceAttributes (
1021 ASSERT_EFI_ERROR (Status
);
1024 "Updated memory space attribute: [%lu] %016lx - %016lx (%016lx -> %016lx)\r\n",
1025 (UINT64
)Index
, BaseAddress
, BaseAddress
+ Length
- 1,
1026 MemorySpaceMap
[Index
].Attributes
,
1031 PageLength
-= Length
;
1032 MemorySpaceLength
-= Length
;
1033 BaseAddress
+= Length
;
1037 FreePool (MemorySpaceMap
);
1041 Initialize a buffer pool for page table use only.
1043 To reduce the potential split operation on page table, the pages reserved for
1044 page table should be allocated in the times of PAGE_TABLE_POOL_UNIT_PAGES and
1045 at the boundary of PAGE_TABLE_POOL_ALIGNMENT. So the page pool is always
1046 initialized with number of pages greater than or equal to the given PoolPages.
1048 Once the pages in the pool are used up, this method should be called again to
1049 reserve at least another PAGE_TABLE_POOL_UNIT_PAGES. Usually this won't happen
1052 @param[in] PoolPages The least page number of the pool to be created.
1054 @retval TRUE The pool is initialized successfully.
1055 @retval FALSE The memory is out of resource.
1058 InitializePageTablePool (
1066 // Do not allow re-entrance.
1068 if (mPageTablePoolLock
) {
1072 mPageTablePoolLock
= TRUE
;
1076 // Always reserve at least PAGE_TABLE_POOL_UNIT_PAGES, including one page for
1079 PoolPages
+= 1; // Add one page for header.
1080 PoolPages
= ((PoolPages
- 1) / PAGE_TABLE_POOL_UNIT_PAGES
+ 1) *
1081 PAGE_TABLE_POOL_UNIT_PAGES
;
1082 Buffer
= AllocateAlignedPages (PoolPages
, PAGE_TABLE_POOL_ALIGNMENT
);
1083 if (Buffer
== NULL
) {
1084 DEBUG ((DEBUG_ERROR
, "ERROR: Out of aligned pages\r\n"));
1090 "Paging: added %lu pages to page table pool\r\n",
1095 // Link all pools into a list for easier track later.
1097 if (mPageTablePool
== NULL
) {
1098 mPageTablePool
= Buffer
;
1099 mPageTablePool
->NextPool
= mPageTablePool
;
1101 ((PAGE_TABLE_POOL
*)Buffer
)->NextPool
= mPageTablePool
->NextPool
;
1102 mPageTablePool
->NextPool
= Buffer
;
1103 mPageTablePool
= Buffer
;
1107 // Reserve one page for pool header.
1109 mPageTablePool
->FreePages
= PoolPages
- 1;
1110 mPageTablePool
->Offset
= EFI_PAGES_TO_SIZE (1);
1113 // Mark the whole pool pages as read-only.
1115 ConvertMemoryPageAttributes (
1117 (PHYSICAL_ADDRESS
)(UINTN
)Buffer
,
1118 EFI_PAGES_TO_SIZE (PoolPages
),
1121 AllocatePageTableMemory
,
1125 ASSERT (IsModified
== TRUE
);
1128 mPageTablePoolLock
= FALSE
;
1133 This API provides a way to allocate memory for page table.
1135 This API can be called more than once to allocate memory for page tables.
1137 Allocates the number of 4KB pages and returns a pointer to the allocated
1138 buffer. The buffer returned is aligned on a 4KB boundary.
1140 If Pages is 0, then NULL is returned.
1141 If there is not enough memory remaining to satisfy the request, then NULL is
1144 @param Pages The number of 4 KB pages to allocate.
1146 @return A pointer to the allocated buffer or NULL if allocation fails.
1151 AllocatePageTableMemory (
1162 // Renew the pool if necessary.
1164 if (mPageTablePool
== NULL
||
1165 Pages
> mPageTablePool
->FreePages
) {
1166 if (!InitializePageTablePool (Pages
)) {
1171 Buffer
= (UINT8
*)mPageTablePool
+ mPageTablePool
->Offset
;
1173 mPageTablePool
->Offset
+= EFI_PAGES_TO_SIZE (Pages
);
1174 mPageTablePool
->FreePages
-= Pages
;
1180 Special handler for #DB exception, which will restore the page attributes
1181 (not-present). It should work with #PF handler which will set pages to
1184 @param ExceptionType Exception type.
1185 @param SystemContext Pointer to EFI_SYSTEM_CONTEXT.
1190 DebugExceptionHandler (
1191 IN EFI_EXCEPTION_TYPE ExceptionType
,
1192 IN EFI_SYSTEM_CONTEXT SystemContext
1197 BOOLEAN IsWpEnabled
;
1199 MpInitLibWhoAmI (&CpuIndex
);
1202 // Clear last PF entries
1204 IsWpEnabled
= IsReadOnlyPageWriteProtected ();
1206 DisableReadOnlyPageWriteProtect ();
1209 for (PFEntry
= 0; PFEntry
< mPFEntryCount
[CpuIndex
]; PFEntry
++) {
1210 if (mLastPFEntryPointer
[CpuIndex
][PFEntry
] != NULL
) {
1211 *mLastPFEntryPointer
[CpuIndex
][PFEntry
] &= ~(UINT64
)IA32_PG_P
;
1216 EnableReadOnlyPageWriteProtect ();
1220 // Reset page fault exception count for next page fault.
1222 mPFEntryCount
[CpuIndex
] = 0;
1230 // Clear TF in EFLAGS
1232 if (mPagingContext
.MachineType
== IMAGE_FILE_MACHINE_I386
) {
1233 SystemContext
.SystemContextIa32
->Eflags
&= (UINT32
)~BIT8
;
1235 SystemContext
.SystemContextX64
->Rflags
&= (UINT64
)~BIT8
;
1240 Special handler for #PF exception, which will set the pages which caused
1241 #PF to be 'present'. The attribute of those pages should be restored in
1242 the subsequent #DB handler.
1244 @param ExceptionType Exception type.
1245 @param SystemContext Pointer to EFI_SYSTEM_CONTEXT.
1250 PageFaultExceptionHandler (
1251 IN EFI_EXCEPTION_TYPE ExceptionType
,
1252 IN EFI_SYSTEM_CONTEXT SystemContext
1257 PAGE_TABLE_LIB_PAGING_CONTEXT PagingContext
;
1258 PAGE_ATTRIBUTE PageAttribute
;
1264 BOOLEAN NonStopMode
;
1266 PFAddress
= AsmReadCr2 () & ~EFI_PAGE_MASK
;
1267 if (PFAddress
< BASE_4KB
) {
1268 NonStopMode
= NULL_DETECTION_NONSTOP_MODE
? TRUE
: FALSE
;
1270 NonStopMode
= HEAP_GUARD_NONSTOP_MODE
? TRUE
: FALSE
;
1274 MpInitLibWhoAmI (&CpuIndex
);
1275 GetCurrentPagingContext (&PagingContext
);
1277 // Memory operation cross page boundary, like "rep mov" instruction, will
1278 // cause infinite loop between this and Debug Trap handler. We have to make
1279 // sure that current page and the page followed are both in PRESENT state.
1282 while (PageNumber
> 0) {
1283 PageEntry
= GetPageTableEntry (&PagingContext
, PFAddress
, &PageAttribute
);
1284 ASSERT(PageEntry
!= NULL
);
1286 if (PageEntry
!= NULL
) {
1287 Attributes
= GetAttributesFromPageEntry (PageEntry
);
1288 if ((Attributes
& EFI_MEMORY_RP
) != 0) {
1289 Attributes
&= ~EFI_MEMORY_RP
;
1290 Status
= AssignMemoryPageAttributes (&PagingContext
, PFAddress
,
1291 EFI_PAGE_SIZE
, Attributes
, NULL
);
1292 if (!EFI_ERROR(Status
)) {
1293 Index
= mPFEntryCount
[CpuIndex
];
1295 // Re-retrieve page entry because above calling might update page
1296 // table due to table split.
1298 PageEntry
= GetPageTableEntry (&PagingContext
, PFAddress
, &PageAttribute
);
1299 mLastPFEntryPointer
[CpuIndex
][Index
++] = PageEntry
;
1300 mPFEntryCount
[CpuIndex
] = Index
;
1305 PFAddress
+= EFI_PAGE_SIZE
;
1311 // Initialize the serial port before dumping.
1313 SerialPortInitialize ();
1315 // Display ExceptionType, CPU information and Image information
1317 DumpCpuContext (ExceptionType
, SystemContext
);
1322 if (mPagingContext
.MachineType
== IMAGE_FILE_MACHINE_I386
) {
1323 SystemContext
.SystemContextIa32
->Eflags
|= (UINT32
)BIT8
;
1325 SystemContext
.SystemContextX64
->Rflags
|= (UINT64
)BIT8
;
1333 Initialize the Page Table lib.
1336 InitializePageTableLib (
1340 PAGE_TABLE_LIB_PAGING_CONTEXT CurrentPagingContext
;
1342 GetCurrentPagingContext (&CurrentPagingContext
);
1345 // Reserve memory of page tables for future uses, if paging is enabled.
1347 if (CurrentPagingContext
.ContextData
.X64
.PageTableBase
!= 0 &&
1348 (CurrentPagingContext
.ContextData
.Ia32
.Attributes
&
1349 PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAE
) != 0) {
1350 DisableReadOnlyPageWriteProtect ();
1351 InitializePageTablePool (1);
1352 EnableReadOnlyPageWriteProtect ();
1355 if (HEAP_GUARD_NONSTOP_MODE
|| NULL_DETECTION_NONSTOP_MODE
) {
1356 mPFEntryCount
= (UINTN
*)AllocateZeroPool (sizeof (UINTN
) * mNumberOfProcessors
);
1357 ASSERT (mPFEntryCount
!= NULL
);
1359 mLastPFEntryPointer
= (UINT64
*(*)[MAX_PF_ENTRY_COUNT
])
1360 AllocateZeroPool (sizeof (mLastPFEntryPointer
[0]) * mNumberOfProcessors
);
1361 ASSERT (mLastPFEntryPointer
!= NULL
);
1364 DEBUG ((DEBUG_INFO
, "CurrentPagingContext:\n", CurrentPagingContext
.MachineType
));
1365 DEBUG ((DEBUG_INFO
, " MachineType - 0x%x\n", CurrentPagingContext
.MachineType
));
1366 DEBUG ((DEBUG_INFO
, " PageTableBase - 0x%x\n", CurrentPagingContext
.ContextData
.X64
.PageTableBase
));
1367 DEBUG ((DEBUG_INFO
, " Attributes - 0x%x\n", CurrentPagingContext
.ContextData
.X64
.Attributes
));