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