]> git.proxmox.com Git - mirror_edk2.git/blobdiff - OvmfPkg/Library/PlatformInitLib/MemDetect.c
UefiCpuPkg: Move AsmRelocateApLoopStart from Mpfuncs.nasm to AmdSev.nasm
[mirror_edk2.git] / OvmfPkg / Library / PlatformInitLib / MemDetect.c
index d1a4f4b207911f06f5f5e962c4ea4724cef838c0..38cece9173e8011fd1930d43e163cd3048b24198 100644 (file)
@@ -26,6 +26,7 @@ Module Name:
 //\r
 #include <Library/BaseLib.h>\r
 #include <Library/BaseMemoryLib.h>\r
+#include <Library/CcProbeLib.h>\r
 #include <Library/DebugLib.h>\r
 #include <Library/HardwareInfoLib.h>\r
 #include <Library/HobLib.h>\r
@@ -42,24 +43,31 @@ Module Name:
 \r
 #include <Library/PlatformInitLib.h>\r
 \r
+#define MEGABYTE_SHIFT  20\r
+\r
 VOID\r
 EFIAPI\r
 PlatformQemuUc32BaseInitialization (\r
   IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
   )\r
 {\r
-  UINT32  LowerMemorySize;\r
-\r
   if (PlatformInfoHob->HostBridgeDevId == 0xffff /* microvm */) {\r
     return;\r
   }\r
 \r
+  if (PlatformInfoHob->HostBridgeDevId == CLOUDHV_DEVICE_ID) {\r
+    PlatformInfoHob->Uc32Size = CLOUDHV_MMIO_HOLE_SIZE;\r
+    PlatformInfoHob->Uc32Base = CLOUDHV_MMIO_HOLE_ADDRESS;\r
+    return;\r
+  }\r
+\r
+  PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob);\r
+\r
   if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) {\r
-    LowerMemorySize = PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob);\r
     ASSERT (PcdGet64 (PcdPciExpressBaseAddress) <= MAX_UINT32);\r
-    ASSERT (PcdGet64 (PcdPciExpressBaseAddress) >= LowerMemorySize);\r
+    ASSERT (PcdGet64 (PcdPciExpressBaseAddress) >= PlatformInfoHob->LowMemory);\r
 \r
