]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Core/Dxe/Mem/Page.c
MdeModulePkg: Fix warning with VS2005 toolchain on IA32
[mirror_edk2.git] / MdeModulePkg / Core / Dxe / Mem / Page.c
index daf00f237d0f8a3b77431dad27d372d0eb2ded8e..5995f97c61b7e6874a5e52f1f6cae01a80e9f25e 100644 (file)
@@ -1,24 +1,24 @@
 /** @file\r
 /** @file\r
-\r
   UEFI Memory page management functions.\r
 \r
   UEFI Memory page management functions.\r
 \r
-Copyright (c) 2007 - 2008, Intel Corporation                                                         \r
-All rights reserved. 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
-                                                                                          \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
+Copyright (c) 2007 - 2010, Intel Corporation. <BR>\r
+All rights reserved. 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
+\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
 \r
 **/\r
 \r
-#include <DxeMain.h>\r
+#include "DxeMain.h"\r
+#include "Imem.h"\r
 \r
 #define EFI_DEFAULT_PAGE_ALLOCATION_ALIGNMENT  (EFI_PAGE_SIZE)\r
 \r
 //\r
 \r
 #define EFI_DEFAULT_PAGE_ALLOCATION_ALIGNMENT  (EFI_PAGE_SIZE)\r
 \r
 //\r
