MemDetect.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. /** @file
  2. Memory Detection for Virtual Machines.
  3. Copyright (c) 2006 - 2019 Intel Corporation. All rights reserved. <BR>
  4. SPDX-License-Identifier: BSD-2-Clause-Patent
  5. **/
  6. //
  7. // The package level header files this module uses
  8. //
  9. #include <PiPei.h>
  10. //
  11. // The Library classes this module consumes
  12. //
  13. #include <Library/BaseMemoryLib.h>
  14. #include <Library/DebugLib.h>
  15. #include <Library/HobLib.h>
  16. #include <Library/IoLib.h>
  17. #include <Library/PcdLib.h>
  18. #include <Library/PeimEntryPoint.h>
  19. #include <Library/ResourcePublicationLib.h>
  20. #include <Library/MtrrLib.h>
  21. #include <Library/CmosAccessLib.h>
  22. #include <SimicsPlatforms.h>
  23. #include <Guid/SmramMemoryReserve.h>
  24. #include <CmosMap.h>
  25. #include "Platform.h"
  26. UINT8 mPhysMemAddressWidth;
  27. STATIC UINT32 mS3AcpiReservedMemoryBase;
  28. STATIC UINT32 mS3AcpiReservedMemorySize;
  29. STATIC UINT16 mX58TsegMbytes;
  30. VOID
  31. X58TsegMbytesInitialization(
  32. VOID
  33. )
  34. {
  35. if (mHostBridgeDevId != INTEL_ICH10_DEVICE_ID) {
  36. DEBUG ((
  37. DEBUG_ERROR,
  38. "%a: no TSEG (SMRAM) on host bridge DID=0x%04x; "
  39. "only DID=0x%04x (X58) is supported\n",
  40. __FUNCTION__,
  41. mHostBridgeDevId,
  42. INTEL_ICH10_DEVICE_ID
  43. ));
  44. ASSERT (FALSE);
  45. CpuDeadLoop ();
  46. }
  47. //
  48. // Check if QEMU offers an extended TSEG.
  49. //
  50. // This can be seen from writing MCH_EXT_TSEG_MB_QUERY to the MCH_EXT_TSEG_MB
  51. // register, and reading back the register.
  52. //
  53. // On a QEMU machine type that does not offer an extended TSEG, the initial
  54. // write overwrites whatever value a malicious guest OS may have placed in
  55. // the (unimplemented) register, before entering S3 or rebooting.
  56. // Subsequently, the read returns MCH_EXT_TSEG_MB_QUERY unchanged.
  57. //
  58. // On a QEMU machine type that offers an extended TSEG, the initial write
  59. // triggers an update to the register. Subsequently, the value read back
  60. // (which is guaranteed to differ from MCH_EXT_TSEG_MB_QUERY) tells us the
  61. // number of megabytes.
  62. //
  63. mX58TsegMbytes = FixedPcdGet8(PcdX58TsegMbytes);
  64. return;
  65. }
  66. /**
  67. Get the system memory size below 4GB
  68. @return The size of system memory below 4GB
  69. **/
  70. UINT32
  71. GetSystemMemorySizeBelow4gb (
  72. VOID
  73. )
  74. {
  75. UINT32 Size;
  76. //
  77. // CMOS 0x34/0x35 specifies the system memory above 16 MB.
  78. // * The size is specified in 64kb chunks
  79. // * Since this is memory above 16MB, the 16MB must be added
  80. // into the calculation to get the total memory size.
  81. //
  82. Size = (UINT32) ((CmosRead16 (CMOS_SYSTEM_MEM_ABOVE_16MB_LOW_BYTE) << 16)
  83. + SIZE_16MB);
  84. return Size;
  85. }
  86. /**
  87. Get the system memory size above 4GB
  88. @return The size of system memory above 4GB
  89. **/
  90. STATIC
  91. UINT64
  92. GetSystemMemorySizeAbove4gb (
  93. )
  94. {
  95. UINT32 Size;
  96. //
  97. // CMOS 0x5b-0x5d specifies the system memory above 4GB MB.
  98. // * The size is specified in 64kb chunks
  99. //
  100. Size = (CmosRead16 (CMOS_SYSTEM_MEM_ABOVE_4GB_MIDDLE_BYTE) << 8)
  101. + CmosRead8 (CMOS_SYSTEM_MEM_ABOVE_4GB_LOW_BYTE);
  102. return LShiftU64 (Size, 16);
  103. }
  104. /**
  105. Return the highest address that DXE could possibly use, plus one.
  106. **/
  107. STATIC
  108. UINT64
  109. GetFirstNonAddress (
  110. VOID
  111. )
  112. {
  113. UINT64 FirstNonAddress;
  114. UINT64 Pci64Base, Pci64Size;
  115. FirstNonAddress = BASE_4GB + GetSystemMemorySizeAbove4gb ();
  116. //
  117. // If DXE is 32-bit, then we're done; PciBusDxe will degrade 64-bit MMIO
  118. // resources to 32-bit anyway. See DegradeResource() in
  119. // "PciResourceSupport.c".
  120. //
  121. #ifdef MDE_CPU_IA32
  122. if (!FeaturePcdGet (PcdDxeIplSwitchToLongMode)) {
  123. return FirstNonAddress;
  124. }
  125. #endif
  126. //
  127. // Otherwise, in order to calculate the highest address plus one, we must
  128. // consider the 64-bit PCI host aperture too. Fetch the default size.
  129. //
  130. Pci64Size = PcdGet64 (PcdPciMmio64Size);
  131. if (Pci64Size == 0) {
  132. if (mBootMode != BOOT_ON_S3_RESUME) {
  133. DEBUG ((EFI_D_INFO, "%a: disabling 64-bit PCI host aperture\n",
  134. __FUNCTION__));
  135. PcdSet64S (PcdPciMmio64Size, 0);
  136. }
  137. //
  138. // There's nothing more to do; the amount of memory above 4GB fully
  139. // determines the highest address plus one. The memory hotplug area (see
  140. // below) plays no role for the firmware in this case.
  141. //
  142. return FirstNonAddress;
  143. }
  144. //
  145. // SeaBIOS aligns both boundaries of the 64-bit PCI host aperture to 1GB, so
  146. // that the host can map it with 1GB hugepages. Follow suit.
  147. //
  148. Pci64Base = ALIGN_VALUE (FirstNonAddress, (UINT64)SIZE_1GB);
  149. Pci64Size = ALIGN_VALUE (Pci64Size, (UINT64)SIZE_1GB);
  150. //
  151. // The 64-bit PCI host aperture should also be "naturally" aligned. The
  152. // alignment is determined by rounding the size of the aperture down to the
  153. // next smaller or equal power of two. That is, align the aperture by the
  154. // largest BAR size that can fit into it.
  155. //
  156. Pci64Base = ALIGN_VALUE (Pci64Base, GetPowerOfTwo64 (Pci64Size));
  157. if (mBootMode != BOOT_ON_S3_RESUME) {
  158. //
  159. // The core PciHostBridgeDxe driver will automatically add this range to
  160. // the GCD memory space map through our PciHostBridgeLib instance; here we
  161. // only need to set the PCDs.
  162. //
  163. PcdSet64S (PcdPciMmio64Base, Pci64Base);
  164. PcdSet64S (PcdPciMmio64Size, Pci64Size);
  165. DEBUG ((EFI_D_INFO, "%a: Pci64Base=0x%Lx Pci64Size=0x%Lx\n",
  166. __FUNCTION__, Pci64Base, Pci64Size));
  167. }
  168. //
  169. // The useful address space ends with the 64-bit PCI host aperture.
  170. //
  171. FirstNonAddress = Pci64Base + Pci64Size;
  172. return FirstNonAddress;
  173. }
  174. /**
  175. Initialize the mPhysMemAddressWidth variable, based on guest RAM size.
  176. **/
  177. VOID
  178. AddressWidthInitialization (
  179. VOID
  180. )
  181. {
  182. UINT64 FirstNonAddress;
  183. //
  184. // As guest-physical memory size grows, the permanent PEI RAM requirements
  185. // are dominated by the identity-mapping page tables built by the DXE IPL.
  186. // The DXL IPL keys off of the physical address bits advertized in the CPU
  187. // HOB. To conserve memory, we calculate the minimum address width here.
  188. //
  189. FirstNonAddress = GetFirstNonAddress ();
  190. mPhysMemAddressWidth = (UINT8)HighBitSet64 (FirstNonAddress);
  191. //
  192. // If FirstNonAddress is not an integral power of two, then we need an
  193. // additional bit.
  194. //
  195. if ((FirstNonAddress & (FirstNonAddress - 1)) != 0) {
  196. ++mPhysMemAddressWidth;
  197. }
  198. //
  199. // The minimum address width is 36 (covers up to and excluding 64 GB, which
  200. // is the maximum for Ia32 + PAE). The theoretical architecture maximum for
  201. // X64 long mode is 52 bits, but the DXE IPL clamps that down to 48 bits. We
  202. // can simply assert that here, since 48 bits are good enough for 256 TB.
  203. //
  204. if (mPhysMemAddressWidth <= 36) {
  205. mPhysMemAddressWidth = 36;
  206. }
  207. ASSERT (mPhysMemAddressWidth <= 48);
  208. }
  209. /**
  210. Calculate the cap for the permanent PEI memory.
  211. **/
  212. STATIC
  213. UINT32
  214. GetPeiMemoryCap (
  215. VOID
  216. )
  217. {
  218. BOOLEAN Page1GSupport;
  219. UINT32 RegEax;
  220. UINT32 RegEdx;
  221. UINT32 Pml4Entries;
  222. UINT32 PdpEntries;
  223. UINTN TotalPages;
  224. //
  225. // If DXE is 32-bit, then just return the traditional 64 MB cap.
  226. //
  227. #ifdef MDE_CPU_IA32
  228. if (!FeaturePcdGet (PcdDxeIplSwitchToLongMode)) {
  229. return SIZE_64MB;
  230. }
  231. #endif
  232. //
  233. // Dependent on physical address width, PEI memory allocations can be
  234. // dominated by the page tables built for 64-bit DXE. So we key the cap off
  235. // of those. The code below is based on CreateIdentityMappingPageTables() in
  236. // "MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c".
  237. //
  238. Page1GSupport = FALSE;
  239. if (PcdGetBool (PcdUse1GPageTable)) {
  240. AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);
  241. if (RegEax >= 0x80000001) {
  242. AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx);
  243. if ((RegEdx & BIT26) != 0) {
  244. Page1GSupport = TRUE;
  245. }
  246. }
  247. }
  248. if (mPhysMemAddressWidth <= 39) {
  249. Pml4Entries = 1;
  250. PdpEntries = 1 << (mPhysMemAddressWidth - 30);
  251. ASSERT (PdpEntries <= 0x200);
  252. } else {
  253. Pml4Entries = 1 << (mPhysMemAddressWidth - 39);
  254. ASSERT (Pml4Entries <= 0x200);
  255. PdpEntries = 512;
  256. }
  257. TotalPages = Page1GSupport ? Pml4Entries + 1 :
  258. (PdpEntries + 1) * Pml4Entries + 1;
  259. ASSERT (TotalPages <= 0x40201);
  260. //
  261. // Add 64 MB for miscellaneous allocations. Note that for
  262. // mPhysMemAddressWidth values close to 36, the cap will actually be
  263. // dominated by this increment.
  264. //
  265. return (UINT32)(EFI_PAGES_TO_SIZE (TotalPages) + SIZE_64MB);
  266. }
  267. /**
  268. Publish PEI core memory
  269. @return EFI_SUCCESS The PEIM initialized successfully.
  270. **/
  271. EFI_STATUS
  272. PublishPeiMemory (
  273. VOID
  274. )
  275. {
  276. EFI_STATUS Status;
  277. EFI_PHYSICAL_ADDRESS MemoryBase;
  278. UINT64 MemorySize;
  279. UINT32 LowerMemorySize;
  280. UINT32 PeiMemoryCap;
  281. LowerMemorySize = GetSystemMemorySizeBelow4gb ();
  282. if (FeaturePcdGet (PcdSmmSmramRequire)) {
  283. //
  284. // TSEG is chipped from the end of low RAM
  285. //
  286. LowerMemorySize -= mX58TsegMbytes * SIZE_1MB;
  287. }
  288. //
  289. // If S3 is supported, then the S3 permanent PEI memory is placed next,
  290. // downwards. Its size is primarily dictated by CpuMpPei. The formula below
  291. // is an approximation.
  292. //
  293. if (mS3Supported) {
  294. mS3AcpiReservedMemorySize = SIZE_512KB +
  295. mMaxCpuCount *
  296. PcdGet32 (PcdCpuApStackSize);
  297. mS3AcpiReservedMemoryBase = LowerMemorySize - mS3AcpiReservedMemorySize;
  298. LowerMemorySize = mS3AcpiReservedMemoryBase;
  299. }
  300. if (mBootMode == BOOT_ON_S3_RESUME) {
  301. MemoryBase = mS3AcpiReservedMemoryBase;
  302. MemorySize = mS3AcpiReservedMemorySize;
  303. } else {
  304. PeiMemoryCap = GetPeiMemoryCap ();
  305. DEBUG ((EFI_D_INFO, "%a: mPhysMemAddressWidth=%d PeiMemoryCap=%u KB\n",
  306. __FUNCTION__, mPhysMemAddressWidth, PeiMemoryCap >> 10));
  307. //
  308. // Determine the range of memory to use during PEI
  309. //
  310. // Technically we could lay the permanent PEI RAM over SEC's temporary
  311. // decompression and scratch buffer even if "secure S3" is needed, since
  312. // their lifetimes don't overlap. However, PeiFvInitialization() will cover
  313. // RAM up to PcdOvmfDecompressionScratchEnd with an EfiACPIMemoryNVS memory
  314. // allocation HOB, and other allocations served from the permanent PEI RAM
  315. // shouldn't overlap with that HOB.
  316. //
  317. MemoryBase = mS3Supported && FeaturePcdGet (PcdSmmSmramRequire) ?
  318. PcdGet32 (PcdSimicsDecompressionScratchEnd) :
  319. PcdGet32 (PcdSimicsDxeMemFvBase) + PcdGet32 (PcdSimicsDxeMemFvSize);
  320. MemorySize = LowerMemorySize - MemoryBase;
  321. }
  322. DEBUG((EFI_D_INFO, "MemoryBase=0x%lx MemorySize=0x%lx\n", MemoryBase, MemorySize));
  323. //
  324. // Publish this memory to the PEI Core
  325. //
  326. Status = PublishSystemMemory(MemoryBase, MemorySize);
  327. ASSERT_EFI_ERROR (Status);
  328. return Status;
  329. }
  330. /**
  331. Peform Memory Detection for QEMU / KVM
  332. **/
  333. STATIC
  334. VOID
  335. QemuInitializeRam (
  336. VOID
  337. )
  338. {
  339. UINT64 LowerMemorySize;
  340. UINT64 UpperMemorySize;
  341. UINTN BufferSize;
  342. UINT8 SmramIndex;
  343. UINT8 SmramRanges;
  344. EFI_PEI_HOB_POINTERS Hob;
  345. EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *SmramHobDescriptorBlock;
  346. UINT8 Index;
  347. DEBUG ((EFI_D_INFO, "%a called\n", __FUNCTION__));
  348. //
  349. // Determine total memory size available
  350. //
  351. LowerMemorySize = GetSystemMemorySizeBelow4gb ();
  352. UpperMemorySize = GetSystemMemorySizeAbove4gb ();
  353. if (mBootMode == BOOT_ON_S3_RESUME) {
  354. //
  355. // Create the following memory HOB as an exception on the S3 boot path.
  356. //
  357. // Normally we'd create memory HOBs only on the normal boot path. However,
  358. // CpuMpPei specifically needs such a low-memory HOB on the S3 path as
  359. // well, for "borrowing" a subset of it temporarily, for the AP startup
  360. // vector.
  361. //
  362. // CpuMpPei saves the original contents of the borrowed area in permanent
  363. // PEI RAM, in a backup buffer allocated with the normal PEI services.
  364. // CpuMpPei restores the original contents ("returns" the borrowed area) at
  365. // End-of-PEI. End-of-PEI in turn is emitted by S3Resume2Pei before
  366. // transferring control to the OS's wakeup vector in the FACS.
  367. //
  368. // We expect any other PEIMs that "borrow" memory similarly to CpuMpPei to
  369. // restore the original contents. Furthermore, we expect all such PEIMs
  370. // (CpuMpPei included) to claim the borrowed areas by producing memory
  371. // allocation HOBs, and to honor preexistent memory allocation HOBs when
  372. // looking for an area to borrow.
  373. //
  374. AddMemoryRangeHob (0, BASE_512KB + BASE_128KB);
  375. } else {
  376. //
  377. // Create memory HOBs
  378. //
  379. AddMemoryRangeHob (0, BASE_512KB + BASE_128KB);
  380. if (FeaturePcdGet (PcdSmmSmramRequire)) {
  381. UINT32 TsegSize;
  382. TsegSize = mX58TsegMbytes * SIZE_1MB;
  383. AddMemoryRangeHob (BASE_1MB, LowerMemorySize - TsegSize);
  384. AddReservedMemoryBaseSizeHob (LowerMemorySize - TsegSize, TsegSize,
  385. TRUE);
  386. BufferSize = sizeof(EFI_SMRAM_HOB_DESCRIPTOR_BLOCK);
  387. SmramRanges = 1;
  388. Hob.Raw = BuildGuidHob(
  389. &gEfiSmmSmramMemoryGuid,
  390. BufferSize
  391. );
  392. ASSERT(Hob.Raw);
  393. SmramHobDescriptorBlock = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)(Hob.Raw);
  394. SmramHobDescriptorBlock->NumberOfSmmReservedRegions = SmramRanges;
  395. SmramIndex = 0;
  396. for (Index = 0; Index < SmramRanges; Index++) {
  397. //
  398. // This is an SMRAM range, create an SMRAM descriptor
  399. //
  400. SmramHobDescriptorBlock->Descriptor[SmramIndex].PhysicalStart = LowerMemorySize - TsegSize;
  401. SmramHobDescriptorBlock->Descriptor[SmramIndex].CpuStart = LowerMemorySize - TsegSize;
  402. SmramHobDescriptorBlock->Descriptor[SmramIndex].PhysicalSize = TsegSize;
  403. SmramHobDescriptorBlock->Descriptor[SmramIndex].RegionState = EFI_SMRAM_CLOSED | EFI_CACHEABLE;
  404. SmramIndex++;
  405. }
  406. } else {
  407. AddMemoryRangeHob (BASE_1MB, LowerMemorySize);
  408. }
  409. //
  410. // If QEMU presents an E820 map, then create memory HOBs for the >=4GB RAM
  411. // entries. Otherwise, create a single memory HOB with the flat >=4GB
  412. // memory size read from the CMOS.
  413. //
  414. if (UpperMemorySize != 0) {
  415. AddMemoryBaseSizeHob (BASE_4GB, UpperMemorySize);
  416. }
  417. }
  418. }
  419. /**
  420. Publish system RAM and reserve memory regions
  421. **/
  422. VOID
  423. InitializeRamRegions (
  424. VOID
  425. )
  426. {
  427. QemuInitializeRam ();
  428. if (mS3Supported && mBootMode != BOOT_ON_S3_RESUME) {
  429. //
  430. // This is the memory range that will be used for PEI on S3 resume
  431. //
  432. BuildMemoryAllocationHob (
  433. mS3AcpiReservedMemoryBase,
  434. mS3AcpiReservedMemorySize,
  435. EfiACPIMemoryNVS
  436. );
  437. //
  438. // Cover the initial RAM area used as stack and temporary PEI heap.
  439. //
  440. // This is reserved as ACPI NVS so it can be used on S3 resume.
  441. //
  442. BuildMemoryAllocationHob (
  443. PcdGet32 (PcdSimicsSecPeiTempRamBase),
  444. PcdGet32 (PcdSimicsSecPeiTempRamSize),
  445. EfiACPIMemoryNVS
  446. );
  447. //
  448. // SEC stores its table of GUIDed section handlers here.
  449. //
  450. BuildMemoryAllocationHob (
  451. PcdGet64 (PcdGuidedExtractHandlerTableAddress),
  452. PcdGet32 (PcdGuidedExtractHandlerTableSize),
  453. EfiACPIMemoryNVS
  454. );
  455. }
  456. if (mBootMode != BOOT_ON_S3_RESUME) {
  457. if (!FeaturePcdGet (PcdSmmSmramRequire)) {
  458. //
  459. // Reserve the lock box storage area
  460. //
  461. // Since this memory range will be used on S3 resume, it must be
  462. // reserved as ACPI NVS.
  463. //
  464. // If S3 is unsupported, then various drivers might still write to the
  465. // LockBox area. We ought to prevent DXE from serving allocation requests
  466. // such that they would overlap the LockBox storage.
  467. //
  468. ZeroMem (
  469. (VOID*)(UINTN) PcdGet32 (PcdSimicsLockBoxStorageBase),
  470. (UINTN) PcdGet32 (PcdSimicsLockBoxStorageSize)
  471. );
  472. BuildMemoryAllocationHob (
  473. (EFI_PHYSICAL_ADDRESS)(UINTN) PcdGet32 (PcdSimicsLockBoxStorageBase),
  474. (UINT64)(UINTN) PcdGet32 (PcdSimicsLockBoxStorageSize),
  475. mS3Supported ? EfiACPIMemoryNVS : EfiBootServicesData
  476. );
  477. }
  478. if (FeaturePcdGet (PcdSmmSmramRequire)) {
  479. UINT32 TsegSize;
  480. //
  481. // Make sure the TSEG area that we reported as a reserved memory resource
  482. // cannot be used for reserved memory allocations.
  483. //
  484. TsegSize = mX58TsegMbytes * SIZE_1MB;
  485. BuildMemoryAllocationHob (
  486. GetSystemMemorySizeBelow4gb() - TsegSize,
  487. TsegSize,
  488. EfiReservedMemoryType
  489. );
  490. }
  491. }
  492. }