-    if (LowerMemorySize <= BASE_2GB) {\r
+    if (PlatformInfoHob->LowMemory <= BASE_2GB) {\r
       // Newer qemu with gigabyte aligned memory,\r
       // 32-bit pci mmio window is 2G -> 4G then.\r
       PlatformInfoHob->Uc32Base = BASE_2GB;\r
@@ -77,20 +85,13 @@ PlatformQemuUc32BaseInitialization (
     return;\r
   }\r
 \r
-  if (PlatformInfoHob->HostBridgeDevId == CLOUDHV_DEVICE_ID) {\r
-    PlatformInfoHob->Uc32Size = CLOUDHV_MMIO_HOLE_SIZE;\r
-    PlatformInfoHob->Uc32Base = CLOUDHV_MMIO_HOLE_ADDRESS;\r
-    return;\r
-  }\r
-\r
   ASSERT (PlatformInfoHob->HostBridgeDevId == INTEL_82441_DEVICE_ID);\r
   //\r
   // On i440fx, start with the [LowerMemorySize, 4GB) range. Make sure one\r
   // variable MTRR suffices by truncating the size to a whole power of two,\r
   // while keeping the end affixed to 4GB. This will round the base up.\r
   //\r
-  LowerMemorySize           = PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob);\r
-  PlatformInfoHob->Uc32Size = GetPowerOfTwo32 ((UINT32)(SIZE_4GB - LowerMemorySize));\r
+  PlatformInfoHob->Uc32Size = GetPowerOfTwo32 ((UINT32)(SIZE_4GB - PlatformInfoHob->LowMemory));\r
   PlatformInfoHob->Uc32Base = (UINT32)(SIZE_4GB - PlatformInfoHob->Uc32Size);\r
   //\r
   // Assuming that LowerMemorySize is at least 1 byte, Uc32Size is at most 2GB.\r
@@ -98,51 +99,191 @@ PlatformQemuUc32BaseInitialization (
   //\r
   ASSERT (PlatformInfoHob->Uc32Base >= BASE_2GB);\r
 \r
-  if (PlatformInfoHob->Uc32Base != LowerMemorySize) {\r
+  if (PlatformInfoHob->Uc32Base != PlatformInfoHob->LowMemory) {\r
     DEBUG ((\r
       DEBUG_VERBOSE,\r
       "%a: rounded UC32 base from 0x%x up to 0x%x, for "\r
       "an UC32 size of 0x%x\n",\r
       __FUNCTION__,\r
-      LowerMemorySize,\r
+      PlatformInfoHob->LowMemory,\r
       PlatformInfoHob->Uc32Base,\r
       PlatformInfoHob->Uc32Size\r
       ));\r
   }\r
 }\r
 \r
+typedef VOID (*E820_SCAN_CALLBACK) (\r
+  EFI_E820_ENTRY64       *E820Entry,\r
+  EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
+  );\r
+\r
 /**\r
-  Iterate over the RAM entries in QEMU's fw_cfg E820 RAM map that start outside\r
-  of the 32-bit address range.\r
+  Store first address not used by e820 RAM entries in\r
+  PlatformInfoHob->FirstNonAddress\r
+**/\r
+STATIC\r
+VOID\r
+PlatformGetFirstNonAddressCB (\r
+  IN     EFI_E820_ENTRY64       *E820Entry,\r
+  IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
+  )\r
+{\r
+  UINT64  Candidate;\r
+\r
+  if (E820Entry->Type != EfiAcpiAddressRangeMemory) {\r
+    return;\r
+  }\r
+\r
+  Candidate = E820Entry->BaseAddr + E820Entry->Length;\r
+  if (PlatformInfoHob->FirstNonAddress < Candidate) {\r
+    DEBUG ((DEBUG_INFO, "%a: FirstNonAddress=0x%Lx\n", __FUNCTION__, Candidate));\r
+    PlatformInfoHob->FirstNonAddress = Candidate;\r
+  }\r
+}\r
+\r
+/**\r
+  Store the low (below 4G) memory size in\r
+  PlatformInfoHob->LowMemory\r
+**/\r
+STATIC\r
+VOID\r
+PlatformGetLowMemoryCB (\r
+  IN     EFI_E820_ENTRY64       *E820Entry,\r
+  IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
+  )\r
+{\r
+  UINT64  Candidate;\r
+\r
+  if (E820Entry->Type != EfiAcpiAddressRangeMemory) {\r
+    return;\r
+  }\r
+\r
+  Candidate = E820Entry->BaseAddr + E820Entry->Length;\r
+  if (Candidate >= BASE_4GB) {\r
+    return;\r
+  }\r
+\r
+  if (PlatformInfoHob->LowMemory < Candidate) {\r
+    DEBUG ((DEBUG_INFO, "%a: LowMemory=0x%Lx\n", __FUNCTION__, Candidate));\r
+    PlatformInfoHob->LowMemory = (UINT32)Candidate;\r
+  }\r
+}\r
+\r
+/**\r
+  Create HOBs for reservations and RAM (except low memory).\r
+**/\r
+STATIC\r
+VOID\r
+PlatformAddHobCB (\r
+  IN     EFI_E820_ENTRY64       *E820Entry,\r
+  IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
+  )\r
+{\r
+  UINT64  Base, End;\r
+\r
+  Base = E820Entry->BaseAddr;\r
+  End  = E820Entry->BaseAddr + E820Entry->Length;\r
+\r
+  switch (E820Entry->Type) {\r
+    case EfiAcpiAddressRangeMemory:\r
+      if (Base >= BASE_4GB) {\r
+        //\r
+        // Round up the start address, and round down the end address.\r
+        //\r
+        Base = ALIGN_VALUE (Base, (UINT64)EFI_PAGE_SIZE);\r
+        End  = End & ~(UINT64)EFI_PAGE_MASK;\r
+        if (Base < End) {\r
+          DEBUG ((DEBUG_INFO, "%a: HighMemory [0x%Lx, 0x%Lx)\n", __FUNCTION__, Base, End));\r
+          PlatformAddMemoryRangeHob (Base, End);\r
+        }\r
+      }\r
+\r
+      break;\r
+    case EfiAcpiAddressRangeReserved:\r
+      BuildResourceDescriptorHob (EFI_RESOURCE_MEMORY_RESERVED, 0, Base, End - Base);\r
+      DEBUG ((DEBUG_INFO, "%a: Reserved [0x%Lx, 0x%Lx)\n", __FUNCTION__, Base, End));\r
+      break;\r
+    default:\r
+      DEBUG ((\r
+        DEBUG_WARN,\r
+        "%a: Type %u [0x%Lx, 0x%Lx) (NOT HANDLED)\n",\r
+        __FUNCTION__,\r
+        E820Entry->Type,\r
+        Base,\r
+        End\r
+        ));\r
+      break;\r
+  }\r
+}\r
+\r
+/**\r
+  Check whenever the 64bit PCI MMIO window overlaps with a reservation\r
+  from qemu.  If so move down the MMIO window to resolve the conflict.\r
+\r
+  This happens on (virtual) AMD machines with 1TB address space,\r
+  because the AMD IOMMU uses an address window just below 1TB.\r
+**/\r
+STATIC\r
+VOID\r
+PlatformReservationConflictCB (\r
+  IN     EFI_E820_ENTRY64       *E820Entry,\r
+  IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
+  )\r
+{\r
+  UINT64  IntersectionBase;\r
+  UINT64  IntersectionEnd;\r
+  UINT64  NewBase;\r
+\r
+  IntersectionBase = MAX (\r
+                       E820Entry->BaseAddr,\r
+                       PlatformInfoHob->PcdPciMmio64Base\r
+                       );\r
+  IntersectionEnd = MIN (\r
+                      E820Entry->BaseAddr + E820Entry->Length,\r
+                      PlatformInfoHob->PcdPciMmio64Base +\r
+                      PlatformInfoHob->PcdPciMmio64Size\r
+                      );\r
+\r
+  if (IntersectionBase >= IntersectionEnd) {\r
+    return;  // no overlap\r
+  }\r
+\r
+  NewBase = E820Entry->BaseAddr - PlatformInfoHob->PcdPciMmio64Size;\r
+  NewBase = NewBase & ~(PlatformInfoHob->PcdPciMmio64Size - 1);\r
+\r
+  DEBUG ((\r
+    DEBUG_INFO,\r
+    "%a: move mmio: 0x%Lx => %Lx\n",\r
+    __FUNCTION__,\r
+    PlatformInfoHob->PcdPciMmio64Base,\r
+    NewBase\r
+    ));\r
+  PlatformInfoHob->PcdPciMmio64Base = NewBase;\r
+}\r
 \r
-  Find the highest exclusive >=4GB RAM address, or produce memory resource\r
-  descriptor HOBs for RAM entries that start at or above 4GB.\r
+/**\r
+  Iterate over the entries in QEMU's fw_cfg E820 RAM map, call the\r
+  passed callback for each entry.\r
 \r
-  @param[out] MaxAddress  If MaxAddress is NULL, then PlatformScanOrAdd64BitE820Ram()\r
-                          produces memory resource descriptor HOBs for RAM\r
-                          entries that start at or above 4GB.\r
+  @param[in] Callback              The callback function to be called.\r
 \r
-                          Otherwise, MaxAddress holds the highest exclusive\r
-                          >=4GB RAM address on output. If QEMU's fw_cfg E820\r
-                          RAM map contains no RAM entry that starts outside of\r
-                          the 32-bit address range, then MaxAddress is exactly\r
-                          4GB on output.\r
+  @param[in out]  PlatformInfoHob  PlatformInfo struct which is passed\r
+                                   through to the callback.\r
 \r
-  @retval EFI_SUCCESS         The fw_cfg E820 RAM map was found and processed.\r
+  @retval EFI_SUCCESS              The fw_cfg E820 RAM map was found and processed.\r
 \r
-  @retval EFI_PROTOCOL_ERROR  The RAM map was found, but its size wasn't a\r
-                              whole multiple of sizeof(EFI_E820_ENTRY64). No\r
-                              RAM entry was processed.\r
+  @retval EFI_PROTOCOL_ERROR       The RAM map was found, but its size wasn't a\r
+                                   whole multiple of sizeof(EFI_E820_ENTRY64). No\r
+                                   RAM entry was processed.\r
 \r
-  @return                     Error codes from QemuFwCfgFindFile(). No RAM\r
-                              entry was processed.\r
+  @return                          Error codes from QemuFwCfgFindFile(). No RAM\r
+                                   entry was processed.\r
 **/\r
 STATIC\r
 EFI_STATUS\r
-PlatformScanOrAdd64BitE820Ram (\r
-  IN BOOLEAN  AddHighHob,\r
-  OUT UINT64  *LowMemory OPTIONAL,\r
-  OUT UINT64  *MaxAddress OPTIONAL\r
+PlatformScanE820 (\r
+  IN      E820_SCAN_CALLBACK     Callback,\r
+  IN OUT  EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
   )\r
 {\r
   EFI_STATUS            Status;\r
@@ -160,73 +301,10 @@ PlatformScanOrAdd64BitE820Ram (
     return EFI_PROTOCOL_ERROR;\r
   }\r
 \r
-  if (LowMemory != NULL) {\r
-    *LowMemory = 0;\r
-  }\r
-\r
-  if (MaxAddress != NULL) {\r
-    *MaxAddress = BASE_4GB;\r
-  }\r
-\r
   QemuFwCfgSelectItem (FwCfgItem);\r
   for (Processed = 0; Processed < FwCfgSize; Processed += sizeof E820Entry) {\r
     QemuFwCfgReadBytes (sizeof E820Entry, &E820Entry);\r
-    DEBUG ((\r
-      DEBUG_VERBOSE,\r
-      "%a: Base=0x%Lx Length=0x%Lx Type=%u\n",\r
-      __FUNCTION__,\r
-      E820Entry.BaseAddr,\r
-      E820Entry.Length,\r
-      E820Entry.Type\r
-      ));\r
-    if (E820Entry.Type == EfiAcpiAddressRangeMemory) {\r
-      if (AddHighHob && (E820Entry.BaseAddr >= BASE_4GB)) {\r
-        UINT64  Base;\r
-        UINT64  End;\r
-\r
-        //\r
-        // Round up the start address, and round down the end address.\r
-        //\r
-        Base = ALIGN_VALUE (E820Entry.BaseAddr, (UINT64)EFI_PAGE_SIZE);\r
-        End  = (E820Entry.BaseAddr + E820Entry.Length) &\r
-               ~(UINT64)EFI_PAGE_MASK;\r
-        if (Base < End) {\r
-          PlatformAddMemoryRangeHob (Base, End);\r
-          DEBUG ((\r
-            DEBUG_VERBOSE,\r
-            "%a: PlatformAddMemoryRangeHob [0x%Lx, 0x%Lx)\n",\r
-            __FUNCTION__,\r
-            Base,\r
-            End\r
-            ));\r
-        }\r
-      }\r
-\r
-      if (MaxAddress || LowMemory) {\r
-        UINT64  Candidate;\r
-\r
-        Candidate = E820Entry.BaseAddr + E820Entry.Length;\r
-        if (MaxAddress && (Candidate > *MaxAddress)) {\r
-          *MaxAddress = Candidate;\r
-          DEBUG ((\r
-            DEBUG_VERBOSE,\r
-            "%a: MaxAddress=0x%Lx\n",\r
-            __FUNCTION__,\r
-            *MaxAddress\r
-            ));\r
-        }\r
-\r
-        if (LowMemory && (Candidate > *LowMemory) && (Candidate < BASE_4GB)) {\r
-          *LowMemory = Candidate;\r
-          DEBUG ((\r
-            DEBUG_VERBOSE,\r
-            "%a: LowMemory=0x%Lx\n",\r
-            __FUNCTION__,\r
-            *LowMemory\r
-            ));\r
-        }\r
-      }\r
-    }\r
+    Callback (&E820Entry, PlatformInfoHob);\r
   }\r
 \r
   return EFI_SUCCESS;\r
@@ -299,25 +377,27 @@ GetHighestSystemMemoryAddressFromPvhMemmap (
   return HighestAddress;\r
 }\r
 \r
-UINT32\r
+VOID\r
 EFIAPI\r
 PlatformGetSystemMemorySizeBelow4gb (\r
   IN EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
   )\r
 {\r
   EFI_STATUS  Status;\r
-  UINT64      LowerMemorySize = 0;\r
   UINT8       Cmos0x34;\r
   UINT8       Cmos0x35;\r
 \r
-  if (PlatformInfoHob->HostBridgeDevId == CLOUDHV_DEVICE_ID) {\r
+  if ((PlatformInfoHob->HostBridgeDevId == CLOUDHV_DEVICE_ID) &&\r
+      (CcProbe () != CcGuestTypeIntelTdx))\r
+  {\r
     // Get the information from PVH memmap\r
-    return (UINT32)GetHighestSystemMemoryAddressFromPvhMemmap (TRUE);\r
+    PlatformInfoHob->LowMemory = (UINT32)GetHighestSystemMemoryAddressFromPvhMemmap (TRUE);\r
+    return;\r
   }\r
 \r
-  Status = PlatformScanOrAdd64BitE820Ram (FALSE, &LowerMemorySize, NULL);\r
-  if ((Status == EFI_SUCCESS) && (LowerMemorySize > 0)) {\r
-    return (UINT32)LowerMemorySize;\r
+  Status = PlatformScanE820 (PlatformGetLowMemoryCB, PlatformInfoHob);\r
+  if (!EFI_ERROR (Status) && (PlatformInfoHob->LowMemory > 0)) {\r
+    return;\r
   }\r
 \r
   //\r
@@ -332,7 +412,7 @@ PlatformGetSystemMemorySizeBelow4gb (
   Cmos0x34 = (UINT8)PlatformCmosRead8 (0x34);\r
   Cmos0x35 = (UINT8)PlatformCmosRead8 (0x35);\r
 \r
-  return (UINT32)(((UINTN)((Cmos0x35 << 8) + Cmos0x34) << 16) + SIZE_16MB);\r
+  PlatformInfoHob->LowMemory = (UINT32)(((UINTN)((Cmos0x35 << 8) + Cmos0x34) << 16) + SIZE_16MB);\r
 }\r
 \r
 STATIC\r
@@ -363,23 +443,17 @@ PlatformGetSystemMemorySizeAbove4gb (
   Return the highest address that DXE could possibly use, plus one.\r
 **/\r
 STATIC\r
-UINT64\r
+VOID\r
 PlatformGetFirstNonAddress (\r
   IN OUT  EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
   )\r
 {\r
-  UINT64                FirstNonAddress;\r
   UINT32                FwCfgPciMmio64Mb;\r
   EFI_STATUS            Status;\r
   FIRMWARE_CONFIG_ITEM  FwCfgItem;\r
   UINTN                 FwCfgSize;\r
   UINT64                HotPlugMemoryEnd;\r
 \r
-  //\r
-  // set FirstNonAddress to suppress incorrect compiler/analyzer warnings\r
-  //\r
-  FirstNonAddress = 0;\r
-\r
   //\r
   // If QEMU presents an E820 map, then get the highest exclusive >=4GB RAM\r
   // address from it. This can express an address >= 4GB+1TB.\r
@@ -387,9 +461,10 @@ PlatformGetFirstNonAddress (
   // Otherwise, get the flat size of the memory above 4GB from the CMOS (which\r
   // can only express a size smaller than 1TB), and add it to 4GB.\r
   //\r
-  Status = PlatformScanOrAdd64BitE820Ram (FALSE, NULL, &FirstNonAddress);\r
+  PlatformInfoHob->FirstNonAddress = BASE_4GB;\r
+  Status                           = PlatformScanE820 (PlatformGetFirstNonAddressCB, PlatformInfoHob);\r
   if (EFI_ERROR (Status)) {\r
-    FirstNonAddress = BASE_4GB + PlatformGetSystemMemorySizeAbove4gb ();\r
+    PlatformInfoHob->FirstNonAddress = BASE_4GB + PlatformGetSystemMemorySizeAbove4gb ();\r
   }\r
 \r
   //\r
@@ -399,7 +474,7 @@ PlatformGetFirstNonAddress (
   //\r
  #ifdef MDE_CPU_IA32\r
   if (!FeaturePcdGet (PcdDxeIplSwitchToLongMode)) {\r
-    return FirstNonAddress;\r
+    return;\r
   }\r
 \r
  #endif\r
@@ -452,7 +527,7 @@ PlatformGetFirstNonAddress (
     // determines the highest address plus one. The memory hotplug area (see\r
     // below) plays no role for the firmware in this case.\r
     //\r
-    return FirstNonAddress;\r
+    return;\r
   }\r
 \r
   //\r
@@ -476,15 +551,15 @@ PlatformGetFirstNonAddress (
       HotPlugMemoryEnd\r
       ));\r
 \r
-    ASSERT (HotPlugMemoryEnd >= FirstNonAddress);\r
-    FirstNonAddress = HotPlugMemoryEnd;\r
+    ASSERT (HotPlugMemoryEnd >= PlatformInfoHob->FirstNonAddress);\r
+    PlatformInfoHob->FirstNonAddress = HotPlugMemoryEnd;\r
   }\r
 \r
   //\r
   // SeaBIOS aligns both boundaries of the 64-bit PCI host aperture to 1GB, so\r
   // that the host can map it with 1GB hugepages. Follow suit.\r
   //\r
-  PlatformInfoHob->PcdPciMmio64Base = ALIGN_VALUE (FirstNonAddress, (UINT64)SIZE_1GB);\r
+  PlatformInfoHob->PcdPciMmio64Base = ALIGN_VALUE (PlatformInfoHob->FirstNonAddress, (UINT64)SIZE_1GB);\r
   PlatformInfoHob->PcdPciMmio64Size = ALIGN_VALUE (PlatformInfoHob->PcdPciMmio64Size, (UINT64)SIZE_1GB);\r
 \r
   //\r
@@ -498,44 +573,138 @@ PlatformGetFirstNonAddress (
   //\r
   // The useful address space ends with the 64-bit PCI host aperture.\r
   //\r
-  FirstNonAddress = PlatformInfoHob->PcdPciMmio64Base + PlatformInfoHob->PcdPciMmio64Size;\r
-  return FirstNonAddress;\r
+  PlatformInfoHob->FirstNonAddress = PlatformInfoHob->PcdPciMmio64Base + PlatformInfoHob->PcdPciMmio64Size;\r
+  return;\r
 }\r
 \r
 /*\r
- * Use CPUID to figure physical address width.  Does *not* work\r
- * reliable on qemu.  For historical reasons qemu returns phys-bits=40\r
- * even in case the host machine supports less than that.\r
+ * Use CPUID to figure physical address width.\r
+ *\r
+ * Does *not* work reliable on qemu.  For historical reasons qemu\r
+ * returns phys-bits=40 by default even in case the host machine\r
+ * supports less than that.\r
+ *\r
+ * So we apply the following rules (which can be enabled/disabled\r
+ * using the QemuQuirk parameter) to figure whenever we can work with\r
+ * the returned physical address width or not:\r
  *\r
- * qemu has a cpu property (host-phys-bits={on,off}) to change that\r
- * and make sure guest phys-bits are not larger than host phys-bits.,\r
- * but it is off by default.  Exception: microvm machine type\r
- * hard-wires that property to on.\r
+ *   (1) If it is 41 or higher consider it valid.\r
+ *   (2) If it is 40 or lower consider it valid in case it matches a\r
+ *       known-good value for the CPU vendor, which is:\r
+ *         ->  36 or 39 for Intel\r
+ *         ->  40 for AMD\r
+ *   (3) Otherwise consider it invalid.\r
+ *\r
+ * Recommendation: Run qemu with host-phys-bits=on.  That will make\r
+ * sure guest phys-bits is not larger than host phys-bits.  Some\r
+ * distro builds do that by default.\r
  */\r
 VOID\r
 EFIAPI\r
 PlatformAddressWidthFromCpuid (\r
-  IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
+  IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob,\r
+  IN     BOOLEAN                QemuQuirk\r
   )\r
 {\r
-  UINT32  RegEax;\r
+  UINT32   RegEax, RegEbx, RegEcx, RegEdx, Max;\r
+  UINT8    PhysBits;\r
+  CHAR8    Signature[13] = { 0 };\r
+  BOOLEAN  Valid         = FALSE;\r
+  BOOLEAN  Page1GSupport = FALSE;\r
+\r
+  AsmCpuid (0x80000000, &RegEax, &RegEbx, &RegEcx, &RegEdx);\r
+  *(UINT32 *)(Signature + 0) = RegEbx;\r
+  *(UINT32 *)(Signature + 4) = RegEdx;\r
+  *(UINT32 *)(Signature + 8) = RegEcx;\r
+  Max                        = RegEax;\r
+\r
+  if (Max >= 0x80000001) {\r
+    AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx);\r
+    if ((RegEdx & BIT26) != 0) {\r
+      Page1GSupport = TRUE;\r
+    }\r
+  }\r
 \r
-  AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);\r
-  if (RegEax >= 0x80000008) {\r
+  if (Max >= 0x80000008) {\r
     AsmCpuid (0x80000008, &RegEax, NULL, NULL, NULL);\r
-    PlatformInfoHob->PhysMemAddressWidth = (UINT8)RegEax;\r
+    PhysBits = (UINT8)RegEax;\r
   } else {\r
-    PlatformInfoHob->PhysMemAddressWidth = 36;\r
+    PhysBits = 36;\r
   }\r
 \r
-  PlatformInfoHob->FirstNonAddress = LShiftU64 (1, PlatformInfoHob->PhysMemAddressWidth);\r
+  if (!QemuQuirk) {\r
+    Valid = TRUE;\r
+  } else if (PhysBits >= 41) {\r
+    Valid = TRUE;\r
+  } else if (AsciiStrCmp (Signature, "GenuineIntel") == 0) {\r
+    if ((PhysBits == 36) || (PhysBits == 39)) {\r
+      Valid = TRUE;\r
+    }\r
+  } else if (AsciiStrCmp (Signature, "AuthenticAMD") == 0) {\r
+    if (PhysBits == 40) {\r
+      Valid = TRUE;\r
+    }\r
+  }\r
 \r
   DEBUG ((\r
     DEBUG_INFO,\r
-    "%a: cpuid: phys-bits is %d\n",\r
+    "%a: Signature: '%a', PhysBits: %d, QemuQuirk: %a, Valid: %a\n",\r
     __FUNCTION__,\r
-    PlatformInfoHob->PhysMemAddressWidth\r
+    Signature,\r
+    PhysBits,\r
+    QemuQuirk ? "On" : "Off",\r
+    Valid ? "Yes" : "No"\r
     ));\r
+\r
+  if (Valid) {\r
+    if (PhysBits > 47) {\r
+      /*\r
+       * Avoid 5-level paging altogether for now, which limits\r
+       * PhysBits to 48.  Also avoid using address bit 48, due to sign\r
+       * extension we can't identity-map these addresses (and lots of\r
+       * places in edk2 assume we have everything identity-mapped).\r
+       * So the actual limit is 47.\r
+       */\r
+      DEBUG ((DEBUG_INFO, "%a: limit PhysBits to 47 (avoid 5-level paging)\n", __func__));\r
+      PhysBits = 47;\r
+    }\r
+\r
+    if (!Page1GSupport && (PhysBits > 40)) {\r
+      DEBUG ((DEBUG_INFO, "%a: limit PhysBits to 40 (no 1G pages available)\n", __func__));\r
+      PhysBits = 40;\r
+    }\r
+\r
+    PlatformInfoHob->PhysMemAddressWidth = PhysBits;\r
+    PlatformInfoHob->FirstNonAddress     = LShiftU64 (1, PlatformInfoHob->PhysMemAddressWidth);\r
+  }\r
+}\r
+\r
+VOID\r
+EFIAPI\r
+PlatformDynamicMmioWindow (\r
+  IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
+  )\r
+{\r
+  UINT64  AddrSpace, MmioSpace;\r
+\r
+  AddrSpace = LShiftU64 (1, PlatformInfoHob->PhysMemAddressWidth);\r
+  MmioSpace = LShiftU64 (1, PlatformInfoHob->PhysMemAddressWidth - 3);\r
+\r
+  if ((PlatformInfoHob->PcdPciMmio64Size < MmioSpace) &&\r
+      (PlatformInfoHob->PcdPciMmio64Base + MmioSpace < AddrSpace))\r
+  {\r
+    DEBUG ((DEBUG_INFO, "%a: using dynamic mmio window\n", __func__));\r
+    DEBUG ((DEBUG_INFO, "%a:   Addr Space 0x%Lx (%Ld GB)\n", __func__, AddrSpace, RShiftU64 (AddrSpace, 30)));\r
+    DEBUG ((DEBUG_INFO, "%a:   MMIO Space 0x%Lx (%Ld GB)\n", __func__, MmioSpace, RShiftU64 (MmioSpace, 30)));\r
+    PlatformInfoHob->PcdPciMmio64Size = MmioSpace;\r
+    PlatformInfoHob->PcdPciMmio64Base = AddrSpace - MmioSpace;\r
+    PlatformScanE820 (PlatformReservationConflictCB, PlatformInfoHob);\r
+  } else {\r
+    DEBUG ((DEBUG_INFO, "%a: using classic mmio window\n", __func__));\r
+  }\r
+\r
+  DEBUG ((DEBUG_INFO, "%a:   Pci64 Base 0x%Lx\n", __func__, PlatformInfoHob->PcdPciMmio64Base));\r
+  DEBUG ((DEBUG_INFO, "%a:   Pci64 Size 0x%Lx\n", __func__, PlatformInfoHob->PcdPciMmio64Size));\r
 }\r
 \r
 /**\r
@@ -667,12 +836,11 @@ PlatformAddressWidthInitialization (
   IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
   )\r
 {\r
-  UINT64      FirstNonAddress;\r
   UINT8       PhysMemAddressWidth;\r
   EFI_STATUS  Status;\r
 \r
   if (PlatformInfoHob->HostBridgeDevId == 0xffff /* microvm */) {\r
-    PlatformAddressWidthFromCpuid (PlatformInfoHob);\r
+    PlatformAddressWidthFromCpuid (PlatformInfoHob, FALSE);\r
     return;\r
   }\r
 \r
@@ -680,7 +848,7 @@ PlatformAddressWidthInitialization (
   // First scan host-provided hardware information to assess if the address\r
   // space is already known. If so, guest must use those values.\r
   //\r
-  Status = PlatformScanHostProvided64BitPciMmioEnd (&FirstNonAddress);\r
+  Status = PlatformScanHostProvided64BitPciMmioEnd (&PlatformInfoHob->FirstNonAddress);\r
 \r
   if (EFI_ERROR (Status)) {\r
     //\r
@@ -692,16 +860,29 @@ PlatformAddressWidthInitialization (
     // The DXL IPL keys off of the physical address bits advertized in the CPU\r
     // HOB. To conserve memory, we calculate the minimum address width here.\r
     //\r
-    FirstNonAddress = PlatformGetFirstNonAddress (PlatformInfoHob);\r
+    PlatformGetFirstNonAddress (PlatformInfoHob);\r
   }\r
 \r
-  PhysMemAddressWidth = (UINT8)HighBitSet64 (FirstNonAddress);\r
+  PlatformAddressWidthFromCpuid (PlatformInfoHob, TRUE);\r
+  if (PlatformInfoHob->PhysMemAddressWidth != 0) {\r
+    // physical address width is known\r
+    PlatformDynamicMmioWindow (PlatformInfoHob);\r
+    return;\r
+  }\r
+\r
+  //\r
+  // physical address width is NOT known\r
+  //   -> do some guess work, mostly based on installed memory\r
+  //   -> try be conservstibe to stay below the guaranteed minimum of\r
+  //      36 phys bits (aka 64 GB).\r
+  //\r
+  PhysMemAddressWidth = (UINT8)HighBitSet64 (PlatformInfoHob->FirstNonAddress);\r
 \r
   //\r
   // If FirstNonAddress is not an integral power of two, then we need an\r
   // additional bit.\r
   //\r
-  if ((FirstNonAddress & (FirstNonAddress - 1)) != 0) {\r
+  if ((PlatformInfoHob->FirstNonAddress & (PlatformInfoHob->FirstNonAddress - 1)) != 0) {\r
     ++PhysMemAddressWidth;\r
   }\r
 \r
@@ -729,7 +910,6 @@ PlatformAddressWidthInitialization (
   ASSERT (PhysMemAddressWidth <= 48);\r
  #endif\r
 \r
-  PlatformInfoHob->FirstNonAddress     = FirstNonAddress;\r
   PlatformInfoHob->PhysMemAddressWidth = PhysMemAddressWidth;\r
 }\r
 \r
@@ -769,7 +949,6 @@ PlatformQemuInitializeRam (
   IN EFI_HOB_PLATFORM_INFO  *PlatformInfoHob\r
   )\r
 {\r
-  UINT64         LowerMemorySize;\r
   UINT64         UpperMemorySize;\r
   MTRR_SETTINGS  MtrrSettings;\r
   EFI_STATUS     Status;\r
@@ -779,7 +958,7 @@ PlatformQemuInitializeRam (
   //\r
   // Determine total memory size available\r
   //\r
-  LowerMemorySize = PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob);\r
+  PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob);\r
 \r
   if (PlatformInfoHob->BootMode == BOOT_ON_S3_RESUME) {\r
     //\r
@@ -813,14 +992,14 @@ PlatformQemuInitializeRam (
       UINT32  TsegSize;\r
 \r
       TsegSize = PlatformInfoHob->Q35TsegMbytes * SIZE_1MB;\r
-      PlatformAddMemoryRangeHob (BASE_1MB, LowerMemorySize - TsegSize);\r
+      PlatformAddMemoryRangeHob (BASE_1MB, PlatformInfoHob->LowMemory - TsegSize);\r
       PlatformAddReservedMemoryBaseSizeHob (\r
-        LowerMemorySize - TsegSize,\r
+        PlatformInfoHob->LowMemory - TsegSize,\r
         TsegSize,\r
         TRUE\r
         );\r
     } else {\r
-      PlatformAddMemoryRangeHob (BASE_1MB, LowerMemorySize);\r
+      PlatformAddMemoryRangeHob (BASE_1MB, PlatformInfoHob->LowMemory);\r
     }\r
 \r
     //\r
@@ -828,7 +1007,7 @@ PlatformQemuInitializeRam (
     // entries. Otherwise, create a single memory HOB with the flat >=4GB\r
     // memory size read from the CMOS.\r
     //\r
-    Status = PlatformScanOrAdd64BitE820Ram (TRUE, NULL, NULL);\r
+    Status = PlatformScanE820 (PlatformAddHobCB, PlatformInfoHob);\r
     if (EFI_ERROR (Status)) {\r
       UpperMemorySize = PlatformGetSystemMemorySizeAbove4gb ();\r
       if (UpperMemorySize != 0) {\r
@@ -840,7 +1019,7 @@ PlatformQemuInitializeRam (
   //\r
   // We'd like to keep the following ranges uncached:\r
   // - [640 KB, 1 MB)\r
-  // - [LowerMemorySize, 4 GB)\r
+  // - [Uc32Base, 4 GB)\r
   //\r
   // Everything else should be WB. Unfortunately, programming the inverse (ie.\r
   // keeping the default UC, and configuring the complement set of the above as\r
@@ -998,9 +1177,10 @@ PlatformQemuInitializeRamForS3 (
       // Make sure the TSEG area that we reported as a reserved memory resource\r
       // cannot be used for reserved memory allocations.\r
       //\r
+      PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob);\r
       TsegSize = PlatformInfoHob->Q35TsegMbytes * SIZE_1MB;\r
       BuildMemoryAllocationHob (\r
-        PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob) - TsegSize,\r
+        PlatformInfoHob->LowMemory - TsegSize,\r
         TsegSize,\r
         EfiReservedMemoryType\r
         );\r