]> git.proxmox.com Git - mirror_edk2.git/blob - OvmfPkg/PlatformPei/MemDetect.c
2b2f3e4bec55e08d14fc8ccc70b9844470e0eb5d
[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
362 ASSERT (HotPlugMemoryEnd >= FirstNonAddress);
363 FirstNonAddress = HotPlugMemoryEnd;
364 }
365
366 //
367 // SeaBIOS aligns both boundaries of the 64-bit PCI host aperture to 1GB, so
368 // that the host can map it with 1GB hugepages. Follow suit.
369 //
370 Pci64Base = ALIGN_VALUE (FirstNonAddress, (UINT64)SIZE_1GB);
371 Pci64Size = ALIGN_VALUE (Pci64Size, (UINT64)SIZE_1GB);
372
373 //
374 // The 64-bit PCI host aperture should also be "naturally" aligned. The
375 // alignment is determined by rounding the size of the aperture down to the
376 // next smaller or equal power of two. That is, align the aperture by the
377 // largest BAR size that can fit into it.
378 //
379 Pci64Base = ALIGN_VALUE (Pci64Base, GetPowerOfTwo64 (Pci64Size));
380
381 if (mBootMode != BOOT_ON_S3_RESUME) {
382 //
383 // The core PciHostBridgeDxe driver will automatically add this range to
384 // the GCD memory space map through our PciHostBridgeLib instance; here we
385 // only need to set the PCDs.
386 //
387 PcdStatus = PcdSet64S (PcdPciMmio64Base, Pci64Base);
388 ASSERT_RETURN_ERROR (PcdStatus);
389 PcdStatus = PcdSet64S (PcdPciMmio64Size, Pci64Size);
390 ASSERT_RETURN_ERROR (PcdStatus);
391
392 DEBUG ((EFI_D_INFO, "%a: Pci64Base=0x%Lx Pci64Size=0x%Lx\n",
393 __FUNCTION__, Pci64Base, Pci64Size));
394 }
395
396 //
397 // The useful address space ends with the 64-bit PCI host aperture.
398 //
399 FirstNonAddress = Pci64Base + Pci64Size;
400 return FirstNonAddress;
401 }
402
403
404 /**
405 Initialize the mPhysMemAddressWidth variable, based on guest RAM size.
406 **/
407 VOID
408 AddressWidthInitialization (
409 VOID
410 )
411 {
412 UINT64 FirstNonAddress;
413
414 //
415 // As guest-physical memory size grows, the permanent PEI RAM requirements
416 // are dominated by the identity-mapping page tables built by the DXE IPL.
417 // The DXL IPL keys off of the physical address bits advertized in the CPU
418 // HOB. To conserve memory, we calculate the minimum address width here.
419 //
420 FirstNonAddress = GetFirstNonAddress ();
421 mPhysMemAddressWidth = (UINT8)HighBitSet64 (FirstNonAddress);
422
423 //
424 // If FirstNonAddress is not an integral power of two, then we need an
425 // additional bit.
426 //
427 if ((FirstNonAddress & (FirstNonAddress - 1)) != 0) {
428 ++mPhysMemAddressWidth;
429 }
430
431 //
432 // The minimum address width is 36 (covers up to and excluding 64 GB, which
433 // is the maximum for Ia32 + PAE). The theoretical architecture maximum for
434 // X64 long mode is 52 bits, but the DXE IPL clamps that down to 48 bits. We
435 // can simply assert that here, since 48 bits are good enough for 256 TB.
436 //
437 if (mPhysMemAddressWidth <= 36) {
438 mPhysMemAddressWidth = 36;
439 }
440 ASSERT (mPhysMemAddressWidth <= 48);
441 }
442
443
444 /**
445 Calculate the cap for the permanent PEI memory.
446 **/
447 STATIC
448 UINT32
449 GetPeiMemoryCap (
450 VOID
451 )
452 {
453 BOOLEAN Page1GSupport;
454 UINT32 RegEax;
455 UINT32 RegEdx;
456 UINT32 Pml4Entries;
457 UINT32 PdpEntries;
458 UINTN TotalPages;
459
460 //
461 // If DXE is 32-bit, then just return the traditional 64 MB cap.
462 //
463 #ifdef MDE_CPU_IA32
464 if (!FeaturePcdGet (PcdDxeIplSwitchToLongMode)) {
465 return SIZE_64MB;
466 }
467 #endif
468
469 //
470 // Dependent on physical address width, PEI memory allocations can be
471 // dominated by the page tables built for 64-bit DXE. So we key the cap off
472 // of those. The code below is based on CreateIdentityMappingPageTables() in
473 // "MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c".
474 //
475 Page1GSupport = FALSE;
476 if (PcdGetBool (PcdUse1GPageTable)) {
477 AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);
478 if (RegEax >= 0x80000001) {
479 AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx);
480 if ((RegEdx & BIT26) != 0) {
481 Page1GSupport = TRUE;
482 }
483 }
484 }
485
486 if (mPhysMemAddressWidth <= 39) {
487 Pml4Entries = 1;
488 PdpEntries = 1 << (mPhysMemAddressWidth - 30);
489 ASSERT (PdpEntries <= 0x200);
490 } else {
491 Pml4Entries = 1 << (mPhysMemAddressWidth - 39);
492 ASSERT (Pml4Entries <= 0x200);
493 PdpEntries = 512;
494 }
495
496 TotalPages = Page1GSupport ? Pml4Entries + 1 :
497 (PdpEntries + 1) * Pml4Entries + 1;
498 ASSERT (TotalPages <= 0x40201);
499
500 //
501 // Add 64 MB for miscellaneous allocations. Note that for
502 // mPhysMemAddressWidth values close to 36, the cap will actually be
503 // dominated by this increment.
504 //
505 return (UINT32)(EFI_PAGES_TO_SIZE (TotalPages) + SIZE_64MB);
506 }
507
508
509 /**
510 Publish PEI core memory
511
512 @return EFI_SUCCESS The PEIM initialized successfully.
513
514 **/
515 EFI_STATUS
516 PublishPeiMemory (
517 VOID
518 )
519 {
520 EFI_STATUS Status;
521 EFI_PHYSICAL_ADDRESS MemoryBase;
522 UINT64 MemorySize;
523 UINT32 LowerMemorySize;
524 UINT32 PeiMemoryCap;
525
526 LowerMemorySize = GetSystemMemorySizeBelow4gb ();
527 if (FeaturePcdGet (PcdSmmSmramRequire)) {
528 //
529 // TSEG is chipped from the end of low RAM
530 //
531 LowerMemorySize -= mQ35TsegMbytes * SIZE_1MB;
532 }
533
534 //
535 // If S3 is supported, then the S3 permanent PEI memory is placed next,
536 // downwards. Its size is primarily dictated by CpuMpPei. The formula below
537 // is an approximation.
538 //
539 if (mS3Supported) {
540 mS3AcpiReservedMemorySize = SIZE_512KB +
541 mMaxCpuCount *
542 PcdGet32 (PcdCpuApStackSize);
543 mS3AcpiReservedMemoryBase = LowerMemorySize - mS3AcpiReservedMemorySize;
544 LowerMemorySize = mS3AcpiReservedMemoryBase;
545 }
546
547 if (mBootMode == BOOT_ON_S3_RESUME) {
548 MemoryBase = mS3AcpiReservedMemoryBase;
549 MemorySize = mS3AcpiReservedMemorySize;
550 } else {
551 PeiMemoryCap = GetPeiMemoryCap ();
552 DEBUG ((EFI_D_INFO, "%a: mPhysMemAddressWidth=%d PeiMemoryCap=%u KB\n",
553 __FUNCTION__, mPhysMemAddressWidth, PeiMemoryCap >> 10));
554
555 //
556 // Determine the range of memory to use during PEI
557 //
558 // Technically we could lay the permanent PEI RAM over SEC's temporary
559 // decompression and scratch buffer even if "secure S3" is needed, since
560 // their lifetimes don't overlap. However, PeiFvInitialization() will cover
561 // RAM up to PcdOvmfDecompressionScratchEnd with an EfiACPIMemoryNVS memory
562 // allocation HOB, and other allocations served from the permanent PEI RAM
563 // shouldn't overlap with that HOB.
564 //
565 MemoryBase = mS3Supported && FeaturePcdGet (PcdSmmSmramRequire) ?
566 PcdGet32 (PcdOvmfDecompressionScratchEnd) :
567 PcdGet32 (PcdOvmfDxeMemFvBase) + PcdGet32 (PcdOvmfDxeMemFvSize);
568 MemorySize = LowerMemorySize - MemoryBase;
569 if (MemorySize > PeiMemoryCap) {
570 MemoryBase = LowerMemorySize - PeiMemoryCap;
571 MemorySize = PeiMemoryCap;
572 }
573 }
574
575 //
576 // Publish this memory to the PEI Core
577 //
578 Status = PublishSystemMemory(MemoryBase, MemorySize);
579 ASSERT_EFI_ERROR (Status);
580
581 return Status;
582 }
583
584
585 /**
586 Peform Memory Detection for QEMU / KVM
587
588 **/
589 STATIC
590 VOID
591 QemuInitializeRam (
592 VOID
593 )
594 {
595 UINT64 LowerMemorySize;
596 UINT64 UpperMemorySize;
597 MTRR_SETTINGS MtrrSettings;
598 EFI_STATUS Status;
599
600 DEBUG ((EFI_D_INFO, "%a called\n", __FUNCTION__));
601
602 //
603 // Determine total memory size available
604 //
605 LowerMemorySize = GetSystemMemorySizeBelow4gb ();
606 UpperMemorySize = GetSystemMemorySizeAbove4gb ();
607
608 if (mBootMode == BOOT_ON_S3_RESUME) {
609 //
610 // Create the following memory HOB as an exception on the S3 boot path.
611 //
612 // Normally we'd create memory HOBs only on the normal boot path. However,
613 // CpuMpPei specifically needs such a low-memory HOB on the S3 path as
614 // well, for "borrowing" a subset of it temporarily, for the AP startup
615 // vector.
616 //
617 // CpuMpPei saves the original contents of the borrowed area in permanent
618 // PEI RAM, in a backup buffer allocated with the normal PEI services.
619 // CpuMpPei restores the original contents ("returns" the borrowed area) at
620 // End-of-PEI. End-of-PEI in turn is emitted by S3Resume2Pei before
621 // transferring control to the OS's wakeup vector in the FACS.
622 //
623 // We expect any other PEIMs that "borrow" memory similarly to CpuMpPei to
624 // restore the original contents. Furthermore, we expect all such PEIMs
625 // (CpuMpPei included) to claim the borrowed areas by producing memory
626 // allocation HOBs, and to honor preexistent memory allocation HOBs when
627 // looking for an area to borrow.
628 //
629 AddMemoryRangeHob (0, BASE_512KB + BASE_128KB);
630 } else {
631 //
632 // Create memory HOBs
633 //
634 AddMemoryRangeHob (0, BASE_512KB + BASE_128KB);
635
636 if (FeaturePcdGet (PcdSmmSmramRequire)) {
637 UINT32 TsegSize;
638
639 TsegSize = mQ35TsegMbytes * SIZE_1MB;
640 AddMemoryRangeHob (BASE_1MB, LowerMemorySize - TsegSize);
641 AddReservedMemoryBaseSizeHob (LowerMemorySize - TsegSize, TsegSize,
642 TRUE);
643 } else {
644 AddMemoryRangeHob (BASE_1MB, LowerMemorySize);
645 }
646
647 //
648 // If QEMU presents an E820 map, then create memory HOBs for the >=4GB RAM
649 // entries. Otherwise, create a single memory HOB with the flat >=4GB
650 // memory size read from the CMOS.
651 //
652 Status = ScanOrAdd64BitE820Ram (NULL);
653 if (EFI_ERROR (Status) && UpperMemorySize != 0) {
654 AddMemoryBaseSizeHob (BASE_4GB, UpperMemorySize);
655 }
656 }
657
658 //
659 // We'd like to keep the following ranges uncached:
660 // - [640 KB, 1 MB)
661 // - [LowerMemorySize, 4 GB)
662 //
663 // Everything else should be WB. Unfortunately, programming the inverse (ie.
664 // keeping the default UC, and configuring the complement set of the above as
665 // WB) is not reliable in general, because the end of the upper RAM can have
666 // practically any alignment, and we may not have enough variable MTRRs to
667 // cover it exactly.
668 //
669 if (IsMtrrSupported ()) {
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
697 //
698 Status = MtrrSetMemoryAttribute (LowerMemorySize,
699 SIZE_4GB - LowerMemorySize, CacheUncacheable);
700 ASSERT_EFI_ERROR (Status);
701 }
702 }
703
704 /**
705 Publish system RAM and reserve memory regions
706
707 **/
708 VOID
709 InitializeRamRegions (
710 VOID
711 )
712 {
713 if (!mXen) {
714 QemuInitializeRam ();
715 } else {
716 XenPublishRamRegions ();
717 }
718
719 if (mS3Supported && mBootMode != BOOT_ON_S3_RESUME) {
720 //
721 // This is the memory range that will be used for PEI on S3 resume
722 //
723 BuildMemoryAllocationHob (
724 mS3AcpiReservedMemoryBase,
725 mS3AcpiReservedMemorySize,
726 EfiACPIMemoryNVS
727 );
728
729 //
730 // Cover the initial RAM area used as stack and temporary PEI heap.
731 //
732 // This is reserved as ACPI NVS so it can be used on S3 resume.
733 //
734 BuildMemoryAllocationHob (
735 PcdGet32 (PcdOvmfSecPeiTempRamBase),
736 PcdGet32 (PcdOvmfSecPeiTempRamSize),
737 EfiACPIMemoryNVS
738 );
739
740 //
741 // SEC stores its table of GUIDed section handlers here.
742 //
743 BuildMemoryAllocationHob (
744 PcdGet64 (PcdGuidedExtractHandlerTableAddress),
745 PcdGet32 (PcdGuidedExtractHandlerTableSize),
746 EfiACPIMemoryNVS
747 );
748
749 #ifdef MDE_CPU_X64
750 //
751 // Reserve the initial page tables built by the reset vector code.
752 //
753 // Since this memory range will be used by the Reset Vector on S3
754 // resume, it must be reserved as ACPI NVS.
755 //
756 BuildMemoryAllocationHob (
757 (EFI_PHYSICAL_ADDRESS)(UINTN) PcdGet32 (PcdOvmfSecPageTablesBase),
758 (UINT64)(UINTN) PcdGet32 (PcdOvmfSecPageTablesSize),
759 EfiACPIMemoryNVS
760 );
761 #endif
762 }
763
764 if (mBootMode != BOOT_ON_S3_RESUME) {
765 if (!FeaturePcdGet (PcdSmmSmramRequire)) {
766 //
767 // Reserve the lock box storage area
768 //
769 // Since this memory range will be used on S3 resume, it must be
770 // reserved as ACPI NVS.
771 //
772 // If S3 is unsupported, then various drivers might still write to the
773 // LockBox area. We ought to prevent DXE from serving allocation requests
774 // such that they would overlap the LockBox storage.
775 //
776 ZeroMem (
777 (VOID*)(UINTN) PcdGet32 (PcdOvmfLockBoxStorageBase),
778 (UINTN) PcdGet32 (PcdOvmfLockBoxStorageSize)
779 );
780 BuildMemoryAllocationHob (
781 (EFI_PHYSICAL_ADDRESS)(UINTN) PcdGet32 (PcdOvmfLockBoxStorageBase),
782 (UINT64)(UINTN) PcdGet32 (PcdOvmfLockBoxStorageSize),
783 mS3Supported ? EfiACPIMemoryNVS : EfiBootServicesData
784 );
785 }
786
787 if (FeaturePcdGet (PcdSmmSmramRequire)) {
788 UINT32 TsegSize;
789
790 //
791 // Make sure the TSEG area that we reported as a reserved memory resource
792 // cannot be used for reserved memory allocations.
793 //
794 TsegSize = mQ35TsegMbytes * SIZE_1MB;
795 BuildMemoryAllocationHob (
796 GetSystemMemorySizeBelow4gb() - TsegSize,
797 TsegSize,
798 EfiReservedMemoryType
799 );
800 }
801 }
802 }