-// Entry for tracking the memory regions for each memory type to help cooalese like memory types\r
+// Entry for tracking the memory regions for each memory type to coalesce similar memory types\r
 //\r
 typedef struct {\r
   EFI_PHYSICAL_ADDRESS  BaseAddress;\r
 //\r
 typedef struct {\r
   EFI_PHYSICAL_ADDRESS  BaseAddress;\r
@@ -35,40 +35,42 @@ typedef struct {
 //\r
 UINTN     mMemoryMapKey = 0;\r
 \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
 #define MAX_MAP_DEPTH 6\r
+\r
+///\r
+/// mMapDepth - depth of new descriptor stack\r
+///\r
 UINTN         mMapDepth = 0;\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
 MEMORY_MAP    mMapStack[MAX_MAP_DEPTH];\r
 UINTN         mFreeMapStack = 0;\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
+/// 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
 \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
+  { 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
 };\r
 \r
-EFI_PHYSICAL_ADDRESS mDefaultMaximumAddress = EFI_MAX_ADDRESS;\r
+EFI_PHYSICAL_ADDRESS mDefaultMaximumAddress = MAX_ADDRESS;\r
 \r
 EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] = {\r
   { EfiReservedMemoryType,      0 },\r
 \r
 EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] = {\r
   { EfiReservedMemoryType,      0 },\r
@@ -87,133 +89,310 @@ EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] = {
   { EfiPalCode,                 0 },\r
   { EfiMaxMemoryType,           0 }\r
 };\r
   { EfiPalCode,                 0 },\r
   { EfiMaxMemoryType,           0 }\r
 };\r
-\r
 //\r
 //\r
-// Internal prototypes\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
 //\r
-STATIC\r
-VOID \r
-PromoteMemoryResource (\r
-  VOID\r
-);\r
+GLOBAL_REMOVE_IF_UNREFERENCED   BOOLEAN       gLoadFixedAddressCodeMemoryReady = FALSE;\r
 \r
 \r
-STATIC\r
-VOID\r
-CoreAddRange (\r
-  IN EFI_MEMORY_TYPE          Type,\r
-  IN EFI_PHYSICAL_ADDRESS     Start,\r
-  IN EFI_PHYSICAL_ADDRESS     End,\r
-  IN UINT64                   Attribute\r
-  );\r
+/**\r
+  Enter critical section by gaining lock on gMemoryLock.\r
 \r
 \r
-STATIC\r
+**/\r
 VOID\r
 VOID\r
-CoreFreeMemoryMapStack (\r
+CoreAcquireMemoryLock (\r
   VOID\r
   VOID\r
-  );\r
+  )\r
+{\r
+  CoreAcquireLock (&gMemoryLock);\r
+}\r
 \r
 \r
-STATIC\r
-EFI_STATUS\r
-CoreConvertPages (\r
-  IN UINT64           Start,\r
-  IN UINT64           NumberOfPages,\r
-  IN EFI_MEMORY_TYPE  NewType\r
-  );\r
 \r
 \r
-STATIC\r
-VOID\r
-RemoveMemoryMapEntry (\r
-  MEMORY_MAP      *Entry\r
-  );\r
-  \r
-STATIC\r
-MEMORY_MAP *\r
-AllocateMemoryMapEntry (\r
-  VOID\r
-  );\r
\r
+\r
+/**\r
+  Exit critical section by releasing lock on gMemoryLock.\r
+\r
+**/\r
 VOID\r
 VOID\r
-CoreAcquireMemoryLock (\r
+CoreReleaseMemoryLock (\r
   VOID\r
   )\r
   VOID\r
   )\r
-/*++\r
-\r
-Routine Description:\r
+{\r
+  CoreReleaseLock (&gMemoryLock);\r
+}\r
 \r
 \r
-  Enter critical section by gaining lock on gMemoryLock\r
 \r
 \r
-Arguments:\r
 \r
 \r
-  None\r
 \r
 \r
-Returns:\r
+/**\r
+  Internal function.  Removes a descriptor entry.\r
 \r
 \r
-  None\r
+  @param  Entry                  The entry to remove\r
 \r
 \r
---*/\r
+**/\r
+VOID\r
+RemoveMemoryMapEntry (\r
+  IN OUT MEMORY_MAP      *Entry\r
+  )\r
 {\r
 {\r
-  CoreAcquireLock (&gMemoryLock);\r
+  RemoveEntryList (&Entry->Link);\r
+  Entry->Link.ForwardLink = NULL;\r
+\r
+  if (Entry->FromPages) {\r
+    //\r
+    // Insert the free memory map descriptor to the end of mFreeMemoryMapEntryList\r
+    //\r
+    InsertTailList (&mFreeMemoryMapEntryList, &Entry->Link);\r
+  }\r
 }\r
 \r
 }\r
 \r
+/**\r
+  Internal function.  Adds a ranges to the memory map.\r
+  The range must not already exist in the map.\r
 \r
 \r
+  @param  Type                   The type of memory range to add\r
+  @param  Start                  The starting address in the memory range Must be\r
+                                 paged aligned\r
+  @param  End                    The last address in the range Must be the last\r
+                                 byte of a page\r
+  @param  Attribute              The attributes of the memory range to add\r
+\r
+**/\r
 VOID\r
 VOID\r
-CoreReleaseMemoryLock (\r
-  VOID\r
+CoreAddRange (\r
+  IN EFI_MEMORY_TYPE          Type,\r
+  IN EFI_PHYSICAL_ADDRESS     Start,\r
+  IN EFI_PHYSICAL_ADDRESS     End,\r
+  IN UINT64                   Attribute\r
   )\r
   )\r
-/*++\r
+{\r
+  LIST_ENTRY        *Link;\r
+  MEMORY_MAP        *Entry;\r
+\r
+  ASSERT ((Start & EFI_PAGE_MASK) == 0);\r
+  ASSERT (End > Start) ;\r
+\r
+  ASSERT_LOCKED (&gMemoryLock);\r
+\r
+  DEBUG ((DEBUG_PAGE, "AddRange: %lx-%lx to %d\n", Start, End, Type));\r
+\r
+  //\r
+  // Memory map being altered so updated key\r
+  //\r
+  mMemoryMapKey += 1;\r
+\r
+  //\r
+  // UEFI 2.0 added an event group for notificaiton on memory map changes.\r
+  // So we need to signal this Event Group every time the memory map changes.\r
+  // If we are in EFI 1.10 compatability mode no event groups will be\r
+  // found and nothing will happen we we call this function. These events\r
+  // will get signaled but since a lock is held around the call to this\r
+  // function the notificaiton events will only be called after this funciton\r
+  // returns and the lock is released.\r
+  //\r
+  CoreNotifySignalList (&gEfiEventMemoryMapChangeGuid);\r
+\r
+  //\r
+  // Look for adjoining memory descriptor\r
+  //\r
+\r
+  // Two memory descriptors can only be merged if they have the same Type\r
+  // and the same Attribute\r
+  //\r
+\r
+  Link = gMemoryMap.ForwardLink;\r
+  while (Link != &gMemoryMap) {\r
+    Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
+    Link  = Link->ForwardLink;\r
+\r
+    if (Entry->Type != Type) {\r
+      continue;\r
+    }\r
+\r
+    if (Entry->Attribute != Attribute) {\r
+      continue;\r
+    }\r
+\r
+    if (Entry->End + 1 == Start) {\r
+\r
+      Start = Entry->Start;\r
+      RemoveMemoryMapEntry (Entry);\r
 \r
 \r
-Routine Description:\r
+    } else if (Entry->Start == End + 1) {\r
 \r
 \r
-  Exit critical section by releasing lock on gMemoryLock\r
+      End = Entry->End;\r
+      RemoveMemoryMapEntry (Entry);\r
+    }\r
+  }\r
 \r
 \r
-Arguments:\r
+  //\r
+  // Add descriptor\r
+  //\r
 \r
 \r
-  None\r
+  mMapStack[mMapDepth].Signature     = MEMORY_MAP_SIGNATURE;\r
+  mMapStack[mMapDepth].FromPages      = FALSE;\r
+  mMapStack[mMapDepth].Type          = Type;\r
+  mMapStack[mMapDepth].Start         = Start;\r
+  mMapStack[mMapDepth].End           = End;\r
+  mMapStack[mMapDepth].VirtualStart  = 0;\r
+  mMapStack[mMapDepth].Attribute     = Attribute;\r
+  InsertTailList (&gMemoryMap, &mMapStack[mMapDepth].Link);\r
+\r
+  mMapDepth += 1;\r
+  ASSERT (mMapDepth < MAX_MAP_DEPTH);\r
+\r
+  return ;\r
+}\r
 \r
 \r
-Returns:\r
+/**\r
+  Internal function.  Deque a descriptor entry from the mFreeMemoryMapEntryList.\r
+  If the list is emtry, then allocate a new page to refuel the list.\r
+  Please Note this algorithm to allocate the memory map descriptor has a property\r
+  that the memory allocated for memory entries always grows, and will never really be freed\r
+  For example, if the current boot uses 2000 memory map entries at the maximum point, but\r
+  ends up with only 50 at the time the OS is booted, then the memory associated with the 1950\r
+  memory map entries is still allocated from EfiBootServicesMemory.\r
 \r
 \r
-  None\r
 \r
 \r
---*/\r
+  @return The Memory map descriptor dequed from the mFreeMemoryMapEntryList\r
+\r
+**/\r
+MEMORY_MAP *\r
+AllocateMemoryMapEntry (\r
+  VOID\r
+  )\r
 {\r
 {\r
-  CoreReleaseLock (&gMemoryLock);\r
+  MEMORY_MAP*            FreeDescriptorEntries;\r
+  MEMORY_MAP*            Entry;\r
+  UINTN                  Index;\r
+\r
+  if (IsListEmpty (&mFreeMemoryMapEntryList)) {\r
+    //\r
+    // The list is empty, to allocate one page to refuel the list\r
+    //\r
+    FreeDescriptorEntries = CoreAllocatePoolPages (EfiBootServicesData, EFI_SIZE_TO_PAGES(DEFAULT_PAGE_ALLOCATION), DEFAULT_PAGE_ALLOCATION);\r
+    if(FreeDescriptorEntries != NULL) {\r
+      //\r
+      // Enque the free memmory map entries into the list\r
+      //\r
+      for (Index = 0; Index< DEFAULT_PAGE_ALLOCATION / sizeof(MEMORY_MAP); Index++) {\r
+        FreeDescriptorEntries[Index].Signature = MEMORY_MAP_SIGNATURE;\r
+        InsertTailList (&mFreeMemoryMapEntryList, &FreeDescriptorEntries[Index].Link);\r
+      }\r
+    } else {\r
+      return NULL;\r
+    }\r
+  }\r
+  //\r
+  // dequeue the first descriptor from the list\r
+  //\r
+  Entry = CR (mFreeMemoryMapEntryList.ForwardLink, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
+  RemoveEntryList (&Entry->Link);\r
+\r
+  return Entry;\r
 }\r
 \r
 }\r
 \r
-STATIC\r
+\r
+/**\r
+  Internal function.  Moves any memory descriptors that are on the\r
+  temporary descriptor stack to heap.\r
+\r
+**/\r
 VOID\r
 VOID\r
-PromoteMemoryResource (\r
+CoreFreeMemoryMapStack (\r
   VOID\r
   )\r
   VOID\r
   )\r
-/*++\r
+{\r
+  MEMORY_MAP      *Entry;\r
+  MEMORY_MAP      *Entry2;\r
+  LIST_ENTRY      *Link2;\r
 \r
 \r
-Routine Description:\r
+  ASSERT_LOCKED (&gMemoryLock);\r
 \r
 \r
-  Find untested but initialized memory regions in GCD map and convert them to be DXE allocatable.\r
+  //\r
+  // If already freeing the map stack, then return\r
+  //\r
+  if (mFreeMapStack != 0) {\r
+    return ;\r
+  }\r
+\r
+  //\r
+  // Move the temporary memory descriptor stack into pool\r
+  //\r
+  mFreeMapStack += 1;\r
+\r
+  while (mMapDepth != 0) {\r
+    //\r
+    // Deque an memory map entry from mFreeMemoryMapEntryList\r
+    //\r
+    Entry = AllocateMemoryMapEntry ();\r
 \r
 \r
-Arguments:\r
+    ASSERT (Entry);\r
 \r
 \r
-  None\r
+    //\r
+    // Update to proper entry\r
+    //\r
+    mMapDepth -= 1;\r
 \r
 \r
-Returns:\r
+    if (mMapStack[mMapDepth].Link.ForwardLink != NULL) {\r
 \r
 \r
-  None\r
+      //\r
+      // Move this entry to general memory\r
+      //\r
+      RemoveEntryList (&mMapStack[mMapDepth].Link);\r
+      mMapStack[mMapDepth].Link.ForwardLink = NULL;\r
+\r
+      CopyMem (Entry , &mMapStack[mMapDepth], sizeof (MEMORY_MAP));\r
+      Entry->FromPages = TRUE;\r
 \r
 \r
---*/\r
+      //\r
+      // Find insertion location\r
+      //\r
+      for (Link2 = gMemoryMap.ForwardLink; Link2 != &gMemoryMap; Link2 = Link2->ForwardLink) {\r
+        Entry2 = CR (Link2, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
+        if (Entry2->FromPages && Entry2->Start > Entry->Start) {\r
+          break;\r
+        }\r
+      }\r
+\r
+      InsertTailList (Link2, &Entry->Link);\r
+\r
+    } else {\r
+      //\r
+      // This item of mMapStack[mMapDepth] has already been dequeued from gMemoryMap list,\r
+      // so here no need to move it to memory.\r
+      //\r
+      InsertTailList (&mFreeMemoryMapEntryList, &Entry->Link);\r
+    }\r
+  }\r
+\r
+  mFreeMapStack -= 1;\r
+}\r
+\r
+/**\r
+  Find untested but initialized memory regions in GCD map and convert them to be DXE allocatable.\r
+\r
+**/\r
+VOID\r
+PromoteMemoryResource (\r
+  VOID\r
+  )\r
 {\r
   LIST_ENTRY                       *Link;\r
   EFI_GCD_MAP_ENTRY                *Entry;\r
 \r
 {\r
   LIST_ENTRY                       *Link;\r
   EFI_GCD_MAP_ENTRY                *Entry;\r
 \r
-  DEBUG ((EFI_D_ERROR | EFI_D_PAGE, "Promote the memory resource\n"));\r
-  \r
+  DEBUG ((DEBUG_PAGE, "Promote the memory resource\n"));\r
+\r
   CoreAcquireGcdMemoryLock ();\r
   CoreAcquireGcdMemoryLock ();\r
-  \r
+\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
   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
         (Entry->Capabilities & (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED)) ==\r
           (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED)) {\r
       //\r
@@ -226,65 +405,118 @@ Returns:
 \r
       //\r
       // Add to allocable system memory resource\r
 \r
       //\r
       // Add to allocable system memory resource\r
-      //      \r
+      //\r
 \r
       CoreAddRange (\r
 \r
       CoreAddRange (\r
-        EfiConventionalMemory, \r
-        Entry->BaseAddress, \r
-        Entry->EndAddress, \r
+        EfiConventionalMemory,\r
+        Entry->BaseAddress,\r
+        Entry->EndAddress,\r
         Entry->Capabilities & ~(EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED | EFI_MEMORY_RUNTIME)\r
         );\r
       CoreFreeMemoryMapStack ();\r
         Entry->Capabilities & ~(EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED | EFI_MEMORY_RUNTIME)\r
         );\r
       CoreFreeMemoryMapStack ();\r
-      \r
+\r
     }\r
 \r
     Link = Link->ForwardLink;\r
   }\r
     }\r
 \r
     Link = Link->ForwardLink;\r
   }\r
-  \r
+\r
   CoreReleaseGcdMemoryLock ();\r
   CoreReleaseGcdMemoryLock ();\r
-  \r
+\r
   return;\r
 }\r
   return;\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
+**/\r
 VOID\r
 VOID\r
-CoreAddMemoryDescriptor (\r
-  IN EFI_MEMORY_TYPE       Type,\r
-  IN EFI_PHYSICAL_ADDRESS  Start,\r
-  IN UINT64                NumberOfPages,\r
-  IN UINT64                Attribute\r
+CoreLoadingFixedAddressHook (\r
+  VOID\r
   )\r
   )\r
