2 Memory Detection for Virtual Machines.
4 Copyright (c) 2020, Rebecca Cran <rebecca@bsdio.com>
5 Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
7 SPDX-License-Identifier: BSD-2-Clause-Patent
16 // The package level header files this module uses
18 #include <IndustryStandard/E820.h>
19 #include <IndustryStandard/Q35MchIch9.h>
23 // The Library classes this module consumes
25 #include <Library/BaseLib.h>
26 #include <Library/BaseMemoryLib.h>
27 #include <Library/DebugLib.h>
28 #include <Library/HobLib.h>
29 #include <Library/IoLib.h>
30 #include <Library/PcdLib.h>
31 #include <Library/PciLib.h>
32 #include <Library/PeimEntryPoint.h>
33 #include <Library/ResourcePublicationLib.h>
34 #include <Library/MtrrLib.h>
39 UINT8 mPhysMemAddressWidth
;
41 STATIC UINT32 mS3AcpiReservedMemoryBase
;
42 STATIC UINT32 mS3AcpiReservedMemorySize
;
44 STATIC UINT16 mQ35TsegMbytes
;
46 BOOLEAN mQ35SmramAtDefaultSmbase
= FALSE
;
49 Q35TsegMbytesInitialization (
53 UINT16 ExtendedTsegMbytes
;
54 RETURN_STATUS PcdStatus
;
56 if (mHostBridgeDevId
!= INTEL_Q35_MCH_DEVICE_ID
) {
59 "%a: no TSEG (SMRAM) on host bridge DID=0x%04x; "
60 "only DID=0x%04x (Q35) is supported\n",
63 INTEL_Q35_MCH_DEVICE_ID
70 // Check if QEMU offers an extended TSEG.
72 // This can be seen from writing MCH_EXT_TSEG_MB_QUERY to the MCH_EXT_TSEG_MB
73 // register, and reading back the register.
75 // On a QEMU machine type that does not offer an extended TSEG, the initial
76 // write overwrites whatever value a malicious guest OS may have placed in
77 // the (unimplemented) register, before entering S3 or rebooting.
78 // Subsequently, the read returns MCH_EXT_TSEG_MB_QUERY unchanged.
80 // On a QEMU machine type that offers an extended TSEG, the initial write
81 // triggers an update to the register. Subsequently, the value read back
82 // (which is guaranteed to differ from MCH_EXT_TSEG_MB_QUERY) tells us the
83 // number of megabytes.
85 PciWrite16 (DRAMC_REGISTER_Q35 (MCH_EXT_TSEG_MB
), MCH_EXT_TSEG_MB_QUERY
);
86 ExtendedTsegMbytes
= PciRead16 (DRAMC_REGISTER_Q35 (MCH_EXT_TSEG_MB
));
87 if (ExtendedTsegMbytes
== MCH_EXT_TSEG_MB_QUERY
) {
88 mQ35TsegMbytes
= PcdGet16 (PcdQ35TsegMbytes
);
94 "%a: QEMU offers an extended TSEG (%d MB)\n",
98 PcdStatus
= PcdSet16S (PcdQ35TsegMbytes
, ExtendedTsegMbytes
);
99 ASSERT_RETURN_ERROR (PcdStatus
);
100 mQ35TsegMbytes
= ExtendedTsegMbytes
;
104 GetSystemMemorySizeBelow4gb (
112 // CMOS 0x34/0x35 specifies the system memory above 16 MB.
113 // * CMOS(0x35) is the high byte
114 // * CMOS(0x34) is the low byte
115 // * The size is specified in 64kb chunks
116 // * Since this is memory above 16MB, the 16MB must be added
117 // into the calculation to get the total memory size.
120 Cmos0x34
= (UINT8
)CmosRead8 (0x34);
121 Cmos0x35
= (UINT8
)CmosRead8 (0x35);
123 return (UINT32
)(((UINTN
)((Cmos0x35
<< 8) + Cmos0x34
) << 16) + SIZE_16MB
);
128 GetSystemMemorySizeAbove4gb (
135 // CMOS 0x5b-0x5d specifies the system memory above 4GB MB.
136 // * CMOS(0x5d) is the most significant size byte
137 // * CMOS(0x5c) is the middle size byte
138 // * CMOS(0x5b) is the least significant size byte
139 // * The size is specified in 64kb chunks
143 for (CmosIndex
= 0x5d; CmosIndex
>= 0x5b; CmosIndex
--) {
144 Size
= (UINT32
)(Size
<< 8) + (UINT32
)CmosRead8 (CmosIndex
);
147 return LShiftU64 (Size
, 16);
151 Return the highest address that DXE could possibly use, plus one.
159 UINT64 FirstNonAddress
;
160 UINT64 Pci64Base
, Pci64Size
;
161 RETURN_STATUS PcdStatus
;
163 FirstNonAddress
= BASE_4GB
+ GetSystemMemorySizeAbove4gb ();
166 // If DXE is 32-bit, then we're done; PciBusDxe will degrade 64-bit MMIO
167 // resources to 32-bit anyway. See DegradeResource() in
168 // "PciResourceSupport.c".
171 if (!FeaturePcdGet (PcdDxeIplSwitchToLongMode
)) {
172 return FirstNonAddress
;
178 // Otherwise, in order to calculate the highest address plus one, we must
179 // consider the 64-bit PCI host aperture too. Fetch the default size.
181 Pci64Size
= PcdGet64 (PcdPciMmio64Size
);
183 if (Pci64Size
== 0) {
184 if (mBootMode
!= BOOT_ON_S3_RESUME
) {
187 "%a: disabling 64-bit PCI host aperture\n",
190 PcdStatus
= PcdSet64S (PcdPciMmio64Size
, 0);
191 ASSERT_RETURN_ERROR (PcdStatus
);
195 // There's nothing more to do; the amount of memory above 4GB fully
196 // determines the highest address plus one. The memory hotplug area (see
197 // below) plays no role for the firmware in this case.
199 return FirstNonAddress
;
203 // SeaBIOS aligns both boundaries of the 64-bit PCI host aperture to 1GB, so
204 // that the host can map it with 1GB hugepages. Follow suit.
206 Pci64Base
= ALIGN_VALUE (FirstNonAddress
, (UINT64
)SIZE_1GB
);
207 Pci64Size
= ALIGN_VALUE (Pci64Size
, (UINT64
)SIZE_1GB
);
210 // The 64-bit PCI host aperture should also be "naturally" aligned. The
211 // alignment is determined by rounding the size of the aperture down to the
212 // next smaller or equal power of two. That is, align the aperture by the
213 // largest BAR size that can fit into it.
215 Pci64Base
= ALIGN_VALUE (Pci64Base
, GetPowerOfTwo64 (Pci64Size
));
217 if (mBootMode
!= BOOT_ON_S3_RESUME
) {
219 // The core PciHostBridgeDxe driver will automatically add this range to
220 // the GCD memory space map through our PciHostBridgeLib instance; here we
221 // only need to set the PCDs.
223 PcdStatus
= PcdSet64S (PcdPciMmio64Base
, Pci64Base
);
224 ASSERT_RETURN_ERROR (PcdStatus
);
225 PcdStatus
= PcdSet64S (PcdPciMmio64Size
, Pci64Size
);
226 ASSERT_RETURN_ERROR (PcdStatus
);
230 "%a: Pci64Base=0x%Lx Pci64Size=0x%Lx\n",
238 // The useful address space ends with the 64-bit PCI host aperture.
240 FirstNonAddress
= Pci64Base
+ Pci64Size
;
241 return FirstNonAddress
;
245 Initialize the mPhysMemAddressWidth variable, based on guest RAM size.
248 AddressWidthInitialization (
252 UINT64 FirstNonAddress
;
255 // As guest-physical memory size grows, the permanent PEI RAM requirements
256 // are dominated by the identity-mapping page tables built by the DXE IPL.
257 // The DXL IPL keys off of the physical address bits advertized in the CPU
258 // HOB. To conserve memory, we calculate the minimum address width here.
260 FirstNonAddress
= GetFirstNonAddress ();
261 mPhysMemAddressWidth
= (UINT8
)HighBitSet64 (FirstNonAddress
);
264 // If FirstNonAddress is not an integral power of two, then we need an
267 if ((FirstNonAddress
& (FirstNonAddress
- 1)) != 0) {
268 ++mPhysMemAddressWidth
;
272 // The minimum address width is 36 (covers up to and excluding 64 GB, which
273 // is the maximum for Ia32 + PAE). The theoretical architecture maximum for
274 // X64 long mode is 52 bits, but the DXE IPL clamps that down to 48 bits. We
275 // can simply assert that here, since 48 bits are good enough for 256 TB.
277 if (mPhysMemAddressWidth
<= 36) {
278 mPhysMemAddressWidth
= 36;
281 ASSERT (mPhysMemAddressWidth
<= 48);
285 Calculate the cap for the permanent PEI memory.
293 BOOLEAN Page1GSupport
;
301 // If DXE is 32-bit, then just return the traditional 64 MB cap.
304 if (!FeaturePcdGet (PcdDxeIplSwitchToLongMode
)) {
311 // Dependent on physical address width, PEI memory allocations can be
312 // dominated by the page tables built for 64-bit DXE. So we key the cap off
313 // of those. The code below is based on CreateIdentityMappingPageTables() in
314 // "MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c".
316 Page1GSupport
= FALSE
;
317 if (PcdGetBool (PcdUse1GPageTable
)) {
318 AsmCpuid (0x80000000, &RegEax
, NULL
, NULL
, NULL
);
319 if (RegEax
>= 0x80000001) {
320 AsmCpuid (0x80000001, NULL
, NULL
, NULL
, &RegEdx
);
321 if ((RegEdx
& BIT26
) != 0) {
322 Page1GSupport
= TRUE
;
327 if (mPhysMemAddressWidth
<= 39) {
329 PdpEntries
= 1 << (mPhysMemAddressWidth
- 30);
330 ASSERT (PdpEntries
<= 0x200);
332 Pml4Entries
= 1 << (mPhysMemAddressWidth
- 39);
333 ASSERT (Pml4Entries
<= 0x200);
337 TotalPages
= Page1GSupport
? Pml4Entries
+ 1 :
338 (PdpEntries
+ 1) * Pml4Entries
+ 1;
339 ASSERT (TotalPages
<= 0x40201);
342 // Add 64 MB for miscellaneous allocations. Note that for
343 // mPhysMemAddressWidth values close to 36, the cap will actually be
344 // dominated by this increment.
346 return (UINT32
)(EFI_PAGES_TO_SIZE (TotalPages
) + SIZE_64MB
);
350 Publish PEI core memory
352 @return EFI_SUCCESS The PEIM initialized successfully.
361 EFI_PHYSICAL_ADDRESS MemoryBase
;
363 UINT32 LowerMemorySize
;
366 LowerMemorySize
= GetSystemMemorySizeBelow4gb ();
367 if (FeaturePcdGet (PcdSmmSmramRequire
)) {
369 // TSEG is chipped from the end of low RAM
371 LowerMemorySize
-= mQ35TsegMbytes
* SIZE_1MB
;
375 // If S3 is supported, then the S3 permanent PEI memory is placed next,
376 // downwards. Its size is primarily dictated by CpuMpPei. The formula below
377 // is an approximation.
380 mS3AcpiReservedMemorySize
= SIZE_512KB
+
382 PcdGet32 (PcdCpuApStackSize
);
383 mS3AcpiReservedMemoryBase
= LowerMemorySize
- mS3AcpiReservedMemorySize
;
384 LowerMemorySize
= mS3AcpiReservedMemoryBase
;
387 if (mBootMode
== BOOT_ON_S3_RESUME
) {
388 MemoryBase
= mS3AcpiReservedMemoryBase
;
389 MemorySize
= mS3AcpiReservedMemorySize
;
391 PeiMemoryCap
= GetPeiMemoryCap ();
394 "%a: mPhysMemAddressWidth=%d PeiMemoryCap=%u KB\n",
396 mPhysMemAddressWidth
,
401 // Determine the range of memory to use during PEI
403 // Technically we could lay the permanent PEI RAM over SEC's temporary
404 // decompression and scratch buffer even if "secure S3" is needed, since
405 // their lifetimes don't overlap. However, PeiFvInitialization() will cover
406 // RAM up to PcdOvmfDecompressionScratchEnd with an EfiACPIMemoryNVS memory
407 // allocation HOB, and other allocations served from the permanent PEI RAM
408 // shouldn't overlap with that HOB.
410 MemoryBase
= mS3Supported
&& FeaturePcdGet (PcdSmmSmramRequire
) ?
411 PcdGet32 (PcdOvmfDecompressionScratchEnd
) :
412 PcdGet32 (PcdOvmfDxeMemFvBase
) + PcdGet32 (PcdOvmfDxeMemFvSize
);
413 MemorySize
= LowerMemorySize
- MemoryBase
;
414 if (MemorySize
> PeiMemoryCap
) {
415 MemoryBase
= LowerMemorySize
- PeiMemoryCap
;
416 MemorySize
= PeiMemoryCap
;
421 // Publish this memory to the PEI Core
423 Status
= PublishSystemMemory (MemoryBase
, MemorySize
);
424 ASSERT_EFI_ERROR (Status
);
430 Peform Memory Detection for QEMU / KVM
439 UINT64 LowerMemorySize
;
440 UINT64 UpperMemorySize
;
441 MTRR_SETTINGS MtrrSettings
;
444 DEBUG ((DEBUG_INFO
, "%a called\n", __FUNCTION__
));
447 // Determine total memory size available
449 LowerMemorySize
= GetSystemMemorySizeBelow4gb ();
450 UpperMemorySize
= GetSystemMemorySizeAbove4gb ();
452 if (mBootMode
== BOOT_ON_S3_RESUME
) {
454 // Create the following memory HOB as an exception on the S3 boot path.
456 // Normally we'd create memory HOBs only on the normal boot path. However,
457 // CpuMpPei specifically needs such a low-memory HOB on the S3 path as
458 // well, for "borrowing" a subset of it temporarily, for the AP startup
461 // CpuMpPei saves the original contents of the borrowed area in permanent
462 // PEI RAM, in a backup buffer allocated with the normal PEI services.
463 // CpuMpPei restores the original contents ("returns" the borrowed area) at
464 // End-of-PEI. End-of-PEI in turn is emitted by S3Resume2Pei before
465 // transferring control to the OS's wakeup vector in the FACS.
467 // We expect any other PEIMs that "borrow" memory similarly to CpuMpPei to
468 // restore the original contents. Furthermore, we expect all such PEIMs
469 // (CpuMpPei included) to claim the borrowed areas by producing memory
470 // allocation HOBs, and to honor preexistent memory allocation HOBs when
471 // looking for an area to borrow.
473 AddMemoryRangeHob (0, BASE_512KB
+ BASE_128KB
);
476 // Create memory HOBs
478 AddMemoryRangeHob (0, BASE_512KB
+ BASE_128KB
);
480 if (FeaturePcdGet (PcdSmmSmramRequire
)) {
483 TsegSize
= mQ35TsegMbytes
* SIZE_1MB
;
484 AddMemoryRangeHob (BASE_1MB
, LowerMemorySize
- TsegSize
);
485 AddReservedMemoryBaseSizeHob (
486 LowerMemorySize
- TsegSize
,
491 AddMemoryRangeHob (BASE_1MB
, LowerMemorySize
);
494 if (UpperMemorySize
!= 0) {
495 AddMemoryBaseSizeHob (BASE_4GB
, UpperMemorySize
);
500 // We'd like to keep the following ranges uncached:
502 // - [LowerMemorySize, 4 GB)
504 // Everything else should be WB. Unfortunately, programming the inverse (ie.
505 // keeping the default UC, and configuring the complement set of the above as
506 // WB) is not reliable in general, because the end of the upper RAM can have
507 // practically any alignment, and we may not have enough variable MTRRs to
510 if (IsMtrrSupported ()) {
511 MtrrGetAllMtrrs (&MtrrSettings
);
514 // MTRRs disabled, fixed MTRRs disabled, default type is uncached
516 ASSERT ((MtrrSettings
.MtrrDefType
& BIT11
) == 0);
517 ASSERT ((MtrrSettings
.MtrrDefType
& BIT10
) == 0);
518 ASSERT ((MtrrSettings
.MtrrDefType
& 0xFF) == 0);
521 // flip default type to writeback
523 SetMem (&MtrrSettings
.Fixed
, sizeof MtrrSettings
.Fixed
, 0x06);
524 ZeroMem (&MtrrSettings
.Variables
, sizeof MtrrSettings
.Variables
);
525 MtrrSettings
.MtrrDefType
|= BIT11
| BIT10
| 6;
526 MtrrSetAllMtrrs (&MtrrSettings
);
529 // Set memory range from 640KB to 1MB to uncacheable
531 Status
= MtrrSetMemoryAttribute (
532 BASE_512KB
+ BASE_128KB
,
533 BASE_1MB
- (BASE_512KB
+ BASE_128KB
),
536 ASSERT_EFI_ERROR (Status
);
539 // Set memory range from the "top of lower RAM" (RAM below 4GB) to 4GB as
542 Status
= MtrrSetMemoryAttribute (
544 SIZE_4GB
- LowerMemorySize
,
547 ASSERT_EFI_ERROR (Status
);
552 Publish system RAM and reserve memory regions
556 InitializeRamRegions (
560 QemuInitializeRam ();
562 if (mS3Supported
&& (mBootMode
!= BOOT_ON_S3_RESUME
)) {
564 // This is the memory range that will be used for PEI on S3 resume
566 BuildMemoryAllocationHob (
567 mS3AcpiReservedMemoryBase
,
568 mS3AcpiReservedMemorySize
,
573 // Cover the initial RAM area used as stack and temporary PEI heap.
575 // This is reserved as ACPI NVS so it can be used on S3 resume.
577 BuildMemoryAllocationHob (
578 PcdGet32 (PcdOvmfSecPeiTempRamBase
),
579 PcdGet32 (PcdOvmfSecPeiTempRamSize
),
584 // SEC stores its table of GUIDed section handlers here.
586 BuildMemoryAllocationHob (
587 PcdGet64 (PcdGuidedExtractHandlerTableAddress
),
588 PcdGet32 (PcdGuidedExtractHandlerTableSize
),
594 // Reserve the initial page tables built by the reset vector code.
596 // Since this memory range will be used by the Reset Vector on S3
597 // resume, it must be reserved as ACPI NVS.
599 BuildMemoryAllocationHob (
600 (EFI_PHYSICAL_ADDRESS
)(UINTN
)PcdGet32 (PcdOvmfSecPageTablesBase
),
601 (UINT64
)(UINTN
)PcdGet32 (PcdOvmfSecPageTablesSize
),
607 if (mBootMode
!= BOOT_ON_S3_RESUME
) {
608 if (!FeaturePcdGet (PcdSmmSmramRequire
)) {
610 // Reserve the lock box storage area
612 // Since this memory range will be used on S3 resume, it must be
613 // reserved as ACPI NVS.
615 // If S3 is unsupported, then various drivers might still write to the
616 // LockBox area. We ought to prevent DXE from serving allocation requests
617 // such that they would overlap the LockBox storage.
620 (VOID
*)(UINTN
)PcdGet32 (PcdOvmfLockBoxStorageBase
),
621 (UINTN
)PcdGet32 (PcdOvmfLockBoxStorageSize
)
623 BuildMemoryAllocationHob (
624 (EFI_PHYSICAL_ADDRESS
)(UINTN
)PcdGet32 (PcdOvmfLockBoxStorageBase
),
625 (UINT64
)(UINTN
)PcdGet32 (PcdOvmfLockBoxStorageSize
),
626 mS3Supported
? EfiACPIMemoryNVS
: EfiBootServicesData
630 if (FeaturePcdGet (PcdSmmSmramRequire
)) {
634 // Make sure the TSEG area that we reported as a reserved memory resource
635 // cannot be used for reserved memory allocations.
637 TsegSize
= mQ35TsegMbytes
* SIZE_1MB
;
638 BuildMemoryAllocationHob (
639 GetSystemMemorySizeBelow4gb () - TsegSize
,
641 EfiReservedMemoryType