]> git.proxmox.com Git - mirror_edk2.git/blob - OvmfPkg/Library/PlatformInitLib/Platform.c
UefiCpuPkg: Move AsmRelocateApLoopStart from Mpfuncs.nasm to AmdSev.nasm
[mirror_edk2.git] / OvmfPkg / Library / PlatformInitLib / Platform.c
1 /**@file
2
3 Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
4 Copyright (c) 2011, Andrei Warkentin <andreiw@motorola.com>
5
6 SPDX-License-Identifier: BSD-2-Clause-Patent
7
8 **/
9
10 //
11 // The package level header files this module uses
12 //
13 #include <PiPei.h>
14
15 //
16 // The Library classes this module consumes
17 //
18 #include <Library/BaseMemoryLib.h>
19 #include <Library/BaseLib.h>
20 #include <Library/DebugLib.h>
21 #include <Library/HobLib.h>
22 #include <Library/IoLib.h>
23 #include <IndustryStandard/I440FxPiix4.h>
24 #include <IndustryStandard/Microvm.h>
25 #include <IndustryStandard/Pci22.h>
26 #include <IndustryStandard/Q35MchIch9.h>
27 #include <IndustryStandard/QemuCpuHotplug.h>
28 #include <Library/MemoryAllocationLib.h>
29 #include <Library/QemuFwCfgLib.h>
30 #include <Library/QemuFwCfgS3Lib.h>
31 #include <Library/QemuFwCfgSimpleParserLib.h>
32 #include <Library/PciLib.h>
33 #include <Guid/SystemNvDataGuid.h>
34 #include <Guid/VariableFormat.h>
35 #include <OvmfPlatforms.h>
36
37 #include <Library/PlatformInitLib.h>
38
39 #define CPUHP_BUGCHECK_OVERRIDE_FWCFG_FILE \
40 "opt/org.tianocore/X-Cpuhp-Bugcheck-Override"
41
42 VOID
43 EFIAPI
44 PlatformAddIoMemoryBaseSizeHob (
45 IN EFI_PHYSICAL_ADDRESS MemoryBase,
46 IN UINT64 MemorySize
47 )
48 {
49 BuildResourceDescriptorHob (
50 EFI_RESOURCE_MEMORY_MAPPED_IO,
51 EFI_RESOURCE_ATTRIBUTE_PRESENT |
52 EFI_RESOURCE_ATTRIBUTE_INITIALIZED |
53 EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE |
54 EFI_RESOURCE_ATTRIBUTE_TESTED,
55 MemoryBase,
56 MemorySize
57 );
58 }
59
60 VOID
61 EFIAPI
62 PlatformAddReservedMemoryBaseSizeHob (
63 IN EFI_PHYSICAL_ADDRESS MemoryBase,
64 IN UINT64 MemorySize,
65 IN BOOLEAN Cacheable
66 )
67 {
68 BuildResourceDescriptorHob (
69 EFI_RESOURCE_MEMORY_RESERVED,
70 EFI_RESOURCE_ATTRIBUTE_PRESENT |
71 EFI_RESOURCE_ATTRIBUTE_INITIALIZED |
72 EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE |
73 (Cacheable ?
74 EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE |
75 EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE |
76 EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE :
77 0
78 ) |
79 EFI_RESOURCE_ATTRIBUTE_TESTED,
80 MemoryBase,
81 MemorySize
82 );
83 }
84
85 VOID
86 EFIAPI
87 PlatformAddIoMemoryRangeHob (
88 IN EFI_PHYSICAL_ADDRESS MemoryBase,
89 IN EFI_PHYSICAL_ADDRESS MemoryLimit
90 )
91 {
92 PlatformAddIoMemoryBaseSizeHob (MemoryBase, (UINT64)(MemoryLimit - MemoryBase));
93 }
94
95 VOID
96 EFIAPI
97 PlatformAddMemoryBaseSizeHob (
98 IN EFI_PHYSICAL_ADDRESS MemoryBase,
99 IN UINT64 MemorySize
100 )
101 {
102 BuildResourceDescriptorHob (
103 EFI_RESOURCE_SYSTEM_MEMORY,
104 EFI_RESOURCE_ATTRIBUTE_PRESENT |
105 EFI_RESOURCE_ATTRIBUTE_INITIALIZED |
106 EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE |
107 EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE |
108 EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE |
109 EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE |
110 EFI_RESOURCE_ATTRIBUTE_TESTED,
111 MemoryBase,
112 MemorySize
113 );
114 }
115
116 VOID
117 EFIAPI
118 PlatformAddMemoryRangeHob (
119 IN EFI_PHYSICAL_ADDRESS MemoryBase,
120 IN EFI_PHYSICAL_ADDRESS MemoryLimit
121 )
122 {
123 PlatformAddMemoryBaseSizeHob (MemoryBase, (UINT64)(MemoryLimit - MemoryBase));
124 }
125
126 VOID
127 EFIAPI
128 PlatformMemMapInitialization (
129 IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob
130 )
131 {
132 UINT64 PciIoBase;
133 UINT64 PciIoSize;
134 UINT64 PciExBarBase;
135 UINT32 PciBase;
136 UINT32 PciSize;
137
138 PciIoBase = 0xC000;
139 PciIoSize = 0x4000;
140
141 //
142 // Video memory + Legacy BIOS region
143 //
144 if (!TdIsEnabled ()) {
145 PlatformAddIoMemoryRangeHob (0x0A0000, BASE_1MB);
146 }
147
148 if (PlatformInfoHob->HostBridgeDevId == 0xffff /* microvm */) {
149 PlatformAddIoMemoryBaseSizeHob (MICROVM_GED_MMIO_BASE, SIZE_4KB);
150 PlatformAddIoMemoryBaseSizeHob (0xFEC00000, SIZE_4KB); /* ioapic #1 */
151 PlatformAddIoMemoryBaseSizeHob (0xFEC10000, SIZE_4KB); /* ioapic #2 */
152 return;
153 }
154
155 PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob);
156 PciExBarBase = 0;
157 if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) {
158 //
159 // The MMCONFIG area is expected to fall between the top of low RAM and
160 // the base of the 32-bit PCI host aperture.
161 //
162 PciExBarBase = PcdGet64 (PcdPciExpressBaseAddress);
163 ASSERT (PlatformInfoHob->LowMemory <= PciExBarBase);
164 ASSERT (PciExBarBase <= MAX_UINT32 - SIZE_256MB);
165 PciBase = (UINT32)(PciExBarBase + SIZE_256MB);
166 } else {
167 ASSERT (PlatformInfoHob->LowMemory <= PlatformInfoHob->Uc32Base);
168 PciBase = PlatformInfoHob->Uc32Base;
169 }
170
171 //
172 // address purpose size
173 // ------------ -------- -------------------------
174 // max(top, 2g) PCI MMIO 0xFC000000 - max(top, 2g)
175 // 0xFC000000 gap 44 MB
176 // 0xFEC00000 IO-APIC 4 KB
177 // 0xFEC01000 gap 1020 KB
178 // 0xFED00000 HPET 1 KB
179 // 0xFED00400 gap 111 KB
180 // 0xFED1C000 gap (PIIX4) / RCRB (ICH9) 16 KB
181 // 0xFED20000 gap 896 KB
182 // 0xFEE00000 LAPIC 1 MB
183 //
184 PciSize = 0xFC000000 - PciBase;
185 PlatformAddIoMemoryBaseSizeHob (PciBase, PciSize);
186
187 PlatformInfoHob->PcdPciMmio32Base = PciBase;
188 PlatformInfoHob->PcdPciMmio32Size = PciSize;
189
190 PlatformAddIoMemoryBaseSizeHob (0xFEC00000, SIZE_4KB);
191 PlatformAddIoMemoryBaseSizeHob (0xFED00000, SIZE_1KB);
192 if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) {
193 PlatformAddIoMemoryBaseSizeHob (ICH9_ROOT_COMPLEX_BASE, SIZE_16KB);
194 //
195 // Note: there should be an
196 //
197 // PlatformAddIoMemoryBaseSizeHob (PciExBarBase, SIZE_256MB);
198 //
199 // call below, just like the one above for RCBA. However, Linux insists
200 // that the MMCONFIG area be marked in the E820 or UEFI memory map as
201 // "reserved memory" -- Linux does not content itself with a simple gap
202 // in the memory map wherever the MCFG ACPI table points to.
203 //
204 // This appears to be a safety measure. The PCI Firmware Specification
205 // (rev 3.1) says in 4.1.2. "MCFG Table Description": "The resources can
206 // *optionally* be returned in [...] EFIGetMemoryMap as reserved memory
207 // [...]". (Emphasis added here.)
208 //
209 // Normally we add memory resource descriptor HOBs in
210 // QemuInitializeRam(), and pre-allocate from those with memory
211 // allocation HOBs in InitializeRamRegions(). However, the MMCONFIG area
212 // is most definitely not RAM; so, as an exception, cover it with
213 // uncacheable reserved memory right here.
214 //
215 PlatformAddReservedMemoryBaseSizeHob (PciExBarBase, SIZE_256MB, FALSE);
216 BuildMemoryAllocationHob (
217 PciExBarBase,
218 SIZE_256MB,
219 EfiReservedMemoryType
220 );
221 }
222
223 PlatformAddIoMemoryBaseSizeHob (PcdGet32 (PcdCpuLocalApicBaseAddress), SIZE_1MB);
224
225 //
226 // On Q35, the IO Port space is available for PCI resource allocations from
227 // 0x6000 up.
228 //
229 if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) {
230 PciIoBase = 0x6000;
231 PciIoSize = 0xA000;
232 ASSERT ((ICH9_PMBASE_VALUE & 0xF000) < PciIoBase);
233 }
234
235 //
236 // Add PCI IO Port space available for PCI resource allocations.
237 //
238 BuildResourceDescriptorHob (
239 EFI_RESOURCE_IO,
240 EFI_RESOURCE_ATTRIBUTE_PRESENT |
241 EFI_RESOURCE_ATTRIBUTE_INITIALIZED,
242 PciIoBase,
243 PciIoSize
244 );
245
246 PlatformInfoHob->PcdPciIoBase = PciIoBase;
247 PlatformInfoHob->PcdPciIoSize = PciIoSize;
248 }
249
250 /**
251 * Fetch "opt/ovmf/PcdSetNxForStack" from QEMU
252 *
253 * @param Setting The pointer to the setting of "/opt/ovmf/PcdSetNxForStack".
254 * @return EFI_SUCCESS Successfully fetch the settings.
255 */
256 EFI_STATUS
257 EFIAPI
258 PlatformNoexecDxeInitialization (
259 IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob
260 )
261 {
262 return QemuFwCfgParseBool ("opt/ovmf/PcdSetNxForStack", &PlatformInfoHob->PcdSetNxForStack);
263 }
264
265 VOID
266 PciExBarInitialization (
267 VOID
268 )
269 {
270 union {
271 UINT64 Uint64;
272 UINT32 Uint32[2];
273 } PciExBarBase;
274
275 //
276 // We only support the 256MB size for the MMCONFIG area:
277 // 256 buses * 32 devices * 8 functions * 4096 bytes config space.
278 //
279 // The masks used below enforce the Q35 requirements that the MMCONFIG area
280 // be (a) correctly aligned -- here at 256 MB --, (b) located under 64 GB.
281 //
282 // Note that (b) also ensures that the minimum address width we have
283 // determined in AddressWidthInitialization(), i.e., 36 bits, will suffice
284 // for DXE's page tables to cover the MMCONFIG area.
285 //
286 PciExBarBase.Uint64 = PcdGet64 (PcdPciExpressBaseAddress);
287 ASSERT ((PciExBarBase.Uint32[1] & MCH_PCIEXBAR_HIGHMASK) == 0);
288 ASSERT ((PciExBarBase.Uint32[0] & MCH_PCIEXBAR_LOWMASK) == 0);
289
290 //
291 // Clear the PCIEXBAREN bit first, before programming the high register.
292 //
293 PciWrite32 (DRAMC_REGISTER_Q35 (MCH_PCIEXBAR_LOW), 0);
294
295 //
296 // Program the high register. Then program the low register, setting the
297 // MMCONFIG area size and enabling decoding at once.
298 //
299 PciWrite32 (DRAMC_REGISTER_Q35 (MCH_PCIEXBAR_HIGH), PciExBarBase.Uint32[1]);
300 PciWrite32 (
301 DRAMC_REGISTER_Q35 (MCH_PCIEXBAR_LOW),
302 PciExBarBase.Uint32[0] | MCH_PCIEXBAR_BUS_FF | MCH_PCIEXBAR_EN
303 );
304 }
305
306 VOID
307 EFIAPI
308 PlatformMiscInitialization (
309 IN EFI_HOB_PLATFORM_INFO *PlatformInfoHob
310 )
311 {
312 UINTN PmCmd;
313 UINTN Pmba;
314 UINT32 PmbaAndVal;
315 UINT32 PmbaOrVal;
316 UINTN AcpiCtlReg;
317 UINT8 AcpiEnBit;
318
319 //
320 // Disable A20 Mask
321 //
322 if (PlatformInfoHob->HostBridgeDevId != CLOUDHV_DEVICE_ID) {
323 IoOr8 (0x92, BIT1);
324 }
325
326 //
327 // Build the CPU HOB with guest RAM size dependent address width and 16-bits
328 // of IO space. (Side note: unlike other HOBs, the CPU HOB is needed during
329 // S3 resume as well, so we build it unconditionally.)
330 //
331 BuildCpuHob (PlatformInfoHob->PhysMemAddressWidth, 16);
332
333 //
334 // Determine platform type and save Host Bridge DID to PCD
335 //
336 switch (PlatformInfoHob->HostBridgeDevId) {
337 case INTEL_82441_DEVICE_ID:
338 PmCmd = POWER_MGMT_REGISTER_PIIX4 (PCI_COMMAND_OFFSET);
339 Pmba = POWER_MGMT_REGISTER_PIIX4 (PIIX4_PMBA);
340 PmbaAndVal = ~(UINT32)PIIX4_PMBA_MASK;
341 PmbaOrVal = PIIX4_PMBA_VALUE;
342 AcpiCtlReg = POWER_MGMT_REGISTER_PIIX4 (PIIX4_PMREGMISC);
343 AcpiEnBit = PIIX4_PMREGMISC_PMIOSE;
344 break;
345 case INTEL_Q35_MCH_DEVICE_ID:
346 PmCmd = POWER_MGMT_REGISTER_Q35 (PCI_COMMAND_OFFSET);
347 Pmba = POWER_MGMT_REGISTER_Q35 (ICH9_PMBASE);
348 PmbaAndVal = ~(UINT32)ICH9_PMBASE_MASK;
349 PmbaOrVal = ICH9_PMBASE_VALUE;
350 AcpiCtlReg = POWER_MGMT_REGISTER_Q35 (ICH9_ACPI_CNTL);
351 AcpiEnBit = ICH9_ACPI_CNTL_ACPI_EN;
352 break;
353 case CLOUDHV_DEVICE_ID:
354 break;
355 default:
356 DEBUG ((
357 DEBUG_ERROR,
358 "%a: Unknown Host Bridge Device ID: 0x%04x\n",
359 __FUNCTION__,
360 PlatformInfoHob->HostBridgeDevId
361 ));
362 ASSERT (FALSE);
363 return;
364 }
365
366 if (PlatformInfoHob->HostBridgeDevId == CLOUDHV_DEVICE_ID) {
367 DEBUG ((DEBUG_INFO, "%a: Cloud Hypervisor is done.\n", __FUNCTION__));
368 return;
369 }
370
371 //
372 // If the appropriate IOspace enable bit is set, assume the ACPI PMBA has
373 // been configured and skip the setup here. This matches the logic in
374 // AcpiTimerLibConstructor ().
375 //
376 if ((PciRead8 (AcpiCtlReg) & AcpiEnBit) == 0) {
377 //
378 // The PEI phase should be exited with fully accessibe ACPI PM IO space:
379 // 1. set PMBA
380 //
381 PciAndThenOr32 (Pmba, PmbaAndVal, PmbaOrVal);
382
383 //
384 // 2. set PCICMD/IOSE
385 //
386 PciOr8 (PmCmd, EFI_PCI_COMMAND_IO_SPACE);
387
388 //
389 // 3. set ACPI PM IO enable bit (PMREGMISC:PMIOSE or ACPI_CNTL:ACPI_EN)
390 //
391 PciOr8 (AcpiCtlReg, AcpiEnBit);
392 }
393
394 if (PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) {
395 //
396 // Set Root Complex Register Block BAR
397 //
398 PciWrite32 (
399 POWER_MGMT_REGISTER_Q35 (ICH9_RCBA),
400 ICH9_ROOT_COMPLEX_BASE | ICH9_RCBA_EN
401 );
402
403 //
404 // Set PCI Express Register Range Base Address
405 //
406 PciExBarInitialization ();
407 }
408 }
409
410 /**
411 Check for various QEMU bugs concerning CPU numbers.
412
413 Compensate for those bugs if various conditions are satisfied, by updating a
414 suitable subset of the input-output parameters. The function may not return
415 (it may hang deliberately), even in RELEASE builds, if the QEMU bug is
416 impossible to cover up.
417
418 @param[in,out] BootCpuCount On input, the boot CPU count reported by QEMU via
419 fw_cfg (QemuFwCfgItemSmpCpuCount). The caller is
420 responsible for ensuring (BootCpuCount > 0); that
421 is, if QEMU does not provide the boot CPU count
422 via fw_cfg *at all*, then this function must not
423 be called.
424
425 @param[in,out] Present On input, the number of present-at-boot CPUs, as
426 reported by QEMU through the modern CPU hotplug
427 register block.
428
429 @param[in,out] Possible On input, the number of possible CPUs, as
430 reported by QEMU through the modern CPU hotplug
431 register block.
432 **/
433 STATIC
434 VOID
435 PlatformCpuCountBugCheck (
436 IN OUT UINT16 *BootCpuCount,
437 IN OUT UINT32 *Present,
438 IN OUT UINT32 *Possible
439 )
440 {
441 ASSERT (*BootCpuCount > 0);
442
443 //
444 // Sanity check: we need at least 1 present CPU (CPU#0 is always present).
445 //
446 // The legacy-to-modern switching of the CPU hotplug register block got broken
447 // (for TCG) in QEMU v5.1.0. Refer to "IO port write width clamping differs
448 // between TCG and KVM" at
449 // <http://mid.mail-archive.com/aaedee84-d3ed-a4f9-21e7-d221a28d1683@redhat.com>
450 // or at
451 // <https://lists.gnu.org/archive/html/qemu-devel/2023-01/msg00199.html>.
452 //
453 // QEMU received the fix in commit dab30fbef389 ("acpi: cpuhp: fix
454 // guest-visible maximum access size to the legacy reg block", 2023-01-08), to
455 // be included in QEMU v8.0.0.
456 //
457 // If we're affected by this QEMU bug, then we must not continue: it confuses
458 // the multiprocessing in UefiCpuPkg/Library/MpInitLib, and breaks CPU
459 // hot(un)plug with SMI in OvmfPkg/CpuHotplugSmm.
460 //
461 if (*Present == 0) {
462 UINTN Idx;
463 STATIC CONST CHAR8 *CONST Message[] = {
464 "Broken CPU hotplug register block found. Update QEMU to version 8+, or",
465 "to a stable release with commit dab30fbef389 backported. Refer to",
466 "<https://bugzilla.tianocore.org/show_bug.cgi?id=4250>.",
467 "Consequences of the QEMU bug may include, but are not limited to:",
468 "- all firmware logic, dependent on the CPU hotplug register block,",
469 " being confused, for example, multiprocessing-related logic;",
470 "- guest OS data loss, including filesystem corruption, due to crash or",
471 " hang during ACPI S3 resume;",
472 "- SMM privilege escalation, by a malicious guest OS or 3rd partty UEFI",
473 " agent, against the platform firmware.",
474 "These symptoms need not necessarily be limited to the QEMU user",
475 "attempting to hot(un)plug a CPU.",
476 "The firmware will now stop (hang) deliberately, in order to prevent the",
477 "above symptoms.",
478 "You can forcibly override the hang, *at your own risk*, with the",
479 "following *experimental* QEMU command line option:",
480 " -fw_cfg name=" CPUHP_BUGCHECK_OVERRIDE_FWCFG_FILE ",string=yes",
481 "Please only report such bugs that you can reproduce *without* the",
482 "override.",
483 };
484 RETURN_STATUS ParseStatus;
485 BOOLEAN Override;
486
487 DEBUG ((
488 DEBUG_ERROR,
489 "%a: Present=%u Possible=%u\n",
490 __FUNCTION__,
491 *Present,
492 *Possible
493 ));
494 for (Idx = 0; Idx < ARRAY_SIZE (Message); ++Idx) {
495 DEBUG ((DEBUG_ERROR, "%a: %a\n", __FUNCTION__, Message[Idx]));
496 }
497
498 ParseStatus = QemuFwCfgParseBool (
499 CPUHP_BUGCHECK_OVERRIDE_FWCFG_FILE,
500 &Override
501 );
502 if (!RETURN_ERROR (ParseStatus) && Override) {
503 DEBUG ((
504 DEBUG_WARN,
505 "%a: \"%a\" active. You've been warned.\n",
506 __FUNCTION__,
507 CPUHP_BUGCHECK_OVERRIDE_FWCFG_FILE
508 ));
509 //
510 // The bug is in QEMU v5.1.0+, where we're not affected by the QEMU v2.7
511 // reset bug, so BootCpuCount from fw_cfg is reliable. Assume a fully
512 // populated topology, like when the modern CPU hotplug interface is
513 // unavailable.
514 //
515 *Present = *BootCpuCount;
516 *Possible = *BootCpuCount;
517 return;
518 }
519
520 ASSERT (FALSE);
521 CpuDeadLoop ();
522 }
523
524 //
525 // Sanity check: fw_cfg and the modern CPU hotplug interface should expose the
526 // same boot CPU count.
527 //
528 if (*BootCpuCount != *Present) {
529 DEBUG ((
530 DEBUG_WARN,
531 "%a: QEMU v2.7 reset bug: BootCpuCount=%d Present=%u\n",
532 __FUNCTION__,
533 *BootCpuCount,
534 *Present
535 ));
536 //
537 // The handling of QemuFwCfgItemSmpCpuCount, across CPU hotplug plus
538 // platform reset (including S3), was corrected in QEMU commit e3cadac073a9
539 // ("pc: fix FW_CFG_NB_CPUS to account for -device added CPUs", 2016-11-16),
540 // part of release v2.8.0.
541 //
542 *BootCpuCount = (UINT16)*Present;
543 }
544 }
545
546 /**
547 Fetch the boot CPU count and the possible CPU count from QEMU, and expose
548 them to UefiCpuPkg modules.
549 **/
550 VOID
551 EFIAPI
552 PlatformMaxCpuCountInitialization (
553 IN OUT EFI_HOB_PLATFORM_INFO *PlatformInfoHob
554 )
555 {
556 UINT16 BootCpuCount = 0;
557 UINT32 MaxCpuCount;
558
559 //
560 // Try to fetch the boot CPU count.
561 //
562 if (QemuFwCfgIsAvailable ()) {
563 QemuFwCfgSelectItem (QemuFwCfgItemSmpCpuCount);
564 BootCpuCount = QemuFwCfgRead16 ();
565 }
566
567 if (BootCpuCount == 0) {
568 //
569 // QEMU doesn't report the boot CPU count. (BootCpuCount == 0) will let
570 // MpInitLib count APs up to (PcdCpuMaxLogicalProcessorNumber - 1), or
571 // until PcdCpuApInitTimeOutInMicroSeconds elapses (whichever is reached
572 // first).
573 //
574 DEBUG ((DEBUG_WARN, "%a: boot CPU count unavailable\n", __FUNCTION__));
575 MaxCpuCount = PlatformInfoHob->DefaultMaxCpuNumber;
576 } else {
577 //
578 // We will expose BootCpuCount to MpInitLib. MpInitLib will count APs up to
579 // (BootCpuCount - 1) precisely, regardless of timeout.
580 //
581 // Now try to fetch the possible CPU count.
582 //
583 UINTN CpuHpBase;
584 UINT32 CmdData2;
585
586 CpuHpBase = ((PlatformInfoHob->HostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) ?
587 ICH9_CPU_HOTPLUG_BASE : PIIX4_CPU_HOTPLUG_BASE);
588
589 //
590 // If only legacy mode is available in the CPU hotplug register block, or
591 // the register block is completely missing, then the writes below are
592 // no-ops.
593 //
594 // 1. Switch the hotplug register block to modern mode.
595 //
596 IoWrite32 (CpuHpBase + QEMU_CPUHP_W_CPU_SEL, 0);
597 //
598 // 2. Select a valid CPU for deterministic reading of
599 // QEMU_CPUHP_R_CMD_DATA2.
600 //
601 // CPU#0 is always valid; it is the always present and non-removable
602 // BSP.
603 //
604 IoWrite32 (CpuHpBase + QEMU_CPUHP_W_CPU_SEL, 0);
605 //
606 // 3. Send a command after which QEMU_CPUHP_R_CMD_DATA2 is specified to
607 // read as zero, and which does not invalidate the selector. (The
608 // selector may change, but it must not become invalid.)
609 //
610 // Send QEMU_CPUHP_CMD_GET_PENDING, as it will prove useful later.
611 //
612 IoWrite8 (CpuHpBase + QEMU_CPUHP_W_CMD, QEMU_CPUHP_CMD_GET_PENDING);
613 //
614 // 4. Read QEMU_CPUHP_R_CMD_DATA2.
615 //
616 // If the register block is entirely missing, then this is an unassigned
617 // IO read, returning all-bits-one.
618 //
619 // If only legacy mode is available, then bit#0 stands for CPU#0 in the
620 // "CPU present bitmap". CPU#0 is always present.
621 //
622 // Otherwise, QEMU_CPUHP_R_CMD_DATA2 is either still reserved (returning
623 // all-bits-zero), or it is specified to read as zero after the above
624 // steps. Both cases confirm modern mode.
625 //
626 CmdData2 = IoRead32 (CpuHpBase + QEMU_CPUHP_R_CMD_DATA2);
627 DEBUG ((DEBUG_VERBOSE, "%a: CmdData2=0x%x\n", __FUNCTION__, CmdData2));
628 if (CmdData2 != 0) {
629 //
630 // QEMU doesn't support the modern CPU hotplug interface. Assume that the
631 // possible CPU count equals the boot CPU count (precluding hotplug).
632 //
633 DEBUG ((
634 DEBUG_WARN,
635 "%a: modern CPU hotplug interface unavailable\n",
636 __FUNCTION__
637 ));
638 MaxCpuCount = BootCpuCount;
639 } else {
640 //
641 // Grab the possible CPU count from the modern CPU hotplug interface.
642 //
643 UINT32 Present, Possible, Selected;
644
645 Present = 0;
646 Possible = 0;
647
648 //
649 // We've sent QEMU_CPUHP_CMD_GET_PENDING last; this ensures
650 // QEMU_CPUHP_RW_CMD_DATA can now be read usefully. However,
651 // QEMU_CPUHP_CMD_GET_PENDING may have selected a CPU with actual pending
652 // hotplug events; therefore, select CPU#0 forcibly.
653 //
654 IoWrite32 (CpuHpBase + QEMU_CPUHP_W_CPU_SEL, Possible);
655
656 do {
657 UINT8 CpuStatus;
658
659 //
660 // Read the status of the currently selected CPU. This will help with
661 // various CPU count sanity checks.
662 //
663 CpuStatus = IoRead8 (CpuHpBase + QEMU_CPUHP_R_CPU_STAT);
664 if ((CpuStatus & QEMU_CPUHP_STAT_ENABLED) != 0) {
665 ++Present;
666 }
667
668 //
669 // Attempt to select the next CPU.
670 //
671 ++Possible;
672 IoWrite32 (CpuHpBase + QEMU_CPUHP_W_CPU_SEL, Possible);
673 //
674 // If the selection is successful, then the following read will return
675 // the selector (which we know is positive at this point). Otherwise,
676 // the read will return 0.
677 //
678 Selected = IoRead32 (CpuHpBase + QEMU_CPUHP_RW_CMD_DATA);
679 ASSERT (Selected == Possible || Selected == 0);
680 } while (Selected > 0);
681
682 PlatformCpuCountBugCheck (&BootCpuCount, &Present, &Possible);
683 ASSERT (Present > 0);
684 ASSERT (Present <= Possible);
685 ASSERT (BootCpuCount == Present);
686
687 MaxCpuCount = Possible;
688 }
689 }
690
691 DEBUG ((
692 DEBUG_INFO,
693 "%a: BootCpuCount=%d MaxCpuCount=%u\n",
694 __FUNCTION__,
695 BootCpuCount,
696 MaxCpuCount
697 ));
698 ASSERT (BootCpuCount <= MaxCpuCount);
699
700 PlatformInfoHob->PcdCpuMaxLogicalProcessorNumber = MaxCpuCount;
701 PlatformInfoHob->PcdCpuBootLogicalProcessorNumber = BootCpuCount;
702 }
703
704 /**
705 Check padding data all bit should be 1.
706
707 @param[in] Buffer - A pointer to buffer header
708 @param[in] BufferSize - Buffer size
709
710 @retval TRUE - The padding data is valid.
711 @retval TRUE - The padding data is invalid.
712
713 **/
714 BOOLEAN
715 CheckPaddingData (
716 IN UINT8 *Buffer,
717 IN UINT32 BufferSize
718 )
719 {
720 UINT32 index;
721
722 for (index = 0; index < BufferSize; index++) {
723 if (Buffer[index] != 0xFF) {
724 return FALSE;
725 }
726 }
727
728 return TRUE;
729 }
730
731 /**
732 Check the integrity of NvVarStore.
733
734 @param[in] NvVarStoreBase - A pointer to NvVarStore header
735 @param[in] NvVarStoreSize - NvVarStore size
736
737 @retval TRUE - The NvVarStore is valid.
738 @retval FALSE - The NvVarStore is invalid.
739
740 **/
741 BOOLEAN
742 EFIAPI
743 PlatformValidateNvVarStore (
744 IN UINT8 *NvVarStoreBase,
745 IN UINT32 NvVarStoreSize
746 )
747 {
748 UINT16 Checksum;
749 UINTN VariableBase;
750 UINT32 VariableOffset;
751 UINT32 VariableOffsetBeforeAlign;
752 EFI_FIRMWARE_VOLUME_HEADER *NvVarStoreFvHeader;
753 VARIABLE_STORE_HEADER *NvVarStoreHeader;
754 AUTHENTICATED_VARIABLE_HEADER *VariableHeader;
755
756 static EFI_GUID FvHdrGUID = EFI_SYSTEM_NV_DATA_FV_GUID;
757 static EFI_GUID VarStoreHdrGUID = EFI_AUTHENTICATED_VARIABLE_GUID;
758
759 VariableOffset = 0;
760
761 if (NvVarStoreBase == NULL) {
762 DEBUG ((DEBUG_ERROR, "NvVarStore pointer is NULL.\n"));
763 return FALSE;
764 }
765
766 //
767 // Verify the header zerovetor, filesystemguid,
768 // revision, signature, attributes, fvlength, checksum
769 // HeaderLength cannot be an odd number
770 //
771 NvVarStoreFvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)NvVarStoreBase;
772
773 if ((!IsZeroBuffer (NvVarStoreFvHeader->ZeroVector, 16)) ||
774 (!CompareGuid (&FvHdrGUID, &NvVarStoreFvHeader->FileSystemGuid)) ||
775 (NvVarStoreFvHeader->Signature != EFI_FVH_SIGNATURE) ||
776 (NvVarStoreFvHeader->Attributes != 0x4feff) ||
777 ((NvVarStoreFvHeader->HeaderLength & 0x01) != 0) ||
778 (NvVarStoreFvHeader->Revision != EFI_FVH_REVISION) ||
779 (NvVarStoreFvHeader->FvLength != NvVarStoreSize)
780 )
781 {
782 DEBUG ((DEBUG_ERROR, "NvVarStore FV headers were invalid.\n"));
783 return FALSE;
784 }
785
786 //
787 // Verify the header checksum
788 //
789 Checksum = CalculateSum16 ((VOID *)NvVarStoreFvHeader, NvVarStoreFvHeader->HeaderLength);
790
791 if (Checksum != 0) {
792 DEBUG ((DEBUG_ERROR, "NvVarStore FV checksum was invalid.\n"));
793 return FALSE;
794 }
795
796 //
797 // Verify the header signature, size, format, state
798 //
799 NvVarStoreHeader = (VARIABLE_STORE_HEADER *)(NvVarStoreBase + NvVarStoreFvHeader->HeaderLength);
800 if ((!CompareGuid (&VarStoreHdrGUID, &NvVarStoreHeader->Signature)) ||
801 (NvVarStoreHeader->Format != VARIABLE_STORE_FORMATTED) ||
802 (NvVarStoreHeader->State != VARIABLE_STORE_HEALTHY) ||
803 (NvVarStoreHeader->Size > (NvVarStoreFvHeader->FvLength - NvVarStoreFvHeader->HeaderLength)) ||
804 (NvVarStoreHeader->Size < sizeof (VARIABLE_STORE_HEADER))
805 )
806 {
807 DEBUG ((DEBUG_ERROR, "NvVarStore header signature/size/format/state were invalid.\n"));
808 return FALSE;
809 }
810
811 //
812 // Verify the header startId, state
813 // Verify data to the end
814 //
815 VariableBase = (UINTN)NvVarStoreBase + NvVarStoreFvHeader->HeaderLength + sizeof (VARIABLE_STORE_HEADER);
816 while (VariableOffset < (NvVarStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER))) {
817 VariableHeader = (AUTHENTICATED_VARIABLE_HEADER *)(VariableBase + VariableOffset);
818 if (VariableHeader->StartId != VARIABLE_DATA) {
819 if (!CheckPaddingData ((UINT8 *)VariableHeader, NvVarStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER) - VariableOffset)) {
820 DEBUG ((DEBUG_ERROR, "NvVarStore variable header StartId was invalid.\n"));
821 return FALSE;
822 }
823
824 VariableOffset = NvVarStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);
825 } else {
826 if (!((VariableHeader->State == VAR_HEADER_VALID_ONLY) ||
827 (VariableHeader->State == VAR_ADDED) ||
828 (VariableHeader->State == (VAR_ADDED & VAR_DELETED)) ||
829 (VariableHeader->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION)) ||
830 (VariableHeader->State == (VAR_ADDED & VAR_IN_DELETED_TRANSITION & VAR_DELETED))))
831 {
832 DEBUG ((DEBUG_ERROR, "NvVarStore Variable header State was invalid.\n"));
833 return FALSE;
834 }
835
836 VariableOffset += sizeof (AUTHENTICATED_VARIABLE_HEADER) + VariableHeader->NameSize + VariableHeader->DataSize;
837 // Verify VariableOffset should be less than or equal NvVarStoreHeader->Size - sizeof(VARIABLE_STORE_HEADER)
838 if (VariableOffset > (NvVarStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER))) {
839 DEBUG ((DEBUG_ERROR, "NvVarStore Variable header VariableOffset was invalid.\n"));
840 return FALSE;
841 }
842
843 VariableOffsetBeforeAlign = VariableOffset;
844 // 4 byte align
845 VariableOffset = (VariableOffset + 3) & (UINTN)(~3);
846
847 if (!CheckPaddingData ((UINT8 *)(VariableBase + VariableOffsetBeforeAlign), VariableOffset - VariableOffsetBeforeAlign)) {
848 DEBUG ((DEBUG_ERROR, "NvVarStore Variable header PaddingData was invalid.\n"));
849 return FALSE;
850 }
851 }
852 }
853
854 return TRUE;
855 }
856
857 /**
858 Allocate storage for NV variables early on so it will be
859 at a consistent address. Since VM memory is preserved
860 across reboots, this allows the NV variable storage to survive
861 a VM reboot.
862
863 *
864 * @retval VOID* The pointer to the storage for NV Variables
865 */
866 VOID *
867 EFIAPI
868 PlatformReserveEmuVariableNvStore (
869 VOID
870 )
871 {
872 VOID *VariableStore;
873 UINT32 VarStoreSize;
874
875 VarStoreSize = 2 * PcdGet32 (PcdFlashNvStorageFtwSpareSize);
876 //
877 // Allocate storage for NV variables early on so it will be
878 // at a consistent address. Since VM memory is preserved
879 // across reboots, this allows the NV variable storage to survive
880 // a VM reboot.
881 //
882 VariableStore =
883 AllocateRuntimePages (
884 EFI_SIZE_TO_PAGES (VarStoreSize)
885 );
886 DEBUG ((
887 DEBUG_INFO,
888 "Reserved variable store memory: 0x%p; size: %dkb\n",
889 VariableStore,
890 VarStoreSize / 1024
891 ));
892
893 return VariableStore;
894 }
895
896 /**
897 When OVMF is lauched with -bios parameter, UEFI variables will be
898 partially emulated, and non-volatile variables may lose their contents
899 after a reboot. This makes the secure boot feature not working.
900
901 This function is used to initialize the EmuVariableNvStore
902 with the conent in PcdOvmfFlashNvStorageVariableBase.
903
904 @param[in] EmuVariableNvStore - A pointer to EmuVariableNvStore
905
906 @retval EFI_SUCCESS - Successfully init the EmuVariableNvStore
907 @retval Others - As the error code indicates
908 */
909 EFI_STATUS
910 EFIAPI
911 PlatformInitEmuVariableNvStore (
912 IN VOID *EmuVariableNvStore
913 )
914 {
915 UINT8 *Base;
916 UINT32 Size;
917 UINT32 EmuVariableNvStoreSize;
918
919 EmuVariableNvStoreSize = 2 * PcdGet32 (PcdFlashNvStorageFtwSpareSize);
920 if ((EmuVariableNvStore == NULL) || (EmuVariableNvStoreSize == 0)) {
921 DEBUG ((DEBUG_ERROR, "Invalid EmuVariableNvStore parameter.\n"));
922 return EFI_INVALID_PARAMETER;
923 }
924
925 Base = (UINT8 *)(UINTN)PcdGet32 (PcdOvmfFlashNvStorageVariableBase);
926 Size = (UINT32)PcdGet32 (PcdFlashNvStorageVariableSize);
927 ASSERT (Size < EmuVariableNvStoreSize);
928
929 if (!PlatformValidateNvVarStore (Base, PcdGet32 (PcdCfvRawDataSize))) {
930 ASSERT (FALSE);
931 return EFI_INVALID_PARAMETER;
932 }
933
934 DEBUG ((DEBUG_INFO, "Init EmuVariableNvStore with the content in FlashNvStorage\n"));
935
936 CopyMem (EmuVariableNvStore, Base, Size);
937
938 return EFI_SUCCESS;
939 }