]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Core/Dxe/Mem/Page.c
MdeModulePkg/DxeCore: Filter out all paging capabilities
[mirror_edk2.git] / MdeModulePkg / Core / Dxe / Mem / Page.c
index 84ebbca141c22810be6ed7b1d891b75c9c1f8431..962ae90d3dd68e48708761bff4610750a20ee9bd 100644 (file)
@@ -1,7 +1,7 @@
 /** @file\r
   UEFI Memory page management functions.\r
 \r
-Copyright (c) 2007 - 2015, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2007 - 2017, 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
@@ -14,8 +14,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 \r
 #include "DxeMain.h"\r
 #include "Imem.h"\r
-\r
-#define EFI_DEFAULT_PAGE_ALLOCATION_ALIGNMENT  (EFI_PAGE_SIZE)\r
+#include "HeapGuard.h"\r
 \r
 //\r
 // Entry for tracking the memory regions for each memory type to coalesce similar memory types\r
@@ -67,6 +66,7 @@ EFI_MEMORY_TYPE_STATISTICS mMemoryTypeStatistics[EfiMaxMemoryType + 1] = {
   { 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 },  // EfiPersistentMemory\r
   { 0, MAX_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE }   // EfiMaxMemoryType\r
 };\r
 \r
@@ -88,6 +88,7 @@ EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] = {
   { EfiMemoryMappedIO,          0 },\r
   { EfiMemoryMappedIOPortSpace, 0 },\r
   { EfiPalCode,                 0 },\r
+  { EfiPersistentMemory,        0 },\r
   { EfiMaxMemoryType,           0 }\r
 };\r
 //\r
@@ -188,7 +189,9 @@ CoreAddRange (
   // 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
+    if ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT0) == 0) {\r
+      SetMem ((VOID *)(UINTN)Start, EFI_PAGE_SIZE, 0);\r
+    }\r
   }\r
   \r
   //\r
@@ -202,7 +205,7 @@ CoreAddRange (
   // 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
+  // function the notificaiton events will only be called after this function\r
   // returns and the lock is released.\r
   //\r
   CoreNotifySignalList (&gEfiEventMemoryMapChangeGuid);\r
@@ -285,12 +288,17 @@ AllocateMemoryMapEntry (
     //\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
+    FreeDescriptorEntries = CoreAllocatePoolPages (\r
+                              EfiBootServicesData,\r
+                              EFI_SIZE_TO_PAGES (DEFAULT_PAGE_ALLOCATION_GRANULARITY),\r
+                              DEFAULT_PAGE_ALLOCATION_GRANULARITY,\r
+                              FALSE\r
+                              );\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
+      for (Index = 0; Index < DEFAULT_PAGE_ALLOCATION_GRANULARITY / sizeof(MEMORY_MAP); Index++) {\r
         FreeDescriptorEntries[Index].Signature = MEMORY_MAP_SIGNATURE;\r
         InsertTailList (&mFreeMemoryMapEntryList, &FreeDescriptorEntries[Index].Link);\r
       }\r
@@ -414,7 +422,11 @@ PromoteMemoryResource (
       //\r
       // Update the GCD map\r
       //\r
-      Entry->GcdMemoryType = EfiGcdMemoryTypeSystemMemory;\r
+      if ((Entry->Capabilities & EFI_MEMORY_MORE_RELIABLE) == EFI_MEMORY_MORE_RELIABLE) {\r
+        Entry->GcdMemoryType = EfiGcdMemoryTypeMoreReliable;\r
+      } else {\r
+        Entry->GcdMemoryType = EfiGcdMemoryTypeSystemMemory;\r
+      }\r
       Entry->Capabilities |= EFI_MEMORY_TESTED;\r
       Entry->ImageHandle  = gDxeCoreImageHandle;\r
       Entry->DeviceHandle = NULL;\r
@@ -538,7 +550,7 @@ CoreAddMemoryDescriptor (
     return;\r
   }\r
 \r
-  if (Type >= EfiMaxMemoryType && Type <= 0x7fffffff) {\r
+  if (Type >= EfiMaxMemoryType && Type < MEMORY_TYPE_OEM_RESERVED_MIN) {\r
     return;\r
   }\r
   CoreAcquireMemoryLock ();\r
@@ -547,6 +559,9 @@ CoreAddMemoryDescriptor (
   CoreFreeMemoryMapStack ();\r
   CoreReleaseMemoryLock ();\r
 \r
+  ApplyMemoryProtectionPolicy (EfiMaxMemoryType, Type, Start,\r
+    LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT));\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
@@ -719,7 +734,7 @@ CoreConvertPagesEx (
   ASSERT_LOCKED (&gMemoryLock);\r
   ASSERT ( (ChangingType == FALSE) || (ChangingAttributes == FALSE) );\r
 \r
-  if (NumberOfPages == 0 || ((Start & EFI_PAGE_MASK) != 0) || (Start > (Start + NumberOfBytes))) {\r
+  if (NumberOfPages == 0 || ((Start & EFI_PAGE_MASK) != 0) || (Start >= End)) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
@@ -745,6 +760,17 @@ CoreConvertPagesEx (
       return EFI_NOT_FOUND;\r
     }\r
 \r
+    //\r
+    // If we are converting the type of the range from EfiConventionalMemory to\r
+    // another type, we have to ensure that the entire range is covered by a\r
+    // single entry.\r
+    //\r
+    if (ChangingType && (NewType != EfiConventionalMemory)) {\r
+      if (Entry->End < End) {\r
+        DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "ConvertPages: range %lx - %lx covers multiple entries\n", Start, End));\r
+        return EFI_NOT_FOUND;\r
+      }\r
+    }\r
     //\r
     // Convert range to the end, or to the end of the descriptor\r
     // if that's all we've got\r
@@ -768,7 +794,12 @@ CoreConvertPagesEx (
       // Debug code - verify conversion is allowed\r
       //\r
       if (!(NewType == EfiConventionalMemory ? 1 : 0) ^ (Entry->Type == EfiConventionalMemory ? 1 : 0)) {\r
-        DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "ConvertPages: Incompatible memory types\n"));\r
+        DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "ConvertPages: Incompatible memory types, "));\r
+        if (Entry->Type == EfiConventionalMemory) {\r
+          DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "the pages to free have been freed\n"));\r
+        } else {\r
+          DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "the pages to allocate have been allocated\n"));\r
+        }\r
         return EFI_NOT_FOUND;\r
       }\r
 \r
@@ -869,17 +900,41 @@ CoreConvertPagesEx (
     //\r
     CoreAddRange (MemType, Start, RangeEnd, Attribute);\r
     if (ChangingType && (MemType == 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
+        //\r
+        // Avoid calling DEBUG_CLEAR_MEMORY() for an address of 0 because this\r
+        // macro will ASSERT() if address is 0.  Instead, CoreAddRange()\r
+        // guarantees that the page starting at address 0 is always filled\r
+        // with zeros.\r
+        //\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
+        // If Heap Guard is enabled, the page at the top and/or bottom of\r
+        // this memory block to free might be inaccessible. Skipping them\r
+        // to avoid page fault exception.\r
+        //\r
+        UINT64  StartToClear;\r
+        UINT64  EndToClear;\r
+\r
+        StartToClear = Start;\r
+        EndToClear   = RangeEnd;\r
+        if (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT1|BIT0)) {\r
+          if (IsGuardPage(StartToClear)) {\r
+            StartToClear += EFI_PAGE_SIZE;\r
+          }\r
+          if (IsGuardPage (EndToClear)) {\r
+            EndToClear -= EFI_PAGE_SIZE;\r
+          }\r
+          ASSERT (EndToClear > StartToClear);\r
+        }\r
+\r
+        DEBUG_CLEAR_MEMORY(\r
+          (VOID *)(UINTN)StartToClear,\r
+          (UINTN)(EndToClear - StartToClear + 1)\r
+          );\r
       }\r
     }\r
 \r
@@ -966,6 +1021,7 @@ CoreUpdateMemoryAttributes (
   @param  NewType                The type of memory the range is going to be\r
                                  turned into\r
   @param  Alignment              Bits to align with\r
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @return The base address of the range, or 0 if the range was not found\r
 \r
@@ -976,7 +1032,8 @@ CoreFindFreePagesI (
   IN UINT64           MinAddress,\r
   IN UINT64           NumberOfPages,\r
   IN EFI_MEMORY_TYPE  NewType,\r
-  IN UINTN            Alignment\r
+  IN UINTN            Alignment,\r
+  IN BOOLEAN          NeedGuard\r
   )\r
 {\r
   UINT64          NumberOfBytes;\r
@@ -1045,6 +1102,11 @@ CoreFindFreePagesI (
 \r
     DescEnd = ((DescEnd + 1) & (~(Alignment - 1))) - 1;\r
 \r
+    // Skip if DescEnd is less than DescStart after alignment clipping\r
+    if (DescEnd < DescStart) {\r
+      continue;\r
+    }\r
+\r
     //\r
     // Compute the number of bytes we can used from this\r
     // descriptor, and see it's enough to satisfy the request\r
@@ -1063,6 +1125,17 @@ CoreFindFreePagesI (
       // If this is the best match so far remember it\r
       //\r
       if (DescEnd > Target) {\r
+        if (NeedGuard) {\r
+          DescEnd = AdjustMemoryS (\r
+                      DescEnd + 1 - DescNumberOfBytes,\r
+                      DescNumberOfBytes,\r
+                      NumberOfBytes\r
+                      );\r
+          if (DescEnd == 0) {\r
+            continue;\r
+          }\r
+        }\r
+\r
         Target = DescEnd;\r
       }\r
     }\r
@@ -1093,6 +1166,7 @@ CoreFindFreePagesI (
   @param  NewType                The type of memory the range is going to be\r
                                  turned into\r
   @param  Alignment              Bits to align with\r
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @return The base address of the range, or 0 if the range was not found.\r
 \r
@@ -1102,7 +1176,8 @@ FindFreePages (
     IN UINT64           MaxAddress,\r
     IN UINT64           NoPages,\r
     IN EFI_MEMORY_TYPE  NewType,\r
-    IN UINTN            Alignment\r
+    IN UINTN            Alignment,\r
+    IN BOOLEAN          NeedGuard\r
     )\r
 {\r
   UINT64   Start;\r
@@ -1116,7 +1191,8 @@ FindFreePages (
               mMemoryTypeStatistics[NewType].BaseAddress, \r
               NoPages, \r
               NewType, \r
-              Alignment\r
+              Alignment,\r
+              NeedGuard\r
               );\r
     if (Start != 0) {\r
       return Start;\r
@@ -1127,7 +1203,8 @@ FindFreePages (
   // Attempt to find free pages in the default allocation bin\r
   //\r
   if (MaxAddress >= mDefaultMaximumAddress) {\r
-    Start = CoreFindFreePagesI (mDefaultMaximumAddress, 0, NoPages, NewType, Alignment);\r
+    Start = CoreFindFreePagesI (mDefaultMaximumAddress, 0, NoPages, NewType,\r
+                                Alignment, NeedGuard);\r
     if (Start != 0) {\r
       if (Start < mDefaultBaseAddress) {\r
         mDefaultBaseAddress = Start;\r
@@ -1142,7 +1219,8 @@ FindFreePages (
   // 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
+  Start = CoreFindFreePagesI (MaxAddress, 0, NoPages, NewType, Alignment,\r
+                              NeedGuard);\r
   if (Start != 0) {\r
     return Start;\r
   }\r
@@ -1157,7 +1235,7 @@ FindFreePages (
   //\r
   // If any memory resources were promoted, then re-attempt the allocation\r
   //\r
-  return FindFreePages (MaxAddress, NoPages, NewType, Alignment);\r
+  return FindFreePages (MaxAddress, NoPages, NewType, Alignment, NeedGuard);\r
 }\r
 \r
 \r
@@ -1170,6 +1248,7 @@ FindFreePages (
   @param  NumberOfPages          The number of pages to allocate\r
   @param  Memory                 A pointer to receive the base allocated memory\r
                                  address\r
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\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
@@ -1185,11 +1264,14 @@ CoreInternalAllocatePages (
   IN EFI_ALLOCATE_TYPE      Type,\r
   IN EFI_MEMORY_TYPE        MemoryType,\r
   IN UINTN                  NumberOfPages,\r
-  IN OUT EFI_PHYSICAL_ADDRESS  *Memory\r
+  IN OUT EFI_PHYSICAL_ADDRESS  *Memory,\r
+  IN BOOLEAN                NeedGuard\r
   )\r
 {\r
   EFI_STATUS      Status;\r
   UINT64          Start;\r
+  UINT64          NumberOfBytes;\r
+  UINT64          End;\r
   UINT64          MaxAddress;\r
   UINTN           Alignment;\r
 \r
@@ -1197,8 +1279,8 @@ CoreInternalAllocatePages (
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
-  if ((MemoryType >= EfiMaxMemoryType && MemoryType <= 0x7fffffff) ||\r
-       MemoryType == EfiConventionalMemory) {\r
+  if ((MemoryType >= EfiMaxMemoryType && MemoryType < MEMORY_TYPE_OEM_RESERVED_MIN) ||\r
+       (MemoryType == EfiConventionalMemory) || (MemoryType == EfiPersistentMemory)) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
@@ -1206,14 +1288,14 @@ CoreInternalAllocatePages (
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
-  Alignment = EFI_DEFAULT_PAGE_ALLOCATION_ALIGNMENT;\r
+  Alignment = DEFAULT_PAGE_ALLOCATION_GRANULARITY;\r
 \r
   if  (MemoryType == EfiACPIReclaimMemory   ||\r
        MemoryType == EfiACPIMemoryNVS       ||\r
        MemoryType == EfiRuntimeServicesCode ||\r
        MemoryType == EfiRuntimeServicesData) {\r
 \r
-    Alignment = EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT;\r
+    Alignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY;\r
   }\r
 \r
   if (Type == AllocateAddress) {\r
@@ -1235,6 +1317,30 @@ CoreInternalAllocatePages (
   //\r
   MaxAddress = MAX_ADDRESS;\r
 \r
+  //\r
+  // Check for Type AllocateAddress,\r
+  // if NumberOfPages is 0 or\r
+  // if (NumberOfPages << EFI_PAGE_SHIFT) is above MAX_ADDRESS or\r
+  // if (Start + NumberOfBytes) rolls over 0 or\r
+  // if Start is above MAX_ADDRESS or\r
+  // if End is above MAX_ADDRESS,\r
+  // return EFI_NOT_FOUND.\r
+  //\r
+  if (Type == AllocateAddress) {\r
+    if ((NumberOfPages == 0) ||\r
+        (NumberOfPages > RShiftU64 (MaxAddress, EFI_PAGE_SHIFT))) {\r
+      return EFI_NOT_FOUND;\r
+    }\r
+    NumberOfBytes = LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT);\r
+    End = Start + NumberOfBytes - 1;\r
+\r
+    if ((Start >= End) ||\r
+        (Start > MaxAddress) || \r
+        (End > MaxAddress)) {\r
+      return EFI_NOT_FOUND;\r
+    }\r
+  }\r
+\r
   if (Type == AllocateMaxAddress) {\r
     MaxAddress = Start;\r
   }\r
@@ -1245,7 +1351,8 @@ CoreInternalAllocatePages (
   // If not a specific address, then find an address to allocate\r
   //\r
   if (Type != AllocateAddress) {\r
-    Start = FindFreePages (MaxAddress, NumberOfPages, MemoryType, Alignment);\r
+    Start = FindFreePages (MaxAddress, NumberOfPages, MemoryType, Alignment,\r
+                           NeedGuard);\r
     if (Start == 0) {\r
       Status = EFI_OUT_OF_RESOURCES;\r
       goto Done;\r
@@ -1255,12 +1362,19 @@ CoreInternalAllocatePages (
   //\r
   // Convert pages from FreeMemory to the requested type\r
   //\r
-  Status = CoreConvertPages (Start, NumberOfPages, MemoryType);\r
+  if (NeedGuard) {\r
+    Status = CoreConvertPagesWithGuard(Start, NumberOfPages, MemoryType);\r
+  } else {\r
+    Status = CoreConvertPages(Start, NumberOfPages, MemoryType);\r
+  }\r
 \r
 Done:\r
   CoreReleaseMemoryLock ();\r
 \r
   if (!EFI_ERROR (Status)) {\r
+    if (NeedGuard) {\r
+      SetGuardForMemory (Start, NumberOfPages);\r
+    }\r
     *Memory = Start;\r
   }\r
 \r
@@ -1295,10 +1409,23 @@ CoreAllocatePages (
   )\r
 {\r
   EFI_STATUS  Status;\r
+  BOOLEAN     NeedGuard;\r
 \r
-  Status = CoreInternalAllocatePages (Type, MemoryType, NumberOfPages, Memory);\r
+  NeedGuard = IsPageTypeToGuard (MemoryType, Type) && !mOnGuarding;\r
+  Status = CoreInternalAllocatePages (Type, MemoryType, NumberOfPages, Memory,\r
+                                      NeedGuard);\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
+    CoreUpdateProfile (\r
+      (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0),\r
+      MemoryProfileActionAllocatePages,\r
+      MemoryType,\r
+      EFI_PAGES_TO_SIZE (NumberOfPages),\r
+      (VOID *) (UINTN) *Memory,\r
+      NULL\r
+      );\r
+    InstallMemoryAttributesTableOnMemoryAllocation (MemoryType);\r
+    ApplyMemoryProtectionPolicy (EfiConventionalMemory, MemoryType, *Memory,\r
+      EFI_PAGES_TO_SIZE (NumberOfPages));\r
   }\r
   return Status;\r
 }\r
@@ -1308,6 +1435,7 @@ CoreAllocatePages (
 \r
   @param  Memory                 Base address of memory being freed\r
   @param  NumberOfPages          The number of pages to free\r
+  @param  MemoryType             Pointer to memory type\r
 \r
   @retval EFI_NOT_FOUND          Could not find the entry that covers the range\r
   @retval EFI_INVALID_PARAMETER  Address not aligned\r
@@ -1318,13 +1446,15 @@ EFI_STATUS
 EFIAPI\r
 CoreInternalFreePages (\r
   IN EFI_PHYSICAL_ADDRESS   Memory,\r
-  IN UINTN                  NumberOfPages\r
+  IN UINTN                  NumberOfPages,\r
+  OUT EFI_MEMORY_TYPE       *MemoryType OPTIONAL\r
   )\r
 {\r
   EFI_STATUS      Status;\r
   LIST_ENTRY      *Link;\r
   MEMORY_MAP      *Entry;\r
   UINTN           Alignment;\r
+  BOOLEAN         IsGuarded;\r
 \r
   //\r
   // Free the range\r
@@ -1334,6 +1464,7 @@ CoreInternalFreePages (
   //\r
   // Find the entry that the covers the range\r
   //\r
+  IsGuarded = FALSE;\r
   Entry = NULL;\r
   for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
     Entry = CR(Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
@@ -1346,7 +1477,7 @@ CoreInternalFreePages (
     goto Done;\r
   }\r
 \r
-  Alignment = EFI_DEFAULT_PAGE_ALLOCATION_ALIGNMENT;\r
+  Alignment = DEFAULT_PAGE_ALLOCATION_GRANULARITY;\r
 \r
   ASSERT (Entry != NULL);\r
   if  (Entry->Type == EfiACPIReclaimMemory   ||\r
@@ -1354,7 +1485,7 @@ CoreInternalFreePages (
        Entry->Type == EfiRuntimeServicesCode ||\r
        Entry->Type == EfiRuntimeServicesData) {\r
 \r
-    Alignment = EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT;\r
+    Alignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY;\r
 \r
   }\r
 \r
@@ -1366,14 +1497,24 @@ CoreInternalFreePages (
   NumberOfPages += EFI_SIZE_TO_PAGES (Alignment) - 1;\r
   NumberOfPages &= ~(EFI_SIZE_TO_PAGES (Alignment) - 1);\r
 \r
-  Status = CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory);\r
+  if (MemoryType != NULL) {\r
+    *MemoryType = Entry->Type;\r
+  }\r
 \r
-  if (EFI_ERROR (Status)) {\r
-    goto Done;\r
+  IsGuarded = IsPageTypeToGuard (Entry->Type, AllocateAnyPages) &&\r
+              IsMemoryGuarded (Memory);\r
+  if (IsGuarded) {\r
+    Status = CoreConvertPagesWithGuard (Memory, NumberOfPages,\r
+                                        EfiConventionalMemory);\r
+  } else {\r
+    Status = CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory);\r
   }\r
 \r
 Done:\r
   CoreReleaseMemoryLock ();\r
+  if (IsGuarded) {\r
+    UnsetGuardForMemory(Memory, NumberOfPages);\r
+  }\r
   return Status;\r
 }\r
 \r
@@ -1395,11 +1536,22 @@ CoreFreePages (
   IN UINTN                 NumberOfPages\r
   )\r
 {\r
-  EFI_STATUS  Status;\r
+  EFI_STATUS        Status;\r
+  EFI_MEMORY_TYPE   MemoryType;\r
 \r
-  Status = CoreInternalFreePages (Memory, NumberOfPages);\r
+  Status = CoreInternalFreePages (Memory, NumberOfPages, &MemoryType);\r
   if (!EFI_ERROR (Status)) {\r
-    CoreUpdateProfile ((EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0), MemoryProfileActionFreePages, (EFI_MEMORY_TYPE) 0, EFI_PAGES_TO_SIZE (NumberOfPages), (VOID *) (UINTN) Memory);\r
+    CoreUpdateProfile (\r
+      (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0),\r
+      MemoryProfileActionFreePages,\r
+      MemoryType,\r
+      EFI_PAGES_TO_SIZE (NumberOfPages),\r
+      (VOID *) (UINTN) Memory,\r
+      NULL\r
+      );\r
+    InstallMemoryAttributesTableOnMemoryAllocation (MemoryType);\r
+    ApplyMemoryProtectionPolicy (MemoryType, EfiConventionalMemory, Memory,\r
+      EFI_PAGES_TO_SIZE (NumberOfPages));\r
   }\r
   return Status;\r
 }\r
@@ -1528,12 +1680,14 @@ CoreGetMemoryMap (
   EFI_STATUS                        Status;\r
   UINTN                             Size;\r
   UINTN                             BufferSize;\r
-  UINTN                             NumberOfRuntimeEntries;\r
+  UINTN                             NumberOfEntries;\r
   LIST_ENTRY                        *Link;\r
   MEMORY_MAP                        *Entry;\r
   EFI_GCD_MAP_ENTRY                 *GcdMapEntry;\r
+  EFI_GCD_MAP_ENTRY                 MergeGcdMapEntry;\r
   EFI_MEMORY_TYPE                   Type;\r
   EFI_MEMORY_DESCRIPTOR             *MemoryMapStart;\r
+  EFI_MEMORY_DESCRIPTOR             *MemoryMapEnd;\r
 \r
   //\r
   // Make sure the parameters are valid\r
@@ -1545,16 +1699,17 @@ CoreGetMemoryMap (
   CoreAcquireGcdMemoryLock ();\r
 \r
   //\r
-  // Count the number of Reserved and MMIO entries that are marked for runtime use\r
+  // Count the number of Reserved and runtime MMIO entries\r
+  // And, count the number of Persistent entries.\r
   //\r
-  NumberOfRuntimeEntries = 0;\r
+  NumberOfEntries = 0;\r
   for (Link = mGcdMemorySpaceMap.ForwardLink; Link != &mGcdMemorySpaceMap; Link = Link->ForwardLink) {\r
     GcdMapEntry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
-    if ((GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeReserved) ||\r
-        (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo)) {\r
-      if ((GcdMapEntry->Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {\r
-        NumberOfRuntimeEntries++;\r
-      }\r
+    if ((GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypePersistent) || \r
+        (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeReserved) ||\r
+        ((GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) &&\r
+        ((GcdMapEntry->Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME))) {\r
+      NumberOfEntries ++;\r
     }\r
   }\r
 \r
@@ -1580,7 +1735,7 @@ CoreGetMemoryMap (
   //\r
   // Compute the buffer size needed to fit the entire map\r
   //\r
-  BufferSize = Size * NumberOfRuntimeEntries;\r
+  BufferSize = Size * NumberOfEntries;\r
   for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
     BufferSize += Size;\r
   }\r
@@ -1642,36 +1797,98 @@ CoreGetMemoryMap (
     MemoryMap = MergeMemoryMapDescriptor (MemoryMapStart, MemoryMap, Size);\r
   }\r
 \r
-  for (Link = mGcdMemorySpaceMap.ForwardLink; Link != &mGcdMemorySpaceMap; Link = Link->ForwardLink) {\r
-    GcdMapEntry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
-    if ((GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeReserved) ||\r
-        (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo)) {\r
-      if ((GcdMapEntry->Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {\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->Attribute     = GcdMapEntry->Attributes & ~EFI_MEMORY_PORT_IO;\r
-\r
-        if (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeReserved) {\r
-          MemoryMap->Type = EfiReservedMemoryType;\r
-        } else if (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) {\r
-          if ((GcdMapEntry->Attributes & EFI_MEMORY_PORT_IO) == EFI_MEMORY_PORT_IO) {\r
-            MemoryMap->Type = EfiMemoryMappedIOPortSpace;\r
-          } else {\r
-            MemoryMap->Type = EfiMemoryMappedIO;\r
-          }\r
-        }\r
\r
+  ZeroMem (&MergeGcdMapEntry, sizeof (MergeGcdMapEntry));\r
+  GcdMapEntry = NULL;\r
+  for (Link = mGcdMemorySpaceMap.ForwardLink; ; Link = Link->ForwardLink) {\r
+    if (Link != &mGcdMemorySpaceMap) {\r
+      //\r
+      // Merge adjacent same type and attribute GCD memory range\r
+      //\r
+      GcdMapEntry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE);\r
+  \r
+      if ((MergeGcdMapEntry.Capabilities == GcdMapEntry->Capabilities) && \r
+          (MergeGcdMapEntry.Attributes == GcdMapEntry->Attributes) &&\r
+          (MergeGcdMapEntry.GcdMemoryType == GcdMapEntry->GcdMemoryType) &&\r
+          (MergeGcdMapEntry.GcdIoType == GcdMapEntry->GcdIoType)) {\r
+        MergeGcdMapEntry.EndAddress  = GcdMapEntry->EndAddress;\r
+        continue;\r
+      }\r
+    }\r
 \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
+    if ((MergeGcdMapEntry.GcdMemoryType == EfiGcdMemoryTypeReserved) ||\r
+        ((MergeGcdMapEntry.GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) &&\r
+        ((MergeGcdMapEntry.Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME))) {\r
+      //\r
+      // Page Align GCD range is required. When it is converted to EFI_MEMORY_DESCRIPTOR, \r
+      // it will be recorded as page PhysicalStart and NumberOfPages. \r
+      //\r
+      ASSERT ((MergeGcdMapEntry.BaseAddress & EFI_PAGE_MASK) == 0);\r
+      ASSERT (((MergeGcdMapEntry.EndAddress - MergeGcdMapEntry.BaseAddress + 1) & EFI_PAGE_MASK) == 0);\r
+      \r
+      // \r
+      // Create EFI_MEMORY_DESCRIPTOR for every Reserved and runtime MMIO GCD entries\r
+      //\r
+      MemoryMap->PhysicalStart = MergeGcdMapEntry.BaseAddress;\r
+      MemoryMap->VirtualStart  = 0;\r
+      MemoryMap->NumberOfPages = RShiftU64 ((MergeGcdMapEntry.EndAddress - MergeGcdMapEntry.BaseAddress + 1), EFI_PAGE_SHIFT);\r
+      MemoryMap->Attribute     = (MergeGcdMapEntry.Attributes & ~EFI_MEMORY_PORT_IO) | \r
+                                (MergeGcdMapEntry.Capabilities & (EFI_MEMORY_RP | EFI_MEMORY_WP | EFI_MEMORY_XP | EFI_MEMORY_RO |\r
+                                EFI_MEMORY_UC | EFI_MEMORY_UCE | EFI_MEMORY_WC | EFI_MEMORY_WT | EFI_MEMORY_WB));\r
+\r
+      if (MergeGcdMapEntry.GcdMemoryType == EfiGcdMemoryTypeReserved) {\r
+        MemoryMap->Type = EfiReservedMemoryType;\r
+      } else if (MergeGcdMapEntry.GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) {\r
+        if ((MergeGcdMapEntry.Attributes & EFI_MEMORY_PORT_IO) == EFI_MEMORY_PORT_IO) {\r
+          MemoryMap->Type = EfiMemoryMappedIOPortSpace;\r
+        } else {\r
+          MemoryMap->Type = EfiMemoryMappedIO;\r
+        }\r
       }\r
+\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
+    if (MergeGcdMapEntry.GcdMemoryType == EfiGcdMemoryTypePersistent) {\r
+      //\r
+      // Page Align GCD range is required. When it is converted to EFI_MEMORY_DESCRIPTOR, \r
+      // it will be recorded as page PhysicalStart and NumberOfPages. \r
+      //\r
+      ASSERT ((MergeGcdMapEntry.BaseAddress & EFI_PAGE_MASK) == 0);\r
+      ASSERT (((MergeGcdMapEntry.EndAddress - MergeGcdMapEntry.BaseAddress + 1) & EFI_PAGE_MASK) == 0);\r
+\r
+      // \r
+      // Create EFI_MEMORY_DESCRIPTOR for every Persistent GCD entries\r
+      //\r
+      MemoryMap->PhysicalStart = MergeGcdMapEntry.BaseAddress;\r
+      MemoryMap->VirtualStart  = 0;\r
+      MemoryMap->NumberOfPages = RShiftU64 ((MergeGcdMapEntry.EndAddress - MergeGcdMapEntry.BaseAddress + 1), EFI_PAGE_SHIFT);\r
+      MemoryMap->Attribute     = MergeGcdMapEntry.Attributes | EFI_MEMORY_NV | \r
+                                (MergeGcdMapEntry.Capabilities & (EFI_MEMORY_RP | EFI_MEMORY_WP | EFI_MEMORY_XP | EFI_MEMORY_RO |\r
+                                EFI_MEMORY_UC | EFI_MEMORY_UCE | EFI_MEMORY_WC | EFI_MEMORY_WT | EFI_MEMORY_WB));\r
+      MemoryMap->Type          = EfiPersistentMemory;\r
+      \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
+    if (Link == &mGcdMemorySpaceMap) {\r
+      //\r
+      // break loop when arrive at head.\r
+      //\r
+      break;\r
+    }\r
+    if (GcdMapEntry != NULL) {\r
+      //\r
+      // Copy new GCD map entry for the following GCD range merge\r
+      //\r
+      CopyMem (&MergeGcdMapEntry, GcdMapEntry, sizeof (MergeGcdMapEntry));\r
     }\r
   }\r
 \r
@@ -1680,6 +1897,25 @@ CoreGetMemoryMap (
   //\r
   BufferSize = ((UINT8 *)MemoryMap - (UINT8 *)MemoryMapStart);\r
 \r
+  //\r
+  // Note: Some OSs will treat EFI_MEMORY_DESCRIPTOR.Attribute as really\r
+  //       set attributes and change memory paging attribute accordingly.\r
+  //       But current EFI_MEMORY_DESCRIPTOR.Attribute is assigned by\r
+  //       value from Capabilities in GCD memory map. This might cause\r
+  //       boot problems. Clearing all paging related capabilities can\r
+  //       workaround it. Following code is supposed to be removed once\r
+  //       the usage of EFI_MEMORY_DESCRIPTOR.Attribute is clarified in\r
+  //       UEFI spec and adopted by both EDK-II Core and all supported\r
+  //       OSs.\r
+  //\r
+  MemoryMapEnd = MemoryMap;\r
+  MemoryMap = MemoryMapStart;\r
+  while (MemoryMap < MemoryMapEnd) {\r
+    MemoryMap->Attribute &= ~(UINT64)(EFI_MEMORY_RP | EFI_MEMORY_RO |\r
+                                      EFI_MEMORY_XP);\r
+    MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, Size);\r
+  }\r
+\r
   Status = EFI_SUCCESS;\r
 \r
 Done:\r
@@ -1696,6 +1932,12 @@ Done:
 \r
   *MemoryMapSize = BufferSize;\r
 \r
+  DEBUG_CODE (\r
+    if (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT1|BIT0)) {\r
+      DumpGuardedMemoryBitmap ();\r
+    }\r
+  );\r
+\r
   return Status;\r
 }\r
 \r
@@ -1707,6 +1949,7 @@ Done:
   @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
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @return The allocated memory, or NULL\r
 \r
@@ -1715,7 +1958,8 @@ VOID *
 CoreAllocatePoolPages (\r
   IN EFI_MEMORY_TYPE    PoolType,\r
   IN UINTN              NumberOfPages,\r
-  IN UINTN              Alignment\r
+  IN UINTN              Alignment,\r
+  IN BOOLEAN            NeedGuard\r
   )\r
 {\r
   UINT64            Start;\r
@@ -1723,7 +1967,8 @@ CoreAllocatePoolPages (
   //\r
   // Find the pages to convert\r
   //\r
-  Start = FindFreePages (MAX_ADDRESS, NumberOfPages, PoolType, Alignment);\r
+  Start = FindFreePages (MAX_ADDRESS, NumberOfPages, PoolType, Alignment,\r
+                         NeedGuard);\r
 \r
   //\r
   // Convert it to boot services data\r
@@ -1731,7 +1976,11 @@ CoreAllocatePoolPages (
   if (Start == 0) {\r
     DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "AllocatePoolPages: failed to allocate %d pages\n", (UINT32)NumberOfPages));\r
   } else {\r
-    CoreConvertPages (Start, NumberOfPages, PoolType);\r
+    if (NeedGuard) {\r
+      CoreConvertPagesWithGuard (Start, NumberOfPages, PoolType);\r
+    } else {\r
+      CoreConvertPages (Start, NumberOfPages, PoolType);\r
+    }\r
   }\r
 \r
   return (VOID *)(UINTN) Start;\r
@@ -1794,12 +2043,12 @@ CoreTerminateMemoryMap (
         if (mMemoryTypeStatistics[Entry->Type].Runtime) {\r
           ASSERT (Entry->Type != EfiACPIReclaimMemory);\r
           ASSERT (Entry->Type != EfiACPIMemoryNVS);\r
-          if ((Entry->Start & (EFI_ACPI_RUNTIME_PAGE_ALLOCATION_ALIGNMENT - 1)) != 0) {\r
+          if ((Entry->Start & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 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)) != 0) {\r
+          if (((Entry->End + 1) & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 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