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