-/*++\r
-\r
-Routine Description:\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
   the current descriptor list.\r
   Called to initialize the memory map and add descriptors to\r
   the current descriptor list.\r
-\r
   The first descriptor that is added must be general usable\r
   memory as the addition allocates heap.\r
 \r
   The first descriptor that is added must be general usable\r
   memory as the addition allocates heap.\r
 \r
-Arguments:\r
-\r
-  Type          - The type of memory to add\r
-\r
-  Start         - The starting address in the memory range\r
-                  Must be page aligned\r
-\r
-  NumberOfPages - The number of pages in the range\r
-\r
-  Attribute     - Attributes of the memory to add\r
-\r
-Returns:\r
+  @param  Type                   The type of memory to add\r
+  @param  Start                  The starting address in the memory range Must be\r
+                                 page aligned\r
+  @param  NumberOfPages          The number of pages in the range\r
+  @param  Attribute              Attributes of the memory to add\r
 \r
 \r
-  None.  The range is added to the memory map\r
+  @return None.  The range is added to the memory map\r
 \r
 \r
---*/\r
+**/\r
+VOID\r
+CoreAddMemoryDescriptor (\r
+  IN EFI_MEMORY_TYPE       Type,\r
+  IN EFI_PHYSICAL_ADDRESS  Start,\r
+  IN UINT64                NumberOfPages,\r
+  IN UINT64                Attribute\r
+  )\r
 {\r
   EFI_PHYSICAL_ADDRESS        End;\r
   EFI_STATUS                  Status;\r
   UINTN                       Index;\r
   UINTN                       FreeIndex;\r
 {\r
   EFI_PHYSICAL_ADDRESS        End;\r
   EFI_STATUS                  Status;\r
   UINTN                       Index;\r
   UINTN                       FreeIndex;\r
-\r
+  \r
   if ((Start & EFI_PAGE_MASK) != 0) {\r
     return;\r
   }\r
   if ((Start & EFI_PAGE_MASK) != 0) {\r
     return;\r
   }\r
@@ -292,13 +524,19 @@ Returns:
   if (Type >= EfiMaxMemoryType && Type <= 0x7fffffff) {\r
     return;\r
   }\r
   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
   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
   //\r
   // Check to see if the statistics for the different memory types have already been established\r
   //\r
@@ -306,6 +544,7 @@ Returns:
     return;\r
   }\r
 \r
     return;\r
   }\r
 \r
+  \r
   //\r
   // Loop through each memory type in the order specified by the gMemoryTypeInformation[] array\r
   //\r
   //\r
   // Loop through each memory type in the order specified by the gMemoryTypeInformation[] array\r
   //\r
@@ -317,7 +556,6 @@ Returns:
     if (Type < 0 || Type > EfiMaxMemoryType) {\r
       continue;\r
     }\r
     if (Type < 0 || 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
     if (gMemoryTypeInformation[Index].NumberOfPages != 0) {\r
       //\r
       // Allocate pages for the current memory type from the top of available memory\r
@@ -330,7 +568,7 @@ Returns:
                  );\r
       if (EFI_ERROR (Status)) {\r
         //\r
                  );\r
       if (EFI_ERROR (Status)) {\r
         //\r
-        // If an error occurs allocating the pages for the current memory type, then \r
+        // If an error occurs allocating the pages for the current memory type, then\r
         // free all the pages allocates for the previous memory types and return.  This\r
         // operation with be retied when/if more memory is added to the system\r
         //\r
         // free all the pages allocates for the previous memory types and return.  This\r
         // operation with be retied when/if more memory is added to the system\r
         //\r
@@ -345,11 +583,11 @@ Returns:
 \r
           if (gMemoryTypeInformation[FreeIndex].NumberOfPages != 0) {\r
             CoreFreePages (\r
 \r
           if (gMemoryTypeInformation[FreeIndex].NumberOfPages != 0) {\r
             CoreFreePages (\r
-              mMemoryTypeStatistics[Type].BaseAddress, \r
+              mMemoryTypeStatistics[Type].BaseAddress,\r
               gMemoryTypeInformation[FreeIndex].NumberOfPages\r
               );\r
             mMemoryTypeStatistics[Type].BaseAddress    = 0;\r
               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
           }\r
         }\r
         return;\r
@@ -358,12 +596,12 @@ Returns:
       //\r
       // Compute the address at the top of the current statistics\r
       //\r
       //\r
       // Compute the address at the top of the current statistics\r
       //\r
-      mMemoryTypeStatistics[Type].MaximumAddress = \r
-        mMemoryTypeStatistics[Type].BaseAddress + \r
+      mMemoryTypeStatistics[Type].MaximumAddress =\r
+        mMemoryTypeStatistics[Type].BaseAddress +\r
         LShiftU64 (gMemoryTypeInformation[Index].NumberOfPages, EFI_PAGE_SHIFT) - 1;\r
 \r
       //\r
         LShiftU64 (gMemoryTypeInformation[Index].NumberOfPages, EFI_PAGE_SHIFT) - 1;\r
 \r
       //\r
-      // If the current base address is the lowest address so far, then update the default \r
+      // If the current base address is the lowest address so far, then update the default\r
       // maximum address\r
       //\r
       if (mMemoryTypeStatistics[Type].BaseAddress < mDefaultMaximumAddress) {\r
       // maximum address\r
       //\r
       if (mMemoryTypeStatistics[Type].BaseAddress < mDefaultMaximumAddress) {\r
@@ -385,10 +623,9 @@ Returns:
     if (Type < 0 || Type > EfiMaxMemoryType) {\r
       continue;\r
     }\r
     if (Type < 0 || Type > EfiMaxMemoryType) {\r
       continue;\r
     }\r
-\r
     if (gMemoryTypeInformation[Index].NumberOfPages != 0) {\r
       CoreFreePages (\r
     if (gMemoryTypeInformation[Index].NumberOfPages != 0) {\r
       CoreFreePages (\r
-        mMemoryTypeStatistics[Type].BaseAddress, \r
+        mMemoryTypeStatistics[Type].BaseAddress,\r
         gMemoryTypeInformation[Index].NumberOfPages\r
         );\r
       mMemoryTypeStatistics[Type].NumberOfPages   = gMemoryTypeInformation[Index].NumberOfPages;\r
         gMemoryTypeInformation[Index].NumberOfPages\r
         );\r
       mMemoryTypeStatistics[Type].NumberOfPages   = gMemoryTypeInformation[Index].NumberOfPages;\r
@@ -407,336 +644,37 @@ Returns:
       }\r
     }\r
     mMemoryTypeStatistics[Type].CurrentNumberOfPages = 0;\r
       }\r
     }\r
     mMemoryTypeStatistics[Type].CurrentNumberOfPages = 0;\r
-    if (mMemoryTypeStatistics[Type].MaximumAddress == EFI_MAX_ADDRESS) {\r
-      mMemoryTypeStatistics[Type].MaximumAddress = mDefaultMaximumAddress;\r
-    }\r
-  }\r
-\r
-  mMemoryTypeInformationInitialized = TRUE;\r
-}\r
-\r
-\r
-STATIC\r
-VOID\r
-CoreAddRange (\r
-  IN EFI_MEMORY_TYPE          Type,\r
-  IN EFI_PHYSICAL_ADDRESS     Start,\r
-  IN EFI_PHYSICAL_ADDRESS     End,\r
-  IN UINT64                   Attribute\r
-  )\r
-/*++\r
-\r
-Routine Description:\r
-\r
-  Internal function.  Adds a ranges to the memory map.\r
-  The range must not already exist in the map.\r
-\r
-Arguments:\r
-\r
-  Type    - The type of memory range to add\r
-\r
-  Start   - The starting address in the memory range\r
-            Must be paged aligned\r
-\r
-  End     - The last address in the range\r
-          Must be the last byte of a page\r
-\r
-  Attribute - The attributes of the memory range to add\r
-\r
-Returns:\r
-\r
-  None.  The range is added to the memory map\r
-\r
---*/\r
-{\r
-  LIST_ENTRY        *Link;\r
-  MEMORY_MAP        *Entry;\r
-\r
-  ASSERT ((Start & EFI_PAGE_MASK) == 0);\r
-  ASSERT (End > Start) ;\r
-\r
-  ASSERT_LOCKED (&gMemoryLock);\r
-  \r
-  DEBUG ((EFI_D_PAGE, "AddRange: %lx-%lx to %d\n", Start, End, Type));\r
-\r
-  //\r
-  // Memory map being altered so updated key\r
-  //\r
-  mMemoryMapKey += 1;\r
-\r
-  //\r
-  // UEFI 2.0 added an event group for notificaiton on memory map changes.\r
-  // So we need to signal this Event Group every time the memory map changes.\r
-  // If we are in EFI 1.10 compatability mode no event groups will be \r
-  // found and nothing will happen we we call this function. These events\r
-  // will get signaled but since a lock is held around the call to this \r
-  // function the notificaiton events will only be called after this funciton\r
-  // returns and the lock is released.\r
-  //\r
-  CoreNotifySignalList (&gEfiEventMemoryMapChangeGuid);\r
-\r
-  //\r
-  // Look for adjoining memory descriptor\r
-  //\r
-  \r
-  // Two memory descriptors can only be merged if they have the same Type\r
-  // and the same Attribute\r
-  //\r
-\r
-  Link = gMemoryMap.ForwardLink;\r
-  while (Link != &gMemoryMap) {\r
-    Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
-    Link  = Link->ForwardLink;\r
-\r
-    if (Entry->Type != Type) {\r
-      continue;\r
-    }\r
-\r
-    if (Entry->Attribute != Attribute) {\r
-      continue;\r
-    }\r
-\r
-    if (Entry->End + 1 == Start) {\r
-      \r
-      Start = Entry->Start;\r
-      RemoveMemoryMapEntry (Entry);\r
-\r
-    } else if (Entry->Start == End + 1) {\r
-      \r
-      End = Entry->End;\r
-      RemoveMemoryMapEntry (Entry);\r
-    }\r
-  }\r
-\r
-  //\r
-  // Add descriptor \r
-  //\r
-\r
-  mMapStack[mMapDepth].Signature     = MEMORY_MAP_SIGNATURE;\r
-  mMapStack[mMapDepth].FromPages      = FALSE;\r
-  mMapStack[mMapDepth].Type          = Type;\r
-  mMapStack[mMapDepth].Start         = Start;\r
-  mMapStack[mMapDepth].End           = End;\r
-  mMapStack[mMapDepth].VirtualStart  = 0;\r
-  mMapStack[mMapDepth].Attribute     = Attribute;\r
-  InsertTailList (&gMemoryMap, &mMapStack[mMapDepth].Link);\r
-\r
-  mMapDepth += 1;\r
-  ASSERT (mMapDepth < MAX_MAP_DEPTH);\r
-\r
-  return ;\r
-}\r
-\r
-STATIC\r
-VOID\r
-CoreFreeMemoryMapStack (\r
-  VOID\r
-  )\r
-/*++\r
-\r
-Routine Description:\r
-\r
-  Internal function.  Moves any memory descriptors that are on the\r
-  temporary descriptor stack to heap.\r
-\r
-Arguments:\r
-\r
-  None\r
-\r
-Returns:\r
-\r
-  None\r
-\r
---*/\r
-{\r
-  MEMORY_MAP      *Entry;\r
-  MEMORY_MAP      *Entry2;\r
-  LIST_ENTRY      *Link2;\r
-\r
-  ASSERT_LOCKED (&gMemoryLock);\r
-\r
-  //\r
-  // If already freeing the map stack, then return\r
-  //\r
-  if (mFreeMapStack) {\r
-    return ;\r
-  }\r
-\r
-  //\r
-  // Move the temporary memory descriptor stack into pool\r
-  //\r
-  mFreeMapStack += 1;\r
-\r
-  while (mMapDepth) {\r
-    //\r
-    // Deque an memory map entry from mFreeMemoryMapEntryList \r
-    //\r
-    Entry = AllocateMemoryMapEntry ();\r
-    \r
-    ASSERT (Entry);\r
-\r
-    //\r
-    // Update to proper entry\r
-    //\r
-    mMapDepth -= 1;\r
-\r
-    if (mMapStack[mMapDepth].Link.ForwardLink != NULL) {\r
-\r
-      //\r
-      // Move this entry to general memory\r
-      //\r
-      RemoveEntryList (&mMapStack[mMapDepth].Link);\r
-      mMapStack[mMapDepth].Link.ForwardLink = NULL;\r
-\r
-      CopyMem (Entry , &mMapStack[mMapDepth], sizeof (MEMORY_MAP));\r
-      Entry->FromPages = TRUE;\r
-\r
-      //\r
-      // Find insertion location\r
-      //\r
-      for (Link2 = gMemoryMap.ForwardLink; Link2 != &gMemoryMap; Link2 = Link2->ForwardLink) {\r
-        Entry2 = CR (Link2, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
-        if (Entry2->FromPages && Entry2->Start > Entry->Start) {\r
-          break;\r
-        }\r
-      }\r
-\r
-      InsertTailList (Link2, &Entry->Link);\r
-\r
-    } else {\r
-      // \r
-      // This item of mMapStack[mMapDepth] has already been dequeued from gMemoryMap list,\r
-      // so here no need to move it to memory.\r
-      //\r
-      InsertTailList (&mFreeMemoryMapEntryList, &Entry->Link);\r
+    if (mMemoryTypeStatistics[Type].MaximumAddress == MAX_ADDRESS) {\r
+      mMemoryTypeStatistics[Type].MaximumAddress = mDefaultMaximumAddress;\r
     }\r
   }\r
 \r
     }\r
   }\r
 \r
-  mFreeMapStack -= 1;\r
-}\r
-\r
-STATIC\r
-VOID\r
-RemoveMemoryMapEntry (\r
-  MEMORY_MAP      *Entry\r
-  )\r
-/*++\r
-\r
-Routine Description:\r
-\r
-  Internal function.  Removes a descriptor entry.\r
-\r
-Arguments:\r
-\r
-  Entry   - The entry to remove\r
-\r
-Returns:\r
-\r
-  None\r
-\r
---*/\r
-{\r
-  RemoveEntryList (&Entry->Link);\r
-  Entry->Link.ForwardLink = NULL;\r
-\r
-  if (Entry->FromPages) {\r
-       //\r
-       // Insert the free memory map descriptor to the end of mFreeMemoryMapEntryList\r
-       //\r
-    InsertTailList (&mFreeMemoryMapEntryList, &Entry->Link);\r
-  }\r
+  mMemoryTypeInformationInitialized = TRUE;\r
 }\r
 \r
 }\r
 \r
