diff --git a/MdeModulePkg/Core/Pei/Memory/MemoryServices.c b/MdeModulePkg/Core/Pei/Memory/MemoryServices.c index 59613e5131..65e3405e9c 100644 --- a/MdeModulePkg/Core/Pei/Memory/MemoryServices.c +++ b/MdeModulePkg/Core/Pei/Memory/MemoryServices.c @@ -555,6 +555,7 @@ PeiAllocatePages ( EFI_PHYSICAL_ADDRESS *FreeMemoryTop; EFI_PHYSICAL_ADDRESS *FreeMemoryBottom; UINTN RemainingPages; + UINTN RemainingMemory; UINTN Granularity; UINTN Padding; @@ -636,24 +637,18 @@ PeiAllocatePages ( // // Verify that there is sufficient memory to satisfy the allocation. // - RemainingPages = (UINTN)(*FreeMemoryTop - *FreeMemoryBottom) >> EFI_PAGE_SHIFT; + RemainingMemory = (UINTN)(*FreeMemoryTop - *FreeMemoryBottom); + RemainingPages = RemainingMemory >> EFI_PAGE_SHIFT; // - // The number of remaining pages needs to be greater than or equal to that of the request pages. + // The number of remaining pages needs to be greater than or equal to that of + // the request pages. In addition, there should be enough space left to hold a + // Memory Allocation HOB. // Pages = ALIGN_VALUE (Pages, EFI_SIZE_TO_PAGES (Granularity)); - if (RemainingPages < Pages) { - // - // Try to find free memory by searching memory allocation HOBs. - // - Status = FindFreeMemoryFromMemoryAllocationHob (MemoryType, Pages, Granularity, Memory); - if (!EFI_ERROR (Status)) { - return Status; - } - - DEBUG ((DEBUG_ERROR, "AllocatePages failed: No 0x%lx Pages is available.\n", (UINT64)Pages)); - DEBUG ((DEBUG_ERROR, "There is only left 0x%lx pages memory resource to be allocated.\n", (UINT64)RemainingPages)); - return EFI_OUT_OF_RESOURCES; - } else { + if ((RemainingPages > Pages) || + ((RemainingPages == Pages) && + ((RemainingMemory & EFI_PAGE_MASK) >= sizeof (EFI_HOB_MEMORY_ALLOCATION)))) + { // // Update the PHIT to reflect the memory usage // @@ -674,6 +669,18 @@ PeiAllocatePages ( ); return EFI_SUCCESS; + } else { + // + // Try to find free memory by searching memory allocation HOBs. + // + Status = FindFreeMemoryFromMemoryAllocationHob (MemoryType, Pages, Granularity, Memory); + if (!EFI_ERROR (Status)) { + return Status; + } + + DEBUG ((DEBUG_ERROR, "AllocatePages failed: No 0x%lx Pages is available.\n", (UINT64)Pages)); + DEBUG ((DEBUG_ERROR, "There is only left 0x%lx pages memory resource to be allocated.\n", (UINT64)RemainingPages)); + return EFI_OUT_OF_RESOURCES; } }