+/** @file\r
+ DxeServicesLib memory allocation routines\r
+\r
+ Copyright (c) 2018, Linaro, Ltd. All rights reserved.<BR>\r
+\r
+ This program and the accompanying materials are licensed and made available\r
+ under the terms and conditions of the BSD License which accompanies this\r
+ distribution. The full text of the license may be found at\r
+ http://opensource.org/licenses/bsd-license.php.\r
+\r
+ THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+**/\r
+\r
+#include <PiDxe.h>\r
+#include <Library/HobLib.h>\r
+#include <Library/UefiBootServicesTableLib.h>\r
+#include <Library/DxeServicesLib.h>\r
+\r
+/**\r
+ Allocates one or more 4KB pages of a given type from a memory region that is\r
+ accessible to PEI.\r
+\r
+ Allocates the number of 4KB pages of type 'MemoryType' and returns a\r
+ pointer to the allocated buffer. The buffer returned is aligned on a 4KB\r
+ boundary. If Pages is 0, then NULL is returned. If there is not enough\r
+ memory remaining to satisfy the request, then NULL is returned.\r
+\r
+ @param[in] MemoryType The memory type to allocate\r
+ @param[in] Pages The number of 4 KB pages to allocate.\r
+\r
+ @return A pointer to the allocated buffer or NULL if allocation fails.\r
+\r
+**/\r
+VOID *\r
+EFIAPI\r
+AllocatePeiAccessiblePages (\r
+ IN EFI_MEMORY_TYPE MemoryType,\r
+ IN UINTN Pages\r
+ )\r
+{\r
+ EFI_STATUS Status;\r
+ EFI_ALLOCATE_TYPE AllocType;\r
+ EFI_PHYSICAL_ADDRESS Memory;\r
+ EFI_HOB_HANDOFF_INFO_TABLE *PhitHob;\r
+\r
+ if (Pages == 0) {\r
+ return NULL;\r
+ }\r
+\r
+ AllocType = AllocateAnyPages;\r
+ //\r
+ // A X64 build of DXE may be combined with a 32-bit build of PEI, and so we\r
+ // need to check the memory limit set by PEI, and allocate below 4 GB if the\r
+ // limit is set to 4 GB or lower.\r
+ //\r
+ PhitHob = (EFI_HOB_HANDOFF_INFO_TABLE *)GetHobList ();\r
+ if (PhitHob->EfiFreeMemoryTop <= MAX_UINT32) {\r
+ AllocType = AllocateMaxAddress;\r
+ Memory = MAX_UINT32;\r
+ }\r
+\r
+ Status = gBS->AllocatePages (AllocType, MemoryType, Pages, &Memory);\r
+ if (EFI_ERROR (Status)) {\r
+ return NULL;\r
+ }\r
+ return (VOID *)(UINTN)Memory;\r
+}\r