-STATIC\r
-MEMORY_MAP *\r
-AllocateMemoryMapEntry (\r
-  VOID\r
-  )\r
-/*++\r
-\r
-Routine Description:\r
-\r
-  Internal function.  Deque a descriptor entry from the mFreeMemoryMapEntryList.\r
-  If the list is emtry, then allocate a new page to refuel the list. \r
-  Please Note this algorithm to allocate the memory map descriptor has a property\r
-  that the memory allocated for memory entries always grows, and will never really be freed \r
-  For example, if the current boot uses 2000 memory map entries at the maximum point, but\r
-  ends up with only 50 at the time the OS is booted, then the memory associated with the 1950 \r
-  memory map entries is still allocated from EfiBootServicesMemory.  \r
-\r
-Arguments:\r
-\r
-  NONE\r
 \r
 \r
-Returns:\r
+/**\r
+  Internal function.  Converts a memory range to the specified type.\r
+  The range must exist in the memory map.\r
 \r
 \r
-  The Memory map descriptor dequed from the mFreeMemoryMapEntryList\r
+  @param  Start                  The first address of the range Must be page\r
+                                 aligned\r
+  @param  NumberOfPages          The number of pages to convert\r
+  @param  NewType                The new type for the memory range\r
 \r
 \r
---*/ \r
-{\r
-  MEMORY_MAP*            FreeDescriptorEntries;\r
-  MEMORY_MAP*            Entry;\r
-  UINTN                  Index;\r
-  \r
-  if (IsListEmpty (&mFreeMemoryMapEntryList)) {\r
-    // \r
-    // The list is empty, to allocate one page to refuel the list\r
-    //\r
-    FreeDescriptorEntries = CoreAllocatePoolPages (EfiBootServicesData, EFI_SIZE_TO_PAGES(DEFAULT_PAGE_ALLOCATION), DEFAULT_PAGE_ALLOCATION);\r
-    if(FreeDescriptorEntries != NULL) {\r
-      //\r
-      // Enque the free memmory map entries into the list\r
-      //\r
-      for (Index = 0; Index< DEFAULT_PAGE_ALLOCATION / sizeof(MEMORY_MAP); Index++) {\r
-        FreeDescriptorEntries[Index].Signature = MEMORY_MAP_SIGNATURE;\r
-        InsertTailList (&mFreeMemoryMapEntryList, &FreeDescriptorEntries[Index].Link);\r
-      }     \r
-    } else {\r
-      return NULL;\r
-    }\r
-  }\r
-  //\r
-  // dequeue the first descriptor from the list\r
-  //\r
-  Entry = CR (mFreeMemoryMapEntryList.ForwardLink, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
-  RemoveEntryList (&Entry->Link);\r
-  \r
-  return Entry;\r
-}    \r
+  @retval EFI_INVALID_PARAMETER  Invalid parameter\r
+  @retval EFI_NOT_FOUND          Could not find a descriptor cover the specified\r
+                                 range  or convertion not allowed.\r
+  @retval EFI_SUCCESS            Successfully converts the memory range to the\r
+                                 specified type.\r
 \r
 \r
-STATIC\r
+**/\r
 EFI_STATUS\r
 CoreConvertPages (\r
   IN UINT64           Start,\r
   IN UINT64           NumberOfPages,\r
   IN EFI_MEMORY_TYPE  NewType\r
   )\r
 EFI_STATUS\r
 CoreConvertPages (\r
   IN UINT64           Start,\r
   IN UINT64           NumberOfPages,\r
   IN EFI_MEMORY_TYPE  NewType\r
   )\r
-/*++\r
-\r
-Routine Description:\r
-\r
-  Internal function.  Converts a memory range to the specified type.\r
-  The range must exist in the memory map.\r
-\r
-Arguments:\r
-\r
-  Start         - The first address of the range\r
-                  Must be page aligned\r
-\r
-  NumberOfPages - The number of pages to convert\r
-\r
-  NewType       - The new type for the memory range\r
-\r
-Returns:\r
-\r
-  EFI_INVALID_PARAMETER   - Invalid parameter\r
-  \r
-  EFI_NOT_FOUND           - Could not find a descriptor cover the specified range \r
-                            or convertion not allowed.\r
-  \r
-  EFI_SUCCESS             - Successfully converts the memory range to the specified type.\r
-\r
---*/\r
 {\r
 \r
   UINT64          NumberOfBytes;\r
 {\r
 \r
   UINT64          NumberOfBytes;\r
@@ -755,7 +693,7 @@ Returns:
   ASSERT (End > Start) ;\r
   ASSERT_LOCKED (&gMemoryLock);\r
 \r
   ASSERT (End > Start) ;\r
   ASSERT_LOCKED (&gMemoryLock);\r
 \r
-  if (NumberOfPages == 0 || (Start & EFI_PAGE_MASK ) || (Start > (Start + NumberOfBytes))) {\r
+  if (NumberOfPages == 0 || ((Start & EFI_PAGE_MASK) != 0) || (Start > (Start + NumberOfBytes))) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
@@ -777,7 +715,7 @@ Returns:
     }\r
 \r
     if (Link == &gMemoryMap) {\r
     }\r
 \r
     if (Link == &gMemoryMap) {\r
-      DEBUG ((EFI_D_ERROR | EFI_D_PAGE, "ConvertPages: failed to find range %lx - %lx\n", Start, End));\r
+      DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "ConvertPages: failed to find range %lx - %lx\n", Start, End));\r
       return EFI_NOT_FOUND;\r
     }\r
 \r
       return EFI_NOT_FOUND;\r
     }\r
 \r
