]> git.proxmox.com Git - mirror_edk2.git/blob - OvmfPkg/PlatformPei/MemDetect.c
OvmfPkg/PlatformPei: remove Xen support
[mirror_edk2.git] / OvmfPkg / PlatformPei / MemDetect.c
1 /**@file
2 Memory Detection for Virtual Machines.
3
4 Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
5 SPDX-License-Identifier: BSD-2-Clause-Patent
6
7 Module Name:
8
9 MemDetect.c
10
11 **/
12
13 //
14 // The package level header files this module uses
15 //
16 #include <IndustryStandard/E820.h>
17 #include <IndustryStandard/I440FxPiix4.h>
18 #include <IndustryStandard/Q35MchIch9.h>
19 #include <PiPei.h>
20 #include <Register/Intel/SmramSaveStateMap.h>
21
22 //
23 // The Library classes this module consumes
24 //
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/MemEncryptSevLib.h>
31 #include <Library/PcdLib.h>
32 #include <Library/PciLib.h>
33 #include <Library/PeimEntryPoint.h>
34 #include <Library/ResourcePublicationLib.h>
35 #include <Library/MtrrLib.h>
36 #include <Library/QemuFwCfgLib.h>
37 #include <Library/QemuFwCfgSimpleParserLib.h>
38
39 #include "Platform.h"
40 #include "Cmos.h"
41
42 UINT8 mPhysMemAddressWidth;
43
44 STATIC UINT32 mS3AcpiReservedMemoryBase;
45 STATIC UINT32 mS3AcpiReservedMemorySize;
46
47 STATIC UINT16 mQ35TsegMbytes;
48
49 BOOLEAN mQ35SmramAtDefaultSmbase;
50
51 UINT32 mQemuUc32Base;
52
53 VOID
54 Q35TsegMbytesInitialization (
55 VOID
56 )
57 {
58 UINT16 ExtendedTsegMbytes;
59 RETURN_STATUS PcdStatus;
60
61 ASSERT (mHostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID);
62
63 //
64 // Check if QEMU offers an extended TSEG.
65 //
66 // This can be seen from writing MCH_EXT_TSEG_MB_QUERY to the MCH_EXT_TSEG_MB
67 // register, and reading back the register.
68 //
69 // On a QEMU machine type that does not offer an extended TSEG, the initial
70 // write overwrites whatever value a malicious guest OS may have placed in
71 // the (unimplemented) register, before entering S3 or rebooting.
72 // Subsequently, the read returns MCH_EXT_TSEG_MB_QUERY unchanged.
73 //
74 // On a QEMU machine type that offers an extended TSEG, the initial write
75 // triggers an update to the register. Subsequently, the value read back
76 // (which is guaranteed to differ from MCH_EXT_TSEG_MB_QUERY) tells us the
77 // number of megabytes.
78 //
79 PciWrite16 (DRAMC_REGISTER_Q35 (MCH_EXT_TSEG_MB), MCH_EXT_TSEG_MB_QUERY);
80 ExtendedTsegMbytes = PciRead16 (DRAMC_REGISTER_Q35 (MCH_EXT_TSEG_MB));
81 if (ExtendedTsegMbytes == MCH_EXT_TSEG_MB_QUERY) {
82 mQ35TsegMbytes = PcdGet16 (PcdQ35TsegMbytes);
83 return;
84 }
85
86 DEBUG ((
87 DEBUG_INFO,
88 "%a: QEMU offers an extended TSEG (%d MB)\n",
89 __FUNCTION__,
90 ExtendedTsegMbytes
91 ));
92 PcdStatus = PcdSet16S (PcdQ35TsegMbytes, ExtendedTsegMbytes);
93 ASSERT_RETURN_ERROR (PcdStatus);
94 mQ35TsegMbytes = ExtendedTsegMbytes;
95 }
96
97
98 VOID
99 Q35SmramAtDefaultSmbaseInitialization (
100 VOID
101 )
102 {
103 RETURN_STATUS PcdStatus;
104
105 ASSERT (mHostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID);
106
107 mQ35SmramAtDefaultSmbase = FALSE;
108 if (FeaturePcdGet (PcdCsmEnable)) {
109 DEBUG ((DEBUG_INFO, "%a: SMRAM at default SMBASE not checked due to CSM\n",
110 __FUNCTION__));
111 } else {
112 UINTN CtlReg;
113 UINT8 CtlRegVal;
114
115 CtlReg = DRAMC_REGISTER_Q35 (MCH_DEFAULT_SMBASE_CTL);
116 PciWrite8 (CtlReg, MCH_DEFAULT_SMBASE_QUERY);
117 CtlRegVal = PciRead8 (CtlReg);
118 mQ35SmramAtDefaultSmbase = (BOOLEAN)(CtlRegVal ==
119 MCH_DEFAULT_SMBASE_IN_RAM);
120 DEBUG ((DEBUG_INFO, "%a: SMRAM at default SMBASE %a\n", __FUNCTION__,
121 mQ35SmramAtDefaultSmbase ? "found" : "not found"));
122 }
123
124 PcdStatus = PcdSetBoolS (PcdQ35SmramAtDefaultSmbase,
125 mQ35SmramAtDefaultSmbase);
126 ASSERT_RETURN_ERROR (PcdStatus);
127 }
128
129
130 VOID
131 QemuUc32BaseInitialization (
132 VOID
133 )
134 {
135 UINT32 LowerMemorySize;
136 UINT32 Uc32Size;
137
138 if (mHostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) {
139 //
140 // On q35, the 32-bit area that we'll mark as UC, through variable MTRRs,
141 // starts at PcdPciExpressBaseAddress. The platform DSC is responsible for
142 // setting PcdPciExpressBaseAddress such that describing the
143 // [PcdPciExpressBaseAddress, 4GB) range require a very small number of
144 // variable MTRRs (preferably 1 or 2).
145 //
146 ASSERT (FixedPcdGet64 (PcdPciExpressBaseAddress) <= MAX_UINT32);
147 mQemuUc32Base = (UINT32)FixedPcdGet64 (PcdPciExpressBaseAddress);
148 return;
149 }
150
151 ASSERT (mHostBridgeDevId == INTEL_82441_DEVICE_ID);
152 //
153 // On i440fx, start with the [LowerMemorySize, 4GB) range. Make sure one
154 // variable MTRR suffices by truncating the size to a whole power of two,
155 // while keeping the end affixed to 4GB. This will round the base up.
156 //
157 LowerMemorySize = GetSystemMemorySizeBelow4gb ();
158 Uc32Size = GetPowerOfTwo32 ((UINT32)(SIZE_4GB - LowerMemorySize));
159 mQemuUc32Base = (UINT32)(SIZE_4GB - Uc32Size);
160 //
161 // Assuming that LowerMemorySize is at least 1 byte, Uc32Size is at most 2GB.
162 // Therefore mQemuUc32Base is at least 2GB.
163 //
164 ASSERT (mQemuUc32Base >= BASE_2GB);
165
166 if (mQemuUc32Base != LowerMemorySize) {
167 DEBUG ((DEBUG_VERBOSE, "%a: rounded UC32 base from 0x%x up to 0x%x, for "
168 "an UC32 size of 0x%x\n", __FUNCTION__, LowerMemorySize, mQemuUc32Base,
169 Uc32Size));
170 }
171 }
172
173
174 /**
175 Iterate over the RAM entries in QEMU's fw_cfg E820 RAM map that start outside
176 of the 32-bit address range.
177
178 Find the highest exclusive >=4GB RAM address, or produce memory resource
179 descriptor HOBs for RAM entries that start at or above 4GB.
180
181 @param[out] MaxAddress If MaxAddress is NULL, then ScanOrAdd64BitE820Ram()
182 produces memory resource descriptor HOBs for RAM
183 entries that start at or above 4GB.
184
185 Otherwise, MaxAddress holds the highest exclusive
186 >=4GB RAM address on output. If QEMU's fw_cfg E820
187 RAM map contains no RAM entry that starts outside of
188 the 32-bit address range, then MaxAddress is exactly
189 4GB on output.
190
191 @retval EFI_SUCCESS The fw_cfg E820 RAM map was found and processed.
192
193 @retval EFI_PROTOCOL_ERROR The RAM map was found, but its size wasn't a
194 whole multiple of sizeof(EFI_E820_ENTRY64). No
195 RAM entry was processed.
196
197 @return Error codes from QemuFwCfgFindFile(). No RAM
198 entry was processed.
199 **/
200 STATIC
201 EFI_STATUS
202 ScanOrAdd64BitE820Ram (
203 OUT UINT64 *MaxAddress OPTIONAL
204 )
205 {
206 EFI_STATUS Status;
207 FIRMWARE_CONFIG_ITEM FwCfgItem;
208 UINTN FwCfgSize;
209 EFI_E820_ENTRY64 E820Entry;
210 UINTN Processed;
211
212 Status = QemuFwCfgFindFile ("etc/e820", &FwCfgItem, &FwCfgSize);
213 if (EFI_ERROR (Status)) {
214 return Status;
215 }
216 if (FwCfgSize % sizeof E820Entry != 0) {
217 return EFI_PROTOCOL_ERROR;
218 }
219
220 if (MaxAddress != NULL) {
221 *MaxAddress = BASE_4GB;
222 }
223
224 QemuFwCfgSelectItem (FwCfgItem);
225 for (Processed = 0; Processed < FwCfgSize; Processed += sizeof E820Entry) {
226 QemuFwCfgReadBytes (sizeof E820Entry, &E820Entry);
227 DEBUG ((
228 DEBUG_VERBOSE,
229 "%a: Base=0x%Lx Length=0x%Lx Type=%u\n",
230 __FUNCTION__,
231 E820Entry.BaseAddr,
232 E820Entry.Length,
233 E820Entry.Type
234 ));
235 if (E820Entry.Type == EfiAcpiAddressRangeMemory &&
236 E820Entry.BaseAddr >= BASE_4GB) {
237 if (MaxAddress == NULL) {
238 UINT64 Base;
239 UINT64 End;
240
241 //
242 // Round up the start address, and round down the end address.
243 //
244 Base = ALIGN_VALUE (E820Entry.BaseAddr, (UINT64)EFI_PAGE_SIZE);
245 End = (E820Entry.BaseAddr + E820Entry.Length) &
246 ~(UINT64)EFI_PAGE_MASK;
247 if (Base < End) {
248 AddMemoryRangeHob (Base, End);
249 DEBUG ((
250 DEBUG_VERBOSE,
251 "%a: AddMemoryRangeHob [0x%Lx, 0x%Lx)\n",
252 __FUNCTION__,
253 Base,
254 End
255 ));
256 }
257 } else {
258 UINT64 Candidate;
259
260 Candidate = E820Entry.BaseAddr + E820Entry.Length;
261 if (Candidate > *MaxAddress) {
262 *MaxAddress = Candidate;
263 DEBUG ((
264 DEBUG_VERBOSE,
265 "%a: MaxAddress=0x%Lx\n",
266 __FUNCTION__,
267 *MaxAddress
268 ));
269 }
270 }
271 }
272 }
273 return EFI_SUCCESS;
274 }
275
276
277 UINT32
278 GetSystemMemorySizeBelow4gb (
279 VOID
280 )
281 {
282 UINT8 Cmos0x34;
283 UINT8 Cmos0x35;
284
285 //
286 // CMOS 0x34/0x35 specifies the system memory above 16 MB.
287 // * CMOS(0x35) is the high byte
288 // * CMOS(0x34) is the low byte
289 // * The size is specified in 64kb chunks
290 // * Since this is memory above 16MB, the 16MB must be added
291 // into the calculation to get the total memory size.
292 //
293
294 Cmos0x34 = (UINT8) CmosRead8 (0x34);
295 Cmos0x35 = (UINT8) CmosRead8 (0x35);
296
297 return (UINT32) (((UINTN)((Cmos0x35 << 8) + Cmos0x34) << 16) + SIZE_16MB);
298 }
299
300
301 STATIC
302 UINT64
303 GetSystemMemorySizeAbove4gb (
304 )
305 {
306 UINT32 Size;
307 UINTN CmosIndex;
308
309 //
310 // CMOS 0x5b-0x5d specifies the system memory above 4GB MB.
311 // * CMOS(0x5d) is the most significant size byte
312 // * CMOS(0x5c) is the middle size byte
313 // * CMOS(0x5b) is the least significant size byte
314 // * The size is specified in 64kb chunks
315 //
316
317 Size = 0;
318 for (CmosIndex = 0x5d; CmosIndex >= 0x5b; CmosIndex--) {
319 Size = (UINT32) (Size << 8) + (UINT32) CmosRead8 (CmosIndex);
320 }
321
322 return LShiftU64 (Size, 16);
323 }
324
325
326 /**
327 Return the highest address that DXE could possibly use, plus one.
328 **/
329 STATIC
330 UINT64
331 GetFirstNonAddress (
332 VOID
333 )
334 {
335 UINT64 FirstNonAddress;
336 UINT64 Pci64Base, Pci64Size;
337 UINT32 FwCfgPciMmio64Mb;
338 EFI_STATUS Status;
339 FIRMWARE_CONFIG_ITEM FwCfgItem;
340 UINTN FwCfgSize;
341 UINT64 HotPlugMemoryEnd;
342 RETURN_STATUS PcdStatus;
343
344 //
345 // set FirstNonAddress to suppress incorrect compiler/analyzer warnings
346 //
347 FirstNonAddress = 0;
348
349 //
350 // If QEMU presents an E820 map, then get the highest exclusive >=4GB RAM
351 // address from it. This can express an address >= 4GB+1TB.
352 //
353 // Otherwise, get the flat size of the memory above 4GB from the CMOS (which
354 // can only express a size smaller than 1TB), and add it to 4GB.
355 //
356 Status = ScanOrAdd64BitE820Ram (&FirstNonAddress);
357 if (EFI_ERROR (Status)) {
358 FirstNonAddress = BASE_4GB + GetSystemMemorySizeAbove4gb ();
359 }
360
361 //
362 // If DXE is 32-bit, then we're done; PciBusDxe will degrade 64-bit MMIO
363 // resources to 32-bit anyway. See DegradeResource() in
364 // "PciResourceSupport.c".
365 //
366 #ifdef MDE_CPU_IA32
367 if (!FeaturePcdGet (PcdDxeIplSwitchToLongMode)) {
368 return FirstNonAddress;
369 }
370 #endif
371
372 //
373 // Otherwise, in order to calculate the highest address plus one, we must
374 // consider the 64-bit PCI host aperture too. Fetch the default size.
375 //
376 Pci64Size = PcdGet64 (PcdPciMmio64Size);
377
378 //
379 // See if the user specified the number of megabytes for the 64-bit PCI host
380 // aperture. Accept an aperture size up to 16TB.
381 //
382 // As signaled by the "X-" prefix, this knob is experimental, and might go
383 // away at any time.
384 //
385 Status = QemuFwCfgParseUint32 ("opt/ovmf/X-PciMmio64Mb", FALSE,
386 &FwCfgPciMmio64Mb);
387 switch (Status) {
388 case EFI_UNSUPPORTED:
389 case EFI_NOT_FOUND:
390 break;
391 case EFI_SUCCESS:
392 if (FwCfgPciMmio64Mb <= 0x1000000) {
393 Pci64Size = LShiftU64 (FwCfgPciMmio64Mb, 20);
394 break;
395 }
396 //
397 // fall through
398 //
399 default:
400 DEBUG ((DEBUG_WARN,
401 "%a: ignoring malformed 64-bit PCI host aperture size from fw_cfg\n",
402 __FUNCTION__));
403 break;
404 }
405
406 if (Pci64Size == 0) {
407 if (mBootMode != BOOT_ON_S3_RESUME) {
408 DEBUG ((DEBUG_INFO, "%a: disabling 64-bit PCI host aperture\n",
409 __FUNCTION__));
410 PcdStatus = PcdSet64S (PcdPciMmio64Size, 0);
411 ASSERT_RETURN_ERROR (PcdStatus);
412 }
413
414 //
415 // There's nothing more to do; the amount of memory above 4GB fully
416 // determines the highest address plus one. The memory hotplug area (see
417 // below) plays no role for the firmware in this case.
418 //
419 return FirstNonAddress;
420 }
421
422 //
423 // The "etc/reserved-memory-end" fw_cfg file, when present, contains an
424 // absolute, exclusive end address for the memory hotplug area. This area
425 // starts right at the end of the memory above 4GB. The 64-bit PCI host
426 // aperture must be placed above it.
427 //
428 Status = QemuFwCfgFindFile ("etc/reserved-memory-end", &FwCfgItem,
429 &FwCfgSize);
430 if (!EFI_ERROR (Status) && FwCfgSize == sizeof HotPlugMemoryEnd) {
431 QemuFwCfgSelectItem (FwCfgItem);
432 QemuFwCfgReadBytes (FwCfgSize, &HotPlugMemoryEnd);
433 DEBUG ((DEBUG_VERBOSE, "%a: HotPlugMemoryEnd=0x%Lx\n", __FUNCTION__,
434 HotPlugMemoryEnd));
435
436 ASSERT (HotPlugMemoryEnd >= FirstNonAddress);
437 FirstNonAddress = HotPlugMemoryEnd;
438 }
439
440 //
441 // SeaBIOS aligns both boundaries of the 64-bit PCI host aperture to 1GB, so
442 // that the host can map it with 1GB hugepages. Follow suit.
443 //
444 Pci64Base = ALIGN_VALUE (FirstNonAddress, (UINT64)SIZE_1GB);
445 Pci64Size = ALIGN_VALUE (Pci64Size, (UINT64)SIZE_1GB);
446
447 //
448 // The 64-bit PCI host aperture should also be "naturally" aligned. The
449 // alignment is determined by rounding the size of the aperture down to the
450 // next smaller or equal power of two. That is, align the aperture by the
451 // largest BAR size that can fit into it.
452 //
453 Pci64Base = ALIGN_VALUE (Pci64Base, GetPowerOfTwo64 (Pci64Size));
454
455 if (mBootMode != BOOT_ON_S3_RESUME) {
456 //
457 // The core PciHostBridgeDxe driver will automatically add this range to
458 // the GCD memory space map through our PciHostBridgeLib instance; here we
459 // only need to set the PCDs.
460 //
461 PcdStatus = PcdSet64S (PcdPciMmio64Base, Pci64Base);
462 ASSERT_RETURN_ERROR (PcdStatus);
463 PcdStatus = PcdSet64S (PcdPciMmio64Size, Pci64Size);
464 ASSERT_RETURN_ERROR (PcdStatus);
465
466 DEBUG ((DEBUG_INFO, "%a: Pci64Base=0x%Lx Pci64Size=0x%Lx\n",
467 __FUNCTION__, Pci64Base, Pci64Size));
468 }
469
470 //
471 // The useful address space ends with the 64-bit PCI host aperture.
472 //
473 FirstNonAddress = Pci64Base + Pci64Size;
474 return FirstNonAddress;
475 }
476
477
478 /**
479 Initialize the mPhysMemAddressWidth variable, based on guest RAM size.
480 **/
481 VOID
482 AddressWidthInitialization (
483 VOID
484 )
485 {
486 UINT64 FirstNonAddress;
487
488 //
489 // As guest-physical memory size grows, the permanent PEI RAM requirements
490 // are dominated by the identity-mapping page tables built by the DXE IPL.
491 // The DXL IPL keys off of the physical address bits advertized in the CPU
492 // HOB. To conserve memory, we calculate the minimum address width here.
493 //
494 FirstNonAddress = GetFirstNonAddress ();
495 mPhysMemAddressWidth = (UINT8)HighBitSet64 (FirstNonAddress);
496
497 //
498 // If FirstNonAddress is not an integral power of two, then we need an
499 // additional bit.
500 //
501 if ((FirstNonAddress & (FirstNonAddress - 1)) != 0) {
502 ++mPhysMemAddressWidth;
503 }
504
505 //
506 // The minimum address width is 36 (covers up to and excluding 64 GB, which
507 // is the maximum for Ia32 + PAE). The theoretical architecture maximum for
508 // X64 long mode is 52 bits, but the DXE IPL clamps that down to 48 bits. We
509 // can simply assert that here, since 48 bits are good enough for 256 TB.
510 //
511 if (mPhysMemAddressWidth <= 36) {
512 mPhysMemAddressWidth = 36;
513 }
514 ASSERT (mPhysMemAddressWidth <= 48);
515 }
516
517
518 /**
519 Calculate the cap for the permanent PEI memory.
520 **/
521 STATIC
522 UINT32
523 GetPeiMemoryCap (
524 VOID
525 )
526 {
527 BOOLEAN Page1GSupport;
528 UINT32 RegEax;
529 UINT32 RegEdx;
530 UINT32 Pml4Entries;
531 UINT32 PdpEntries;
532 UINTN TotalPages;
533
534 //
535 // If DXE is 32-bit, then just return the traditional 64 MB cap.
536 //
537 #ifdef MDE_CPU_IA32
538 if (!FeaturePcdGet (PcdDxeIplSwitchToLongMode)) {
539 return SIZE_64MB;
540 }
541 #endif
542
543 //
544 // Dependent on physical address width, PEI memory allocations can be
545 // dominated by the page tables built for 64-bit DXE. So we key the cap off
546 // of those. The code below is based on CreateIdentityMappingPageTables() in
547 // "MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c".
548 //
549 Page1GSupport = FALSE;
550 if (PcdGetBool (PcdUse1GPageTable)) {
551 AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);
552 if (RegEax >= 0x80000001) {
553 AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx);
554 if ((RegEdx & BIT26) != 0) {
555 Page1GSupport = TRUE;
556 }
557 }
558 }
559
560 if (mPhysMemAddressWidth <= 39) {
561 Pml4Entries = 1;
562 PdpEntries = 1 << (mPhysMemAddressWidth - 30);
563 ASSERT (PdpEntries <= 0x200);
564 } else {
565 Pml4Entries = 1 << (mPhysMemAddressWidth - 39);
566 ASSERT (Pml4Entries <= 0x200);
567 PdpEntries = 512;
568 }
569
570 TotalPages = Page1GSupport ? Pml4Entries + 1 :
571 (PdpEntries + 1) * Pml4Entries + 1;
572 ASSERT (TotalPages <= 0x40201);
573
574 //
575 // Add 64 MB for miscellaneous allocations. Note that for
576 // mPhysMemAddressWidth values close to 36, the cap will actually be
577 // dominated by this increment.
578 //
579 return (UINT32)(EFI_PAGES_TO_SIZE (TotalPages) + SIZE_64MB);
580 }
581
582
583 /**
584 Publish PEI core memory
585
586 @return EFI_SUCCESS The PEIM initialized successfully.
587
588 **/
589 EFI_STATUS
590 PublishPeiMemory (
591 VOID
592 )
593 {
594 EFI_STATUS Status;
595 EFI_PHYSICAL_ADDRESS MemoryBase;
596 UINT64 MemorySize;
597 UINT32 LowerMemorySize;
598 UINT32 PeiMemoryCap;
599
600 LowerMemorySize = GetSystemMemorySizeBelow4gb ();
601 if (FeaturePcdGet (PcdSmmSmramRequire)) {
602 //
603 // TSEG is chipped from the end of low RAM
604 //
605 LowerMemorySize -= mQ35TsegMbytes * SIZE_1MB;
606 }
607
608 //
609 // If S3 is supported, then the S3 permanent PEI memory is placed next,
610 // downwards. Its size is primarily dictated by CpuMpPei. The formula below
611 // is an approximation.
612 //
613 if (mS3Supported) {
614 mS3AcpiReservedMemorySize = SIZE_512KB +
615 mMaxCpuCount *
616 PcdGet32 (PcdCpuApStackSize);
617 mS3AcpiReservedMemoryBase = LowerMemorySize - mS3AcpiReservedMemorySize;
618 LowerMemorySize = mS3AcpiReservedMemoryBase;
619 }
620
621 if (mBootMode == BOOT_ON_S3_RESUME) {
622 MemoryBase = mS3AcpiReservedMemoryBase;
623 MemorySize = mS3AcpiReservedMemorySize;
624 } else {
625 PeiMemoryCap = GetPeiMemoryCap ();
626 DEBUG ((DEBUG_INFO, "%a: mPhysMemAddressWidth=%d PeiMemoryCap=%u KB\n",
627 __FUNCTION__, mPhysMemAddressWidth, PeiMemoryCap >> 10));
628
629 //
630 // Determine the range of memory to use during PEI
631 //
632 // Technically we could lay the permanent PEI RAM over SEC's temporary
633 // decompression and scratch buffer even if "secure S3" is needed, since
634 // their lifetimes don't overlap. However, PeiFvInitialization() will cover
635 // RAM up to PcdOvmfDecompressionScratchEnd with an EfiACPIMemoryNVS memory
636 // allocation HOB, and other allocations served from the permanent PEI RAM
637 // shouldn't overlap with that HOB.
638 //
639 MemoryBase = mS3Supported && FeaturePcdGet (PcdSmmSmramRequire) ?
640 PcdGet32 (PcdOvmfDecompressionScratchEnd) :
641 PcdGet32 (PcdOvmfDxeMemFvBase) + PcdGet32 (PcdOvmfDxeMemFvSize);
642 MemorySize = LowerMemorySize - MemoryBase;
643 if (MemorySize > PeiMemoryCap) {
644 MemoryBase = LowerMemorySize - PeiMemoryCap;
645 MemorySize = PeiMemoryCap;
646 }
647 }
648
649 //
650 // MEMFD_BASE_ADDRESS separates the SMRAM at the default SMBASE from the
651 // normal boot permanent PEI RAM. Regarding the S3 boot path, the S3
652 // permanent PEI RAM is located even higher.
653 //
654 if (FeaturePcdGet (PcdSmmSmramRequire) && mQ35SmramAtDefaultSmbase) {
655 ASSERT (SMM_DEFAULT_SMBASE + MCH_DEFAULT_SMBASE_SIZE <= MemoryBase);
656 }
657
658 //
659 // Publish this memory to the PEI Core
660 //
661 Status = PublishSystemMemory(MemoryBase, MemorySize);
662 ASSERT_EFI_ERROR (Status);
663
664 return Status;
665 }
666
667
668 STATIC
669 VOID
670 QemuInitializeRamBelow1gb (
671 VOID
672 )
673 {
674 if (FeaturePcdGet (PcdSmmSmramRequire) && mQ35SmramAtDefaultSmbase) {
675 AddMemoryRangeHob (0, SMM_DEFAULT_SMBASE);
676 AddReservedMemoryBaseSizeHob (SMM_DEFAULT_SMBASE, MCH_DEFAULT_SMBASE_SIZE,
677 TRUE /* Cacheable */);
678 STATIC_ASSERT (
679 SMM_DEFAULT_SMBASE + MCH_DEFAULT_SMBASE_SIZE < BASE_512KB + BASE_128KB,
680 "end of SMRAM at default SMBASE ends at, or exceeds, 640KB"
681 );
682 AddMemoryRangeHob (SMM_DEFAULT_SMBASE + MCH_DEFAULT_SMBASE_SIZE,
683 BASE_512KB + BASE_128KB);
684 } else {
685 AddMemoryRangeHob (0, BASE_512KB + BASE_128KB);
686 }
687 }
688
689
690 /**
691 Peform Memory Detection for QEMU / KVM
692
693 **/
694 STATIC
695 VOID
696 QemuInitializeRam (
697 VOID
698 )
699 {
700 UINT64 LowerMemorySize;
701 UINT64 UpperMemorySize;
702 MTRR_SETTINGS MtrrSettings;
703 EFI_STATUS Status;
704
705 DEBUG ((DEBUG_INFO, "%a called\n", __FUNCTION__));
706
707 //
708 // Determine total memory size available
709 //
710 LowerMemorySize = GetSystemMemorySizeBelow4gb ();
711 UpperMemorySize = GetSystemMemorySizeAbove4gb ();
712
713 if (mBootMode == BOOT_ON_S3_RESUME) {
714 //
715 // Create the following memory HOB as an exception on the S3 boot path.
716 //
717 // Normally we'd create memory HOBs only on the normal boot path. However,
718 // CpuMpPei specifically needs such a low-memory HOB on the S3 path as
719 // well, for "borrowing" a subset of it temporarily, for the AP startup
720 // vector.
721 //
722 // CpuMpPei saves the original contents of the borrowed area in permanent
723 // PEI RAM, in a backup buffer allocated with the normal PEI services.
724 // CpuMpPei restores the original contents ("returns" the borrowed area) at
725 // End-of-PEI. End-of-PEI in turn is emitted by S3Resume2Pei before
726 // transferring control to the OS's wakeup vector in the FACS.
727 //
728 // We expect any other PEIMs that "borrow" memory similarly to CpuMpPei to
729 // restore the original contents. Furthermore, we expect all such PEIMs
730 // (CpuMpPei included) to claim the borrowed areas by producing memory
731 // allocation HOBs, and to honor preexistent memory allocation HOBs when
732 // looking for an area to borrow.
733 //
734 QemuInitializeRamBelow1gb ();
735 } else {
736 //
737 // Create memory HOBs
738 //
739 QemuInitializeRamBelow1gb ();
740
741 if (FeaturePcdGet (PcdSmmSmramRequire)) {
742 UINT32 TsegSize;
743
744 TsegSize = mQ35TsegMbytes * SIZE_1MB;
745 AddMemoryRangeHob (BASE_1MB, LowerMemorySize - TsegSize);
746 AddReservedMemoryBaseSizeHob (LowerMemorySize - TsegSize, TsegSize,
747 TRUE);
748 } else {
749 AddMemoryRangeHob (BASE_1MB, LowerMemorySize);
750 }
751
752 //
753 // If QEMU presents an E820 map, then create memory HOBs for the >=4GB RAM
754 // entries. Otherwise, create a single memory HOB with the flat >=4GB
755 // memory size read from the CMOS.
756 //
757 Status = ScanOrAdd64BitE820Ram (NULL);
758 if (EFI_ERROR (Status) && UpperMemorySize != 0) {
759 AddMemoryBaseSizeHob (BASE_4GB, UpperMemorySize);
760 }
761 }
762
763 //
764 // We'd like to keep the following ranges uncached:
765 // - [640 KB, 1 MB)
766 // - [LowerMemorySize, 4 GB)
767 //
768 // Everything else should be WB. Unfortunately, programming the inverse (ie.
769 // keeping the default UC, and configuring the complement set of the above as
770 // WB) is not reliable in general, because the end of the upper RAM can have
771 // practically any alignment, and we may not have enough variable MTRRs to
772 // cover it exactly.
773 //
774 if (IsMtrrSupported ()) {
775 MtrrGetAllMtrrs (&MtrrSettings);
776
777 //
778 // MTRRs disabled, fixed MTRRs disabled, default type is uncached
779 //
780 ASSERT ((MtrrSettings.MtrrDefType & BIT11) == 0);
781 ASSERT ((MtrrSettings.MtrrDefType & BIT10) == 0);
782 ASSERT ((MtrrSettings.MtrrDefType & 0xFF) == 0);
783
784 //
785 // flip default type to writeback
786 //
787 SetMem (&MtrrSettings.Fixed, sizeof MtrrSettings.Fixed, 0x06);
788 ZeroMem (&MtrrSettings.Variables, sizeof MtrrSettings.Variables);
789 MtrrSettings.MtrrDefType |= BIT11 | BIT10 | 6;
790 MtrrSetAllMtrrs (&MtrrSettings);
791
792 //
793 // Set memory range from 640KB to 1MB to uncacheable
794 //
795 Status = MtrrSetMemoryAttribute (BASE_512KB + BASE_128KB,
796 BASE_1MB - (BASE_512KB + BASE_128KB), CacheUncacheable);
797 ASSERT_EFI_ERROR (Status);
798
799 //
800 // Set the memory range from the start of the 32-bit MMIO area (32-bit PCI
801 // MMIO aperture on i440fx, PCIEXBAR on q35) to 4GB as uncacheable.
802 //
803 Status = MtrrSetMemoryAttribute (mQemuUc32Base, SIZE_4GB - mQemuUc32Base,
804 CacheUncacheable);
805 ASSERT_EFI_ERROR (Status);
806 }
807 }
808
809 /**
810 Publish system RAM and reserve memory regions
811
812 **/
813 VOID
814 InitializeRamRegions (
815 VOID
816 )
817 {
818 QemuInitializeRam ();
819
820 if (mS3Supported && mBootMode != BOOT_ON_S3_RESUME) {
821 //
822 // This is the memory range that will be used for PEI on S3 resume
823 //
824 BuildMemoryAllocationHob (
825 mS3AcpiReservedMemoryBase,
826 mS3AcpiReservedMemorySize,
827 EfiACPIMemoryNVS
828 );
829
830 //
831 // Cover the initial RAM area used as stack and temporary PEI heap.
832 //
833 // This is reserved as ACPI NVS so it can be used on S3 resume.
834 //
835 BuildMemoryAllocationHob (
836 PcdGet32 (PcdOvmfSecPeiTempRamBase),
837 PcdGet32 (PcdOvmfSecPeiTempRamSize),
838 EfiACPIMemoryNVS
839 );
840
841 //
842 // SEC stores its table of GUIDed section handlers here.
843 //
844 BuildMemoryAllocationHob (
845 PcdGet64 (PcdGuidedExtractHandlerTableAddress),
846 PcdGet32 (PcdGuidedExtractHandlerTableSize),
847 EfiACPIMemoryNVS
848 );
849
850 #ifdef MDE_CPU_X64
851 //
852 // Reserve the initial page tables built by the reset vector code.
853 //
854 // Since this memory range will be used by the Reset Vector on S3
855 // resume, it must be reserved as ACPI NVS.
856 //
857 BuildMemoryAllocationHob (
858 (EFI_PHYSICAL_ADDRESS)(UINTN) PcdGet32 (PcdOvmfSecPageTablesBase),
859 (UINT64)(UINTN) PcdGet32 (PcdOvmfSecPageTablesSize),
860 EfiACPIMemoryNVS
861 );
862
863 if (MemEncryptSevEsIsEnabled ()) {
864 //
865 // If SEV-ES is enabled, reserve the GHCB-related memory area. This
866 // includes the extra page table used to break down the 2MB page
867 // mapping into 4KB page entries where the GHCB resides and the
868 // GHCB area itself.
869 //
870 // Since this memory range will be used by the Reset Vector on S3
871 // resume, it must be reserved as ACPI NVS.
872 //
873 BuildMemoryAllocationHob (
874 (EFI_PHYSICAL_ADDRESS)(UINTN) PcdGet32 (PcdOvmfSecGhcbPageTableBase),
875 (UINT64)(UINTN) PcdGet32 (PcdOvmfSecGhcbPageTableSize),
876 EfiACPIMemoryNVS
877 );
878 BuildMemoryAllocationHob (
879 (EFI_PHYSICAL_ADDRESS)(UINTN) PcdGet32 (PcdOvmfSecGhcbBase),
880 (UINT64)(UINTN) PcdGet32 (PcdOvmfSecGhcbSize),
881 EfiACPIMemoryNVS
882 );
883 BuildMemoryAllocationHob (
884 (EFI_PHYSICAL_ADDRESS)(UINTN) PcdGet32 (PcdOvmfSecGhcbBackupBase),
885 (UINT64)(UINTN) PcdGet32 (PcdOvmfSecGhcbBackupSize),
886 EfiACPIMemoryNVS
887 );
888 }
889 #endif
890 }
891
892 if (mBootMode != BOOT_ON_S3_RESUME) {
893 if (!FeaturePcdGet (PcdSmmSmramRequire)) {
894 //
895 // Reserve the lock box storage area
896 //
897 // Since this memory range will be used on S3 resume, it must be
898 // reserved as ACPI NVS.
899 //
900 // If S3 is unsupported, then various drivers might still write to the
901 // LockBox area. We ought to prevent DXE from serving allocation requests
902 // such that they would overlap the LockBox storage.
903 //
904 ZeroMem (
905 (VOID*)(UINTN) PcdGet32 (PcdOvmfLockBoxStorageBase),
906 (UINTN) PcdGet32 (PcdOvmfLockBoxStorageSize)
907 );
908 BuildMemoryAllocationHob (
909 (EFI_PHYSICAL_ADDRESS)(UINTN) PcdGet32 (PcdOvmfLockBoxStorageBase),
910 (UINT64)(UINTN) PcdGet32 (PcdOvmfLockBoxStorageSize),
911 mS3Supported ? EfiACPIMemoryNVS : EfiBootServicesData
912 );
913 }
914
915 if (FeaturePcdGet (PcdSmmSmramRequire)) {
916 UINT32 TsegSize;
917
918 //
919 // Make sure the TSEG area that we reported as a reserved memory resource
920 // cannot be used for reserved memory allocations.
921 //
922 TsegSize = mQ35TsegMbytes * SIZE_1MB;
923 BuildMemoryAllocationHob (
924 GetSystemMemorySizeBelow4gb() - TsegSize,
925 TsegSize,
926 EfiReservedMemoryType
927 );
928 //
929 // Similarly, allocate away the (already reserved) SMRAM at the default
930 // SMBASE, if it exists.
931 //
932 if (mQ35SmramAtDefaultSmbase) {
933 BuildMemoryAllocationHob (
934 SMM_DEFAULT_SMBASE,
935 MCH_DEFAULT_SMBASE_SIZE,
936 EfiReservedMemoryType
937 );
938 }
939 }
940
941 #ifdef MDE_CPU_X64
942 if (MemEncryptSevEsIsEnabled ()) {
943 //
944 // If SEV-ES is enabled, reserve the SEV-ES work area.
945 //
946 // Since this memory range will be used by the Reset Vector on S3
947 // resume, it must be reserved as ACPI NVS.
948 //
949 // If S3 is unsupported, then various drivers might still write to the
950 // work area. We ought to prevent DXE from serving allocation requests
951 // such that they would overlap the work area.
952 //
953 BuildMemoryAllocationHob (
954 (EFI_PHYSICAL_ADDRESS)(UINTN) FixedPcdGet32 (PcdSevEsWorkAreaBase),
955 (UINT64)(UINTN) FixedPcdGet32 (PcdSevEsWorkAreaSize),
956 mS3Supported ? EfiACPIMemoryNVS : EfiBootServicesData
957 );
958 }
959 #endif
960 }
961 }