summaryrefslogtreecommitdiff
path: root/MdeModulePkg/Core/Dxe/Mem
AgeCommit message (Collapse)AuthorFilesLines
2026-07-31MdeModulePkg: MemoryBins: make GoogleTest page-granularity awareJeff Brasen1-6/+36
MemoryBinGoogleTest.PopulatesFromValidHob asserted fixed page counts for each memory type. PopulateMemoryTypeInformation, however, rounds the runtime memory types (EfiReservedMemoryType, EfiACPIMemoryNVS, EfiRuntimeServicesCode, EfiRuntimeServicesData) up to RUNTIME_PAGE_ALLOCATION_GRANULARITY. That granularity equals EFI_PAGE_SIZE on IA32/X64, so the hard-coded values happened to match, but it is 64 KiB on AArch64, where the same inputs round up to different page counts and the test failed. Compute the expected page counts with the same granularity rounding the production code uses, so the test passes on all host architectures instead of only x86. Signed-off-by: Jeff Brasen <jbrasen@nvidia.com>
2026-07-09MdeModulePkg: Dxe Core: Correct gMemoryTypeInformation DefinitionOliver Smith-Denny2-2/+2
Commit 43e306806e3c1ed3ad7e9913492732e893cafa0f added support to DXE Core for EfiUnacceptedMemoryType. However, it incorrectly added EFI_GCD_MEMORY_TYPE_UNACCEPTED to gMemoryTypeInformation, which is the GCD memory type that is associated with EfiUnacceptedMemoryType. All other changes from that PR appear correct. This is corrected to the EFI memory type. The Memory Bin Google Test copied this incorrect definition, so it is updated as well. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24MdeModulePkg: MemoryBins: Add GoogleTest and READMEOliver Smith-Denny2-0/+694
This commit adds unit tests and documentation for the Memory Bin feature. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24MdeModulePkg: Dxe Core: Split Memory Bin Logic Into Separate FileOliver Smith-Denny2-381/+646
This commits splits out logic currently contained in Gcd.c and Page.c to a new file called MemoryBin.c. This is set up in preparation to add support to PEI for memory bins (an S4 resume stability feature). MemoryBin.c takes all global state in as parameters so that DXE core can use globals and PEI core can use HOBs. There is no logic change here, just consolidating the functionality to share with PEI. This was requested not to be a library. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24MdeModulePkg: Dxe Core: Add Resource Desc Hob GenerationOliver Smith-Denny1-2/+22
This commit adds a parameter to the memory bin allocation function to tell it whether it should create the Resource Descriptor HOB owned by gMemoryTypeInformationGuid. This will be used by PEI to tell DXE where the memory bins are. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24MdeModulePkg: Dxe Core: Add Stats Init HelperOliver Smith-Denny1-32/+49
This adds a helper function to initialize the memory bin statistics as the same logic is repeated in several places. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24MdeModulePkg: Dxe Core: Prep CoreSetMemoryTypeInformationRange for PEIOliver Smith-Denny1-38/+51
Migrate CoreSetMemoryTypeInformationRange() to not use globals so it can be used in PEI as well. This temporarily moves the EFI_MEMORY_STATISTICS structure to DxeMain.h so that it can be used in Gcd.c as well as Page.c. This will migrate to a different private header once that is included. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24MdeModulePkg: Dxe Core: Add UpdateMemoryStatistics Helper FnOliver Smith-Denny1-25/+83
In preparation for sharing logic with PEI, create a helper function to update the memory bin statistics. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24MdeModulePkg: Dxe Core: Add AllocateMemoryBins Helper FnOliver Smith-Denny1-107/+156
In preparation for sharing logic with PEI for memory bins, add AllocateMemoryTypeInformationBins(). Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-24MdeModulePkg: Dxe Core: Update Bin Size Helper FnOliver Smith-Denny1-2/+2
In preparation for sharing memory bin logic between PEI and DXE, update CaclulateTotalMemoryBinSizeNeeded() to take gMemoryTypeInformation by reference. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-18MdeModulePkg: Dxe Core: Allocate Memory Bins ContiguouslyOliver Smith-Denny1-73/+53
Currently, there is no guarantee that the memory bins will be allocated contiguously. However, there are assumptions in the code that bins are allocated contiguously, such as the GCD init code requiring a free memory region be large enough for a contiguous bin range on DXE Core init. Ensuring contiguous bins also makes a cleaner model for the bins and keeps the memory map in a more standard configuration between different configurations, as platforms today can pass a resource descriptor HOB to DXE core to describe the bin range and this only supports a contiguous range. This also sets up reusing the memory bin logic for PEI memory bin support which will use the aforementioned resource descriptor HOB to pass the bin range to DXE. This commit updates CoreAddMemoryDescriptor() to allocate a contiguous range. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-06-09MdeModulePkg: Replace manual alignment checks with helper macrosMingjie Shen1-2/+2
Replace manual alignment checks with IS_ALIGNED() and ADDRESS_IS_ALIGNED(). Convert the following bitmask and modulo forms: - ((E & ((PowOf2Expr) - ONE)) == ZERO) - ((E & ((PowOf2Expr) - ONE)) != ZERO) - ((E % (PowOf2Expr)) == ZERO) - ((E % (PowOf2Expr)) != ZERO) to the corresponding helper macro forms: + IS_ALIGNED (E, PowOf2Expr) + !IS_ALIGNED (E, PowOf2Expr) PowOf2Expr is limited to known power-of-two expressions, including SIZE_* and BASE_* macros, EFI_PAGE_SIZE, CPU_STACK_ALIGNMENT, RUNTIME_PAGE_ALLOCATION_GRANULARITY, sizeof() of UEFI integer types (e.g. BOOLEAN, CHAR16, UINT32, UINTN) and pointer types, and 1 << E1 expressions. Address checks that cast the checked value to UINTN are written with ADDRESS_IS_ALIGNED(). The change was generated with the Coccinelle semantic patch below. ```smpl @power_of_2_expr@ expression PowOf2Expr; expression E1; typedef BOOLEAN, CHAR8, CHAR16, INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, INTN, UINTN; type ScalarType = { BOOLEAN, CHAR8, CHAR16, INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, INTN, UINTN }; type AnyType; type PointerType = AnyType *; idexpression ScalarType ScalarValue; idexpression PointerType PointerValue; constant SizeBase =~ "^(SIZE|BASE)_(1|2|4|8|16|32|64|128|256|512)[KMGTPE]B$"; constant NamedPowerOf2 =~ "^(EFI_PAGE_SIZE|CPU_STACK_ALIGNMENT|RUNTIME_PAGE_ALLOCATION_GRANULARITY)$"; constant ONE = {1, 1U, 1u}; @@ ( ( SizeBase | NamedPowerOf2 | ONE << E1 | sizeof (ScalarType) | sizeof (PointerType) | sizeof (ScalarValue) | sizeof (PointerValue) ) & PowOf2Expr ) @aligned depends on power_of_2_expr disable is_zero,isnt_zero@ expression E; expression power_of_2_expr.PowOf2Expr; constant ONE = {1, 1U, 1u}; constant ZERO = {0, 0U, 0u}; @@ ( ((E & (E - ONE)) == ZERO) | - ((E & ((PowOf2Expr) - ONE)) == ZERO) + IS_ALIGNED (E, PowOf2Expr) | ((E & (E - ONE)) != ZERO) | - ((E & ((PowOf2Expr) - ONE)) != ZERO) + !IS_ALIGNED (E, PowOf2Expr) | - ((E % (PowOf2Expr)) == ZERO) + IS_ALIGNED (E, PowOf2Expr) | - ((E % (PowOf2Expr)) != ZERO) + !IS_ALIGNED (E, PowOf2Expr) ) @address_is_aligned@ typedef UINTN; expression *Address; expression Alignment; @@ - IS_ALIGNED ((UINTN) Address, Alignment) + ADDRESS_IS_ALIGNED (Address, Alignment) @normalize_aligned disable paren expression@ expression E, SZ; @@ ( - (IS_ALIGNED (E, SZ)) + IS_ALIGNED (E, SZ) | - (!IS_ALIGNED (E, SZ)) + !IS_ALIGNED (E, SZ) ) @normalize_macro_args disable paren expression@ expression E, SZ; @@ ( - IS_ALIGNED ((E), SZ) + IS_ALIGNED (E, SZ) | - IS_ALIGNED (E, (SZ)) + IS_ALIGNED (E, SZ) ) ``` Signed-off-by: Mingjie Shen <shen497@purdue.edu>
2026-06-08MdeModulePkg: Dxe Core: Use CalculateTotalMemoryBinSizeNeeded()Oliver Smith-Denny1-57/+4
CoreSetMemoryTypeInformationRange() currently calculates the bin size needed independently from the CalculateTotalMemoryBinSizeNeeded() function. This commit updates to use that function and remove the duplication. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-04-23MdeModulePkg: Don't Allow Guard Pages to Cross Bin BoundariesOliver Smith-Denny3-32/+79
Currently, the DXE page allocator does not ensure that guard page allocations stay within the bin that it is attempting to allocate within. As a result, S4 resume is jeopardized by bins expanding due to guard pages, either into other bins or out of bins. This is caught by a new assert in CoreGetMemoryMap() to ensure the bins are correct. This fixes this by changing the internal heap guard API to return the adjusted size and start address of a proposed allocation. The page allocator then can ensure that the adjusted allocation still fits within the bin it is attempting to allocate within; if not, it will search for another descriptor. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2026-02-28MdeModulePkg: DxeMain: Check memory type overlap inside CoreGetMemoryMapKun Qin1-0/+115
This change adds validation to CoreGetMemoryMap to ensure that special memory bins are fully respected. Specifically, any memory map entry that falls within a special bin must be entirely contained within that bin, and its memory type must match the bin's designated type. This check helps preventing unintended changes that could cause the system memory map to cross bin boundaries unexpectedly. Signed-off-by: Kun Qin <kun.qin@microsoft.com>
2026-02-24MdeModulePkg: Replace include guards with #pragma onceMichael Kubacki2-7/+2
Replace traditional `#ifndef`/`#define`/`#endif` include guards with `#pragma` once. `#pragma once` is a widely supported preprocessor directive that prevents header files from being included multiple times. It is supported by all toolchains used to build edk2: GCC, Clang/LLVM, and MSVC. Compared to macro-based include guards, `#pragma once`: - Eliminates the risk of macro name collisions or copy/paste errors where two headers inadvertently use the same guard macro. - Eliminate inconsistency in the way include guard macros are named (e.g., some files use `__FILE_H__`, others use `FILE_H_`, etc.). - Reduces boilerplate (three lines replaced by one). - Avoids polluting the macro namespace with guard symbols. - Can improve build times as the preprocessor can skip re-opening the file entirely, rather than re-reading it to find the matching `#endif` ("multiple-include optimization"). - Note that some compilers may already optimize traditional include guards, by recognzining the idiomatic pattern. This change is made acknowledging that overall portability of the code will technically be reduced, as `#pragma once` is not part of the C/C++ standards. However, this is considered acceptable given: 1. edk2 already defines a subset of supported compilers in BaseTools/Conf/tools_def.template, all of which have supported `#pragma once` for over two decades. 2. There have been concerns raised to the project about inconsistent include guard naming and potential macro collisions. Approximate compiler support dates: - MSVC: Supported since Visual C++ 4.2 (1996) - GCC: Supported since 3.4 (2004) (http://gnu.ist.utl.pt/software/gcc/gcc-3.4/changes.html) - Clang (LLVM based): Since initial release in 2007 Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com>
2026-01-28MdeModulePkg/Core/Dxe/Mem: Fix GetMemoryMap() Alignment IssuesMichael D Kinney1-32/+257
Fix alignment issues in memory map entries returned by GetMemoryMap() when RUNTIME_PAGE_ALLOCATION_GRANULARITY is larger than DEFAULT_PAGE_ALLOCATION_GRANULARITY. There are no issues in the Page/Pool Allocation/Free services. Logic issues issues are addressed in the memory map returned by GetMemoryMap() due to missing cases for memory map entries of type EfiConventionalMemory that overlap special memory bins. Add logic to handle all possible memory map splits required to convert internal memory map entries into an EFI Memory Map with EFI Memory Map entries the follow alignment requirements when the EFI Memory Map entries cover memory bins. The four cases that must be handled are: * Memory map entry contained within a bin. [Already covered] Convert memory map entry type * Memory map entry overlaps beginning of bin. [Added] Split memory map entry at beginning of bin. * Memory map entry overlaps end of bin. [Added] Split memory map entry at end of bin. * Memory map entry overlaps entire bin. [Added] Split memory map entry at both ends of bin. Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2026-01-28MdeModulePkg/Core/Dxe/Mem: Align initial memory map entriesMichael D Kinney1-5/+63
Fix alignment issues in memory map entries returned by GetMemoryMap() when RUNTIME_PAGE_ALLOCATION_GRANULARITY is larger than DEFAULT_PAGE_ALLOCATION_GRANULARITY. Alignment issues are addressed in the initial memory map layout when Memory Type Information is provided with memory bins that use RUNTIME_PAGE_ALLOCATION_GRANULARITY. There are no issues in the Page/Pool Allocation/Free services. * CoreSetMemoryTypeInformationRange() make sure there is room for all bins when accounting for alignment requirements. Allocate space for bins with base and length following alignment requirements. * CoreSetMemoryTypeInformationRange() round up NumberOfPages in Memory Type Information based on alignment requirements. This is required so GetMemoryMap() will generate memory map entries that always follow alignment requirements. * CoreAddMemoryDescriptor() round up NumberOfPages in Memory Type Information based on alignment requirements. This is required so GetMemoryMap() will generate memory map entries that always follow alignment requirements. Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com>
2025-12-30MdeModulePkg: Fix FreePages not existent memoryPiotr Wejman1-1/+3
Commit 2d69507a4dde02f1abf20c7eb3a43d1d3ef6b98f added an attribute check to prevent freeing memory that is read-only, read-protected, or for which attribute retrieval fails. In such cases the code returned EFI_SUCCESS and leaked the memory. This introduced a regression in the System Architecture Compliance Suite (ACS) BS.FreePages – Not Existent Memory test. Link: https://github.com/tianocore/edk2-test/blob/edk2-test-stable202509/uefi-sct/Doc/TestCaseSpec/03_Services_Boot_Services.md#freepages Test number: 5.1.2.2.1 GetMemoryAttributes() returns EFI_UNSUPPORTED for memory regions outside system memory. The previous change treated all errors as a reason to leak memory, while only the EFI_NO_MAPPING error code should trigger that behavior. As a result, freeing non-existent memory incorrectly returned EFI_SUCCESS instead of EFI_NOT_FOUND. To fix this, memory is now leaked only when: - GetMemoryAttributes() returns EFI_NO_MAPPING (inconsistent attributes), or - GetMemoryAttributes() succeeds and the pages are marked RO or RP. All other errors fall through to CoreInternalFreePages(), restoring the previous and correct behavior. Signed-off-by: Piotr Wejman <piotr.wejman@arm.com>
2025-11-22MdeModulePkg: Fix missing NULL tests.Aaron Pop3-5/+20
https://github.com/github/codeql/blob/codeql-cli-2.7.3/cpp/ql/src/Critical/MissingNullTest.qhelp For items which allocate memory, or get a pointer from another structure, it is important to validate that the pointers are not null before they are dereferenced. Signed-off-by: Aaron Pop <aaronpop@microsoft.com>
2025-11-06MdeModulePkg: CoreDxe: Handle multilple MemoryAllocationModulesKun Qin1-1/+3
The current implementation from Dxe/Image/Image.c does not handle the configuration where there might be multiple MemoryAllocationModules. Given that the `ModuleName` is included in the hob data and used for targetting the consumer, DXE core should specify the GUID when looking up for its own MemoryAllocationModule. This change adds a check to ensure the located hob is targetting DXE core. Signed-off-by: Kun Qin <kuqin12@gmail.com>
2025-10-17MdeModulePkg: CoreGetMemoryMap: Account for Unaccepted EntriesOliver Smith-Denny1-0/+1
Commit 43e306806e3c1ed3ad7e9913492732e893cafa0f added EFIGcdMemoryTypeUnaccepted (as it was later renamed) to be returned in the EFI_MEMORY_MAP. However, it did not add it to the number of entries calculation, so if any EfiGcdMemoryTypeUnaccepted entries exist in the GCD they will overflow the EFI_MEMORY_MAP buffer provided by the bootloader. This resolves that by accounting for unaccepted entries in the number of entries calculation. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2025-07-09MdeModulePkg: Leak Memory if Not RW on FreePagesOliver Smith-Denny1-0/+32
Currently, if the DebugClearMemory bit is set in the PcdDebugPropertyMask, CoreConvertPagesEx will attempt to write a pattern to the pages being freed. However, it does not check that the page is writeable, which will cause a page fault if not. Furthermore, if NX protections are not enabled, the core does not ensure that any freed pages are RW, which is the state expected when they are allocated next. If they are not RW, the allocating driver will crash trying to use them. This patch updates the page freeing code to query the memory attributes protocol, if present, for the attributes. If this call fails or the attributes are not RW at a minimum, the core leaks the memory (returning success to the caller). If the memory attribute protocol is not present (either because a platform doesn't produce it or it is before the protocol has been produced, the core continues with freeing memory. This is either before the CPU Arch protocol is available (so drivers can't change memory attributes) or otherwise matches existing behavior. This was deemed the best approach to let memory that can't be guaranteed to be RW leak instead of letting a driver crash when allocating it. It was deemed less brittle to simply leak the memory instead of attempting to change the attributes. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2025-07-08MdeModulePkg: Don't Allocate Page 0Oliver Smith-Denny1-0/+5
Currently DxeIpl attempts to set page 0 to all 0's and to create a memory allocation HOB for it. However, DxeIpl will also unmap the page when mapping page tables and if null detection is not enabled, DxeCore will set the page to 0, regardless of allocation status. Because no consumers are using the memory allocation HOB for page 0, drop it. Instead, ensure that PeiCore and DxeCore do not allow allocating page 0; it should always be reserved for null pointer detection. It also complicates the story for platforms that are attempting to audit the system and ensure that no modules are using page 0. With these memory allocation HOBs in place, it is difficult to tell if it is simply DxeIpl who has allocated the memory or another module. This commit drops the memory allocation HOB publishing and ensures that DxeCore and PeiCore do not allocate page 0. DxeCore already will not allocate page 0 to callers of AllocatePages who call with a type other than AllocateAddress, this just changes so that AllocateAddress cannot allocate at page 0 (which if null detection is enabled will cause a page fault). PeiCore does not have AllocateAddress and so this ensures standard allocations do not receive page 0. Signed-off-by: Oliver Smith-Denny <osde@microsoft.com>
2024-07-26MdeModulePkg: Remove EFI_MEMORY_* DefinesDmitry Antipov1-16/+0
Now that all of the EFI_MEMORY_* defines live in the EFI_MEMORY_TYPE enum, remove the old defines. Signed-off-by: Oliver Smith-Denny <osde@linux.microsoft.com>
2024-07-17MdeModulePkg: DxeCore: Fix Use-After-Free guard causing page faultKun Qin1-23/+28
REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2411 With Use-After-Free heap guard feature enabled, the DxeCore would blindly attempt to "level-up" when the `GuardAllFreedPages` inspect a non-max level table entry from the last loop. This could cause the next round of inspection to dereference a potentially null pointer and as such causing a page fault. This change adds a null pointer check to prevent such case from happening. Cc: Liming Gao <gaoliming@byosoft.com.cn> Signed-off-by: Kun Qin <kun.qin@microsoft.com>
2024-06-19MdeModulePkg: Avoid efi memory allocation for SP memoryDhaval1-0/+7
HBM/CXL memory systems are treated as special purpose memories. In many cases it is desirable not to use special purpose memory for regular edk2 usages as these memories (HBm/CXL) are either meant for special purposes or are less reliable to be used. Until such memory systems evolve and we have better clarity from UEFI spec, avoid using them for edk2 boot memory purposes. Cc: Liming Gao <gaoliming@byosoft.com.cn> Cc: Michael Kinney <michael.d.kinney@intel.com> Cc: Oliver Smith-Denny <osde@linux.microsoft.com> Signed-off-by: Dhaval Sharma <dhaval@rivosinc.com> Co-authored-by: Tim Wawrzynczak <tim@rivosinc.com>
2024-05-08MdeModulePkg: Use newly defined Unaccepted Memory TypeSachin Ganesh1-19/+19
EFI_RESOURCE_MEMORY_UNACCEPTED has been officially defined in the PI 1.8 specification. So all temporary solutions have been replaced with the actual definition. Cc: Felix Polyudov <felixp@ami.com> Cc: Dhanaraj V <vdhanaraj@ami.com> Cc: Liming Gao <gaoliming@byosoft.com.cn> Signed-off-by: Sachin Ganesh <sachinganesh@ami.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
2024-03-14MdeModulePkg: DxeCore: Do Not Apply Guards to Unsupported TypesOliver Smith-Denny3-0/+36
Currently, there are multiple issues when page or pool guards are allocated for runtime memory regions that are aligned to non-EFI_PAGE_SIZE alignments. Multiple other issues have been fixed for these same systems (notably ARM64 which has a 64k runtime page allocation granularity) recently. The heap guard system is only built to support 4k guard pages and 4k alignment. Today, the address returned to a caller of AllocatePages will not be aligned correctly to the runtime page allocation granularity, because the heap guard system does not take non-4k alignment requirements into consideration. However, even with this bug fixed, the Memory Allocation Table cannot be produced and an OS with a larger than 4k page granularity will not have aligned memory regions because the guard pages are reported as part of the same memory allocation. So what would have been, on an ARM64 system, a 64k runtime memory allocation is actually a 72k memory allocation as tracked by the Page.c code because the guard pages are tracked as part of the same allocation. This is a core function of the current heap guard architecture. This could also be fixed with rearchitecting the heap guard system to respect alignment requirements and shift the guard pages inside of the outer rounded allocation or by having guard pages be the runtime granularity. Both of these approaches have issues. In the former case, we break UEFI spec 2.10 section 2.3.6 for AARCH64, which states that each 64k page for runtime memory regions may not have mixed memory attributes, which pushing the guard pages inside would create. In the latter case, an immense amount of memory is wasted to support such large guard pages, and with pool guard many systems could not support an additional 128k allocation for all runtime memory. The simpler and safer solution is to disallow page and pool guards for runtime memory allocations for systems that have a runtime granularity greater than the EFI_PAGE_SIZE (4k). The usefulness of such guards is limited, as OSes do not map guard pages today, so there is only boot time protection of these ranges. This also prevents other bugs from being exposed by using guards for regions that have a non-4k alignment requirement, as again, multiple have cropped up because the heap guard system was not built to support it. This patch adds both a static assert to ensure that either the runtime granularity is the EFI_PAGE_SIZE or that the PCD bits are not set to enable heap guard for runtime memory regions. It also adds a check in the page and pool allocation system to ensure that at runtime we are not allocating a runtime region and attempt to guard it (the PCDs are close to being removed in favor of dynamic heap guard configurations). BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4674 Github PR: https://github.com/tianocore/edk2/pull/5382 Cc: Leif Lindholm <quic_llindhol@quicinc.com> Cc: Ard Biesheuvel <ardb+tianocore@kernel.org> Cc: Sami Mujawar <sami.mujawar@arm.com> Cc: Liming Gao <gaoliming@byosoft.com.cn> Signed-off-by: Oliver Smith-Denny <osde@linux.microsoft.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
2024-03-14MdeModulePkg: DxeCore: Correct Runtime Granularity Memory TypeOliver Smith-Denny2-4/+4
Per the UEFI spec 2.10, section 2.3.6 (for the AARCH64 arch, other architectures in section two confirm the same) the memory types that need runtime page allocation granularity are EfiReservedMemoryType, EfiACPIMemoryNVS, EfiRuntimeServicesCode, and EfiRuntimeServicesData. However, legacy code was setting runtime page allocation granularity for EfiACPIReclaimMemory and not EfiReservedMemoryType. This patch fixes that error. Cc: Leif Lindholm <quic_llindhol@quicinc.com> Cc: Ard Biesheuvel <ardb+tianocore@kernel.org> Cc: Sami Mujawar <sami.mujawar@arm.com> Cc: Liming Gao <gaoliming@byosoft.com.cn> Signed-off-by: Oliver Smith-Denny <osde@linux.microsoft.com> Suggested-by: Ard Biesheuvel <ardb+tianocore@kernel.org> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
2024-03-14MdeModulePkg: DxeCore: Fix CodeQL Error in FreePagesOliver Smith-Denny1-1/+6
CodeQL flags the Free Pages logic for not ensuring that Entry is non-null before using it. Add a check for this and appropriately bail out if we hit this case. Cc: Liming Gao <gaoliming@byosoft.com.cn> Signed-off-by: Oliver Smith-Denny <osde@linux.microsoft.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
2024-01-30MdeModulePkg/Core/Dxe: Set MemoryTypeInfo bin range from HOBMichael D Kinney1-0/+102
Provide an optional method for PEI to declare a specific address range to use for the Memory Type Information bins. The current algorithm uses heuristics that tends to place the Memory Type Information bins in the same location, but memory configuration changes across boots or algorithm changes across a firmware updates could potentially change the Memory Type Information bin location. If the bin locations move across an S4 save/resume cycle, then the S4 resume may fail. Enabling this feature increases the number of scenarios that an S4 resume operation may succeed. If the HOB List contains a Resource Descriptor HOB that describes tested system memory and has an Owner GUID of gEfiMemoryTypeInformationGuid, then use the address range described by the Resource Descriptor HOB as the preferred location of the Memory Type Information bins. If this HOB is not detected, then the current behavior is preserved. The HOB with an Owner GUID of gEfiMemoryTypeInformationGuid is ignored for the following conditions: * The HOB with an Owner GUID of gEfiMemoryTypeInformationGuid is smaller than the Memory Type Information bins. * The HOB list contains more than one Resource Descriptor HOB with an owner GUID of gEfiMemoryTypeInformationGuid. * The Resource Descriptor HOB with an Owner GUID of gEfiMemoryTypeInformationGuid is the same Resource Descriptor HOB that that describes the PHIT memory range. Cc: Liming Gao <gaoliming@byosoft.com.cn> Cc: Aaron Li <aaron.li@intel.com> Cc: Liu Yun <yun.y.liu@intel.com> Cc: Andrew Fish <afish@apple.com> Cc: Laszlo Ersek <lersek@redhat.com> Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn> Reviewed-by: Laszlo Ersek <lersek@redhat.com>
2023-09-19MdeModulePkg: Memory Bin Range Update Accounts for Guard PageTaylor Beebe1-1/+1
When finding a free page range for allocation, if the found range starts below the tracked memory bin address range, the lowest memory bin address is updated which will not include the guard page if present. When CoreConvertPagesWithGuard() is called on the range being allocated, the memory range is adjusted to include guard pages which can push it out of the memory bin address range and cause the memory type statistics to be unaltered. This patch updates the lowest memory bin address range to account for the guard page if NeedGuard is TRUE so the memory type statistics are updated correctly. Cc: Jian J Wang <jian.j.wang@intel.com> Cc: Liming Gao <gaoliming@byosoft.com.cn> Cc: Dandan Bi <dandan.bi@intel.com> Signed-off-by: Taylor Beebe <t@taylorbeebe.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
2023-08-19MdeModulePkg: HeapGuard: Don't Assume Pool Head Allocated In First PageOliver Smith-Denny3-5/+18
Currently, HeapGuard, when in the GuardAlignedToTail mode, assumes that the pool head has been allocated in the first page of memory that was allocated. This is not the case for ARM64 platforms when allocating runtime pools, as RUNTIME_PAGE_ALLOCATION_GRANULARITY is 64k, unlike X64, which has RUNTIME_PAGE_ALLOCATION_GRANULARITY as 4k. When a runtime pool is allocated on ARM64, the minimum number of pages allocated is 16, to match the runtime granularity. When a small pool is allocated and GuardAlignedToTail is true, HeapGuard instructs the pool head to be placed as (MemoryAllocated + EFI_PAGES_TO_SIZE(Number of Pages) - SizeRequiredForPool). This gives this scenario: |Head Guard|Large Free Number of Pages|PoolHead|TailGuard| When this pool goes to be freed, HeapGuard instructs the pool code to free from (PoolHead & ~EFI_PAGE_MASK). However, this assumes that the PoolHead is in the first page allocated, which as shown above is not true in this case. For the 4k granularity case (i.e. where the correct number of pages are allocated for this pool), this logic does work. In this failing case, HeapGuard then instructs the pool code to free 16 (or more depending) pages from the page the pool head was allocated on, which as seen above means we overrun the pool and attempt to free memory far past the pool. We end up running into the tail guard and getting an access flag fault. This causes ArmVirtQemu to fail to boot with an access flag fault when GuardAlignedToTail is set to true (and pool guard enabled for runtime memory). It should also cause all ARM64 platforms to fail in this configuration, for exactly the same reason, as this is core code making the assumption. This patch removes HeapGuard's assumption that the pool head is allocated on the first page and instead undoes the same logic that HeapGuard did when allocating the pool head in the first place. With this patch in place, ArmVirtQemu boots with GuardAlignedToTail set to true (and when it is false, also). BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4521 Github PR: https://github.com/tianocore/edk2/pull/4731 Cc: Leif Lindholm <quic_llindhol@quicinc.com> Cc: Ard Biesheuvel <ardb+tianocore@kernel.org> Cc: Jian J Wang <jian.j.wang@intel.com> Cc: Liming Gao <gaoliming@byosoft.com.cn> Cc: Dandan Bi <dandan.bi@intel.com> Signed-off-by: Oliver Smith-Denny <osde@linux.microsoft.com> Reviewed-by: Ard Biesheuvel <ardb@kernel.org> Acked-by: Leif Lindholm <quic_llindhol@quicinc.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
2023-04-03MdeModulePkg: Fix conditionally uninitialized variablesMichael Kubacki1-8/+9
Fixes CodeQL alerts for CWE-457: https://cwe.mitre.org/data/definitions/457.html Cc: Dandan Bi <dandan.bi@intel.com> Cc: Eric Dong <eric.dong@intel.com> Cc: Erich McMillan <emcmillan@microsoft.com> Cc: Guomin Jiang <guomin.jiang@intel.com> Cc: Jian J Wang <jian.j.wang@intel.com> Cc: Liming Gao <gaoliming@byosoft.com.cn> Cc: Michael Kubacki <mikuback@linux.microsoft.com> Cc: Ray Ni <ray.ni@intel.com> Cc: Zhichao Gao <zhichao.gao@intel.com> Co-authored-by: Erich McMillan <emcmillan@microsoft.com> Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn> Reviewed-by: Oliver Smith-Denny <osd@smith-denny.com>
2023-02-07MdeModulePkg: EfiUnacceptedMemoryType is not allowed in AllocatePoolMin M Xu1-1/+1
BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=4315 MemoryType of EfiUnacceptedMemoryType should not be allocated in AllocatePool. Instead it should return EFI_INVALID_PARAMETER. Cc: Liming Gao <gaoliming@byosoft.com.cn> Cc: Dandan Bi <dandan.bi@intel.com> Cc: Erdem Aktas <erdemaktas@google.com> Cc: James Bottomley <jejb@linux.ibm.com> Cc: Jiewen Yao <jiewen.yao@intel.com> Cc: Gerd Hoffmann <kraxel@redhat.com> Cc: Tom Lendacky <thomas.lendacky@amd.com> Cc: Michael Roth <michael.roth@amd.com> Reported-by: Liming Gao <gaoliming@byosoft.com.cn> Signed-off-by: Min Xu <min.m.xu@intel.com> Acked-by: Gerd Hoffmann <kraxel@redhat.com> Reviewed-by: Jiewen Yao <Jiewen.yao@intel.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
2022-12-08MdeModulePkg/DxeCore: Use correct type for alignment maskArd Biesheuvel1-1/+1
The page allocator code in CoreFindFreePagesI() uses a mask derived from its UINTN Alignment argument to align the descriptor end address of a MEMORY_MAP entry to the requested alignment, in order to check whether the descriptor covers enough sufficiently aligned area to satisfy the request. However, on 32-bit architectures, 'Alignment' is a 32-bit type, whereas DescEnd is a 64-bit type, and so the resulting operation performed on the end address comes down to masking with 0xfffff000 instead of the intended 0xffffffff_fffff000. Given the -1 at the end of the expression, the resulting address is 0xffffffff_fffffffff for any descriptor that ends on a 4G aligned boundary, and this is certainly not what was intended. So cast Alignment to UINT64 to ensure that the mask has the right size. Signed-off-by: Ard Biesheuvel <ardb@kernel.org> Reported-by: Nathan Chancellor <nathan@kernel.org> Reviewed-by: Michael D Kinney <michael.d.kinney@intel.com>
2022-11-01MdeModulePkg: Update Dxe to handle unaccepted memory typeMin M Xu1-17/+46
RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3937 Unaccepted memory is a kind of new memory type, CoreInitializeGcdServices() and CoreGetMemoryMap() are updated to handle the unaccepted memory type. Ref: microsoft/mu_basecore@97e9c31 Cc: Jian J Wang <jian.j.wang@intel.com> Cc: Liming Gao <gaoliming@byosoft.com.cn> Cc: Ray Ni <ray.ni@intel.com> Cc: Erdem Aktas <erdemaktas@google.com> Cc: Gerd Hoffmann <kraxel@redhat.com> Cc: James Bottomley <jejb@linux.ibm.com> Cc: Jiewen Yao <jiewen.yao@intel.com> Cc: Tom Lendacky <thomas.lendacky@amd.com> Acked-by: Gerd Hoffmann <kraxel@redhat.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn> Signed-off-by: Min Xu <min.m.xu@intel.com>
2022-07-22MdeModulePkg/CoreDxe: Allow DXE Drivers to use untested memoryStacy Howell1-0/+14
REF: https://https://bugzilla.tianocore.org/show_bug.cgi?id=3795 Cc: Dandan Bi <dandan.bi@intel.com> Cc: Liming Gao <gaoliming@byosoft.com.cn> Updated CoreInternalAllocatePages() to call PromoteMemoryResource() and re-attempt the allocation if unable to convert the specified memory range Signed-off-by: Stacy Howell <stacy.howell@intel.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
2021-12-07MdeModulePkg: Apply uncrustify changesMichael Kubacki7-1178/+1256
REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3737 Apply uncrustify changes to .c/.h files in the MdeModulePkg package Cc: Andrew Fish <afish@apple.com> Cc: Leif Lindholm <leif@nuviainc.com> Cc: Michael D Kinney <michael.d.kinney@intel.com> Signed-off-by: Michael Kubacki <michael.kubacki@microsoft.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
2021-12-07MdeModulePkg: Change use of EFI_D_* to DEBUG_*Michael D Kinney1-1/+1
REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3739 Update all use of EFI_D_* defines in DEBUG() macros to DEBUG_* defines. Cc: Andrew Fish <afish@apple.com> Cc: Leif Lindholm <leif@nuviainc.com> Cc: Michael Kubacki <michael.kubacki@microsoft.com> Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
2020-10-10MdeModulePkg/Core/Dxe: expose SP and CRYPTO capabilities in UEFI memmapMalgorzata Kukiello1-6/+6
OSs are now capable of treating SP and CRYPTO memory as true capabilities and therefore these should be exposed. This requires usage of a separate ACCESS_MASK to hide all page-access permission capabilities. Change in masking and hiding of SP and CRYPTO was introduced in 3bd5c994c879f78e8e3d5346dc3b627f199291aa Signed-off-by: Malgorzata Kukiello <jacek.kukiello@intel.com> Cc: Jian J Wang <jian.j.wang@intel.com> Cc: Hao A Wu <hao.a.wu@intel.com> Cc: Dandan Bi <dandan.bi@intel.com> Cc: Liming Gao <gaoliming@byosoft.com.cn> Cc: Oleksiy Yakovlev <oleksiyy@ami.com> Cc: Ard Biesheuvel (ARM address) <ard.biesheuvel@arm.com> Reviewed-by: Laszlo Ersek <lersek@redhat.com> Reviewed-by: Liming Gao <gaoliming@byosoft.com.cn>
2020-07-15MdeModulePkg: Add New Memory AttributesOleksiy Yakovlev1-6/+3
Add usage of EFI_MEMORY_SP and EFI_MEMORY_CPU_CRYPTO attributes introduced in UEFI 2.8 (UEFI 2.8, mantis 1919 and 1872) Use attributes bitmasks, defined in MdePkg. Signed-off-by: Oleksiy Yakovlev <oleksiyy@ami.com> Reviewed-by: Laszlo Ersek <lersek@redhat.com> Message-Id: <20200702205039.52400-3-oleksiyy@ami.com> Reviewed-by: Dandan Bi <dandan.bi@intel.com> Tested-by: Laszlo Ersek <lersek@redhat.com>
2019-11-04MdeModulePkg/Mem: Initialize the variable MapMemoryShenglei Zhang1-0/+2
MapMemory is not initialized by FindGuardedMemoryMap or CoreInternalAllocatePages which calls MapMemory. So we give a 0 to it. Cc: Dandan Bi <dandan.bi@intel.com> Cc: Liming Gao <liming.gao@intel.com> Signed-off-by: Shenglei Zhang <shenglei.zhang@intel.com> Reviewed-by: Dandan Bi <dandan.bi@intel.com>
2019-08-20MdeModulePkg DxeCore: Fix for missing Memory Attributes Table (MAT) updateMike Turner1-6/+35
The Fpdt driver (FirmwarePerformanceDxe) saves a memory address across reboots, and then does an AllocatePage for that memory address. If, on this boot, that memory comes from a Runtime memory bucket, the MAT table is not updated. This causes Windows to boot into Recovery. This patch blocks the memory manager from changing the page from a special bucket to a different memory type. Once the buckets are allocated, we freeze the memory ranges for the OS, and fragmenting the special buckets will cause errors resuming from hibernate (S4). The references to S4 here are the use case that fails. This failure is root caused to an inconsistent behavior of the core memory services themselves when type AllocateAddress is used. The main issue is apparently with the UEFI memory map -- the UEFI memory map reflects the pre-allocated bins, but the actual allocations at fixed addresses may go out of sync with that. Everything else, such as: - EFI_MEMORY_ATTRIBUTES_TABLE (page protections) being out of sync, - S4 failing are just symptoms / consequences. This patch is cherry pick from Project Mu: https://github.com/microsoft/mu_basecore/commit/a9be767d9be96af94016ebd391ea6f340920735a With the minor change, 1. Update commit message format to keep the message in 80 characters one line. 2. Remove // MU_CHANGE comments in source code. 3. Update comments style to follow edk2 style. Cc: Jian J Wang <jian.j.wang@intel.com> Cc: Hao A Wu <hao.a.wu@intel.com> Cc: Dandan Bi <dandan.bi@intel.com> Cc: Laszlo Ersek <lersek@redhat.com> Signed-off-by: Liming Gao <liming.gao@intel.com> Acked-by: Laszlo Ersek <lersek@redhat.com> Reviewed-by: Dandan Bi <dandan.bi@intel.com> Acked-by: Hao A Wu <hao.a.wu@intel.com>
2019-04-09MdeModulePkg: Replace BSD License with BSD+Patent LicenseMichael D Kinney7-49/+7
https://bugzilla.tianocore.org/show_bug.cgi?id=1373 Replace BSD 2-Clause License with BSD+Patent License. This change is based on the following emails: https://lists.01.org/pipermail/edk2-devel/2019-February/036260.html https://lists.01.org/pipermail/edk2-devel/2018-October/030385.html RFCs with detailed process for the license change: V3: https://lists.01.org/pipermail/edk2-devel/2019-March/038116.html V2: https://lists.01.org/pipermail/edk2-devel/2019-March/037669.html V1: https://lists.01.org/pipermail/edk2-devel/2019-March/037500.html Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com> Reviewed-by: Hao Wu <hao.a.wu@intel.com> Reviewed-by: Jian J Wang <jian.j.wang@intel.com>
2018-12-20MdeModulePkg/Dxe/Page: take MAX_ALLOC_ADDRESS into accountArd Biesheuvel1-26/+26
Take MAX_ALLOC_ADDRESS into account in the implementation of the page allocation routines, so that they will only return memory that is addressable by the CPU at boot time, even if more memory is available in the GCD memory map. Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Ard Biesheuvel <ard.biesheuvel@linaro.org> Reviewed-by: Jian J Wang <jian.j.wang@intel.com>
2018-10-27MdeModulePkg/Core: correct one coding styleJian J Wang1-1/+1
REF: https://bugzilla.tianocore.org/show_bug.cgi?id=1284 Non-Boolean comparisons should use a compare operator (==, !=, >, < >=, <=) Cc: Dandan Bi <dandan.bi@intel.com> Cc: Star Zeng <star.zeng@intel.com> Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jian J Wang <jian.j.wang@intel.com> Reviewed-by: Dandan Bi <dandan.bi@intel.com>
2018-10-26MdeModulePkg/Core: fix an IA32 build failureJian J Wang1-5/+5
REF: https://bugzilla.tianocore.org/show_bug.cgi?id=1277 The failure is caused by data type conversion between UINTN and UINT64, which is checked in at 63ebde8ef6d4ff497d054ccc010904ecd4441198. Cc: Star Zeng <star.zeng@intel.com> Cc: Liming Gao <liming.gao@intel.com> Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jian J Wang <jian.j.wang@intel.com> Reviewed-by: Star Zeng <star.zeng@intel.com>
2018-10-26MdeModulePkg/Core: add freed-memory guard featureJian J Wang4-23/+516
Freed-memory guard is used to detect UAF (Use-After-Free) memory issue which is illegal access to memory which has been freed. The principle behind is similar to pool guard feature, that is we'll turn all pool memory allocation to page allocation and mark them to be not-present once they are freed. This also implies that, once a page is allocated and freed, it cannot be re-allocated. This will bring another issue, which is that there's risk that memory space will be used out. To address it, the memory service add logic to put part (at most 64 pages a time) of freed pages back into page pool, so that the memory service can still have memory to allocate, when all memory space have been allocated once. This is called memory promotion. The promoted pages are always from the eldest pages which haven been freed. This feature brings another problem is that memory map descriptors will be increased enormously (200+ -> 2000+). One of change in this patch is to update MergeMemoryMap() in file PropertiesTable.c to allow merge freed pages back into the memory map. Now the number can stay at around 510. Cc: Star Zeng <star.zeng@intel.com> Cc: Michael D Kinney <michael.d.kinney@intel.com> Cc: Jiewen Yao <jiewen.yao@intel.com> Cc: Ruiyu Ni <ruiyu.ni@intel.com> Cc: Laszlo Ersek <lersek@redhat.com> Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jian J Wang <jian.j.wang@intel.com> Reviewed-by: Star Zeng <star.zeng@intel.com>