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