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