]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Core/Dxe/Mem/Page.c
MdeModulePkg DxeCore/PiSmmCore: Add UEFI memory and SMRAM profile support.
[mirror_edk2.git] / MdeModulePkg / Core / Dxe / Mem / Page.c
index 179376dc31c6bc50a07845a5d80a3aafc259bc55..18780070c5eaf8df44a27756933ba236c8c3800a 100644 (file)
@@ -1,8 +1,8 @@
 /** @file\r
   UEFI Memory page management functions.\r
 \r
-Copyright (c) 2007 - 2008, Intel Corporation. <BR>\r
-All rights reserved. This program and the accompanying materials\r
+Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR>\r
+This program and the accompanying materials\r
 are licensed and made available under the terms and conditions of the BSD License\r
 which accompanies this distribution.  The full text of the license may be found at\r
 http://opensource.org/licenses/bsd-license.php\r
@@ -13,6 +13,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 **/\r
 \r
 #include "DxeMain.h"\r
+#include "Imem.h"\r
 \r
 #define EFI_DEFAULT_PAGE_ALLOCATION_ALIGNMENT  (EFI_PAGE_SIZE)\r
 \r
@@ -27,47 +28,50 @@ typedef struct {
   UINTN                 InformationIndex;\r
   BOOLEAN               Special;\r
   BOOLEAN               Runtime;\r
-} EFI_MEMORY_TYPE_STAISTICS;\r
+} EFI_MEMORY_TYPE_STATISTICS;\r
 \r
 //\r
 // MemoryMap - The current memory map\r
 //\r
 UINTN     mMemoryMapKey = 0;\r
 \r
-//\r
-// mMapStack - space to use as temp storage to build new map descriptors\r
-// mMapDepth - depth of new descriptor stack\r
-//\r
-\r
 #define MAX_MAP_DEPTH 6\r
+\r
+///\r
+/// mMapDepth - depth of new descriptor stack\r
+///\r
 UINTN         mMapDepth = 0;\r
+///\r
+/// mMapStack - space to use as temp storage to build new map descriptors\r
+///\r
 MEMORY_MAP    mMapStack[MAX_MAP_DEPTH];\r
 UINTN         mFreeMapStack = 0;\r
-//\r
-// This list maintain the free memory map list\r
-//\r
+///\r
+/// This list maintain the free memory map list\r
+///\r
 LIST_ENTRY   mFreeMemoryMapEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mFreeMemoryMapEntryList);\r
 BOOLEAN      mMemoryTypeInformationInitialized = FALSE;\r
 \r
-EFI_MEMORY_TYPE_STAISTICS mMemoryTypeStatistics[EfiMaxMemoryType + 1] = {\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  FALSE },  // EfiReservedMemoryType\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiLoaderCode\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiLoaderData\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiBootServicesCode\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiBootServicesData\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  TRUE  },  // EfiRuntimeServicesCode\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  TRUE  },  // EfiRuntimeServicesData\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiConventionalMemory\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiUnusableMemory\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  FALSE },  // EfiACPIReclaimMemory\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  FALSE },  // EfiACPIMemoryNVS\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiMemoryMappedIO\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiMemoryMappedIOPortSpace\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  TRUE  },  // EfiPalCode\r
-  { 0, EFI_MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE }   // EfiMaxMemoryType\r
+EFI_MEMORY_TYPE_STATISTICS mMemoryTypeStatistics[EfiMaxMemoryType + 1] = {\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  FALSE },  // EfiReservedMemoryType\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiLoaderCode\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiLoaderData\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiBootServicesCode\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiBootServicesData\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  TRUE  },  // EfiRuntimeServicesCode\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  TRUE  },  // EfiRuntimeServicesData\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiConventionalMemory\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiUnusableMemory\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  FALSE },  // EfiACPIReclaimMemory\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  FALSE },  // EfiACPIMemoryNVS\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiMemoryMappedIO\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE },  // EfiMemoryMappedIOPortSpace\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE,  TRUE  },  // EfiPalCode\r
+  { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE }   // EfiMaxMemoryType\r
 };\r
 \r
-EFI_PHYSICAL_ADDRESS mDefaultMaximumAddress = EFI_MAX_ADDRESS;\r
+EFI_PHYSICAL_ADDRESS mDefaultMaximumAddress = MAX_ADDRESS;\r
+EFI_PHYSICAL_ADDRESS mDefaultBaseAddress = MAX_ADDRESS;\r
 \r
 EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] = {\r
   { EfiReservedMemoryType,      0 },\r
@@ -86,7 +90,12 @@ EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] = {
   { EfiPalCode,                 0 },\r
   { EfiMaxMemoryType,           0 }\r
 };\r