@@ -786,25 +724,27 @@ Returns:
     // if that's all we've got\r
     //\r
     RangeEnd = End;\r
     // 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
 \r
     if (Entry->End < End) {\r
       RangeEnd = Entry->End;\r
     }\r
 \r
-    DEBUG ((EFI_D_PAGE, "ConvertRange: %lx-%lx to %d\n", Start, RangeEnd, NewType));\r
+    DEBUG ((DEBUG_PAGE, "ConvertRange: %lx-%lx to %d\n", Start, RangeEnd, NewType));\r
 \r
     //\r
     // Debug code - verify conversion is allowed\r
     //\r
     if (!(NewType == EfiConventionalMemory ? 1 : 0) ^ (Entry->Type == EfiConventionalMemory ? 1 : 0)) {\r
 \r
     //\r
     // Debug code - verify conversion is allowed\r
     //\r
     if (!(NewType == EfiConventionalMemory ? 1 : 0) ^ (Entry->Type == EfiConventionalMemory ? 1 : 0)) {\r
-      DEBUG ((EFI_D_ERROR , "ConvertPages: Incompatible memory types\n"));\r
+      DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "ConvertPages: Incompatible memory types\n"));\r
       return EFI_NOT_FOUND;\r
       return EFI_NOT_FOUND;\r
-    }  \r
+    }\r
 \r
     //\r
     // Update counters for the number of pages allocated to each memory type\r
     //\r
     if (Entry->Type >= 0 && Entry->Type < EfiMaxMemoryType) {\r
 \r
     //\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
+      if (Start >= mMemoryTypeStatistics[Entry->Type].BaseAddress &&\r
           Start <= mMemoryTypeStatistics[Entry->Type].MaximumAddress) {\r
         if (NumberOfPages > mMemoryTypeStatistics[Entry->Type].CurrentNumberOfPages) {\r
           mMemoryTypeStatistics[Entry->Type].CurrentNumberOfPages = 0;\r
           Start <= mMemoryTypeStatistics[Entry->Type].MaximumAddress) {\r
         if (NumberOfPages > mMemoryTypeStatistics[Entry->Type].CurrentNumberOfPages) {\r
           mMemoryTypeStatistics[Entry->Type].CurrentNumberOfPages = 0;\r
@@ -817,7 +757,7 @@ Returns:
     if (NewType >= 0 && NewType < EfiMaxMemoryType) {\r
       if (Start >= mMemoryTypeStatistics[NewType].BaseAddress && Start <= mMemoryTypeStatistics[NewType].MaximumAddress) {\r
         mMemoryTypeStatistics[NewType].CurrentNumberOfPages += NumberOfPages;\r
     if (NewType >= 0 && NewType < EfiMaxMemoryType) {\r
       if (Start >= mMemoryTypeStatistics[NewType].BaseAddress && Start <= mMemoryTypeStatistics[NewType].MaximumAddress) {\r
         mMemoryTypeStatistics[NewType].CurrentNumberOfPages += NumberOfPages;\r
-        if (mMemoryTypeStatistics[NewType].CurrentNumberOfPages > \r
+        if (mMemoryTypeStatistics[NewType].CurrentNumberOfPages >\r
             gMemoryTypeInformation[mMemoryTypeStatistics[NewType].InformationIndex].NumberOfPages) {\r
           gMemoryTypeInformation[mMemoryTypeStatistics[NewType].InformationIndex].NumberOfPages = (UINT32)mMemoryTypeStatistics[NewType].CurrentNumberOfPages;\r
         }\r
             gMemoryTypeInformation[mMemoryTypeStatistics[NewType].InformationIndex].NumberOfPages) {\r
           gMemoryTypeInformation[mMemoryTypeStatistics[NewType].InformationIndex].NumberOfPages = (UINT32)mMemoryTypeStatistics[NewType].CurrentNumberOfPages;\r
         }\r
@@ -828,14 +768,14 @@ Returns:
     // Pull range out of descriptor\r
     //\r
     if (Entry->Start == Start) {\r
     // Pull range out of descriptor\r
     //\r
     if (Entry->Start == Start) {\r
-      \r
+\r
       //\r
       // Clip start\r
       //\r
       Entry->Start = RangeEnd + 1;\r
 \r
     } else if (Entry->End == RangeEnd) {\r
       //\r
       // Clip start\r
       //\r
       Entry->Start = RangeEnd + 1;\r
 \r
     } else if (Entry->End == RangeEnd) {\r
-      \r
+\r
       //\r
       // Clip end\r
       //\r
       //\r
       // Clip end\r
       //\r
@@ -846,7 +786,7 @@ Returns:
       //\r
       // Pull it out of the center, clip current\r
       //\r
       //\r
       // Pull it out of the center, clip current\r
       //\r
-      \r
+\r
       //\r
       // Add a new one\r
       //\r
       //\r
       // Add a new one\r
       //\r
@@ -872,7 +812,7 @@ Returns:
     }\r
 \r
     //\r
     }\r
 \r
     //\r
-    // The new range inherits the same Attribute as the Entry \r
+    // The new range inherits the same Attribute as the Entry\r
     //it is being cut out of\r
     //\r
     Attribute = Entry->Attribute;\r
     //it is being cut out of\r
     //\r
     Attribute = Entry->Attribute;\r
@@ -884,11 +824,14 @@ Returns:
       RemoveMemoryMapEntry (Entry);\r
       Entry = NULL;\r
     }\r
       RemoveMemoryMapEntry (Entry);\r
       Entry = NULL;\r
     }\r
-    \r
+\r
     //\r
     // Add our new range in\r
     //\r
     CoreAddRange (NewType, Start, RangeEnd, Attribute);\r
     //\r
     // Add our new range in\r
     //\r
     CoreAddRange (NewType, Start, RangeEnd, Attribute);\r
+    if (NewType == EfiConventionalMemory) {\r
+      DEBUG_CLEAR_MEMORY ((VOID *)(UINTN) Start, (UINTN) (RangeEnd - Start + 1));\r
+    }\r
 \r
     //\r
     // Move any map descriptor stack to general pool\r
 \r
     //\r
     // Move any map descriptor stack to general pool\r
@@ -909,7 +852,20 @@ Returns:
 }\r
 \r
 \r
 }\r
 \r
 \r
-STATIC\r
+\r
+/**\r
+  Internal function. Finds a consecutive free page range below\r
+  the requested address.\r
+\r
+  @param  MaxAddress             The address that the range must be below\r
+  @param  NumberOfPages          Number of pages needed\r
+  @param  NewType                The type of memory the range is going to be\r
+                                 turned into\r
+  @param  Alignment              Bits to align with\r
+\r
+  @return The base address of the range, or 0 if the range was not found\r
+\r
+**/\r
 UINT64\r
 CoreFindFreePagesI (\r
   IN UINT64           MaxAddress,\r
 UINT64\r
 CoreFindFreePagesI (\r
   IN UINT64           MaxAddress,\r
@@ -917,28 +873,6 @@ CoreFindFreePagesI (
   IN EFI_MEMORY_TYPE  NewType,\r
   IN UINTN            Alignment\r
   )\r
   IN EFI_MEMORY_TYPE  NewType,\r
   IN UINTN            Alignment\r
   )\r
-/*++\r
-\r
-Routine Description:\r
-\r
-  Internal function. Finds a consecutive free page range below\r
-  the requested address.\r
-\r
-Arguments:\r
-\r
-  MaxAddress    - The address that the range must be below\r
-\r
-  NumberOfPages - Number of pages needed\r
-\r
-  NewType       - The type of memory the range is going to be turned into\r
-\r
-  Alignment     - Bits to align with\r
-\r
-Returns:\r
-\r
-  The base address of the range, or 0 if the range was not found\r
-\r
---*/\r
 {\r
   UINT64          NumberOfBytes;\r
   UINT64          Target;\r
 {\r
   UINT64          NumberOfBytes;\r
   UINT64          Target;\r
@@ -953,21 +887,21 @@ Returns:
   }\r
 \r
   if ((MaxAddress & EFI_PAGE_MASK) != EFI_PAGE_MASK) {\r
   }\r
 \r
   if ((MaxAddress & EFI_PAGE_MASK) != EFI_PAGE_MASK) {\r
-    \r
+\r
     //\r
     // If MaxAddress is not aligned to the end of a page\r
     //\r
     //\r
     // If MaxAddress is not aligned to the end of a page\r
     //\r
-    \r
+\r
     //\r
     // Change MaxAddress to be 1 page lower\r
     //\r
     MaxAddress -= (EFI_PAGE_MASK + 1);\r
     //\r
     // Change MaxAddress to be 1 page lower\r
     //\r
     MaxAddress -= (EFI_PAGE_MASK + 1);\r
-    \r
+\r
     //\r
     // Set MaxAddress to a page boundary\r
     //\r
     MaxAddress &= ~EFI_PAGE_MASK;\r
     //\r
     // Set MaxAddress to a page boundary\r
     //\r
     MaxAddress &= ~EFI_PAGE_MASK;\r
-    \r
+\r
     //\r
     // Set MaxAddress to end of the page\r
     //\r
     //\r
     // Set MaxAddress to end of the page\r
     //\r
@@ -979,7 +913,7 @@ Returns:
 \r
   for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
     Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
 \r
   for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
     Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
-  \r
+\r
     //\r
     // If it's not a free entry, don't bother with it\r
     //\r
     //\r
     // If it's not a free entry, don't bother with it\r
     //\r
@@ -1007,7 +941,7 @@ Returns:
     DescEnd = ((DescEnd + 1) & (~(Alignment - 1))) - 1;\r
 \r
     //\r
     DescEnd = ((DescEnd + 1) & (~(Alignment - 1))) - 1;\r
 \r
     //\r
-    // Compute the number of bytes we can used from this \r
+    // Compute the number of bytes we can used from this\r
     // descriptor, and see it's enough to satisfy the request\r
     //\r
     DescNumberOfBytes = DescEnd - DescStart + 1;\r
     // descriptor, and see it's enough to satisfy the request\r
     //\r
     DescNumberOfBytes = DescEnd - DescStart + 1;\r
@@ -1021,7 +955,7 @@ Returns:
         Target = DescEnd;\r
       }\r
     }\r
         Target = DescEnd;\r
       }\r
     }\r
-  }          \r
+  }\r
 \r
   //\r
   // If this is a grow down, adjust target to be the allocation base\r
 \r
   //\r
   // If this is a grow down, adjust target to be the allocation base\r
@@ -1038,7 +972,20 @@ Returns:
   return Target;\r
 }\r
 \r
   return Target;\r
 }\r
 \r
