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