-\r
+//\r
+// Only used when load module at fixed address feature is enabled. True means the memory is alreay successfully allocated\r
+// and ready to load the module in to specified address.or else, the memory is not ready and module will be loaded at a \r
+//  address assigned by DXE core.\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED   BOOLEAN       gLoadFixedAddressCodeMemoryReady = FALSE;\r
 \r
 /**\r
   Enter critical section by gaining lock on gMemoryLock.\r
@@ -168,7 +177,20 @@ CoreAddRange (
   ASSERT_LOCKED (&gMemoryLock);\r
 \r
   DEBUG ((DEBUG_PAGE, "AddRange: %lx-%lx to %d\n", Start, End, Type));\r
-\r
+  \r
+  //\r
+  // If memory of type EfiConventionalMemory is being added that includes the page \r
+  // starting at address 0, then zero the page starting at address 0.  This has \r
+  // two benifits.  It helps find NULL pointer bugs and it also maximizes \r
+  // compatibility with operating systems that may evaluate memory in this page \r
+  // for legacy data structures.  If memory of any other type is added starting \r
+  // at address 0, then do not zero the page at address 0 because the page is being \r
+  // used for other purposes.\r
+  //  \r
+  if (Type == EfiConventionalMemory && Start == 0 && (End >= EFI_PAGE_SIZE - 1)) {\r
+    SetMem ((VOID *)(UINTN)Start, EFI_PAGE_SIZE, 0);\r
+  }\r
+  \r
   //\r
   // Memory map being altered so updated key\r
   //\r
@@ -366,25 +388,27 @@ CoreFreeMemoryMapStack (
   Find untested but initialized memory regions in GCD map and convert them to be DXE allocatable.\r
 \r
 **/\r