-STATIC\r
+\r
+/**\r
+  Internal function.  Finds a consecutive free page range below\r
+  the requested address\r
+\r
+  @param  MaxAddress             The address that the range must be below\r
+  @param  NoPages                Number of pages needed\r
+  @param  NewType                The type of memory the range is going to be\r
+                                 turned into\r
+  @param  Alignment              Bits to align with\r
+\r
+  @return The base address of the range, or 0 if the range was not found.\r
+\r
+**/\r
 UINT64\r
 FindFreePages (\r
     IN UINT64           MaxAddress,\r
 UINT64\r
 FindFreePages (\r
     IN UINT64           MaxAddress,\r
@@ -1046,28 +993,6 @@ FindFreePages (
     IN EFI_MEMORY_TYPE  NewType,\r
     IN UINTN            Alignment\r
     )\r
     IN EFI_MEMORY_TYPE  NewType,\r
     IN UINTN            Alignment\r
     )\r
-/*++\r
-\r
-Routine Description:\r
-\r
-    Internal function.  Finds a consecutive free page range below\r
-    the requested address\r
-\r
-Arguments:\r
-\r
-    MaxAddress          - The address that the range must be below\r
-\r
-    NoPages             - Number of pages needed\r
-\r
-    NewType             - The type of memory the range is going to be turned into\r
-\r
-    Alignment           - Bits to align with\r
-\r
-Returns:\r
-\r
-    The base address of the range, or 0 if the range was not found.\r
-\r
---*/\r
 {\r
   UINT64  NewMaxAddress;\r
   UINT64  Start;\r
 {\r
   UINT64  NewMaxAddress;\r
   UINT64  Start;\r
@@ -1083,9 +1008,9 @@ Returns:
   }\r
 \r
   Start = CoreFindFreePagesI (NewMaxAddress, NoPages, NewType, Alignment);\r
   }\r
 \r
   Start = CoreFindFreePagesI (NewMaxAddress, NoPages, NewType, Alignment);\r
-  if (!Start) {\r
+  if (Start == 0) {\r
     Start = CoreFindFreePagesI (MaxAddress, NoPages, NewType, Alignment);\r
     Start = CoreFindFreePagesI (MaxAddress, NoPages, NewType, Alignment);\r
-    if (!Start) {\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
       // 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
@@ -1103,6 +1028,25 @@ Returns:
 }\r
 \r
 \r
 }\r
 \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
 EFI_STATUS\r
 EFIAPI\r
 CoreAllocatePages (\r
@@ -1111,35 +1055,6 @@ CoreAllocatePages (
   IN UINTN                  NumberOfPages,\r
   IN OUT EFI_PHYSICAL_ADDRESS  *Memory\r
   )\r
   IN UINTN                  NumberOfPages,\r
   IN OUT EFI_PHYSICAL_ADDRESS  *Memory\r
   )\r
-/*++\r
-\r
-Routine Description:\r
-\r
-  Allocates pages from the memory map.\r
-\r
-Arguments:\r
-\r
-  Type          - The type of allocation to perform\r
-\r
-  MemoryType    - The type of memory to turn the allocated pages into\r
-\r
-  NumberOfPages - The number of pages to allocate\r
-\r
-  Memory        - A pointer to receive the base allocated memory address\r
-\r
-Returns:\r
-\r
-  Status. On success, Memory is filled in with the base address allocated\r
-\r
-  EFI_INVALID_PARAMETER     - Parameters violate checking rules defined in spec.\r
-  \r
-  EFI_NOT_FOUND             - Could not allocate pages match the requirement.\r
-  \r
-  EFI_OUT_OF_RESOURCES      - No enough pages to allocate.\r
-  \r
-  EFI_SUCCESS               - Pages successfully allocated.\r
-\r
---*/\r
 {\r
   EFI_STATUS      Status;\r
   UINT64          Start;\r
 {\r
   EFI_STATUS      Status;\r
   UINT64          Start;\r
@@ -1175,21 +1090,21 @@ Returns:
   NumberOfPages &= ~(EFI_SIZE_TO_PAGES (Alignment) - 1);\r
 \r
   //\r
   NumberOfPages &= ~(EFI_SIZE_TO_PAGES (Alignment) - 1);\r
 \r
   //\r
-  // If this is for below a particular address, then \r
+  // If this is for below a particular address, then\r
   //\r
   Start = *Memory;\r
   //\r
   Start = *Memory;\r
-  \r
+\r
   //\r
   // The max address is the max natively addressable address for the processor\r
   //\r
   //\r
   // The max address is the max natively addressable address for the processor\r
   //\r
-  MaxAddress = EFI_MAX_ADDRESS;\r
-  \r
+  MaxAddress = MAX_ADDRESS;\r
+\r
   if (Type == AllocateMaxAddress) {\r
     MaxAddress = Start;\r
   }\r
 \r
   CoreAcquireMemoryLock ();\r
   if (Type == AllocateMaxAddress) {\r
     MaxAddress = Start;\r
   }\r
 \r
   CoreAcquireMemoryLock ();\r
-  \r
+\r
   //\r
   // If not a specific address, then find an address to allocate\r
   //\r
   //\r
   // If not a specific address, then find an address to allocate\r
   //\r
@@ -1217,35 +1132,23 @@ Done:
 }\r
 \r
 \r
 }\r
 \r
 \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
 \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
+**/\r
+EFI_STATUS\r
 EFIAPI\r
 CoreFreePages (\r
   IN EFI_PHYSICAL_ADDRESS   Memory,\r
   IN UINTN                  NumberOfPages\r
   )\r
 EFIAPI\r
 CoreFreePages (\r
   IN EFI_PHYSICAL_ADDRESS   Memory,\r
   IN UINTN                  NumberOfPages\r
   )\r
-/*++\r
-\r
-Routine Description:\r
-\r
-  Frees previous allocated pages.\r
-\r
-Arguments:\r
-\r
-  Memory        - Base address of memory being freed\r
-\r
-  NumberOfPages - The number of pages to free\r
-\r
-Returns:\r
-\r
-  EFI_NOT_FOUND       - Could not find the entry that covers the range\r
-  \r
-  EFI_INVALID_PARAMETER   - Address not aligned\r
-  \r
-  EFI_SUCCESS         -Pages successfully freed.\r
-\r
---*/\r
 {\r
   EFI_STATUS      Status;\r
   LIST_ENTRY      *Link;\r
 {\r
   EFI_STATUS      Status;\r
   LIST_ENTRY      *Link;\r
@@ -1268,12 +1171,13 @@ Returns:
     }\r
   }\r
   if (Link == &gMemoryMap) {\r
     }\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
   }\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
   if  (Entry->Type == EfiACPIReclaimMemory   ||\r
        Entry->Type == EfiACPIMemoryNVS       ||\r
        Entry->Type == EfiRuntimeServicesCode ||\r
@@ -1284,8 +1188,8 @@ Returns:
   }\r
 \r
   if ((Memory & (Alignment - 1)) != 0) {\r
   }\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
   }\r
 \r
   NumberOfPages += EFI_SIZE_TO_PAGES (Alignment) - 1;\r
