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