-VOID\r
+BOOLEAN\r
 PromoteMemoryResource (\r
   VOID\r
   )\r
 {\r
-  LIST_ENTRY                       *Link;\r
-  EFI_GCD_MAP_ENTRY                *Entry;\r
+  LIST_ENTRY         *Link;\r
+  EFI_GCD_MAP_ENTRY  *Entry;\r
+  BOOLEAN            Promoted;\r
 \r
   DEBUG ((DEBUG_PAGE, "Promote the memory resource\n"));\r
 \r
   CoreAcquireGcdMemoryLock ();\r
 \r
+  Promoted = FALSE;\r
   Link = mGcdMemorySpaceMap.ForwardLink;\r
   while (Link != &mGcdMemorySpaceMap) {\r
 \r
     Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
 \r
     if (Entry->GcdMemoryType == EfiGcdMemoryTypeReserved &&\r
-        Entry->EndAddress < EFI_MAX_ADDRESS &&\r
+        Entry->EndAddress < MAX_ADDRESS &&\r
         (Entry->Capabilities & (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED)) ==\r
           (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED)) {\r
       //\r
@@ -407,6 +431,7 @@ PromoteMemoryResource (
         );\r
       CoreFreeMemoryMapStack ();\r
 \r
+      Promoted = TRUE;\r
     }\r
 \r
     Link = Link->ForwardLink;\r
@@ -414,9 +439,72 @@ PromoteMemoryResource (
 \r
   CoreReleaseGcdMemoryLock ();\r
 \r
-  return;\r
+  return Promoted;\r
 }\r
+/**\r
+  This function try to allocate Runtime code & Boot time code memory range. If LMFA enabled, 2 patchable PCD \r
+  PcdLoadFixAddressRuntimeCodePageNumber & PcdLoadFixAddressBootTimeCodePageNumber which are set by tools will record the \r
+  size of boot time and runtime code.\r
 \r
+**/\r
+VOID\r
+CoreLoadingFixedAddressHook (\r
+  VOID\r
+  )\r
+{\r
+   UINT32                     RuntimeCodePageNumber;\r
+   UINT32                     BootTimeCodePageNumber;\r
+   EFI_PHYSICAL_ADDRESS       RuntimeCodeBase;\r
+   EFI_PHYSICAL_ADDRESS       BootTimeCodeBase;\r
+   EFI_STATUS                 Status;\r
+\r
+   //\r
+   // Make sure these 2 areas are not initialzied.\r
+   //\r
+   if (!gLoadFixedAddressCodeMemoryReady) {   \r
+     RuntimeCodePageNumber = PcdGet32(PcdLoadFixAddressRuntimeCodePageNumber);\r
+     BootTimeCodePageNumber= PcdGet32(PcdLoadFixAddressBootTimeCodePageNumber);\r
+     RuntimeCodeBase       = (EFI_PHYSICAL_ADDRESS)(gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress - EFI_PAGES_TO_SIZE (RuntimeCodePageNumber));\r
+     BootTimeCodeBase      = (EFI_PHYSICAL_ADDRESS)(RuntimeCodeBase - EFI_PAGES_TO_SIZE (BootTimeCodePageNumber));\r
+     //\r
+     // Try to allocate runtime memory.\r
+     //\r
+     Status = CoreAllocatePages (\r
+                       AllocateAddress,\r
+                       EfiRuntimeServicesCode,\r
+                       RuntimeCodePageNumber,\r
+                       &RuntimeCodeBase\r
+                       );\r
+     if (EFI_ERROR(Status)) {\r
+       //\r
+       // Runtime memory allocation failed \r
+       //\r
+       return;\r
+     }\r
+     //\r
+     // Try to allocate boot memory.\r
+     //\r
+     Status = CoreAllocatePages (\r
+                       AllocateAddress,\r
+                       EfiBootServicesCode,\r
+                       BootTimeCodePageNumber,\r
+                       &BootTimeCodeBase\r
+                       );\r
+     if (EFI_ERROR(Status)) {\r
+       //\r
+        // boot memory allocation failed. Free Runtime code range and will try the allocation again when \r
+        // new memory range is installed.\r
+        //\r
+        CoreFreePages (\r
+              RuntimeCodeBase,\r
+              RuntimeCodePageNumber\r
+              );\r
+       return;\r
+     }\r
+     gLoadFixedAddressCodeMemoryReady = TRUE;\r
+   } \r
+   return;\r
+}  \r
 \r
 /**\r
   Called to initialize the memory map and add descriptors to\r
@@ -445,7 +533,7 @@ CoreAddMemoryDescriptor (
   EFI_STATUS                  Status;\r
   UINTN                       Index;\r
   UINTN                       FreeIndex;\r
-\r
+  \r
   if ((Start & EFI_PAGE_MASK) != 0) {\r
     return;\r
   }\r
@@ -453,13 +541,19 @@ CoreAddMemoryDescriptor (
   if (Type >= EfiMaxMemoryType && Type <= 0x7fffffff) {\r
     return;\r
   }\r
-\r
   CoreAcquireMemoryLock ();\r
   End = Start + LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT) - 1;\r
   CoreAddRange (Type, Start, End, Attribute);\r
   CoreFreeMemoryMapStack ();\r
   CoreReleaseMemoryLock ();\r
 \r
+  //\r
+  // If Loading Module At Fixed Address feature is enabled. try to allocate memory with Runtime code & Boot time code type\r
+  //\r
+  if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) {\r
+    CoreLoadingFixedAddressHook();\r
+  }\r
+  \r
   //\r
   // Check to see if the statistics for the different memory types have already been established\r
   //\r
@@ -467,6 +561,7 @@ CoreAddMemoryDescriptor (
     return;\r
   }\r
 \r
+  \r
   //\r
   // Loop through each memory type in the order specified by the gMemoryTypeInformation[] array\r
   //\r
@@ -475,10 +570,9 @@ CoreAddMemoryDescriptor (
     // Make sure the memory type in the gMemoryTypeInformation[] array is valid\r
     //\r
     Type = (EFI_MEMORY_TYPE) (gMemoryTypeInformation[Index].Type);\r
-    if (Type < 0 || Type > EfiMaxMemoryType) {\r
+    if ((UINT32)Type > EfiMaxMemoryType) {\r
       continue;\r
     }\r
-\r
     if (gMemoryTypeInformation[Index].NumberOfPages != 0) {\r
       //\r
       // Allocate pages for the current memory type from the top of available memory\r
@@ -500,7 +594,7 @@ CoreAddMemoryDescriptor (
           // Make sure the memory type in the gMemoryTypeInformation[] array is valid\r
           //\r
           Type = (EFI_MEMORY_TYPE) (gMemoryTypeInformation[FreeIndex].Type);\r
-          if (Type < 0 || Type > EfiMaxMemoryType) {\r
+          if ((UINT32)Type > EfiMaxMemoryType) {\r
             continue;\r
           }\r
 \r
@@ -510,7 +604,7 @@ CoreAddMemoryDescriptor (
               gMemoryTypeInformation[FreeIndex].NumberOfPages\r
               );\r
             mMemoryTypeStatistics[Type].BaseAddress    = 0;\r
-            mMemoryTypeStatistics[Type].MaximumAddress = EFI_MAX_ADDRESS;\r
+            mMemoryTypeStatistics[Type].MaximumAddress = MAX_ADDRESS;\r
           }\r
         }\r
         return;\r
@@ -543,10 +637,9 @@ CoreAddMemoryDescriptor (
     // Make sure the memory type in the gMemoryTypeInformation[] array is valid\r
     //\r
     Type = (EFI_MEMORY_TYPE) (gMemoryTypeInformation[Index].Type);\r
-    if (Type < 0 || Type > EfiMaxMemoryType) {\r
+    if ((UINT32)Type > EfiMaxMemoryType) {\r
       continue;\r
     }\r
-\r
     if (gMemoryTypeInformation[Index].NumberOfPages != 0) {\r
       CoreFreePages (\r
         mMemoryTypeStatistics[Type].BaseAddress,\r
@@ -568,7 +661,7 @@ CoreAddMemoryDescriptor (
       }\r
     }\r
     mMemoryTypeStatistics[Type].CurrentNumberOfPages = 0;\r
-    if (mMemoryTypeStatistics[Type].MaximumAddress == EFI_MAX_ADDRESS) {\r
+    if (mMemoryTypeStatistics[Type].MaximumAddress == MAX_ADDRESS) {\r
       mMemoryTypeStatistics[Type].MaximumAddress = mDefaultMaximumAddress;\r
     }\r
   }\r
@@ -648,6 +741,8 @@ CoreConvertPages (
     // if that's all we've got\r
     //\r
     RangeEnd = End;\r
+\r
+    ASSERT (Entry != NULL);\r
     if (Entry->End < End) {\r
       RangeEnd = Entry->End;\r
     }\r
@@ -665,9 +760,9 @@ CoreConvertPages (
     //\r
     // Update counters for the number of pages allocated to each memory type\r
     //\r
-    if (Entry->Type >= 0 && Entry->Type < EfiMaxMemoryType) {\r
-      if (Start >= mMemoryTypeStatistics[Entry->Type].BaseAddress &&\r
-          Start <= mMemoryTypeStatistics[Entry->Type].MaximumAddress) {\r
+    if ((UINT32)Entry->Type < EfiMaxMemoryType) {\r
+      if ((Start >= mMemoryTypeStatistics[Entry->Type].BaseAddress && Start <= mMemoryTypeStatistics[Entry->Type].MaximumAddress) ||\r
+          (Start >= mDefaultBaseAddress && Start <= mDefaultMaximumAddress)                                                          ) {\r
         if (NumberOfPages > mMemoryTypeStatistics[Entry->Type].CurrentNumberOfPages) {\r
           mMemoryTypeStatistics[Entry->Type].CurrentNumberOfPages = 0;\r
         } else {\r
@@ -676,11 +771,11 @@ CoreConvertPages (
       }\r
     }\r
 \r
-    if (NewType >= 0 && NewType < EfiMaxMemoryType) {\r
-      if (Start >= mMemoryTypeStatistics[NewType].BaseAddress && Start <= mMemoryTypeStatistics[NewType].MaximumAddress) {\r
+    if ((UINT32)NewType < EfiMaxMemoryType) {\r
+      if ((Start >= mMemoryTypeStatistics[NewType].BaseAddress && Start <= mMemoryTypeStatistics[NewType].MaximumAddress) ||\r
+          (Start >= mDefaultBaseAddress && Start <= mDefaultMaximumAddress)                                                  ) {\r
         mMemoryTypeStatistics[NewType].CurrentNumberOfPages += NumberOfPages;\r
-        if (mMemoryTypeStatistics[NewType].CurrentNumberOfPages >\r
-            gMemoryTypeInformation[mMemoryTypeStatistics[NewType].InformationIndex].NumberOfPages) {\r
+        if (mMemoryTypeStatistics[NewType].CurrentNumberOfPages > gMemoryTypeInformation[mMemoryTypeStatistics[NewType].InformationIndex].NumberOfPages) {\r
           gMemoryTypeInformation[mMemoryTypeStatistics[NewType].InformationIndex].NumberOfPages = (UINT32)mMemoryTypeStatistics[NewType].CurrentNumberOfPages;\r
         }\r
       }\r
@@ -751,6 +846,20 @@ CoreConvertPages (
     // Add our new range in\r
     //\r
     CoreAddRange (NewType, Start, RangeEnd, Attribute);\r
+    if (NewType == EfiConventionalMemory) {\r
+      //\r
+      // Avoid calling DEBUG_CLEAR_MEMORY() for an address of 0 because this\r
+      // macro will ASSERT() if address is 0.  Instead, CoreAddRange() guarantees\r
+      // that the page starting at address 0 is always filled with zeros.\r
+      //\r
+      if (Start == 0) {\r
+        if (RangeEnd > EFI_PAGE_SIZE) {\r
+          DEBUG_CLEAR_MEMORY ((VOID *)(UINTN) EFI_PAGE_SIZE, (UINTN) (RangeEnd - EFI_PAGE_SIZE + 1));\r
+        }\r
+      } else {\r
+        DEBUG_CLEAR_MEMORY ((VOID *)(UINTN) Start, (UINTN) (RangeEnd - Start + 1));\r
+      }\r
+    }\r
 \r
     //\r
     // Move any map descriptor stack to general pool\r
@@ -777,6 +886,7 @@ CoreConvertPages (
   the requested address.\r
 \r
   @param  MaxAddress             The address that the range must be below\r
+  @param  MinAddress             The address that the range must be above\r
   @param  NumberOfPages          Number of pages needed\r
   @param  NewType                The type of memory the range is going to be\r
                                  turned into\r
@@ -788,6 +898,7 @@ CoreConvertPages (
 UINT64\r
 CoreFindFreePagesI (\r
   IN UINT64           MaxAddress,\r
+  IN UINT64           MinAddress,\r
   IN UINT64           NumberOfPages,\r
   IN EFI_MEMORY_TYPE  NewType,\r
   IN UINTN            Alignment\r
@@ -819,7 +930,7 @@ CoreFindFreePagesI (
     //\r
     // Set MaxAddress to a page boundary\r
     //\r
-    MaxAddress &= ~EFI_PAGE_MASK;\r
+    MaxAddress &= ~(UINT64)EFI_PAGE_MASK;\r
 \r
     //\r
     // Set MaxAddress to end of the page\r
@@ -844,9 +955,9 @@ CoreFindFreePagesI (
     DescEnd = Entry->End;\r
 \r
     //\r
-    // If desc is past max allowed address, skip it\r
+    // If desc is past max allowed address or below min allowed address, skip it\r
     //\r
-    if (DescStart >= MaxAddress) {\r
+    if ((DescStart >= MaxAddress) || (DescEnd < MinAddress)) {\r
       continue;\r
     }\r
 \r
@@ -866,6 +977,12 @@ CoreFindFreePagesI (
     DescNumberOfBytes = DescEnd - DescStart + 1;\r
 \r
     if (DescNumberOfBytes >= NumberOfBytes) {\r
+      //\r
+      // If the start of the allocated range is below the min address allowed, skip it\r
+      //\r
+      if ((DescEnd - NumberOfBytes + 1) < MinAddress) {\r
+        continue;\r
+      }\r
 \r
       //\r
       // If this is the best match so far remember it\r
@@ -913,41 +1030,62 @@ FindFreePages (
     IN UINTN            Alignment\r
     )\r
 {\r
-  UINT64  NewMaxAddress;\r
-  UINT64  Start;\r
+  UINT64   Start;\r
 \r
-  NewMaxAddress = MaxAddress;\r
+  //\r
+  // Attempt to find free pages in the preferred bin based on the requested memory type\r
+  //\r
+  if ((UINT32)NewType < EfiMaxMemoryType && MaxAddress >= mMemoryTypeStatistics[NewType].MaximumAddress) {\r
+    Start = CoreFindFreePagesI (\r
+              mMemoryTypeStatistics[NewType].MaximumAddress, \r
+              mMemoryTypeStatistics[NewType].BaseAddress, \r
+              NoPages, \r
+              NewType, \r
+              Alignment\r
+              );\r
+    if (Start != 0) {\r
+      return Start;\r
+    }\r
+  }\r
 \r
-  if (NewType >= 0 && NewType < EfiMaxMemoryType && NewMaxAddress >= mMemoryTypeStatistics[NewType].MaximumAddress) {\r
-    NewMaxAddress  = mMemoryTypeStatistics[NewType].MaximumAddress;\r
-  } else {\r
-    if (NewMaxAddress > mDefaultMaximumAddress) {\r
-      NewMaxAddress  = mDefaultMaximumAddress;\r
+  //\r
+  // Attempt to find free pages in the default allocation bin\r
+  //\r
+  if (MaxAddress >= mDefaultMaximumAddress) {\r
+    Start = CoreFindFreePagesI (mDefaultMaximumAddress, 0, NoPages, NewType, Alignment);\r
+    if (Start != 0) {\r
+      if (Start < mDefaultBaseAddress) {\r
+        mDefaultBaseAddress = Start;\r
+      }\r
+      return Start;\r
     }\r
   }\r
 \r
-  Start = CoreFindFreePagesI (NewMaxAddress, NoPages, NewType, Alignment);\r
-  if (Start == 0) {\r
-    Start = CoreFindFreePagesI (MaxAddress, NoPages, NewType, Alignment);\r
-    if (Start == 0) {\r
-      //\r
-      // Here means there may be no enough memory to use, so try to go through\r
-      // all the memory descript to promote the untested memory directly\r
-      //\r
-      PromoteMemoryResource ();\r
+  //\r
+  // The allocation did not succeed in any of the prefered bins even after \r
+  // promoting resources. Attempt to find free pages anywhere is the requested \r
+  // address range.  If this allocation fails, then there are not enough \r
+  // resources anywhere to satisfy the request.\r
+  //\r
+  Start = CoreFindFreePagesI (MaxAddress, 0, NoPages, NewType, Alignment);\r
+  if (Start != 0) {\r
+    return Start;\r
+  }\r
 \r
-      //\r
-      // Allocate memory again after the memory resource re-arranged\r
-      //\r
-      Start = CoreFindFreePagesI (MaxAddress, NoPages, NewType, Alignment);\r
-    }\r
+  //\r
+  // If allocations from the preferred bins fail, then attempt to promote memory resources.\r
+  //\r
+  if (!PromoteMemoryResource ()) {\r
+    return 0;\r
   }\r
 \r
-  return Start;\r
+  //\r
+  // If any memory resources were promoted, then re-attempt the allocation\r
+  //\r
+  return FindFreePages (MaxAddress, NoPages, NewType, Alignment);\r
 }\r
 \r
 \r
-\r
 /**\r
   Allocates pages from the memory map.\r
 \r
@@ -968,7 +1106,7 @@ FindFreePages (
 **/\r
 EFI_STATUS\r
 EFIAPI\r
-CoreAllocatePages (\r
+CoreInternalAllocatePages (\r
   IN EFI_ALLOCATE_TYPE      Type,\r
   IN EFI_MEMORY_TYPE        MemoryType,\r
   IN UINTN                  NumberOfPages,\r
@@ -980,7 +1118,7 @@ CoreAllocatePages (
   UINT64          MaxAddress;\r
   UINTN           Alignment;\r
 \r
-  if (Type < AllocateAnyPages || Type >= (UINTN) MaxAllocateType) {\r
+  if ((UINT32)Type >= MaxAllocateType) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
@@ -989,6 +1127,10 @@ CoreAllocatePages (
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
+  if (Memory == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
   Alignment = EFI_DEFAULT_PAGE_ALLOCATION_ALIGNMENT;\r
 \r
   if  (MemoryType == EfiACPIReclaimMemory   ||\r
@@ -1016,7 +1158,7 @@ CoreAllocatePages (
   //\r
   // The max address is the max natively addressable address for the processor\r
   //\r
-  MaxAddress = EFI_MAX_ADDRESS;\r
+  MaxAddress = MAX_ADDRESS;\r
 \r
   if (Type == AllocateMaxAddress) {\r
     MaxAddress = Start;\r
@@ -1050,6 +1192,41 @@ Done:
   return Status;\r
 }\r
 \r
+/**\r
+  Allocates pages from the memory map.\r
+\r
+  @param  Type                   The type of allocation to perform\r
+  @param  MemoryType             The type of memory to turn the allocated pages\r
+                                 into\r
+  @param  NumberOfPages          The number of pages to allocate\r
+  @param  Memory                 A pointer to receive the base allocated memory\r
+                                 address\r
+\r
+  @return Status. On success, Memory is filled in with the base address allocated\r
+  @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in\r
+                                 spec.\r
+  @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
+  @retval EFI_OUT_OF_RESOURCES   No enough pages to allocate.\r
+  @retval EFI_SUCCESS            Pages successfully allocated.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+CoreAllocatePages (\r
+  IN  EFI_ALLOCATE_TYPE     Type,\r
+  IN  EFI_MEMORY_TYPE       MemoryType,\r
+  IN  UINTN                 NumberOfPages,\r
+  OUT EFI_PHYSICAL_ADDRESS  *Memory\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+\r
+  Status = CoreInternalAllocatePages (Type, MemoryType, NumberOfPages, Memory);\r
+  if (!EFI_ERROR (Status)) {\r
+    CoreUpdateProfile ((EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0), MemoryProfileActionAllocatePages, MemoryType, EFI_PAGES_TO_SIZE (NumberOfPages), (VOID *) (UINTN) *Memory);\r
+  }\r
+  return Status;\r
+}\r
 \r
 /**\r
   Frees previous allocated pages.\r
@@ -1064,7 +1241,7 @@ Done:
 **/\r
 EFI_STATUS\r
 EFIAPI\r
-CoreFreePages (\r
+CoreInternalFreePages (\r
   IN EFI_PHYSICAL_ADDRESS   Memory,\r
   IN UINTN                  NumberOfPages\r
   )\r
@@ -1090,12 +1267,13 @@ CoreFreePages (
     }\r
   }\r
   if (Link == &gMemoryMap) {\r
-    CoreReleaseMemoryLock ();\r
-    return EFI_NOT_FOUND;\r
+    Status = EFI_NOT_FOUND;\r
+    goto Done;\r
   }\r
 \r
   Alignment = EFI_DEFAULT_PAGE_ALLOCATION_ALIGNMENT;\r
 \r
+  ASSERT (Entry != NULL);\r
   if  (Entry->Type == EfiACPIReclaimMemory   ||\r
        Entry->Type == EfiACPIMemoryNVS       ||\r
        Entry->Type == EfiRuntimeServicesCode ||\r
@@ -1106,8 +1284,8 @@ CoreFreePages (
   }\r
 \r
   if ((Memory & (Alignment - 1)) != 0) {\r
-    CoreReleaseMemoryLock ();\r
-    return EFI_INVALID_PARAMETER;\r
+    Status = EFI_INVALID_PARAMETER;\r
+    goto Done;\r
   }\r
 \r
   NumberOfPages += EFI_SIZE_TO_PAGES (Alignment) - 1;\r
@@ -1115,23 +1293,123 @@ CoreFreePages (
 \r
   Status = CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory);\r
 \r
+  if (EFI_ERROR (Status)) {\r
+    goto Done;\r
+  }\r
+\r
+Done:\r
   CoreReleaseMemoryLock ();\r
+  return Status;\r
+}\r
 \r
-  if (EFI_ERROR (Status)) {\r
-    return Status;\r
+/**\r
+  Frees previous allocated pages.\r
+\r
+  @param  Memory                 Base address of memory being freed\r
+  @param  NumberOfPages          The number of pages to free\r
+\r
+  @retval EFI_NOT_FOUND          Could not find the entry that covers the range\r
+  @retval EFI_INVALID_PARAMETER  Address not aligned\r
+  @return EFI_SUCCESS         -Pages successfully freed.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+CoreFreePages (\r
+  IN EFI_PHYSICAL_ADDRESS  Memory,\r
+  IN UINTN                 NumberOfPages\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+\r
+  Status = CoreInternalFreePages (Memory, NumberOfPages);\r
+  if (!EFI_ERROR (Status)) {\r
+    CoreUpdateProfile ((EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0), MemoryProfileActionFreePages, 0, EFI_PAGES_TO_SIZE (NumberOfPages), (VOID *) (UINTN) Memory);\r
   }\r
+  return Status;\r
+}\r
 \r
+/**\r
+  This function checks to see if the last memory map descriptor in a memory map\r
+  can be merged with any of the other memory map descriptors in a memorymap.\r
+  Memory descriptors may be merged if they are adjacent and have the same type\r
+  and attributes.\r
+\r
+  @param  MemoryMap              A pointer to the start of the memory map.\r
+  @param  MemoryMapDescriptor    A pointer to the last descriptor in MemoryMap.\r
+  @param  DescriptorSize         The size, in bytes, of an individual\r
+                                 EFI_MEMORY_DESCRIPTOR.\r
+\r
+  @return  A pointer to the next available descriptor in MemoryMap\r
+\r
+**/\r
+EFI_MEMORY_DESCRIPTOR *\r
+MergeMemoryMapDescriptor (\r
+  IN EFI_MEMORY_DESCRIPTOR  *MemoryMap,\r
+  IN EFI_MEMORY_DESCRIPTOR  *MemoryMapDescriptor,\r
+  IN UINTN                  DescriptorSize\r
+  )\r
+{\r
   //\r
-  // Destroy the contents\r
+  // Traverse the array of descriptors in MemoryMap\r
   //\r
-  if (Memory < EFI_MAX_ADDRESS) {\r
-    DEBUG_CLEAR_MEMORY ((VOID *)(UINTN)Memory, NumberOfPages << EFI_PAGE_SHIFT);\r
+  for (; MemoryMap != MemoryMapDescriptor; MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, DescriptorSize)) {\r
+    //\r
+    // Check to see if the Type fields are identical.\r
+    //\r
+    if (MemoryMap->Type != MemoryMapDescriptor->Type) {\r
+      continue;\r
+    }\r
+\r
+    //\r
+    // Check to see if the Attribute fields are identical.\r
+    //\r
+    if (MemoryMap->Attribute != MemoryMapDescriptor->Attribute) {\r
+      continue;\r
+    }\r
+\r
+    //\r
+    // Check to see if MemoryMapDescriptor is immediately above MemoryMap\r
+    //\r
+    if (MemoryMap->PhysicalStart + EFI_PAGES_TO_SIZE ((UINTN)MemoryMap->NumberOfPages) == MemoryMapDescriptor->PhysicalStart) { \r
+      //\r
+      // Merge MemoryMapDescriptor into MemoryMap\r
+      //\r
+      MemoryMap->NumberOfPages += MemoryMapDescriptor->NumberOfPages;\r
+\r
+      //\r
+      // Return MemoryMapDescriptor as the next available slot int he MemoryMap array\r
+      //\r
+      return MemoryMapDescriptor;\r
+    }\r
+\r
+    //\r
+    // Check to see if MemoryMapDescriptor is immediately below MemoryMap\r
+    //\r
+    if (MemoryMap->PhysicalStart - EFI_PAGES_TO_SIZE ((UINTN)MemoryMapDescriptor->NumberOfPages) == MemoryMapDescriptor->PhysicalStart) {\r
+      //\r
+      // Merge MemoryMapDescriptor into MemoryMap\r
+      //\r
+      MemoryMap->PhysicalStart  = MemoryMapDescriptor->PhysicalStart;\r
+      MemoryMap->VirtualStart   = MemoryMapDescriptor->VirtualStart;\r
+      MemoryMap->NumberOfPages += MemoryMapDescriptor->NumberOfPages;\r
+\r
+      //\r
+      // Return MemoryMapDescriptor as the next available slot int he MemoryMap array\r
+      //\r
+      return MemoryMapDescriptor;\r
+    }\r
   }\r
 \r
-  return Status;\r
+  //\r
+  // MemoryMapDescrtiptor could not be merged with any descriptors in MemoryMap.\r
+  //\r
+  // Return the slot immediately after MemoryMapDescriptor as the next available \r
+  // slot in the MemoryMap array\r
+  //\r
+  return NEXT_MEMORY_DESCRIPTOR (MemoryMapDescriptor, DescriptorSize);\r
 }\r
 \r
-\r
 /**\r
   This function returns a copy of the current memory map. The map is an array of\r
   memory descriptors, each of which describes a contiguous block of memory.\r
@@ -1180,6 +1458,7 @@ CoreGetMemoryMap (
   MEMORY_MAP                        *Entry;\r
   EFI_GCD_MAP_ENTRY                 *GcdMapEntry;\r
   EFI_MEMORY_TYPE                   Type;\r
+  EFI_MEMORY_DESCRIPTOR             *MemoryMapStart;\r
 \r
   //\r
   // Make sure the parameters are valid\r
@@ -1245,6 +1524,7 @@ CoreGetMemoryMap (
   // Build the map\r
   //\r
   ZeroMem (MemoryMap, BufferSize);\r
+  MemoryMapStart = MemoryMap;\r
   for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
     Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
     ASSERT (Entry->VirtualStart == 0);\r
@@ -1274,11 +1554,17 @@ CoreGetMemoryMap (
       }\r
     }\r
     MemoryMap->Attribute = Entry->Attribute;\r
-    if (mMemoryTypeStatistics[MemoryMap->Type].Runtime) {\r
-      MemoryMap->Attribute |= EFI_MEMORY_RUNTIME;\r
+    if (MemoryMap->Type < EfiMaxMemoryType) {\r
+      if (mMemoryTypeStatistics[MemoryMap->Type].Runtime) {\r
+        MemoryMap->Attribute |= EFI_MEMORY_RUNTIME;\r
+      }\r
     }\r
 \r
-    MemoryMap = NextMemoryDescriptor (MemoryMap, Size);\r
+    //\r
+    // Check to see if the new Memory Map Descriptor can be merged with an \r
+    // existing descriptor if they are adjacent and have the same attributes\r
+    //\r
+    MemoryMap = MergeMemoryMapDescriptor (MemoryMapStart, MemoryMap, Size);\r
   }\r
 \r
   for (Link = mGcdMemorySpaceMap.ForwardLink; Link != &mGcdMemorySpaceMap; Link = Link->ForwardLink) {\r
@@ -1286,7 +1572,10 @@ CoreGetMemoryMap (
     if ((GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeReserved) ||\r
         (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo)) {\r
       if ((GcdMapEntry->Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {\r
-\r
+        // \r
+        // Create EFI_MEMORY_DESCRIPTOR for every Reserved and MMIO GCD entries\r
+        // that are marked for runtime use\r
+        //\r
         MemoryMap->PhysicalStart = GcdMapEntry->BaseAddress;\r
         MemoryMap->VirtualStart  = 0;\r
         MemoryMap->NumberOfPages = RShiftU64 ((GcdMapEntry->EndAddress - GcdMapEntry->BaseAddress + 1), EFI_PAGE_SHIFT);\r
@@ -1302,19 +1591,23 @@ CoreGetMemoryMap (
           }\r
         }\r
 \r
-        MemoryMap = NextMemoryDescriptor (MemoryMap, Size);\r
+        //\r
+        // Check to see if the new Memory Map Descriptor can be merged with an \r
+        // existing descriptor if they are adjacent and have the same attributes\r
+        //\r
+        MemoryMap = MergeMemoryMapDescriptor (MemoryMapStart, MemoryMap, Size);\r
       }\r
     }\r
   }\r
 \r
+  //\r
+  // Compute the size of the buffer actually used after all memory map descriptor merge operations\r
+  //\r
+  BufferSize = ((UINT8 *)MemoryMap - (UINT8 *)MemoryMapStart);\r
+\r
   Status = EFI_SUCCESS;\r
 \r
 Done:\r
-\r
-  CoreReleaseMemoryLock ();\r
-\r
-  CoreReleaseGcdMemoryLock ();\r
-\r
   //\r
   // Update the map key finally\r
   //\r
@@ -1322,6 +1615,10 @@ Done:
     *MapKey = mMemoryMapKey;\r
   }\r
 \r
+  CoreReleaseMemoryLock ();\r
+\r
+  CoreReleaseGcdMemoryLock ();\r
+\r
   *MemoryMapSize = BufferSize;\r
 \r
   return Status;\r
@@ -1351,13 +1648,13 @@ CoreAllocatePoolPages (
   //\r
   // Find the pages to convert\r
   //\r
-  Start = FindFreePages (EFI_MAX_ADDRESS, NumberOfPages, PoolType, Alignment);\r
+  Start = FindFreePages (MAX_ADDRESS, NumberOfPages, PoolType, Alignment);\r
 \r
   //\r
   // Convert it to boot services data\r
   //\r
   if (Start == 0) {\r
-    DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "AllocatePoolPages: failed to allocate %d pages\n", NumberOfPages));\r
+    DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "AllocatePoolPages: failed to allocate %d pages\n", (UINT32)NumberOfPages));\r
   } else {\r
     CoreConvertPages (Start, NumberOfPages, PoolType);\r
   }\r
@@ -1418,18 +1715,18 @@ CoreTerminateMemoryMap (
 \r
     for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
       Entry = CR(Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
-      if (Entry->Attribute & EFI_MEMORY_RUNTIME) {\r
+      if ((Entry->Attribute & EFI_MEMORY_RUNTIME) != 0) {\r
         if (Entry->Type == EfiACPIReclaimMemory || Entry->Type == EfiACPIMemoryNVS) {\r
           DEBUG((DEBUG_ERROR | DEBUG_PAGE, "ExitBootServices: ACPI memory entry has RUNTIME attribute set.\n"));\r
           Status =  EFI_INVALID_PARAMETER;\r
           goto Done;\r
         }\r
-        if (Entry->Start & (EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT - 1)) {\r
+        if ((Entry->Start & (EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT - 1)) != 0) {\r
           DEBUG((DEBUG_ERROR | DEBUG_PAGE, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n"));\r
           Status =  EFI_INVALID_PARAMETER;\r
           goto Done;\r
         }\r
-        if ((Entry->End + 1) & (EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT - 1)) {\r
+        if (((Entry->End + 1) & (EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT - 1)) != 0) {\r
           DEBUG((DEBUG_ERROR | DEBUG_PAGE, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n"));\r
           Status =  EFI_INVALID_PARAMETER;\r
           goto Done;\r