@@ -1293,24 +1197,46 @@ Returns:
 \r
   Status = CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory);\r
 \r
 \r
   Status = CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory);\r
 \r
-  CoreReleaseMemoryLock ();\r
-\r
   if (EFI_ERROR (Status)) {\r
   if (EFI_ERROR (Status)) {\r
-    return Status;\r
+    goto Done;\r
   }\r
 \r
   }\r
 \r
-  //\r
-  // Destroy the contents\r
-  //\r
-  if (Memory < EFI_MAX_ADDRESS) {\r
-    DEBUG_CLEAR_MEMORY ((VOID *)(UINTN)Memory, NumberOfPages << EFI_PAGE_SHIFT);\r
-  }\r
-  \r
+Done:\r
+  CoreReleaseMemoryLock ();\r
   return Status;\r
 }\r
 \r
 \r
   return Status;\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
+\r
+  @param  MemoryMapSize          A pointer to the size, in bytes, of the\r
+                                 MemoryMap buffer. On input, this is the size of\r
+                                 the buffer allocated by the caller.  On output,\r
+                                 it is the size of the buffer returned by the\r
+                                 firmware  if the buffer was large enough, or the\r
+                                 size of the buffer needed  to contain the map if\r
+                                 the buffer was too small.\r
+  @param  MemoryMap              A pointer to the buffer in which firmware places\r
+                                 the current memory map.\r
+  @param  MapKey                 A pointer to the location in which firmware\r
+                                 returns the key for the current memory map.\r
+  @param  DescriptorSize         A pointer to the location in which firmware\r
+                                 returns the size, in bytes, of an individual\r
+                                 EFI_MEMORY_DESCRIPTOR.\r
+  @param  DescriptorVersion      A pointer to the location in which firmware\r
+                                 returns the version number associated with the\r
+                                 EFI_MEMORY_DESCRIPTOR.\r
+\r
+  @retval EFI_SUCCESS            The memory map was returned in the MemoryMap\r
+                                 buffer.\r
+  @retval EFI_BUFFER_TOO_SMALL   The MemoryMap buffer was too small. The current\r
+                                 buffer size needed to hold the memory map is\r
+                                 returned in MemoryMapSize.\r
+  @retval EFI_INVALID_PARAMETER  One of the parameters has an invalid value.\r
 \r
 \r
+**/\r
 EFI_STATUS\r
 EFIAPI\r
 CoreGetMemoryMap (\r
 EFI_STATUS\r
 EFIAPI\r
 CoreGetMemoryMap (\r
@@ -1320,44 +1246,14 @@ CoreGetMemoryMap (
   OUT UINTN                     *DescriptorSize,\r
   OUT UINT32                    *DescriptorVersion\r
   )\r
   OUT UINTN                     *DescriptorSize,\r
   OUT UINT32                    *DescriptorVersion\r
   )\r
-/*++\r
-\r
-Routine Description:\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
-\r
-Arguments:\r
-\r
-  MemoryMapSize     - A pointer to the size, in bytes, of the MemoryMap buffer. On\r
-                      input, this is the size of the buffer allocated by the caller. \r
-                      On output, it is the size of the buffer returned by the firmware \r
-                      if the buffer was large enough, or the size of the buffer needed \r
-                      to contain the map if the buffer was too small.\r
-  MemoryMap         - A pointer to the buffer in which firmware places the current memory map.\r
-  MapKey            - A pointer to the location in which firmware returns the key for the\r
-                      current memory map.\r
-  DescriptorSize    - A pointer to the location in which firmware returns the size, in\r
-                      bytes, of an individual EFI_MEMORY_DESCRIPTOR.\r
-  DescriptorVersion - A pointer to the location in which firmware returns the version\r
-                      number associated with the EFI_MEMORY_DESCRIPTOR.\r
-\r
-Returns:\r
-\r
-  EFI_SUCCESS           - The memory map was returned in the MemoryMap buffer.       \r
-  EFI_BUFFER_TOO_SMALL  - The MemoryMap buffer was too small. The current buffer size\r
-                          needed to hold the memory map is returned in MemoryMapSize.\r
-  EFI_INVALID_PARAMETER - One of the parameters has an invalid value.                \r
-\r
---*/\r
 {\r
   EFI_STATUS                        Status;\r
 {\r
   EFI_STATUS                        Status;\r
-  UINTN                             Size;  \r
-  UINTN                             BufferSize;  \r
+  UINTN                             Size;\r
+  UINTN                             BufferSize;\r
   UINTN                             NumberOfRuntimeEntries;\r
   LIST_ENTRY                        *Link;\r
   UINTN                             NumberOfRuntimeEntries;\r
   LIST_ENTRY                        *Link;\r
-  MEMORY_MAP                        *Entry;  \r
-  EFI_GCD_MAP_ENTRY                 *GcdMapEntry;  \r
+  MEMORY_MAP                        *Entry;\r
+  EFI_GCD_MAP_ENTRY                 *GcdMapEntry;\r
   EFI_MEMORY_TYPE                   Type;\r
 \r
   //\r
   EFI_MEMORY_TYPE                   Type;\r
 \r
   //\r
@@ -1366,9 +1262,9 @@ Returns:
   if (MemoryMapSize == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
   if (MemoryMapSize == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
-  \r
+\r
   CoreAcquireGcdMemoryLock ();\r
   CoreAcquireGcdMemoryLock ();\r
-  \r
+\r
   //\r
   // Count the number of Reserved and MMIO entries that are marked for runtime use\r
   //\r
   //\r
   // Count the number of Reserved and MMIO entries that are marked for runtime use\r
   //\r
@@ -1395,7 +1291,7 @@ Returns:
   if (DescriptorSize != NULL) {\r
     *DescriptorSize = Size;\r
   }\r
   if (DescriptorSize != NULL) {\r
     *DescriptorSize = Size;\r
   }\r
-  \r
+\r
   if (DescriptorVersion != NULL) {\r
     *DescriptorVersion = EFI_MEMORY_DESCRIPTOR_VERSION;\r
   }\r
   if (DescriptorVersion != NULL) {\r
     *DescriptorVersion = EFI_MEMORY_DESCRIPTOR_VERSION;\r
   }\r
@@ -1437,8 +1333,8 @@ Returns:
     MemoryMap->NumberOfPages  = RShiftU64 (Entry->End - Entry->Start + 1, EFI_PAGE_SHIFT);\r
     //\r
     // If the memory type is EfiConventionalMemory, then determine if the range is part of a\r
     MemoryMap->NumberOfPages  = RShiftU64 (Entry->End - Entry->Start + 1, EFI_PAGE_SHIFT);\r
     //\r
     // If the memory type is EfiConventionalMemory, then determine if the range is part of a\r
-    // memory type bin and needs to be converted to the same memory type as the rest of the \r
-    // memory type bin in order to minimize EFI Memory Map changes across reboots.  This \r
+    // memory type bin and needs to be converted to the same memory type as the rest of the\r
+    // memory type bin in order to minimize EFI Memory Map changes across reboots.  This\r
     // improves the chances for a successful S4 resume in the presence of minor page allocation\r
     // differences across reboots.\r
     //\r
     // improves the chances for a successful S4 resume in the presence of minor page allocation\r
     // differences across reboots.\r
     //\r
@@ -1447,7 +1343,7 @@ Returns:
         if (mMemoryTypeStatistics[Type].Special                        &&\r
             mMemoryTypeStatistics[Type].NumberOfPages > 0              &&\r
             Entry->Start >= mMemoryTypeStatistics[Type].BaseAddress    &&\r
         if (mMemoryTypeStatistics[Type].Special                        &&\r
             mMemoryTypeStatistics[Type].NumberOfPages > 0              &&\r
             Entry->Start >= mMemoryTypeStatistics[Type].BaseAddress    &&\r
-            Entry->End   <= mMemoryTypeStatistics[Type].MaximumAddress    ) {\r
+            Entry->End   <= mMemoryTypeStatistics[Type].MaximumAddress) {\r
           MemoryMap->Type = Type;\r
         }\r
       }\r
           MemoryMap->Type = Type;\r
         }\r
       }\r
@@ -1456,8 +1352,8 @@ Returns:
     if (mMemoryTypeStatistics[MemoryMap->Type].Runtime) {\r
       MemoryMap->Attribute |= EFI_MEMORY_RUNTIME;\r
     }\r
     if (mMemoryTypeStatistics[MemoryMap->Type].Runtime) {\r
       MemoryMap->Attribute |= EFI_MEMORY_RUNTIME;\r
     }\r
-    \r
-    MemoryMap = NextMemoryDescriptor (MemoryMap, Size);\r
+\r
+    MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, Size);\r
   }\r
 \r
   for (Link = mGcdMemorySpaceMap.ForwardLink; Link != &mGcdMemorySpaceMap; Link = Link->ForwardLink) {\r
   }\r
 \r
   for (Link = mGcdMemorySpaceMap.ForwardLink; Link != &mGcdMemorySpaceMap; Link = Link->ForwardLink) {\r
@@ -1465,7 +1361,10 @@ Returns:
     if ((GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeReserved) ||\r
         (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo)) {\r
       if ((GcdMapEntry->Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {\r
     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
         MemoryMap->PhysicalStart = GcdMapEntry->BaseAddress;\r
         MemoryMap->VirtualStart  = 0;\r
         MemoryMap->NumberOfPages = RShiftU64 ((GcdMapEntry->EndAddress - GcdMapEntry->BaseAddress + 1), EFI_PAGE_SHIFT);\r
@@ -1481,126 +1380,103 @@ Returns:
           }\r
         }\r
 \r
           }\r
         }\r
 \r
-        MemoryMap = NextMemoryDescriptor (MemoryMap, Size);\r
+        MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, Size);\r
       }\r
     }\r
   }\r
       }\r
     }\r
   }\r
