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