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