-  \r
+\r
   Status = EFI_SUCCESS;\r
 \r
 Done:\r
 \r
   CoreReleaseMemoryLock ();\r
   Status = EFI_SUCCESS;\r
 \r
 Done:\r
 \r
   CoreReleaseMemoryLock ();\r
-  \r
+\r
   CoreReleaseGcdMemoryLock ();\r
   CoreReleaseGcdMemoryLock ();\r
-  \r
-  // \r
-  // Update the map key finally \r
-  // \r
+\r
+  //\r
+  // Update the map key finally\r
+  //\r
   if (MapKey != NULL) {\r
     *MapKey = mMemoryMapKey;\r
   }\r
   if (MapKey != NULL) {\r
     *MapKey = mMemoryMapKey;\r
   }\r
-  \r
+\r
   *MemoryMapSize = BufferSize;\r
   *MemoryMapSize = BufferSize;\r
-  \r
+\r
   return Status;\r
 }\r
 \r
   return Status;\r
 }\r
 \r
-VOID *\r
-CoreAllocatePoolPages (\r
-  IN EFI_MEMORY_TYPE    PoolType,\r
-  IN UINTN              NumberOfPages,\r
-  IN UINTN              Alignment\r
-  )\r
-/*++\r
-\r
-Routine Description:\r
 \r
 \r
+/**\r
   Internal function.  Used by the pool functions to allocate pages\r
   to back pool allocation requests.\r
 \r
   Internal function.  Used by the pool functions to allocate pages\r
   to back pool allocation requests.\r
 \r
-Arguments:\r
+  @param  PoolType               The type of memory for the new pool pages\r
+  @param  NumberOfPages          No of pages to allocate\r
+  @param  Alignment              Bits to align.\r
 \r
 \r
-  PoolType      - The type of memory for the new pool pages\r
+  @return The allocated memory, or NULL\r
 \r
 \r
-  NumberOfPages - No of pages to allocate\r
-\r
-  Alignment     - Bits to align.\r
-\r
-Returns:\r
-\r
-  The allocated memory, or NULL\r
-\r
---*/\r
+**/\r
+VOID *\r
+CoreAllocatePoolPages (\r
+  IN EFI_MEMORY_TYPE    PoolType,\r
+  IN UINTN              NumberOfPages,\r
+  IN UINTN              Alignment\r
+  )\r
 {\r
   UINT64            Start;\r
 \r
   //\r
   // Find the pages to convert\r
   //\r
 {\r
   UINT64            Start;\r
 \r
   //\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
 \r
   //\r
   // Convert it to boot services data\r
   //\r
   if (Start == 0) {\r
-    DEBUG ((EFI_D_ERROR | EFI_D_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
 \r
   } else {\r
     CoreConvertPages (Start, NumberOfPages, PoolType);\r
   }\r
 \r
-  return (VOID *)(UINTN)Start;\r
+  return (VOID *)(UINTN) Start;\r
 }\r
 \r
 }\r
 \r
+\r
+/**\r
+  Internal function.  Frees pool pages allocated via AllocatePoolPages ()\r
+\r
+  @param  Memory                 The base address to free\r
+  @param  NumberOfPages          The number of pages to free\r
+\r
+**/\r
 VOID\r
 CoreFreePoolPages (\r
   IN EFI_PHYSICAL_ADDRESS   Memory,\r
   IN UINTN                  NumberOfPages\r
   )\r
 VOID\r
 CoreFreePoolPages (\r
   IN EFI_PHYSICAL_ADDRESS   Memory,\r
   IN UINTN                  NumberOfPages\r
   )\r
-/*++\r
-\r
-Routine Description:\r
-\r
-  Internal function.  Frees pool pages allocated via AllocatePoolPages ()\r
-\r
-Arguments:\r
-\r
-  Memory        - The base address to free\r
-\r
-  NumberOfPages - The number of pages to free\r
-\r
-Returns:\r
-\r
-  None\r
-\r
---*/\r
 {\r
   CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory);\r
 }\r
 \r
 \r
 {\r
   CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory);\r
 }\r
 \r
 \r
-EFI_STATUS\r
-CoreTerminateMemoryMap (\r
-  IN UINTN          MapKey\r
-  )\r
-/*++\r
-\r
-Routine Description:\r
 \r
 \r
-  Make sure the memory map is following all the construction rules, \r
+/**\r
+  Make sure the memory map is following all the construction rules,\r
   it is the last time to check memory map error before exit boot services.\r
 \r
   it is the last time to check memory map error before exit boot services.\r
 \r
-Arguments:\r
-\r
-  MapKey        - Memory map key\r
-\r
-Returns:\r
+  @param  MapKey                 Memory map key\r
 \r
 \r
-  EFI_INVALID_PARAMETER       - Memory map not consistent with construction rules.\r
-  \r
-  EFI_SUCCESS                 - Valid memory map.\r
+  @retval EFI_INVALID_PARAMETER  Memory map not consistent with construction\r
+                                 rules.\r
+  @retval EFI_SUCCESS            Valid memory map.\r
 \r
 \r
---*/\r
+**/\r
+EFI_STATUS\r
+CoreTerminateMemoryMap (\r
+  IN UINTN          MapKey\r
+  )\r
 {\r
   EFI_STATUS        Status;\r
   LIST_ENTRY        *Link;\r
 {\r
   EFI_STATUS        Status;\r
   LIST_ENTRY        *Link;\r
@@ -1620,21 +1496,21 @@ Returns:
 \r
     for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
       Entry = CR(Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
 \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
         if (Entry->Type == EfiACPIReclaimMemory || Entry->Type == EfiACPIMemoryNVS) {\r
-          DEBUG((EFI_D_ERROR, "ExitBootServices: ACPI memory entry has RUNTIME attribute set.\n"));\r
-          CoreReleaseMemoryLock ();\r
-          return EFI_INVALID_PARAMETER;\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
         }\r
-        if (Entry->Start & (EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT - 1)) {\r
-          DEBUG((EFI_D_ERROR, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n"));\r
-          CoreReleaseMemoryLock ();\r
-          return EFI_INVALID_PARAMETER;\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
         }\r
-        if ((Entry->End + 1) & (EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT - 1)) {\r
-          DEBUG((EFI_D_ERROR, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n"));\r
-          CoreReleaseMemoryLock ();\r
-          return EFI_INVALID_PARAMETER;\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
         }\r
       }\r
     }\r
         }\r
       }\r
     }\r
@@ -1650,6 +1526,7 @@ Returns:
     Status = EFI_INVALID_PARAMETER;\r
   }\r
 \r
     Status = EFI_INVALID_PARAMETER;\r
   }\r
 \r
+Done:\r
   CoreReleaseMemoryLock ();\r
 \r
   return Status;\r
   CoreReleaseMemoryLock ();\r
 \r
   return Status;\r
@@ -1662,3 +1539,4 @@ Returns:
 \r
 \r
 \r
 \r
 \r
 \r
+\r