public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg
@ 2021-12-14 13:41 Min Xu
  2021-12-14 13:41 ` [PATCH 01/10] OvmfPkg: Introduce IntelTdxX64 for TDVF Config-B Min Xu
                   ` (10 more replies)
  0 siblings, 11 replies; 37+ messages in thread
From: Min Xu @ 2021-12-14 13:41 UTC (permalink / raw)
  To: devel
  Cc: Min Xu, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Gerd Hoffmann,
	Leif Lindholm, Ard Biesheuvel, Abner Chang, Daniel Schaefer

RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429

Intel's Trust Domain Extensions (Intel TDX) refers to an Intel technology
that extends Virtual Machines Extensions (VMX) and Multi-Key Total Memory
Encryption (MKTME) with a new kind of virutal machines guest called a
Trust Domain (TD). A TD is desinged to run in a CPU mode that protects the
confidentiality of TD memory contents and the TD's CPU state from other
software, including the hosting Virtual-Machine Monitor (VMM), unless
explicitly shared by the TD itself.

There are 2 configurations for TDVF to upstream. See below link for
the definitions of the 2 configurations.
https://edk2.groups.io/g/devel/message/76367

This patch-set is to enable the basic feature of Config-B in OvmfPkg.
 - Add a standalone IntelTdxX64.dsc to a TDX specific directory for a
   *full* feature TDVF. (Align with existing SEV)
 - IntelTdxX64.dsc includes TDX/normal OVMF basic boot capability. The
   final binary can run on TDX/normal OVMF.
 - PEI phase is skipped.

By design in Config-B there should be more advanced features, such as:
 - RTMR based measurement and measure boot.
 - Remove unnecessary drivers to reduce attack surface, such as
   network stack.

To make the code review more efficiency, Config-B is split into 2 waves:
 - Basic feature of Config-B
 - Advanced feature of Config-B

Patch 1:
Create standalone IntelTdxX64.dsc / IntelTdxX64.fdf

Patch 2/3:
This patch-set leverage the PrePiLib and MemoryAllocationLib in
EmbeddedPkg. Some new funtions are added to meet the Tdvf Config-B
requirement.

Patch 4/5/6:
They are helper libs used in Tdvf Config-B. TdxStartupLib is the most
important one which brings up Tdx guest from SEC to PEI.

Patch 7:
This patch updates TdxDxe driver for the Tdvf Config-B.

Patch 8:
Now it's time to update SecMain to call TdxStartup () to bring Tdx guest
from SEC to DXE.

Patch 9:
This patch update DxeAcpiTimerLib for the Tdvf Config-B.

Patch 10:
With the introduction of Config-B changes, some Tdx libs should be added in
OvmfPkg's dsc to prevent the broken of building.

Code at: https://github.com/mxu9/edk2/tree/tdvf_wave3

Please be noted:
This patch-set is based on the code base of tdvf_wave2.v4 which is at:
https://github.com/mxu9/edk2/tree/tdvf_wave2.v4

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Leif Lindholm <leif@nuviainc.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Abner Chang <abner.chang@hpe.com>
Cc: Daniel Schaefer <daniel.schaefer@hpe.com>
Signed-off-by: Min Xu <min.m.xu@intel.com>

Min Xu (10):
  OvmfPkg: Introduce IntelTdxX64 for TDVF Config-B
  EmbeddedPkg/PrePiLib: Update PrePiLib
  EmbeddedPkg/MemoryAllocationLib: Add null stub for AllocateCopyPool
  OvmfPkg: Add PrePiHobListPointerLibTdx
  OvmfPkg: Add SecPlatformLibQemuTdx
  OvmfPkg: Add TdxStartupLib
  OvmfPkg: Update TdxDxe to set TDX PCDs
  OvmfPkg: Update Sec to support Tdvf Config-B
  OvmfPkg: Update DxeAcpiTimerLib to read HostBridgeDevId in
    PlatformInfoHob
  OvmfPkg: Add Tdx libs to prevent building broken

 EmbeddedPkg/Include/Library/PrePiLib.h        |  21 +-
 EmbeddedPkg/Library/PrePiLib/FwVol.c          | 399 +++++++-
 .../MemoryAllocationLib.c                     |  28 +
 OvmfPkg/AmdSev/AmdSevX64.dsc                  |   3 +
 OvmfPkg/Bhyve/BhyveX64.dsc                    |   3 +
 OvmfPkg/Include/Library/TdxPlatformLib.h      |  38 +
 OvmfPkg/Include/Library/TdxStartupLib.h       |  35 +
 .../IntelTdxX64.dsc}                          |  23 +-
 OvmfPkg/IntelTdx/IntelTdxX64.fdf              | 548 +++++++++++
 .../PrePiHobListPointer.c                     |  45 +
 .../PrePiHobListPointerLibTdx.inf             |  25 +
 .../IntelTdx/SecPlatformLibQemuTdx/Platform.c | 286 ++++++
 .../SecPlatformLibQemuTdx/TdxPlatformLib.inf  |  49 +
 OvmfPkg/IntelTdx/TdxStartupLib/DxeLoad.c      | 344 +++++++
 OvmfPkg/IntelTdx/TdxStartupLib/Hob.c          | 150 +++
 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartup.c   | 143 +++
 .../TdxStartupLib/TdxStartupInternal.h        |  68 ++
 .../IntelTdx/TdxStartupLib/TdxStartupLib.inf  |  85 ++
 .../TdxStartupLib/TdxStartupLibNull.inf       |  40 +
 .../IntelTdx/TdxStartupLib/TdxStartupNull.c   |  19 +
 .../IntelTdx/TdxStartupLib/X64/PageTables.h   | 206 ++++
 .../TdxStartupLib/X64/VirtualMemory.c         | 915 ++++++++++++++++++
 .../Library/AcpiTimerLib/DxeAcpiTimerLib.c    |  23 +-
 .../Library/AcpiTimerLib/DxeAcpiTimerLib.inf  |   4 +
 OvmfPkg/Microvm/MicrovmX64.dsc                |   5 +
 OvmfPkg/OvmfPkg.dec                           |  11 +
 OvmfPkg/OvmfPkgX64.dsc                        |   1 +
 OvmfPkg/OvmfXen.dsc                           |   3 +
 OvmfPkg/Sec/IntelTdx.c                        |   7 +-
 OvmfPkg/Sec/SecMain.c                         |  17 +
 OvmfPkg/Sec/SecMain.inf                       |   2 +
 OvmfPkg/TdxDxe/TdxDxe.c                       |  12 +
 OvmfPkg/TdxDxe/TdxDxe.inf                     |   3 +
 33 files changed, 3550 insertions(+), 11 deletions(-)
 create mode 100644 OvmfPkg/Include/Library/TdxPlatformLib.h
 create mode 100644 OvmfPkg/Include/Library/TdxStartupLib.h
 copy OvmfPkg/{OvmfPkgX64.dsc => IntelTdx/IntelTdxX64.dsc} (96%)
 create mode 100644 OvmfPkg/IntelTdx/IntelTdxX64.fdf
 create mode 100644 OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointer.c
 create mode 100644 OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointerLibTdx.inf
 create mode 100644 OvmfPkg/IntelTdx/SecPlatformLibQemuTdx/Platform.c
 create mode 100644 OvmfPkg/IntelTdx/SecPlatformLibQemuTdx/TdxPlatformLib.inf
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/DxeLoad.c
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/Hob.c
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartup.c
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupInternal.h
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLib.inf
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLibNull.inf
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupNull.c
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/X64/PageTables.h
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/X64/VirtualMemory.c

-- 
2.29.2.windows.2


^ permalink raw reply	[flat|nested] 37+ messages in thread

* [PATCH 01/10] OvmfPkg: Introduce IntelTdxX64 for TDVF Config-B
  2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
@ 2021-12-14 13:41 ` Min Xu
  2021-12-15  9:32   ` Gerd Hoffmann
  2021-12-14 13:41 ` [PATCH 02/10] EmbeddedPkg/PrePiLib: Update PrePiLib Min Xu
                   ` (9 subsequent siblings)
  10 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2021-12-14 13:41 UTC (permalink / raw)
  To: devel
  Cc: Min Xu, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Gerd Hoffmann

RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429

Intel's Trust Domain Extensions (Intel TDX) refers to an Intel technology
that extends Virtual Machines Extensions (VMX) and Multi-Key Total Memory
Encryption (MKTME) with a new kind of virutal machines guest called a
Trust Domain (TD). A TD is desinged to run in a CPU mode that protects the
confidentiality of TD memory contents and the TD's CPU state from other
software, including the hosting Virtual-Machine Monitor (VMM), unless
explicitly shared by the TD itself.

There are 2 configurations for TDVF to upstream. See below link for
the definitions of the 2 configurations.
https://edk2.groups.io/g/devel/message/76367

This patch-set is to enable the basic feature of Config-B in OvmfPkg.
 - Add a standalone IntelTdxX64.dsc to a TDX specific directory for a
   *full* feature TDVF. (Align with existing SEV)
 - IntelTdx.dsc includes TDX/normal OVMF basic boot capability. The
   final binary can run on TDX/normal OVMF.
 - PEI phase is skipped.

By design in Config-B there should be more advanced features, such as:
 - RTMR based measurement and measure boot.
 - Remove unnecessary drivers to reduce attack surface, such as
   network stack.

To make the code review more efficiency, Config-B is split into 2 waves:
 - Basic feature of Config-B
 - Advanced feature of Config-B

This patch contains 2 files (IntelTdxX64.dsc/IntelTdxX64.fdf) which
enable the basic feature of Config-B. In the waves of Advanced feature
of Config-B, we will re-visit these 2 files.

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Min Xu <min.m.xu@intel.com>
---
 OvmfPkg/IntelTdx/IntelTdxX64.dsc | 1096 ++++++++++++++++++++++++++++++
 OvmfPkg/IntelTdx/IntelTdxX64.fdf |  548 +++++++++++++++
 2 files changed, 1644 insertions(+)
 create mode 100644 OvmfPkg/IntelTdx/IntelTdxX64.dsc
 create mode 100644 OvmfPkg/IntelTdx/IntelTdxX64.fdf

diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
new file mode 100644
index 000000000000..fe31d7b378c3
--- /dev/null
+++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
@@ -0,0 +1,1096 @@
+## @file
+#  EFI/Framework Open Virtual Machine Firmware (OVMF) platform
+#
+#  Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.<BR>
+#  (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
+#  Copyright (c) Microsoft Corporation.
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+################################################################################
+#
+# Defines Section - statements that will be processed to create a Makefile.
+#
+################################################################################
+[Defines]
+  PLATFORM_NAME                  = Ovmf
+  PLATFORM_GUID                  = 5a9e7754-d81b-49ea-85ad-69eaa7b1539b
+  PLATFORM_VERSION               = 0.1
+  DSC_SPECIFICATION              = 0x00010005
+  OUTPUT_DIRECTORY               = Build/IntelTdx
+  SUPPORTED_ARCHITECTURES        = X64
+  BUILD_TARGETS                  = NOOPT|DEBUG|RELEASE
+  SKUID_IDENTIFIER               = DEFAULT
+  FLASH_DEFINITION               = OvmfPkg/IntelTdx/IntelTdxX64.fdf
+
+  #
+  # Defines for default states.  These can be changed on the command line.
+  # -D FLAG=VALUE
+  #
+  DEFINE SECURE_BOOT_ENABLE      = FALSE
+  DEFINE SMM_REQUIRE             = FALSE
+  DEFINE SOURCE_DEBUG_ENABLE     = FALSE
+  DEFINE TPM_ENABLE              = FALSE
+  DEFINE TPM_CONFIG_ENABLE       = FALSE
+
+  #
+  # Network definition
+  #
+  DEFINE NETWORK_TLS_ENABLE             = FALSE
+  DEFINE NETWORK_IP6_ENABLE             = FALSE
+  DEFINE NETWORK_HTTP_BOOT_ENABLE       = FALSE
+  DEFINE NETWORK_ALLOW_HTTP_CONNECTIONS = TRUE
+  DEFINE NETWORK_ISCSI_ENABLE           = TRUE
+
+!include NetworkPkg/NetworkDefines.dsc.inc
+
+  #
+  # Device drivers
+  #
+  DEFINE PVSCSI_ENABLE           = TRUE
+  DEFINE MPT_SCSI_ENABLE         = TRUE
+  DEFINE LSI_SCSI_ENABLE         = FALSE
+
+  #
+  # Flash size selection. Setting FD_SIZE_IN_KB on the command line directly to
+  # one of the supported values, in place of any of the convenience macros, is
+  # permitted.
+  #
+!ifdef $(FD_SIZE_1MB)
+  DEFINE FD_SIZE_IN_KB           = 1024
+!else
+!ifdef $(FD_SIZE_2MB)
+  DEFINE FD_SIZE_IN_KB           = 2048
+!else
+!ifdef $(FD_SIZE_4MB)
+  DEFINE FD_SIZE_IN_KB           = 4096
+!else
+  DEFINE FD_SIZE_IN_KB           = 4096
+!endif
+!endif
+!endif
+
+[BuildOptions]
+  GCC:RELEASE_*_*_CC_FLAGS             = -DMDEPKG_NDEBUG
+  INTEL:RELEASE_*_*_CC_FLAGS           = /D MDEPKG_NDEBUG
+  MSFT:RELEASE_*_*_CC_FLAGS            = /D MDEPKG_NDEBUG
+!if $(TOOL_CHAIN_TAG) != "XCODE5" && $(TOOL_CHAIN_TAG) != "CLANGPDB"
+  GCC:*_*_*_CC_FLAGS                   = -mno-mmx -mno-sse
+!endif
+!if $(SOURCE_DEBUG_ENABLE) == TRUE
+  MSFT:*_*_X64_GENFW_FLAGS  = --keepexceptiontable
+  GCC:*_*_X64_GENFW_FLAGS   = --keepexceptiontable
+  INTEL:*_*_X64_GENFW_FLAGS = --keepexceptiontable
+!endif
+  RELEASE_*_*_GENFW_FLAGS = --zero
+
+  #
+  # Disable deprecated APIs.
+  #
+  MSFT:*_*_*_CC_FLAGS = /D DISABLE_NEW_DEPRECATED_INTERFACES
+  INTEL:*_*_*_CC_FLAGS = /D DISABLE_NEW_DEPRECATED_INTERFACES
+  GCC:*_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES
+
+  #
+  # Add INTEL_TDX_FULL_FEATURE
+  #
+  MSFT:*_*_*_CC_FLAGS = /D INTEL_TDX_FULL_FEATURE
+  INTEL:*_*_*_CC_FLAGS = /D INTEL_TDX_FULL_FEATURE
+  GCC:*_*_*_CC_FLAGS = -D INTEL_TDX_FULL_FEATURE
+
+!include NetworkPkg/NetworkBuildOptions.dsc.inc
+
+[BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER]
+  GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000
+  XCODE:*_*_*_DLINK_FLAGS = -seg1addr 0x1000 -segalign 0x1000
+  XCODE:*_*_*_MTOC_FLAGS = -align 0x1000
+  CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:4096
+
+# Force PE/COFF sections to be aligned at 4KB boundaries to support page level
+# protection of DXE_SMM_DRIVER/SMM_CORE modules
+[BuildOptions.common.EDKII.DXE_SMM_DRIVER, BuildOptions.common.EDKII.SMM_CORE]
+  GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000
+  XCODE:*_*_*_DLINK_FLAGS = -seg1addr 0x1000 -segalign 0x1000
+  XCODE:*_*_*_MTOC_FLAGS = -align 0x1000
+  CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:4096
+
+################################################################################
+#
+# SKU Identification section - list of all SKU IDs supported by this Platform.
+#
+################################################################################
+[SkuIds]
+  0|DEFAULT
+
+################################################################################
+#
+# Library Class section - list of all Library Classes needed by this Platform.
+#
+################################################################################
+
+!include MdePkg/MdeLibs.dsc.inc
+
+[LibraryClasses]
+  PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+  TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.inf
+  ResetSystemLib|OvmfPkg/Library/ResetSystemLib/BaseResetSystemLib.inf
+  PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
+  BaseMemoryLib|MdePkg/Library/BaseMemoryLibRepStr/BaseMemoryLibRepStr.inf
+  BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
+  SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf
+  TimeBaseLib|EmbeddedPkg/Library/TimeBaseLib/TimeBaseLib.inf
+  BmpSupportLib|MdeModulePkg/Library/BaseBmpSupportLib/BaseBmpSupportLib.inf
+  SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf
+  CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
+  PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf
+  PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf
+  CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf
+  UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf
+  UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf
+  HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf
+  SortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf
+  UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf
+  BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf
+  FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf
+  CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf
+  DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf
+  DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf
+  PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
+  PciCf8Lib|MdePkg/Library/BasePciCf8Lib/BasePciCf8Lib.inf
+  PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf
+  PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf
+  PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf
+  PciCapLib|OvmfPkg/Library/BasePciCapLib/BasePciCapLib.inf
+  PciCapPciSegmentLib|OvmfPkg/Library/BasePciCapPciSegmentLib/BasePciCapPciSegmentLib.inf
+  PciCapPciIoLib|OvmfPkg/Library/UefiPciCapPciIoLib/UefiPciCapPciIoLib.inf
+  IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
+  OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
+  SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
+  MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
+  MicrocodeLib|UefiCpuPkg/Library/MicrocodeLib/MicrocodeLib.inf
+  UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
+  UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
+  UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
+  UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
+  UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
+  DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf
+  NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf
+  FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf
+  UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf
+  SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf
+  UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf
+  SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf
+  QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
+  QemuFwCfgSimpleParserLib|OvmfPkg/Library/QemuFwCfgSimpleParserLib/QemuFwCfgSimpleParserLib.inf
+  VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
+  LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
+  MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptSevLib.inf
+  MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
+
+!if $(SMM_REQUIRE) == FALSE
+  LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
+!endif
+  CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
+  FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
+
+!if $(SOURCE_DEBUG_ENABLE) == TRUE
+  PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
+  DebugCommunicationLib|SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf
+!else
+  PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf
+  DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf
+!endif
+
+  LocalApicLib|UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf
+  DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf
+
+  IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf
+!if $(NETWORK_TLS_ENABLE) == TRUE
+  OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf
+!else
+  OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf
+!endif
+  RngLib|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf
+
+!if $(SECURE_BOOT_ENABLE) == TRUE
+  PlatformSecureLib|OvmfPkg/Library/PlatformSecureLib/PlatformSecureLib.inf
+  AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf
+  SecureBootVariableLib|SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.inf
+  SecureBootVariableProvisionLib|SecurityPkg/Library/SecureBootVariableProvisionLib/SecureBootVariableProvisionLib.inf
+!else
+  AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf
+!endif
+  VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf
+  VariablePolicyLib|MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.inf
+  VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf
+
+
+  #
+  # Network libraries
+  #
+!include NetworkPkg/NetworkLibs.dsc.inc
+
+!if $(NETWORK_TLS_ENABLE) == TRUE
+  TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf
+!endif
+
+  ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf
+  ShellCEntryLib|ShellPkg/Library/UefiShellCEntryLib/UefiShellCEntryLib.inf
+  S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf
+  SmbusLib|MdePkg/Library/BaseSmbusLibNull/BaseSmbusLibNull.inf
+  OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf
+
+!if $(TPM_ENABLE) == TRUE
+  Tpm12CommandLib|SecurityPkg/Library/Tpm12CommandLib/Tpm12CommandLib.inf
+  Tpm2CommandLib|SecurityPkg/Library/Tpm2CommandLib/Tpm2CommandLib.inf
+  Tcg2PhysicalPresenceLib|OvmfPkg/Library/Tcg2PhysicalPresenceLibQemu/DxeTcg2PhysicalPresenceLib.inf
+  Tcg2PpVendorLib|SecurityPkg/Library/Tcg2PpVendorLibNull/Tcg2PpVendorLibNull.inf
+  TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf
+!else
+  Tcg2PhysicalPresenceLib|OvmfPkg/Library/Tcg2PhysicalPresenceLibNull/DxeTcg2PhysicalPresenceLib.inf
+  TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf
+!endif
+
+[LibraryClasses.common]
+  BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
+  VmgExitLib|OvmfPkg/Library/VmgExitLib/VmgExitLib.inf
+  TdxLib|MdePkg/Library/TdxLib/TdxLib.inf
+  TdxMailboxLib|OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf
+
+[LibraryClasses.common.SEC]
+  TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.inf
+  QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
+!ifdef $(DEBUG_ON_SERIAL_PORT)
+  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+!else
+  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf
+!endif
+  ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf
+  ExtractGuidedSectionLib|MdePkg/Library/BaseExtractGuidedSectionLib/BaseExtractGuidedSectionLib.inf
+!if $(SOURCE_DEBUG_ENABLE) == TRUE
+  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf
+!endif
+  PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf
+  PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf
+  MemoryAllocationLib|EmbeddedPkg/Library/PrePiMemoryAllocationLib/PrePiMemoryAllocationLib.inf
+!if $(TOOL_CHAIN_TAG) == "XCODE5"
+  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/Xcode5SecPeiCpuExceptionHandlerLib.inf
+!else
+  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf
+!endif
+  VmgExitLib|OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf
+  MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf
+  PrePiHobListPointerLib|OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointerLibTdx.inf
+  HobLib|EmbeddedPkg/Library/PrePiHobLib/PrePiHobLib.inf
+  TdxPlatformLib|OvmfPkg/IntelTdx/SecPlatformLibQemuTdx/TdxPlatformLib.inf
+  PrePiLib|EmbeddedPkg/Library/PrePiLib/PrePiLib.inf
+  TdxStartupLib|OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLib.inf
+
+
+[LibraryClasses.common.PEI_CORE]
+  HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf
+  PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf
+  PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf
+  MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf
+  PeiCoreEntryPoint|MdePkg/Library/PeiCoreEntryPoint/PeiCoreEntryPoint.inf
+  ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf
+  OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
+  PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
+!ifdef $(DEBUG_ON_SERIAL_PORT)
+  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+!else
+  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
+!endif
+  PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf
+
+[LibraryClasses.common.PEIM]
+  HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf
+  PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf
+  PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf
+  MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf
+  PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf
+  ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf
+  OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
+  PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
+!ifdef $(DEBUG_ON_SERIAL_PORT)
+  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+!else
+  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
+!endif
+  PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf
+  ResourcePublicationLib|MdePkg/Library/PeiResourcePublicationLib/PeiResourcePublicationLib.inf
+  ExtractGuidedSectionLib|MdePkg/Library/PeiExtractGuidedSectionLib/PeiExtractGuidedSectionLib.inf
+!if $(SOURCE_DEBUG_ENABLE) == TRUE
+  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf
+!endif
+  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf
+  MpInitLib|UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf
+  QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/PeiQemuFwCfgS3LibFwCfg.inf
+  PcdLib|MdePkg/Library/PeiPcdLib/PeiPcdLib.inf
+  QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf
+
+!if $(TPM_ENABLE) == TRUE
+  BaseCryptLib|CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf
+  Tpm12DeviceLib|SecurityPkg/Library/Tpm12DeviceLibDTpm/Tpm12DeviceLibDTpm.inf
+  Tpm2DeviceLib|SecurityPkg/Library/Tpm2DeviceLibDTpm/Tpm2DeviceLibDTpm.inf
+!endif
+
+  MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLib.inf
+
+[LibraryClasses.common.DXE_CORE]
+  HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf
+  DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf
+  MemoryAllocationLib|MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationLib.inf
+  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
+!ifdef $(DEBUG_ON_SERIAL_PORT)
+  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+!else
+  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
+!endif
+  ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf
+!if $(SOURCE_DEBUG_ENABLE) == TRUE
+  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf
+!endif
+  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf
+  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+
+[LibraryClasses.common.DXE_RUNTIME_DRIVER]
+  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
+  ResetSystemLib|OvmfPkg/Library/ResetSystemLib/DxeResetSystemLib.inf
+  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
+  DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf
+  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+  ReportStatusCodeLib|MdeModulePkg/Library/RuntimeDxeReportStatusCodeLib/RuntimeDxeReportStatusCodeLib.inf
+!ifdef $(DEBUG_ON_SERIAL_PORT)
+  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+!else
+  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
+!endif
+  UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf
+  BaseCryptLib|CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf
+  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf
+  QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf
+  VariablePolicyLib|MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLibRuntimeDxe.inf
+!if $(SMM_REQUIRE) == TRUE
+  MmUnblockMemoryLib|MdePkg/Library/MmUnblockMemoryLib/MmUnblockMemoryLibNull.inf
+!endif
+
+[LibraryClasses.common.UEFI_DRIVER]
+  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
+  ResetSystemLib|OvmfPkg/Library/ResetSystemLib/DxeResetSystemLib.inf
+  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
+  DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf
+  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
+!ifdef $(DEBUG_ON_SERIAL_PORT)
+  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+!else
+  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
+!endif
+  UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf
+  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf
+
+[LibraryClasses.common.DXE_DRIVER]
+  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
+  ResetSystemLib|OvmfPkg/Library/ResetSystemLib/DxeResetSystemLib.inf
+  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
+  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
+  UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf
+!ifdef $(DEBUG_ON_SERIAL_PORT)
+  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+!else
+  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
+!endif
+  PlatformBootManagerLib|OvmfPkg/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf
+  PlatformBmPrintScLib|OvmfPkg/Library/PlatformBmPrintScLib/PlatformBmPrintScLib.inf
+  QemuBootOrderLib|OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.inf
+  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf
+!if $(SMM_REQUIRE) == TRUE
+  LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.inf
+!else
+  LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxDxeLib.inf
+!endif
+!if $(SOURCE_DEBUG_ENABLE) == TRUE
+  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf
+!endif
+  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf
+  MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf
+  QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf
+  QemuLoadImageLib|OvmfPkg/Library/X86QemuLoadImageLib/X86QemuLoadImageLib.inf
+!if $(TPM_ENABLE) == TRUE
+  Tpm12DeviceLib|SecurityPkg/Library/Tpm12DeviceLibTcg/Tpm12DeviceLibTcg.inf
+  Tpm2DeviceLib|SecurityPkg/Library/Tpm2DeviceLibTcg2/Tpm2DeviceLibTcg2.inf
+!endif
+
+[LibraryClasses.common.UEFI_APPLICATION]
+  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
+  ResetSystemLib|OvmfPkg/Library/ResetSystemLib/DxeResetSystemLib.inf
+  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
+  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
+  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
+!ifdef $(DEBUG_ON_SERIAL_PORT)
+  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+!else
+  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
+!endif
+  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf
+
+[LibraryClasses.common.DXE_SMM_DRIVER]
+  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
+  ResetSystemLib|OvmfPkg/Library/ResetSystemLib/DxeResetSystemLib.inf
+  MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf
+  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
+  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
+  SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf
+  MmServicesTableLib|MdePkg/Library/MmServicesTableLib/MmServicesTableLib.inf
+  SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf
+!ifdef $(DEBUG_ON_SERIAL_PORT)
+  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+!else
+  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
+!endif
+  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf
+!if $(SOURCE_DEBUG_ENABLE) == TRUE
+  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgentLib.inf
+!endif
+  BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf
+  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf
+
+[LibraryClasses.common.SMM_CORE]
+  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
+  ResetSystemLib|OvmfPkg/Library/ResetSystemLib/DxeResetSystemLib.inf
+  SmmCorePlatformHookLib|MdeModulePkg/Library/SmmCorePlatformHookLibNull/SmmCorePlatformHookLibNull.inf
+  MemoryAllocationLib|MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryAllocationLib.inf
+  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
+  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
+  SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf
+  SmmServicesTableLib|MdeModulePkg/Library/PiSmmCoreSmmServicesTableLib/PiSmmCoreSmmServicesTableLib.inf
+!ifdef $(DEBUG_ON_SERIAL_PORT)
+  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+!else
+  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
+!endif
+  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf
+
+################################################################################
+#
+# Pcd Section - list of all EDK II PCD Entries defined by this Platform.
+#
+################################################################################
+[PcdsFeatureFlag]
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHiiOsRuntimeSupport|FALSE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSupportUefiDecompress|FALSE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSwitchToLongMode|FALSE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdConOutGopSupport|TRUE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdConOutUgaSupport|FALSE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdInstallAcpiSdtProtocol|TRUE
+!ifdef $(CSM_ENABLE)
+  gUefiOvmfPkgTokenSpaceGuid.PcdCsmEnable|TRUE
+!endif
+!if $(SMM_REQUIRE) == TRUE
+  gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire|TRUE
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugSupport|TRUE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE
+!endif
+
+[PcdsFixedAtBuild]
+  gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1
+!if $(SMM_REQUIRE) == FALSE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange|FALSE
+!endif
+  gEfiMdePkgTokenSpaceGuid.PcdMaximumGuidedExtractHandler|0x10
+  gEfiMdePkgTokenSpaceGuid.PcdMaximumLinkedListLength|0
+!if ($(FD_SIZE_IN_KB) == 1024) || ($(FD_SIZE_IN_KB) == 2048)
+  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x2000
+  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x2800
+!if $(NETWORK_TLS_ENABLE) == FALSE
+  # match PcdFlashNvStorageVariableSize purely for convenience
+  gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize|0xe000
+!endif
+!endif
+!if $(FD_SIZE_IN_KB) == 4096
+  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x8400
+  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x8400
+!if $(NETWORK_TLS_ENABLE) == FALSE
+  # match PcdFlashNvStorageVariableSize purely for convenience
+  gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize|0x40000
+!endif
+!endif
+!if $(NETWORK_TLS_ENABLE) == TRUE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize|0x80000
+  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVolatileVariableSize|0x40000
+!endif
+
+  gEfiMdeModulePkgTokenSpaceGuid.PcdVpdBaseAddress|0x0
+  gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseSerial|FALSE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseMemory|TRUE
+
+  gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x07
+
+  # DEBUG_INIT      0x00000001  // Initialization
+  # DEBUG_WARN      0x00000002  // Warnings
+  # DEBUG_LOAD      0x00000004  // Load events
+  # DEBUG_FS        0x00000008  // EFI File system
+  # DEBUG_POOL      0x00000010  // Alloc & Free (pool)
+  # DEBUG_PAGE      0x00000020  // Alloc & Free (page)
+  # DEBUG_INFO      0x00000040  // Informational debug messages
+  # DEBUG_DISPATCH  0x00000080  // PEI/DXE/SMM Dispatchers
+  # DEBUG_VARIABLE  0x00000100  // Variable
+  # DEBUG_BM        0x00000400  // Boot Manager
+  # DEBUG_BLKIO     0x00001000  // BlkIo Driver
+  # DEBUG_NET       0x00004000  // SNP Driver
+  # DEBUG_UNDI      0x00010000  // UNDI Driver
+  # DEBUG_LOADFILE  0x00020000  // LoadFile
+  # DEBUG_EVENT     0x00080000  // Event messages
+  # DEBUG_GCD       0x00100000  // Global Coherency Database changes
+  # DEBUG_CACHE     0x00200000  // Memory range cachability changes
+  # DEBUG_VERBOSE   0x00400000  // Detailed debug messages that may
+  #                             // significantly impact boot performance
+  # DEBUG_ERROR     0x80000000  // Error
+  gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000004F
+
+!if $(SOURCE_DEBUG_ENABLE) == TRUE
+  gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x17
+!else
+  gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2F
+!endif
+
+  # This PCD is used to set the base address of the PCI express hierarchy. It
+  # is only consulted when OVMF runs on Q35. In that case it is programmed into
+  # the PCIEXBAR register.
+  #
+  # On Q35 machine types that QEMU intends to support in the long term, QEMU
+  # never lets the RAM below 4 GB exceed 2816 MB.
+  gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xB0000000
+
+!if $(SOURCE_DEBUG_ENABLE) == TRUE
+  gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugLoadImageMethod|0x2
+!endif
+
+  #
+  # The NumberOfPages values below are ad-hoc. They are updated sporadically at
+  # best (please refer to git-blame for past updates). The values capture a set
+  # of BIN hints that made sense at a particular time, for some (now likely
+  # unknown) workloads / boot paths.
+  #
+  gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIMemoryNVS|0x80
+  gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiACPIReclaimMemory|0x10
+  gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiReservedMemoryType|0x80
+  gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesCode|0x100
+  gEmbeddedTokenSpaceGuid.PcdMemoryTypeEfiRuntimeServicesData|0x100
+
+  #
+  # TDX need 1G PageTable support
+  gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable|TRUE
+
+  #
+  # Network Pcds
+  #
+!include NetworkPkg/NetworkPcds.dsc.inc
+
+  gEfiShellPkgTokenSpaceGuid.PcdShellFileOperationSize|0x20000
+
+!if $(SMM_REQUIRE) == TRUE
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackSize|0x4000
+!endif
+
+  # IRQs 5, 9, 10, 11 are level-triggered
+  gUefiOvmfPkgTokenSpaceGuid.Pcd8259LegacyModeEdgeLevel|0x0E20
+
+  # Point to the MdeModulePkg/Application/UiApp/UiApp.inf
+  gEfiMdeModulePkgTokenSpaceGuid.PcdBootManagerMenuFile|{ 0x21, 0xaa, 0x2c, 0x46, 0x14, 0x76, 0x03, 0x45, 0x83, 0x6e, 0x8a, 0xb6, 0xf4, 0x66, 0x23, 0x31 }
+
+################################################################################
+#
+# Pcd Dynamic Section - list of all EDK II PCD Entries defined by this Platform
+#
+################################################################################
+
+[PcdsDynamicDefault]
+  # only set when
+  #   ($(SMM_REQUIRE) == FALSE)
+  gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved|0
+
+!if $(SMM_REQUIRE) == FALSE
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64|0
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64|0
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64|0
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|0
+!endif
+  gEfiMdeModulePkgTokenSpaceGuid.PcdVideoHorizontalResolution|800
+  gEfiMdeModulePkgTokenSpaceGuid.PcdVideoVerticalResolution|600
+  gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiS3Enable|FALSE
+  gUefiOvmfPkgTokenSpaceGuid.PcdOvmfHostBridgePciDevId|0
+  gUefiOvmfPkgTokenSpaceGuid.PcdPciIoBase|0x0
+  gUefiOvmfPkgTokenSpaceGuid.PcdPciIoSize|0x0
+  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio32Base|0x0
+  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio32Size|0x0
+  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio64Base|0x0
+!ifdef $(CSM_ENABLE)
+  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio64Size|0x0
+!else
+  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio64Size|0x800000000
+!endif
+
+  gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut|0
+
+  # Set video resolution for text setup.
+  gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoHorizontalResolution|640
+  gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoVerticalResolution|480
+
+  gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosVersion|0x0208
+  gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0
+  gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE
+
+  # Noexec settings for DXE.
+  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|TRUE
+
+  # UefiCpuPkg PCDs related to initial AP bringup and general AP management.
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuBootLogicalProcessorNumber|0
+
+  # Set memory encryption mask
+  gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask|0x0
+
+  # Set SEV-ES defaults
+  gEfiMdeModulePkgTokenSpaceGuid.PcdGhcbBase|0
+  gEfiMdeModulePkgTokenSpaceGuid.PcdGhcbSize|0
+  gUefiCpuPkgTokenSpaceGuid.PcdSevEsIsEnabled|0
+
+!if $(SMM_REQUIRE) == TRUE
+  gUefiOvmfPkgTokenSpaceGuid.PcdQ35TsegMbytes|8
+  gUefiOvmfPkgTokenSpaceGuid.PcdQ35SmramAtDefaultSmbase|FALSE
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x01
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|100000
+!endif
+
+  gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x00
+
+!if $(TPM_ENABLE) == TRUE
+  gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
+!endif
+
+  # IPv4 and IPv6 PXE Boot support.
+  gEfiNetworkPkgTokenSpaceGuid.PcdIPv4PXESupport|0x01
+  gEfiNetworkPkgTokenSpaceGuid.PcdIPv6PXESupport|0x01
+
+  # Set ConfidentialComputing defaults
+  gEfiMdePkgTokenSpaceGuid.PcdConfidentialComputingGuestAttr|0
+
+!if $(CSM_ENABLE) == FALSE
+  gEfiMdePkgTokenSpaceGuid.PcdFSBClock|100000000
+!endif
+
+[PcdsDynamicHii]
+!if $(TPM_ENABLE) == TRUE && $(TPM_CONFIG_ENABLE) == TRUE
+  gEfiSecurityPkgTokenSpaceGuid.PcdTcgPhysicalPresenceInterfaceVer|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x0|"1.3"|NV,BS
+  gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableRev|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x8|3|NV,BS
+!endif
+
+################################################################################
+#
+# Components Section - list of all EDK II Modules needed by this Platform.
+#
+################################################################################
+[Components]
+  OvmfPkg/ResetVector/ResetVector.inf
+
+  #
+  # SEC Phase modules
+  #
+  OvmfPkg/Sec/SecMain.inf {
+    <LibraryClasses>
+      NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf
+  }
+
+  #
+  # PEI Phase modules
+  #
+  MdeModulePkg/Core/Pei/PeiMain.inf
+  MdeModulePkg/Universal/PCD/Pei/Pcd.inf  {
+    <LibraryClasses>
+      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+  }
+  MdeModulePkg/Universal/ReportStatusCodeRouter/Pei/ReportStatusCodeRouterPei.inf {
+    <LibraryClasses>
+      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+  }
+  MdeModulePkg/Universal/StatusCodeHandler/Pei/StatusCodeHandlerPei.inf {
+    <LibraryClasses>
+      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+  }
+  MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
+
+  OvmfPkg/PlatformPei/PlatformPei.inf
+  UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf {
+    <LibraryClasses>
+!if $(SMM_REQUIRE) == TRUE
+      LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib.inf
+!endif
+  }
+!if $(SMM_REQUIRE) == TRUE
+  MdeModulePkg/Universal/FaultTolerantWritePei/FaultTolerantWritePei.inf
+  MdeModulePkg/Universal/Variable/Pei/VariablePei.inf
+  OvmfPkg/SmmAccess/SmmAccessPei.inf
+!endif
+  UefiCpuPkg/CpuMpPei/CpuMpPei.inf
+
+!if $(TPM_ENABLE) == TRUE
+  OvmfPkg/Tcg/TpmMmioSevDecryptPei/TpmMmioSevDecryptPei.inf
+  OvmfPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf
+  SecurityPkg/Tcg/TcgPei/TcgPei.inf
+  SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.inf {
+    <LibraryClasses>
+      HashLib|SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterPei.inf
+      NULL|SecurityPkg/Library/HashInstanceLibSha1/HashInstanceLibSha1.inf
+      NULL|SecurityPkg/Library/HashInstanceLibSha256/HashInstanceLibSha256.inf
+      NULL|SecurityPkg/Library/HashInstanceLibSha384/HashInstanceLibSha384.inf
+      NULL|SecurityPkg/Library/HashInstanceLibSha512/HashInstanceLibSha512.inf
+      NULL|SecurityPkg/Library/HashInstanceLibSm3/HashInstanceLibSm3.inf
+  }
+  SecurityPkg/Tcg/Tcg2PlatformPei/Tcg2PlatformPei.inf {
+    <LibraryClasses>
+      TpmPlatformHierarchyLib|SecurityPkg/Library/PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.inf
+  }
+!endif
+
+  #
+  # DXE Phase modules
+  #
+  MdeModulePkg/Core/Dxe/DxeMain.inf {
+    <LibraryClasses>
+      NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf
+      DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
+  }
+
+  MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf
+  MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf
+  MdeModulePkg/Universal/PCD/Dxe/Pcd.inf  {
+   <LibraryClasses>
+      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+  }
+
+  MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
+
+  MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf {
+    <LibraryClasses>
+!if $(SECURE_BOOT_ENABLE) == TRUE
+      NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf
+!endif
+!if $(TPM_ENABLE) == TRUE
+      NULL|SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.inf
+      NULL|SecurityPkg/Library/DxeTpm2MeasureBootLib/DxeTpm2MeasureBootLib.inf
+!endif
+  }
+
+  MdeModulePkg/Universal/EbcDxe/EbcDxe.inf
+  UefiCpuPkg/CpuIo2Dxe/CpuIo2Dxe.inf
+  UefiCpuPkg/CpuDxe/CpuDxe.inf
+!ifdef $(CSM_ENABLE)
+  OvmfPkg/8259InterruptControllerDxe/8259.inf
+  OvmfPkg/8254TimerDxe/8254Timer.inf
+!else
+  UefiCpuPkg/LocalApicTimerDxe/LocalApicTimerDxe.inf
+!endif
+  OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.inf
+  OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf
+  MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf {
+    <LibraryClasses>
+      PciHostBridgeLib|OvmfPkg/Library/PciHostBridgeLib/PciHostBridgeLib.inf
+      PciHostBridgeUtilityLib|OvmfPkg/Library/PciHostBridgeUtilityLib/PciHostBridgeUtilityLib.inf
+      NULL|OvmfPkg/Library/PlatformHasIoMmuLib/PlatformHasIoMmuLib.inf
+  }
+  MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf {
+    <LibraryClasses>
+      PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+  }
+  MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
+  MdeModulePkg/Universal/Metronome/Metronome.inf
+  PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf
+  MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf
+  MdeModulePkg/Universal/BdsDxe/BdsDxe.inf {
+    <LibraryClasses>
+      XenPlatformLib|OvmfPkg/Library/XenPlatformLib/XenPlatformLib.inf
+!ifdef $(CSM_ENABLE)
+      NULL|OvmfPkg/Csm/CsmSupportLib/CsmSupportLib.inf
+      NULL|OvmfPkg/Csm/LegacyBootManagerLib/LegacyBootManagerLib.inf
+!endif
+  }
+  MdeModulePkg/Logo/LogoDxe.inf
+  MdeModulePkg/Application/UiApp/UiApp.inf {
+    <LibraryClasses>
+      NULL|MdeModulePkg/Library/DeviceManagerUiLib/DeviceManagerUiLib.inf
+      NULL|MdeModulePkg/Library/BootManagerUiLib/BootManagerUiLib.inf
+      NULL|MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerUiLib.inf
+!ifdef $(CSM_ENABLE)
+      NULL|OvmfPkg/Csm/LegacyBootManagerLib/LegacyBootManagerLib.inf
+      NULL|OvmfPkg/Csm/LegacyBootMaintUiLib/LegacyBootMaintUiLib.inf
+!endif
+  }
+  OvmfPkg/QemuKernelLoaderFsDxe/QemuKernelLoaderFsDxe.inf {
+    <LibraryClasses>
+      NULL|OvmfPkg/Library/BlobVerifierLibNull/BlobVerifierLibNull.inf
+  }
+  OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf
+  OvmfPkg/Virtio10Dxe/Virtio10.inf
+  OvmfPkg/VirtioBlkDxe/VirtioBlk.inf
+  OvmfPkg/VirtioScsiDxe/VirtioScsi.inf
+  OvmfPkg/VirtioRngDxe/VirtioRng.inf
+!if $(PVSCSI_ENABLE) == TRUE
+  OvmfPkg/PvScsiDxe/PvScsiDxe.inf
+!endif
+!if $(MPT_SCSI_ENABLE) == TRUE
+  OvmfPkg/MptScsiDxe/MptScsiDxe.inf
+!endif
+!if $(LSI_SCSI_ENABLE) == TRUE
+  OvmfPkg/LsiScsiDxe/LsiScsiDxe.inf
+!endif
+  MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
+  MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
+  MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
+  MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
+  MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
+  MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf {
+    <LibraryClasses>
+      PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+  }
+  MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf
+  MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf {
+    <LibraryClasses>
+      DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
+      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+  }
+
+  MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
+  MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
+  MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf
+  MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
+  FatPkg/EnhancedFatDxe/Fat.inf
+  MdeModulePkg/Universal/Disk/UdfDxe/UdfDxe.inf
+  OvmfPkg/VirtioFsDxe/VirtioFsDxe.inf
+  MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf
+  MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf
+  OvmfPkg/SataControllerDxe/SataControllerDxe.inf
+  MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf
+  MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf
+  MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf
+  MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
+  MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf
+  MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf
+  MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf
+
+!ifndef $(CSM_ENABLE)
+  OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
+!endif
+  OvmfPkg/QemuRamfbDxe/QemuRamfbDxe.inf
+  OvmfPkg/VirtioGpuDxe/VirtioGpu.inf
+
+  #
+  # ISA Support
+  #
+  OvmfPkg/SioBusDxe/SioBusDxe.inf
+  MdeModulePkg/Bus/Pci/PciSioSerialDxe/PciSioSerialDxe.inf
+  MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KeyboardDxe.inf
+
+  #
+  # SMBIOS Support
+  #
+  MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf {
+    <LibraryClasses>
+      NULL|OvmfPkg/Library/SmbiosVersionLib/DetectSmbiosVersionLib.inf
+  }
+  OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf
+
+  #
+  # ACPI Support
+  #
+  MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf
+  OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf
+  MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveStateDxe.inf
+  MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/BootScriptExecutorDxe.inf
+  MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf
+
+  #
+  # Network Support
+  #
+!include NetworkPkg/NetworkComponents.dsc.inc
+
+  NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf {
+    <LibraryClasses>
+      NULL|OvmfPkg/Library/PxeBcPcdProducerLib/PxeBcPcdProducerLib.inf
+  }
+
+!if $(NETWORK_TLS_ENABLE) == TRUE
+  NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf {
+    <LibraryClasses>
+      NULL|OvmfPkg/Library/TlsAuthConfigLib/TlsAuthConfigLib.inf
+  }
+!endif
+  OvmfPkg/VirtioNetDxe/VirtioNet.inf
+
+  #
+  # Usb Support
+  #
+  MdeModulePkg/Bus/Pci/UhciDxe/UhciDxe.inf
+  MdeModulePkg/Bus/Pci/EhciDxe/EhciDxe.inf
+  MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf
+  MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf
+  MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf
+  MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf
+
+!ifdef $(CSM_ENABLE)
+  OvmfPkg/Csm/BiosThunk/VideoDxe/VideoDxe.inf {
+    <LibraryClasses>
+      PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
+  }
+  OvmfPkg/Csm/LegacyBiosDxe/LegacyBiosDxe.inf
+  OvmfPkg/Csm/Csm16/Csm16.inf
+!endif
+
+!if $(TOOL_CHAIN_TAG) != "XCODE5"
+  ShellPkg/DynamicCommand/TftpDynamicCommand/TftpDynamicCommand.inf {
+    <PcdsFixedAtBuild>
+      gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE
+  }
+  ShellPkg/DynamicCommand/HttpDynamicCommand/HttpDynamicCommand.inf {
+    <PcdsFixedAtBuild>
+      gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE
+  }
+  OvmfPkg/LinuxInitrdDynamicShellCommand/LinuxInitrdDynamicShellCommand.inf {
+    <PcdsFixedAtBuild>
+      gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE
+  }
+!endif
+  ShellPkg/Application/Shell/Shell.inf {
+    <LibraryClasses>
+      ShellCommandLib|ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.inf
+      NULL|ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.inf
+      NULL|ShellPkg/Library/UefiShellLevel1CommandsLib/UefiShellLevel1CommandsLib.inf
+      NULL|ShellPkg/Library/UefiShellLevel3CommandsLib/UefiShellLevel3CommandsLib.inf
+      NULL|ShellPkg/Library/UefiShellDriver1CommandsLib/UefiShellDriver1CommandsLib.inf
+      NULL|ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf
+      NULL|ShellPkg/Library/UefiShellInstall1CommandsLib/UefiShellInstall1CommandsLib.inf
+      NULL|ShellPkg/Library/UefiShellNetwork1CommandsLib/UefiShellNetwork1CommandsLib.inf
+!if $(NETWORK_IP6_ENABLE) == TRUE
+      NULL|ShellPkg/Library/UefiShellNetwork2CommandsLib/UefiShellNetwork2CommandsLib.inf
+!endif
+      HandleParsingLib|ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.inf
+      PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
+      BcfgCommandLib|ShellPkg/Library/UefiShellBcfgCommandLib/UefiShellBcfgCommandLib.inf
+
+    <PcdsFixedAtBuild>
+      gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0xFF
+      gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE
+      gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|8000
+  }
+
+!if $(SECURE_BOOT_ENABLE) == TRUE
+  SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
+  OvmfPkg/EnrollDefaultKeys/EnrollDefaultKeys.inf
+!endif
+
+  OvmfPkg/PlatformDxe/Platform.inf
+  OvmfPkg/AmdSevDxe/AmdSevDxe.inf {
+    <LibraryClasses>
+    PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf
+  }
+  OvmfPkg/IoMmuDxe/IoMmuDxe.inf
+
+  OvmfPkg/TdxDxe/TdxDxe.inf
+
+!if $(SMM_REQUIRE) == TRUE
+  OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
+  OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.inf
+  OvmfPkg/CpuS3DataDxe/CpuS3DataDxe.inf
+
+  #
+  # SMM Initial Program Load (a DXE_RUNTIME_DRIVER)
+  #
+  MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf
+
+  #
+  # SMM_CORE
+  #
+  MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf
+
+  #
+  # Privileged drivers (DXE_SMM_DRIVER modules)
+  #
+  OvmfPkg/CpuHotplugSmm/CpuHotplugSmm.inf
+  UefiCpuPkg/CpuIo2Smm/CpuIo2Smm.inf
+  MdeModulePkg/Universal/LockBox/SmmLockBox/SmmLockBox.inf {
+    <LibraryClasses>
+      LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxSmmLib.inf
+  }
+  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf {
+    <LibraryClasses>
+      SmmCpuPlatformHookLib|OvmfPkg/Library/SmmCpuPlatformHookLibQemu/SmmCpuPlatformHookLibQemu.inf
+      SmmCpuFeaturesLib|OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
+  }
+
+  #
+  # Variable driver stack (SMM)
+  #
+  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf
+  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf
+  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf {
+    <LibraryClasses>
+      NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf
+      NULL|MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.inf
+  }
+  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
+
+!else
+
+  #
+  # Variable driver stack (non-SMM)
+  #
+  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
+  OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf {
+    <LibraryClasses>
+      PlatformFvbLib|OvmfPkg/Library/EmuVariableFvbLib/EmuVariableFvbLib.inf
+  }
+  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
+  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf {
+    <LibraryClasses>
+      NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf
+  }
+!endif
+
+  #
+  # TPM support
+  #
+!if $(TPM_ENABLE) == TRUE
+  SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf {
+    <LibraryClasses>
+      Tpm2DeviceLib|SecurityPkg/Library/Tpm2DeviceLibRouter/Tpm2DeviceLibRouterDxe.inf
+      NULL|SecurityPkg/Library/Tpm2DeviceLibDTpm/Tpm2InstanceLibDTpm.inf
+      HashLib|SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterDxe.inf
+      NULL|SecurityPkg/Library/HashInstanceLibSha1/HashInstanceLibSha1.inf
+      NULL|SecurityPkg/Library/HashInstanceLibSha256/HashInstanceLibSha256.inf
+      NULL|SecurityPkg/Library/HashInstanceLibSha384/HashInstanceLibSha384.inf
+      NULL|SecurityPkg/Library/HashInstanceLibSha512/HashInstanceLibSha512.inf
+      NULL|SecurityPkg/Library/HashInstanceLibSm3/HashInstanceLibSm3.inf
+  }
+!if $(TPM_CONFIG_ENABLE) == TRUE
+  SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigDxe.inf
+!endif
+  SecurityPkg/Tcg/TcgDxe/TcgDxe.inf {
+    <LibraryClasses>
+      Tpm12DeviceLib|SecurityPkg/Library/Tpm12DeviceLibDTpm/Tpm12DeviceLibDTpm.inf
+  }
+  SecurityPkg/Tcg/Tcg2PlatformDxe/Tcg2PlatformDxe.inf {
+    <LibraryClasses>
+      TpmPlatformHierarchyLib|SecurityPkg/Library/PeiDxeTpmPlatformHierarchyLib/PeiDxeTpmPlatformHierarchyLib.inf
+  }
+!endif
diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.fdf b/OvmfPkg/IntelTdx/IntelTdxX64.fdf
new file mode 100644
index 000000000000..96725703f3ea
--- /dev/null
+++ b/OvmfPkg/IntelTdx/IntelTdxX64.fdf
@@ -0,0 +1,548 @@
+## @file
+#  Open Virtual Machine Firmware: FDF
+#
+#  Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.<BR>
+#  (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+################################################################################
+
+[Defines]
+!include OvmfPkg/OvmfPkgDefines.fdf.inc
+
+#
+# Build the variable store and the firmware code as one unified flash device
+# image.
+#
+[FD.OVMF]
+BaseAddress   = $(FW_BASE_ADDRESS)
+Size          = $(FW_SIZE)
+ErasePolarity = 1
+BlockSize     = $(BLOCK_SIZE)
+NumBlocks     = $(FW_BLOCKS)
+
+!include OvmfPkg/VarStore.fdf.inc
+
+$(VARS_SIZE)|$(FVMAIN_SIZE)
+FV = FVMAIN_COMPACT
+
+$(SECFV_OFFSET)|$(SECFV_SIZE)
+FV = SECFV
+
+#
+# Build the variable store and the firmware code as separate flash device
+# images.
+#
+[FD.OVMF_VARS]
+BaseAddress   = $(FW_BASE_ADDRESS)
+Size          = $(VARS_SIZE)
+ErasePolarity = 1
+BlockSize     = $(BLOCK_SIZE)
+NumBlocks     = $(VARS_BLOCKS)
+
+!include OvmfPkg/VarStore.fdf.inc
+
+[FD.OVMF_CODE]
+BaseAddress   = $(CODE_BASE_ADDRESS)
+Size          = $(CODE_SIZE)
+ErasePolarity = 1
+BlockSize     = $(BLOCK_SIZE)
+NumBlocks     = $(CODE_BLOCKS)
+
+0x00000000|$(FVMAIN_SIZE)
+FV = FVMAIN_COMPACT
+
+$(FVMAIN_SIZE)|$(SECFV_SIZE)
+FV = SECFV
+
+################################################################################
+
+[FD.MEMFD]
+BaseAddress   = $(MEMFD_BASE_ADDRESS)
+Size          = 0xD00000
+ErasePolarity = 1
+BlockSize     = 0x10000
+NumBlocks     = 0xD0
+
+0x000000|0x006000
+gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesSize
+
+0x006000|0x001000
+gUefiOvmfPkgTokenSpaceGuid.PcdOvmfLockBoxStorageBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfLockBoxStorageSize
+
+0x007000|0x001000
+gEfiMdePkgTokenSpaceGuid.PcdGuidedExtractHandlerTableAddress|gUefiOvmfPkgTokenSpaceGuid.PcdGuidedExtractHandlerTableSize
+
+0x008000|0x001000
+gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbPageTableBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbPageTableSize
+
+0x009000|0x002000
+gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbSize
+
+0x00B000|0x001000
+gUefiOvmfPkgTokenSpaceGuid.PcdOvmfWorkAreaBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfWorkAreaSize
+
+0x00C000|0x001000
+gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBackupBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBackupSize
+
+0x00D000|0x001000
+gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSnpSecretsBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSnpSecretsSize
+
+0x00E000|0x001000
+gUefiOvmfPkgTokenSpaceGuid.PcdOvmfCpuidBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfCpuidSize
+
+0x010000|0x010000
+gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamSize
+
+0x020000|0x0E0000
+gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvSize
+FV = PEIFV
+
+0x100000|0xC00000
+gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize
+FV = DXEFV
+
+##########################################################################################
+# Set the SEV-ES specific work area PCDs
+#
+SET gUefiCpuPkgTokenSpaceGuid.PcdSevEsWorkAreaBase = $(MEMFD_BASE_ADDRESS) +  gUefiOvmfPkgTokenSpaceGuid.PcdOvmfWorkAreaBase + gUefiOvmfPkgTokenSpaceGuid.PcdOvmfConfidentialComputingWorkAreaHeader
+SET gUefiCpuPkgTokenSpaceGuid.PcdSevEsWorkAreaSize = gUefiOvmfPkgTokenSpaceGuid.PcdOvmfWorkAreaSize - gUefiOvmfPkgTokenSpaceGuid.PcdOvmfConfidentialComputingWorkAreaHeader
+##########################################################################################
+
+################################################################################
+
+[FV.SECFV]
+FvNameGuid         = 763BED0D-DE9F-48F5-81F1-3E90E1B1A015
+BlockSize          = 0x1000
+FvAlignment        = 16
+ERASE_POLARITY     = 1
+MEMORY_MAPPED      = TRUE
+STICKY_WRITE       = TRUE
+LOCK_CAP           = TRUE
+LOCK_STATUS        = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP  = TRUE
+WRITE_STATUS       = TRUE
+WRITE_LOCK_CAP     = TRUE
+WRITE_LOCK_STATUS  = TRUE
+READ_DISABLED_CAP  = TRUE
+READ_ENABLED_CAP   = TRUE
+READ_STATUS        = TRUE
+READ_LOCK_CAP      = TRUE
+READ_LOCK_STATUS   = TRUE
+
+#
+# SEC Phase modules
+#
+# The code in this FV handles the initial firmware startup, and
+# decompresses the PEI and DXE FVs which handles the rest of the boot sequence.
+#
+INF  OvmfPkg/Sec/SecMain.inf
+
+INF  RuleOverride=RESET_VECTOR OvmfPkg/ResetVector/ResetVector.inf
+
+################################################################################
+[FV.PEIFV]
+FvNameGuid         = 6938079B-B503-4E3D-9D24-B28337A25806
+BlockSize          = 0x10000
+FvAlignment        = 16
+ERASE_POLARITY     = 1
+MEMORY_MAPPED      = TRUE
+STICKY_WRITE       = TRUE
+LOCK_CAP           = TRUE
+LOCK_STATUS        = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP  = TRUE
+WRITE_STATUS       = TRUE
+WRITE_LOCK_CAP     = TRUE
+WRITE_LOCK_STATUS  = TRUE
+READ_DISABLED_CAP  = TRUE
+READ_ENABLED_CAP   = TRUE
+READ_STATUS        = TRUE
+READ_LOCK_CAP      = TRUE
+READ_LOCK_STATUS   = TRUE
+
+APRIORI PEI {
+  INF  MdeModulePkg/Universal/PCD/Pei/Pcd.inf
+}
+
+#
+#  PEI Phase modules
+#
+INF  MdeModulePkg/Core/Pei/PeiMain.inf
+INF  MdeModulePkg/Universal/PCD/Pei/Pcd.inf
+INF  MdeModulePkg/Universal/ReportStatusCodeRouter/Pei/ReportStatusCodeRouterPei.inf
+INF  MdeModulePkg/Universal/StatusCodeHandler/Pei/StatusCodeHandlerPei.inf
+INF  OvmfPkg/PlatformPei/PlatformPei.inf
+INF  MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
+INF  UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf
+!if $(SMM_REQUIRE) == TRUE
+INF  MdeModulePkg/Universal/FaultTolerantWritePei/FaultTolerantWritePei.inf
+INF  MdeModulePkg/Universal/Variable/Pei/VariablePei.inf
+INF  OvmfPkg/SmmAccess/SmmAccessPei.inf
+!endif
+INF  UefiCpuPkg/CpuMpPei/CpuMpPei.inf
+
+!if $(TPM_ENABLE) == TRUE
+INF  OvmfPkg/Tcg/TpmMmioSevDecryptPei/TpmMmioSevDecryptPei.inf
+INF  OvmfPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf
+INF  SecurityPkg/Tcg/TcgPei/TcgPei.inf
+INF  SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.inf
+INF  SecurityPkg/Tcg/Tcg2PlatformPei/Tcg2PlatformPei.inf
+!endif
+
+################################################################################
+
+[FV.DXEFV]
+FvForceRebase      = FALSE
+FvNameGuid         = 7CB8BDC9-F8EB-4F34-AAEA-3EE4AF6516A1
+BlockSize          = 0x10000
+FvAlignment        = 16
+ERASE_POLARITY     = 1
+MEMORY_MAPPED      = TRUE
+STICKY_WRITE       = TRUE
+LOCK_CAP           = TRUE
+LOCK_STATUS        = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP  = TRUE
+WRITE_STATUS       = TRUE
+WRITE_LOCK_CAP     = TRUE
+WRITE_LOCK_STATUS  = TRUE
+READ_DISABLED_CAP  = TRUE
+READ_ENABLED_CAP   = TRUE
+READ_STATUS        = TRUE
+READ_LOCK_CAP      = TRUE
+READ_LOCK_STATUS   = TRUE
+
+APRIORI DXE {
+  INF  MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
+  INF  MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
+  INF  OvmfPkg/TdxDxe/TdxDxe.inf
+  INF  OvmfPkg/AmdSevDxe/AmdSevDxe.inf
+!if $(SMM_REQUIRE) == FALSE
+  INF  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
+!endif
+}
+
+#
+# DXE Phase modules
+#
+INF  MdeModulePkg/Core/Dxe/DxeMain.inf
+
+INF  MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf
+INF  MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf
+INF  MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
+
+INF  MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
+INF  MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
+INF  MdeModulePkg/Universal/EbcDxe/EbcDxe.inf
+INF  UefiCpuPkg/CpuIo2Dxe/CpuIo2Dxe.inf
+INF  UefiCpuPkg/CpuDxe/CpuDxe.inf
+!ifdef $(CSM_ENABLE)
+  INF  OvmfPkg/8259InterruptControllerDxe/8259.inf
+  INF  OvmfPkg/8254TimerDxe/8254Timer.inf
+!else
+  INF  UefiCpuPkg/LocalApicTimerDxe/LocalApicTimerDxe.inf
+!endif
+INF  OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.inf
+INF  OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf
+INF  MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf
+INF  MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf
+INF  MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
+INF  MdeModulePkg/Universal/Metronome/Metronome.inf
+INF  PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf
+
+INF  OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf
+INF  OvmfPkg/Virtio10Dxe/Virtio10.inf
+INF  OvmfPkg/VirtioBlkDxe/VirtioBlk.inf
+INF  OvmfPkg/VirtioScsiDxe/VirtioScsi.inf
+INF  OvmfPkg/VirtioRngDxe/VirtioRng.inf
+!if $(PVSCSI_ENABLE) == TRUE
+INF  OvmfPkg/PvScsiDxe/PvScsiDxe.inf
+!endif
+!if $(MPT_SCSI_ENABLE) == TRUE
+INF  OvmfPkg/MptScsiDxe/MptScsiDxe.inf
+!endif
+!if $(LSI_SCSI_ENABLE) == TRUE
+INF  OvmfPkg/LsiScsiDxe/LsiScsiDxe.inf
+!endif
+
+!if $(SECURE_BOOT_ENABLE) == TRUE
+  INF  SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
+!endif
+
+INF  MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
+INF  MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
+INF  MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
+INF  MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
+INF  MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
+INF  MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
+INF  MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf
+INF  MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf
+INF  MdeModulePkg/Universal/BdsDxe/BdsDxe.inf
+INF  MdeModulePkg/Application/UiApp/UiApp.inf
+INF  OvmfPkg/QemuKernelLoaderFsDxe/QemuKernelLoaderFsDxe.inf
+INF  MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
+INF  MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
+INF  MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
+INF  MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf
+INF  MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
+INF  MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf
+INF  MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf
+INF  OvmfPkg/SataControllerDxe/SataControllerDxe.inf
+INF  MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf
+INF  MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf
+INF  MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf
+INF  MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
+INF  MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf
+INF  MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf
+INF  MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf
+
+INF  OvmfPkg/SioBusDxe/SioBusDxe.inf
+!if $(SOURCE_DEBUG_ENABLE) == FALSE
+INF  MdeModulePkg/Bus/Pci/PciSioSerialDxe/PciSioSerialDxe.inf
+!endif
+INF  MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KeyboardDxe.inf
+
+INF  MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf
+INF  OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf
+
+INF  MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf
+INF  OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf
+INF  MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveStateDxe.inf
+INF  MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/BootScriptExecutorDxe.inf
+INF  MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf
+
+INF  FatPkg/EnhancedFatDxe/Fat.inf
+INF  MdeModulePkg/Universal/Disk/UdfDxe/UdfDxe.inf
+INF  OvmfPkg/VirtioFsDxe/VirtioFsDxe.inf
+
+!if $(TOOL_CHAIN_TAG) != "XCODE5"
+INF  ShellPkg/DynamicCommand/TftpDynamicCommand/TftpDynamicCommand.inf
+INF  ShellPkg/DynamicCommand/HttpDynamicCommand/HttpDynamicCommand.inf
+INF  OvmfPkg/LinuxInitrdDynamicShellCommand/LinuxInitrdDynamicShellCommand.inf
+!endif
+INF  ShellPkg/Application/Shell/Shell.inf
+
+INF MdeModulePkg/Logo/LogoDxe.inf
+
+INF OvmfPkg/TdxDxe/TdxDxe.inf
+
+#
+# Network modules
+#
+!if $(E1000_ENABLE)
+  FILE DRIVER = 5D695E11-9B3F-4b83-B25F-4A8D5D69BE07 {
+    SECTION PE32 = Intel3.5/EFIX64/E3522X2.EFI
+  }
+!endif
+!include NetworkPkg/Network.fdf.inc
+  INF  OvmfPkg/VirtioNetDxe/VirtioNet.inf
+
+#
+# Usb Support
+#
+INF  MdeModulePkg/Bus/Pci/UhciDxe/UhciDxe.inf
+INF  MdeModulePkg/Bus/Pci/EhciDxe/EhciDxe.inf
+INF  MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf
+INF  MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf
+INF  MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf
+INF  MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf
+
+!ifdef $(CSM_ENABLE)
+INF  OvmfPkg/Csm/BiosThunk/VideoDxe/VideoDxe.inf
+INF  OvmfPkg/Csm/LegacyBiosDxe/LegacyBiosDxe.inf
+INF  RuleOverride=CSM OvmfPkg/Csm/Csm16/Csm16.inf
+!else
+INF  OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
+!endif
+
+INF  OvmfPkg/QemuRamfbDxe/QemuRamfbDxe.inf
+INF  OvmfPkg/VirtioGpuDxe/VirtioGpu.inf
+INF  OvmfPkg/PlatformDxe/Platform.inf
+INF  OvmfPkg/AmdSevDxe/AmdSevDxe.inf
+INF  OvmfPkg/IoMmuDxe/IoMmuDxe.inf
+
+!if $(SMM_REQUIRE) == TRUE
+INF  OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
+INF  OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.inf
+INF  OvmfPkg/CpuS3DataDxe/CpuS3DataDxe.inf
+INF  MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf
+INF  MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf
+INF  OvmfPkg/CpuHotplugSmm/CpuHotplugSmm.inf
+INF  UefiCpuPkg/CpuIo2Smm/CpuIo2Smm.inf
+INF  MdeModulePkg/Universal/LockBox/SmmLockBox/SmmLockBox.inf
+INF  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf
+
+#
+# Variable driver stack (SMM)
+#
+INF  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf
+INF  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf
+INF  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
+INF  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
+
+!else
+
+#
+# Variable driver stack (non-SMM)
+#
+INF  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
+INF  OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf
+INF  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
+INF  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
+!endif
+
+#
+# TPM support
+#
+!if $(TPM_ENABLE) == TRUE
+INF  SecurityPkg/Tcg/TcgDxe/TcgDxe.inf
+INF  SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf
+INF  SecurityPkg/Tcg/Tcg2PlatformDxe/Tcg2PlatformDxe.inf
+!if $(TPM_CONFIG_ENABLE) == TRUE
+INF  SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigDxe.inf
+!endif
+!endif
+
+################################################################################
+
+[FV.FVMAIN_COMPACT]
+FvNameGuid         = 48DB5E17-707C-472D-91CD-1613E7EF51B0
+FvAlignment        = 16
+ERASE_POLARITY     = 1
+MEMORY_MAPPED      = TRUE
+STICKY_WRITE       = TRUE
+LOCK_CAP           = TRUE
+LOCK_STATUS        = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP  = TRUE
+WRITE_STATUS       = TRUE
+WRITE_LOCK_CAP     = TRUE
+WRITE_LOCK_STATUS  = TRUE
+READ_DISABLED_CAP  = TRUE
+READ_ENABLED_CAP   = TRUE
+READ_STATUS        = TRUE
+READ_LOCK_CAP      = TRUE
+READ_LOCK_STATUS   = TRUE
+
+FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
+   SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
+     #
+     # These firmware volumes will have files placed in them uncompressed,
+     # and then both firmware volumes will be compressed in a single
+     # compression operation in order to achieve better overall compression.
+     #
+     SECTION FV_IMAGE = PEIFV
+     SECTION FV_IMAGE = DXEFV
+   }
+ }
+
+!include OvmfPkg/FvmainCompactScratchEnd.fdf.inc
+
+################################################################################
+
+[Rule.Common.SEC]
+  FILE SEC = $(NAMED_GUID) {
+    PE32     PE32           $(INF_OUTPUT)/$(MODULE_NAME).efi
+    UI       STRING ="$(MODULE_NAME)" Optional
+    VERSION  STRING ="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+  }
+
+[Rule.Common.PEI_CORE]
+  FILE PEI_CORE = $(NAMED_GUID) {
+    PE32     PE32   Align=Auto    $(INF_OUTPUT)/$(MODULE_NAME).efi
+    UI       STRING ="$(MODULE_NAME)" Optional
+    VERSION  STRING ="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+  }
+
+[Rule.Common.PEIM]
+  FILE PEIM = $(NAMED_GUID) {
+     PEI_DEPEX PEI_DEPEX Optional        $(INF_OUTPUT)/$(MODULE_NAME).depex
+     PE32      PE32   Align=Auto         $(INF_OUTPUT)/$(MODULE_NAME).efi
+     UI       STRING="$(MODULE_NAME)" Optional
+     VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+  }
+
+[Rule.Common.DXE_CORE]
+  FILE DXE_CORE = $(NAMED_GUID) {
+    PE32     PE32           $(INF_OUTPUT)/$(MODULE_NAME).efi
+    UI       STRING="$(MODULE_NAME)" Optional
+    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+  }
+
+[Rule.Common.DXE_DRIVER]
+  FILE DRIVER = $(NAMED_GUID) {
+    DXE_DEPEX    DXE_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex
+    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi
+    UI       STRING="$(MODULE_NAME)" Optional
+    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+    RAW ACPI  Optional               |.acpi
+    RAW ASL   Optional               |.aml
+  }
+
+[Rule.Common.DXE_RUNTIME_DRIVER]
+  FILE DRIVER = $(NAMED_GUID) {
+    DXE_DEPEX    DXE_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex
+    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi
+    UI       STRING="$(MODULE_NAME)" Optional
+    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+  }
+
+[Rule.Common.UEFI_DRIVER]
+  FILE DRIVER = $(NAMED_GUID) {
+    DXE_DEPEX    DXE_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex
+    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi
+    UI       STRING="$(MODULE_NAME)" Optional
+    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+  }
+
+[Rule.Common.UEFI_DRIVER.BINARY]
+  FILE DRIVER = $(NAMED_GUID) {
+    DXE_DEPEX DXE_DEPEX Optional      |.depex
+    PE32      PE32                    |.efi
+    UI        STRING="$(MODULE_NAME)" Optional
+    VERSION   STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+  }
+
+[Rule.Common.UEFI_APPLICATION]
+  FILE APPLICATION = $(NAMED_GUID) {
+    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi
+    UI       STRING="$(MODULE_NAME)" Optional
+    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+  }
+
+[Rule.Common.UEFI_APPLICATION.BINARY]
+  FILE APPLICATION = $(NAMED_GUID) {
+    PE32      PE32                    |.efi
+    UI        STRING="$(MODULE_NAME)" Optional
+    VERSION   STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+  }
+
+[Rule.Common.USER_DEFINED.CSM]
+  FILE FREEFORM = $(NAMED_GUID) {
+    RAW BIN                |.bin
+  }
+
+[Rule.Common.SEC.RESET_VECTOR]
+  FILE RAW = $(NAMED_GUID) {
+    RAW BIN   Align = 16   |.bin
+  }
+
+[Rule.Common.SMM_CORE]
+  FILE SMM_CORE = $(NAMED_GUID) {
+    PE32     PE32           $(INF_OUTPUT)/$(MODULE_NAME).efi
+    UI       STRING="$(MODULE_NAME)" Optional
+    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+  }
+
+[Rule.Common.DXE_SMM_DRIVER]
+  FILE SMM = $(NAMED_GUID) {
+    SMM_DEPEX    SMM_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex
+    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi
+    UI       STRING="$(MODULE_NAME)" Optional
+    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+  }
-- 
2.29.2.windows.2


^ permalink raw reply related	[flat|nested] 37+ messages in thread

* [PATCH 02/10] EmbeddedPkg/PrePiLib: Update PrePiLib
  2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
  2021-12-14 13:41 ` [PATCH 01/10] OvmfPkg: Introduce IntelTdxX64 for TDVF Config-B Min Xu
@ 2021-12-14 13:41 ` Min Xu
  2021-12-14 14:00   ` [edk2-devel] " Ard Biesheuvel
  2021-12-14 13:41 ` [PATCH 03/10] EmbeddedPkg/MemoryAllocationLib: Add null stub for AllocateCopyPool Min Xu
                   ` (8 subsequent siblings)
  10 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2021-12-14 13:41 UTC (permalink / raw)
  To: devel
  Cc: Min Xu, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Gerd Hoffmann,
	Leif Lindholm, Ard Biesheuvel, Abner Chang, Daniel Schaefer

RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429

There are below new functions added in EmbeddedPkg/PrePiLib.
1. FfsAnyFvFindFileByName
   This function is to find the file by name in the FvImage.
2. FfsDecompressSection
   This function is to decompress a compressed section.
3. FfsProcessFvFileEx
   This function is to decompress a compressed section and create
   FvHob/Fv2Hob for all the FvImages.

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Leif Lindholm <leif@nuviainc.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Abner Chang <abner.chang@hpe.com>
Cc: Daniel Schaefer <daniel.schaefer@hpe.com>
Signed-off-by: Min Xu <min.m.xu@intel.com>
---
 EmbeddedPkg/Include/Library/PrePiLib.h |  21 +-
 EmbeddedPkg/Library/PrePiLib/FwVol.c   | 399 ++++++++++++++++++++++++-
 2 files changed, 418 insertions(+), 2 deletions(-)

diff --git a/EmbeddedPkg/Include/Library/PrePiLib.h b/EmbeddedPkg/Include/Library/PrePiLib.h
index 7b2cea296f1c..80698e559cdf 100644
--- a/EmbeddedPkg/Include/Library/PrePiLib.h
+++ b/EmbeddedPkg/Include/Library/PrePiLib.h
@@ -180,6 +180,9 @@ FfsAnyFvFindFirstFile (
 
 /**
   Get Fv image from the FV type file, then add FV & FV2 Hob.
+  This function can handle the situation that a compressed
+  section contains multi-FvImages and create FV/FV2 Hob for
+  all the FvImages.
 
   @param FileHandle  File handle of a Fv type file.
 
@@ -190,7 +193,7 @@ FfsAnyFvFindFirstFile (
 **/
 EFI_STATUS
 EFIAPI
-FfsProcessFvFile (
+FfsProcessFvFileEx (
   IN  EFI_PEI_FILE_HANDLE  FvFileHandle
   );
 
@@ -735,4 +738,20 @@ DecompressFirstFv (
   VOID
   );
 
+/**
+ * This function find the file by GUID name from a FvImage.
+ *
+ * @param Name          GUID name of the file
+ * @param VolumeHandle  The handle of the Fv
+ * @param FileHandle    The handle of the File
+ * @return EFI_STATUS   Successfully find the file.
+ */
+EFI_STATUS
+EFIAPI
+FfsAnyFvFindFileByName (
+  IN  CONST EFI_GUID       *Name,
+  OUT EFI_PEI_FV_HANDLE    *VolumeHandle,
+  OUT EFI_PEI_FILE_HANDLE  *FileHandle
+  );
+
 #endif
diff --git a/EmbeddedPkg/Library/PrePiLib/FwVol.c b/EmbeddedPkg/Library/PrePiLib/FwVol.c
index 92ae68f0d382..e714f4876ff5 100644
--- a/EmbeddedPkg/Library/PrePiLib/FwVol.c
+++ b/EmbeddedPkg/Library/PrePiLib/FwVol.c
@@ -335,7 +335,7 @@ FfsProcessSection (
 
         Status = UefiDecompressGetInfo (
                    CompressedData,
-                   CompressedDataLength,
+                   (UINT32)CompressedDataLength,
                    &DstBufferSize,
                    &ScratchBufferSize
                    );
@@ -850,6 +850,403 @@ FfsProcessFvFile (
     &FvImageInfo.FvName,
     &(((EFI_FFS_FILE_HEADER *)FvFileHandle)->Name)
     );
+  return EFI_SUCCESS;
+}
+
+/**
+ * This function find the file by GUID name from a FvImage.
+ *
+ * @param Name          GUID name of the file
+ * @param VolumeHandle  The handle of the Fv
+ * @param FileHandle    The handle of the File
+ * @return EFI_STATUS   Successfully find the file.
+ */
+EFI_STATUS
+EFIAPI
+FfsAnyFvFindFileByName (
+  IN  CONST EFI_GUID       *Name,
+  OUT EFI_PEI_FV_HANDLE    *VolumeHandle,
+  OUT EFI_PEI_FILE_HANDLE  *FileHandle
+  )
+{
+  EFI_STATUS  Status;
+  UINTN       Instance;
+
+  //
+  // Search every FV for the file by name
+  //
+  Instance    = 0;
+  *FileHandle = NULL;
+
+  while (1) {
+    Status = FfsFindNextVolume (Instance++, VolumeHandle);
+    if (EFI_ERROR (Status)) {
+      break;
+    }
+
+    Status = FfsFindFileByName (Name, *VolumeHandle, FileHandle);
+    if (!EFI_ERROR (Status)) {
+      break;
+    }
+  }
+
+  DEBUG ((DEBUG_INFO, "FfsAnyFvFindFileByName with name = %g, %r\n", Name, Status));
+
+  return Status;
+}
+
+/**
+ * This function decompress the compressed section.
+ *
+ * @param FileHandle        File handle
+ * @param OutputBuffer      Pointer to the decompressed data
+ * @param OutputBufferSize  Pointer to the size of the decompressed data
+ * @return EFI_STATUS
+ */
+EFI_STATUS
+FfsDecompressSection (
+  IN VOID     *FileHandle,
+  OUT VOID    **OutputBuffer,
+  OUT UINT32  *OutputBufferSize
+  )
+{
+  EFI_STATUS                 Status;
+  UINT32                     SectionLength;
+  UINT32                     ParsedLength;
+  EFI_COMPRESSION_SECTION    *CompressionSection;
+  EFI_COMPRESSION_SECTION2   *CompressionSection2;
+  UINT32                     DstBufferSize;
+  VOID                       *ScratchBuffer;
+  UINT32                     ScratchBufferSize;
+  VOID                       *DstBuffer;
+  UINT16                     SectionAttribute;
+  UINT32                     AuthenticationStatus;
+  CHAR8                      *CompressedData;
+  UINTN                      CompressedDataLength;
+  EFI_COMMON_SECTION_HEADER  *Section;
+  UINT32                     SectionSize;
+  EFI_FFS_FILE_HEADER        *FfsFileHeader;
+
+  *OutputBuffer     = NULL;
+  *OutputBufferSize = 0;
+  ParsedLength      = 0;
+  Status            = EFI_NOT_FOUND;
+
+  FfsFileHeader = (EFI_FFS_FILE_HEADER *)(FileHandle);
+  //
+  // Size is 24 bits wide so mask upper 8 bits.
+  // Does not include FfsFileHeader header size
+  // FileSize is adjusted to FileOccupiedSize as it is 8 byte aligned.
+  //
+  Section      = (EFI_COMMON_SECTION_HEADER *)(FfsFileHeader + 1);
+  SectionSize  = *(UINT32 *)(FfsFileHeader->Size) & 0x00FFFFFF;
+  SectionSize -= sizeof (EFI_FFS_FILE_HEADER);
+
+  while (ParsedLength < SectionSize) {
+    if (IS_SECTION2 (Section)) {
+      ASSERT (SECTION2_SIZE (Section) > 0x00FFFFFF);
+    }
+
+    DEBUG ((DEBUG_INFO, "Check section type=%x\n", Section->Type));
+
+    if ((Section->Type == EFI_SECTION_COMPRESSION) || (Section->Type == EFI_SECTION_GUID_DEFINED)) {
+      DEBUG ((DEBUG_INFO, "It is a compressed section.\n"));
+
+      if (Section->Type == EFI_SECTION_COMPRESSION) {
+        if (IS_SECTION2 (Section)) {
+          CompressionSection2 = (EFI_COMPRESSION_SECTION2 *)Section;
+          SectionLength       = SECTION2_SIZE (Section);
+
+          if (CompressionSection2->CompressionType != EFI_STANDARD_COMPRESSION) {
+            return EFI_UNSUPPORTED;
+          }
+
+          CompressedData       = (CHAR8 *)((EFI_COMPRESSION_SECTION2 *)Section + 1);
+          CompressedDataLength = (UINT32)SectionLength - sizeof (EFI_COMPRESSION_SECTION2);
+        } else {
+          CompressionSection = (EFI_COMPRESSION_SECTION *)Section;
+          SectionLength      = SECTION_SIZE (Section);
+
+          if (CompressionSection->CompressionType != EFI_STANDARD_COMPRESSION) {
+            return EFI_UNSUPPORTED;
+          }
+
+          CompressedData       = (CHAR8 *)((EFI_COMPRESSION_SECTION *)Section + 1);
+          CompressedDataLength = (UINT32)SectionLength - sizeof (EFI_COMPRESSION_SECTION);
+        }
+
+        Status = UefiDecompressGetInfo (
+                   CompressedData,
+                   (UINT32)CompressedDataLength,
+                   &DstBufferSize,
+                   &ScratchBufferSize
+                   );
+      } else if (Section->Type == EFI_SECTION_GUID_DEFINED) {
+        Status = ExtractGuidedSectionGetInfo (
+                   Section,
+                   &DstBufferSize,
+                   &ScratchBufferSize,
+                   &SectionAttribute
+                   );
+      }
+
+      if (EFI_ERROR (Status)) {
+        //
+        // GetInfo failed
+        //
+        DEBUG ((DEBUG_ERROR, "Decompress GetInfo Failed - %r\n", Status));
+        return EFI_NOT_FOUND;
+      }
+
+      //
+      // Allocate scratch buffer
+      //
+      ScratchBuffer = (VOID *)(UINTN)AllocatePages (EFI_SIZE_TO_PAGES (ScratchBufferSize));
+      if (ScratchBuffer == NULL) {
+        return EFI_OUT_OF_RESOURCES;
+      }
+
+      //
+      // Allocate destination buffer, extra one page for adjustment
+      //
+      DstBuffer = (VOID *)(UINTN)AllocatePages (EFI_SIZE_TO_PAGES (DstBufferSize) + 1);
+      if (DstBuffer == NULL) {
+        return EFI_OUT_OF_RESOURCES;
+      }
+
+      //
+      // DstBuffer still is one section. Adjust DstBuffer offset, skip EFI section header
+      // to make section data at page alignment.
+      //
+      if (IS_SECTION2 (Section)) {
+        DstBuffer = (UINT8 *)DstBuffer + EFI_PAGE_SIZE - sizeof (EFI_COMMON_SECTION_HEADER2);
+      } else {
+        DstBuffer = (UINT8 *)DstBuffer + EFI_PAGE_SIZE - sizeof (EFI_COMMON_SECTION_HEADER);
+      }
+
+      //
+      // Call decompress function
+      //
+      if (Section->Type == EFI_SECTION_COMPRESSION) {
+        if (IS_SECTION2 (Section)) {
+          CompressedData = (CHAR8 *)((EFI_COMPRESSION_SECTION2 *)Section + 1);
+        } else {
+          CompressedData = (CHAR8 *)((EFI_COMPRESSION_SECTION *)Section + 1);
+        }
+
+        Status = UefiDecompress (
+                   CompressedData,
+                   DstBuffer,
+                   ScratchBuffer
+                   );
+      } else if (Section->Type == EFI_SECTION_GUID_DEFINED) {
+        Status = ExtractGuidedSectionDecode (
+                   Section,
+                   &DstBuffer,
+                   ScratchBuffer,
+                   &AuthenticationStatus
+                   );
+      }
+
+      if (EFI_ERROR (Status)) {
+        //
+        // Decompress failed
+        //
+        DEBUG ((DEBUG_ERROR, "Decompress Failed - %r\n", Status));
+        return EFI_NOT_FOUND;
+      } else {
+        *OutputBuffer     = DstBuffer;
+        *OutputBufferSize = DstBufferSize;
+        DEBUG ((
+          DEBUG_INFO,
+          "Decompressed data is at %x, %x\n",
+          DstBuffer,
+          DstBufferSize
+          ));
+        return EFI_SUCCESS;
+      }
+    }
+
+    if (IS_SECTION2 (Section)) {
+      SectionLength = SECTION2_SIZE (Section);
+    } else {
+      SectionLength = SECTION_SIZE (Section);
+    }
+
+    //
+    // SectionLength is adjusted it is 4 byte aligned.
+    // Go to the next section
+    //
+    SectionLength = GET_OCCUPIED_SIZE (SectionLength, 4);
+    ASSERT (SectionLength != 0);
+    ParsedLength += SectionLength;
+    Section       = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)Section + SectionLength);
+    DEBUG ((DEBUG_INFO, "Go to next section.\n"));
+  }
+
+  return EFI_NOT_FOUND;
+}
+
+#define MAX_FV_IMAGES  8
+/**
+  Get Fv image from the FV type file, then add FV & FV2 Hob.
+  This function can handle the situation that a compressed
+  section contains multi-FvImages and create FV/FV2 Hob for
+  all the FvImages.
+
+  We assume there are at most MAX_FV_IMAGES (8) FvImages in
+  a compressed section. If it is not the case, it can be
+  expanded to a larger one.
+
+  @param FileHandle  File handle of a Fv type file.
+
+
+  @retval EFI_NOT_FOUND  FV image can't be found.
+  @retval EFI_SUCCESS    Successfully to process it.
+
+**/
+EFI_STATUS
+EFIAPI
+FfsProcessFvFileEx (
+  IN  EFI_PEI_FILE_HANDLE  FvFileHandle
+  )
+{
+  EFI_STATUS                    Status;
+  EFI_FV_INFO                   FvImageInfo;
+  UINT32                        FvAlignment;
+  VOID                          *FvBuffer;
+  EFI_PEI_HOB_POINTERS          HobFv2;
+  UINT32                        ParsedLength;
+  VOID                          *DecompressBuffer;
+  UINT32                        DecompressBufferSize;
+  UINT32                        FvImagesCnt;
+  UINT32                        SectionLength;
+  UINTN                         FvImageHandles[MAX_FV_IMAGES];
+  UINT32                        Index;
+  IN EFI_COMMON_SECTION_HEADER  *Section;
+
+  FvBuffer             = NULL;
+  DecompressBuffer     = NULL;
+  DecompressBufferSize = 0;
+
+  //
+  // Check if this EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE file has already
+  // been extracted.
+  //
+  HobFv2.Raw = GetHobList ();
+  while ((HobFv2.Raw = GetNextHob (EFI_HOB_TYPE_FV2, HobFv2.Raw)) != NULL) {
+    if (CompareGuid (&(((EFI_FFS_FILE_HEADER *)FvFileHandle)->Name), &HobFv2.FirmwareVolume2->FileName)) {
+      //
+      // this FILE has been dispatched, it will not be dispatched again.
+      //
+      return EFI_SUCCESS;
+    }
+
+    HobFv2.Raw = GET_NEXT_HOB (HobFv2);
+  }
+
+  //
+  // Decompress section
+  //
+  Status = FfsDecompressSection (FvFileHandle, (VOID **)&DecompressBuffer, &DecompressBufferSize);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "Failed to decompress section. %r\n", Status));
+    ASSERT (FALSE);
+    return Status;
+  }
+
+  //
+  // Find all the FvImages in the decompressed buffer
+  //
+  ParsedLength = 0;
+  FvImagesCnt  = 0;
+  Section      = (EFI_COMMON_SECTION_HEADER *)(DecompressBuffer);
+
+  while (ParsedLength < DecompressBufferSize && FvImagesCnt < MAX_FV_IMAGES) {
+    if (IS_SECTION2 (Section)) {
+      ASSERT (SECTION2_SIZE (Section) > 0x00FFFFFF);
+    }
+
+    if (Section->Type == EFI_SECTION_FIRMWARE_VOLUME_IMAGE) {
+      if (IS_SECTION2 (Section)) {
+        FvImageHandles[FvImagesCnt++] = (UINTN)(VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER2));
+      } else {
+        FvImageHandles[FvImagesCnt++] = (UINTN)(VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER));
+      }
+    }
+
+    if (IS_SECTION2 (Section)) {
+      SectionLength = SECTION2_SIZE (Section);
+    } else {
+      SectionLength = SECTION_SIZE (Section);
+    }
+
+    //
+    // SectionLength is adjusted it is 4 byte aligned.
+    // Go to the next section
+    //
+    SectionLength = GET_OCCUPIED_SIZE (SectionLength, 4);
+    ASSERT (SectionLength != 0);
+    ParsedLength += SectionLength;
+    Section       = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)Section + SectionLength);
+  }
+
+  if (FvImagesCnt == 0) {
+    ASSERT (FALSE);
+    DEBUG ((DEBUG_ERROR, "Cannot find FvImages.\n"));
+    return EFI_NOT_FOUND;
+  }
+
+  DEBUG ((DEBUG_INFO, "Collect FvImageInfo\n"));
+  for (Index = 0; Index < FvImagesCnt; Index++) {
+    //
+    // Collect FvImage Info.
+    //
+    ZeroMem (&FvImageInfo, sizeof (FvImageInfo));
+    Status = FfsGetVolumeInfo ((VOID *)FvImageHandles[Index], &FvImageInfo);
+    ASSERT_EFI_ERROR (Status);
+    DEBUG ((DEBUG_INFO, "  Fv Name=%g, Format=%g, Size=0x%x\n", FvImageInfo.FvName, FvImageInfo.FvFormat, FvImageInfo.FvSize));
+
+    //
+    // FvAlignment must be more than 8 bytes required by FvHeader structure.
+    //
+    FvAlignment = 1 << ((FvImageInfo.FvAttributes & EFI_FVB2_ALIGNMENT) >> 16);
+    if (FvAlignment < 8) {
+      FvAlignment = 8;
+    }
+
+    //
+    // Check FvImage
+    //
+    if ((UINTN)FvImageInfo.FvStart % FvAlignment != 0) {
+      FvBuffer = AllocateAlignedPages (EFI_SIZE_TO_PAGES ((UINT32)FvImageInfo.FvSize), FvAlignment);
+      if (FvBuffer == NULL) {
+        return EFI_OUT_OF_RESOURCES;
+      }
+
+      CopyMem (FvBuffer, FvImageInfo.FvStart, (UINTN)FvImageInfo.FvSize);
+      //
+      // Update FvImageInfo after reload FvImage to new aligned memory
+      //
+      FfsGetVolumeInfo ((EFI_PEI_FV_HANDLE)FvBuffer, &FvImageInfo);
+    }
+
+    //
+    // Inform HOB consumer phase, i.e. DXE core, the existence of this FV
+    //
+    BuildFvHob ((EFI_PHYSICAL_ADDRESS)(UINTN)FvImageInfo.FvStart, FvImageInfo.FvSize);
+
+    //
+    // Makes the encapsulated volume show up in DXE phase to skip processing of
+    // encapsulated file again.
+    //
+    BuildFv2Hob (
+      (EFI_PHYSICAL_ADDRESS)(UINTN)FvImageInfo.FvStart,
+      FvImageInfo.FvSize,
+      &FvImageInfo.FvName,
+      &(((EFI_FFS_FILE_HEADER *)FvFileHandle)->Name)
+      );
+  }
 
   return EFI_SUCCESS;
 }
-- 
2.29.2.windows.2


^ permalink raw reply related	[flat|nested] 37+ messages in thread

* [PATCH 03/10] EmbeddedPkg/MemoryAllocationLib: Add null stub for AllocateCopyPool
  2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
  2021-12-14 13:41 ` [PATCH 01/10] OvmfPkg: Introduce IntelTdxX64 for TDVF Config-B Min Xu
  2021-12-14 13:41 ` [PATCH 02/10] EmbeddedPkg/PrePiLib: Update PrePiLib Min Xu
@ 2021-12-14 13:41 ` Min Xu
  2021-12-14 13:59   ` [edk2-devel] " Ard Biesheuvel
  2021-12-14 13:41 ` [PATCH 04/10] OvmfPkg: Add PrePiHobListPointerLibTdx Min Xu
                   ` (7 subsequent siblings)
  10 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2021-12-14 13:41 UTC (permalink / raw)
  To: devel
  Cc: Min Xu, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Gerd Hoffmann,
	Leif Lindholm, Ard Biesheuvel, Abner Chang, Daniel Schaefer

RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429

This function is a null stub to make the build success.

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Leif Lindholm <leif@nuviainc.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Abner Chang <abner.chang@hpe.com>
Cc: Daniel Schaefer <daniel.schaefer@hpe.com>
Signed-off-by: Min Xu <min.m.xu@intel.com>
---
 .../MemoryAllocationLib.c                     | 28 +++++++++++++++++++
 1 file changed, 28 insertions(+)

diff --git a/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c b/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c
index 78f8da5e9527..ddc27150c680 100644
--- a/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c
+++ b/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c
@@ -220,6 +220,34 @@ AllocateZeroPool (
   return Buffer;
 }
 
+/**
+  Copies a buffer to an allocated buffer of type EfiBootServicesData.
+
+  Allocates the number bytes specified by AllocationSize of type EfiBootServicesData, copies
+  AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the
+  allocated buffer.  If AllocationSize is 0, then a valid buffer of 0 size is returned.  If there
+  is not enough memory remaining to satisfy the request, then NULL is returned.
+
+  If Buffer is NULL, then ASSERT().
+  If AllocationSize is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT().
+
+  @param  AllocationSize        The number of bytes to allocate and zero.
+  @param  Buffer                The buffer to copy to the allocated buffer.
+
+  @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+AllocateCopyPool (
+  IN UINTN       AllocationSize,
+  IN CONST VOID  *Buffer
+  )
+{
+  ASSERT (FALSE);
+  return NULL;
+}
+
 /**
   Frees a buffer that was previously allocated with one of the pool allocation functions in the
   Memory Allocation Library.
-- 
2.29.2.windows.2


^ permalink raw reply related	[flat|nested] 37+ messages in thread

* [PATCH 04/10] OvmfPkg: Add PrePiHobListPointerLibTdx
  2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
                   ` (2 preceding siblings ...)
  2021-12-14 13:41 ` [PATCH 03/10] EmbeddedPkg/MemoryAllocationLib: Add null stub for AllocateCopyPool Min Xu
@ 2021-12-14 13:41 ` Min Xu
  2021-12-14 13:41 ` [PATCH 05/10] OvmfPkg: Add SecPlatformLibQemuTdx Min Xu
                   ` (6 subsequent siblings)
  10 siblings, 0 replies; 37+ messages in thread
From: Min Xu @ 2021-12-14 13:41 UTC (permalink / raw)
  To: devel
  Cc: Min Xu, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Gerd Hoffmann

RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429

This library is needed by EmbeddedPkg/PrePiHobLib to set / get the
Hob list pointer.

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Min Xu <min.m.xu@intel.com>
---
 .../PrePiHobListPointer.c                     | 45 +++++++++++++++++++
 .../PrePiHobListPointerLibTdx.inf             | 25 +++++++++++
 2 files changed, 70 insertions(+)
 create mode 100644 OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointer.c
 create mode 100644 OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointerLibTdx.inf

diff --git a/OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointer.c b/OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointer.c
new file mode 100644
index 000000000000..a64ca5f04fc5
--- /dev/null
+++ b/OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointer.c
@@ -0,0 +1,45 @@
+/** @file
+*
+*  Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+*  SPDX-License-Identifier: BSD-2-Clause-Patent
+*
+**/
+
+#include <PiPei.h>
+#include <Library/PrePiHobListPointerLib.h>
+#include <Library/DebugLib.h>
+
+static VOID  *mHobList = NULL;
+
+/**
+  Returns the pointer to the HOB list.
+
+  This function returns the pointer to first HOB in the list.
+
+  @return The pointer to the HOB list.
+
+**/
+VOID *
+EFIAPI
+PrePeiGetHobList (
+  VOID
+  )
+{
+  return mHobList;
+}
+
+/**
+  Updates the pointer to the HOB list.
+
+  @param  HobList       Hob list pointer to store
+
+**/
+EFI_STATUS
+EFIAPI
+PrePeiSetHobList (
+  IN  VOID  *HobList
+  )
+{
+  mHobList = HobList;
+  return EFI_SUCCESS;
+}
diff --git a/OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointerLibTdx.inf b/OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointerLibTdx.inf
new file mode 100644
index 000000000000..4d50d28a1614
--- /dev/null
+++ b/OvmfPkg/IntelTdx/PrePiHobListPointerLibTdx/PrePiHobListPointerLibTdx.inf
@@ -0,0 +1,25 @@
+#/** @file
+#
+#  Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#**/
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = PrePiHobListPointerLibTdx
+  FILE_GUID                      = 28297DB9-4CE7-4679-80E6-0270B215A2F2
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = PrePiHobListPointerLib
+
+[Sources]
+  PrePiHobListPointer.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
+  EmbeddedPkg/EmbeddedPkg.dec
+
+[LibraryClasses]
+  PcdLib
-- 
2.29.2.windows.2


^ permalink raw reply related	[flat|nested] 37+ messages in thread

* [PATCH 05/10] OvmfPkg: Add SecPlatformLibQemuTdx
  2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
                   ` (3 preceding siblings ...)
  2021-12-14 13:41 ` [PATCH 04/10] OvmfPkg: Add PrePiHobListPointerLibTdx Min Xu
@ 2021-12-14 13:41 ` Min Xu
  2021-12-15  9:48   ` Gerd Hoffmann
  2021-12-14 13:41 ` [PATCH 06/10] OvmfPkg: Add TdxStartupLib Min Xu
                   ` (5 subsequent siblings)
  10 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2021-12-14 13:41 UTC (permalink / raw)
  To: devel
  Cc: Min Xu, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Gerd Hoffmann

RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429

SecPlatformLibQemuTdx initialize the platform in Tdx guest. It sets
the HostBridgePciDevId in PlatformInfoHob which will be transferred
to DXE phase. Another task is to download QEMU configurations via fw_cfg
interface.

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Min Xu <min.m.xu@intel.com>
---
 OvmfPkg/Include/Library/TdxPlatformLib.h      |  38 +++
 .../IntelTdx/SecPlatformLibQemuTdx/Platform.c | 286 ++++++++++++++++++
 .../SecPlatformLibQemuTdx/TdxPlatformLib.inf  |  49 +++
 OvmfPkg/OvmfPkg.dec                           |   4 +
 4 files changed, 377 insertions(+)
 create mode 100644 OvmfPkg/Include/Library/TdxPlatformLib.h
 create mode 100644 OvmfPkg/IntelTdx/SecPlatformLibQemuTdx/Platform.c
 create mode 100644 OvmfPkg/IntelTdx/SecPlatformLibQemuTdx/TdxPlatformLib.inf

diff --git a/OvmfPkg/Include/Library/TdxPlatformLib.h b/OvmfPkg/Include/Library/TdxPlatformLib.h
new file mode 100644
index 000000000000..a6118a0edd98
--- /dev/null
+++ b/OvmfPkg/Include/Library/TdxPlatformLib.h
@@ -0,0 +1,38 @@
+/** @file
+
+  Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef TDX_PLATFORM_LIB_H_
+#define TDX_PLATFORM_LIB_H_
+
+#include <Uefi/UefiBaseType.h>
+#include <Uefi/UefiMultiPhase.h>
+#include <Pi/PiBootMode.h>
+#include <Pi/PiHob.h>
+#include <Library/HobLib.h>
+#include <IndustryStandard/IntelTdx.h>
+
+#define FW_CFG_NX_STACK_ITEM        "opt/ovmf/PcdSetNxForStack"
+#define FW_CFG_SYSTEM_STATE_ITEM    "etc/system-states"
+
+/**
+ * Perform Platform initialization.
+ *
+ * @param PlatformInfoHob       Pointer to the PlatformInfo Hob
+ * @param CfgSysStateDefault    Indicate if using the default SysState
+ * @param CfgNxForStackDefault  Indicate if using the default NxForStack
+ * @return VOID
+ */
+VOID
+EFIAPI
+TdxPlatformInitialize (
+  IN OUT EFI_HOB_PLATFORM_INFO  *PlatformInfoHob,
+  OUT BOOLEAN                   *CfgSysStateDefault,
+  OUT BOOLEAN                   *CfgNxForStackDefault
+  );
+
+#endif
diff --git a/OvmfPkg/IntelTdx/SecPlatformLibQemuTdx/Platform.c b/OvmfPkg/IntelTdx/SecPlatformLibQemuTdx/Platform.c
new file mode 100644
index 000000000000..e205db18cd88
--- /dev/null
+++ b/OvmfPkg/IntelTdx/SecPlatformLibQemuTdx/Platform.c
@@ -0,0 +1,286 @@
+/**@file
+
+  Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <PiPei.h>
+
+//
+// The Library classes this module consumes
+//
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/HobLib.h>
+#include <Library/IoLib.h>
+#include <Library/PcdLib.h>
+#include <Library/PciLib.h>
+#include <Library/QemuFwCfgLib.h>
+#include <Library/ResourcePublicationLib.h>
+#include <Ppi/MasterBootMode.h>
+#include <IndustryStandard/Pci22.h>
+#include <Uefi/UefiBaseType.h>
+#include <Library/BaseMemoryLib.h>
+#include <Uefi/UefiMultiPhase.h>
+#include <Pi/PiBootMode.h>
+#include <Pi/PiHob.h>
+#include <Library/HobLib.h>
+#include <Library/TdxPlatformLib.h>
+#include <Library/PciLib.h>
+#include <IndustryStandard/Pci22.h>
+#include <IndustryStandard/Q35MchIch9.h>
+#include <IndustryStandard/I440FxPiix4.h>
+
+//
+// Host Bridge DID Address
+//
+#define HOSTBRIDGE_DID \
+  PCI_LIB_ADDRESS (0, 0, 0, PCI_DEVICE_ID_OFFSET)
+
+//
+// Values we program into the PM base address registers
+//
+#define PIIX4_PMBA_VALUE   0xB000
+#define ICH9_PMBASE_VALUE  0x0600
+
+EFI_STATUS
+GetNamedFwCfgBoolean (
+  IN  CHAR8    *FwCfgFileName,
+  OUT BOOLEAN  *Setting
+  )
+{
+  EFI_STATUS            Status;
+  FIRMWARE_CONFIG_ITEM  FwCfgItem;
+  UINTN                 FwCfgSize;
+  UINT8                 Value[3];
+
+  Status = QemuFwCfgFindFile (FwCfgFileName, &FwCfgItem, &FwCfgSize);
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  if (FwCfgSize > sizeof Value) {
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  QemuFwCfgSelectItem (FwCfgItem);
+  QemuFwCfgReadBytes (FwCfgSize, Value);
+
+  if ((FwCfgSize == 1) ||
+      ((FwCfgSize == 2) && (Value[1] == '\n')) ||
+      ((FwCfgSize == 3) && (Value[1] == '\r') && (Value[2] == '\n')))
+  {
+    switch (Value[0]) {
+      case '0':
+      case 'n':
+      case 'N':
+        *Setting = FALSE;
+        return EFI_SUCCESS;
+
+      case '1':
+      case 'y':
+      case 'Y':
+        *Setting = TRUE;
+        return EFI_SUCCESS;
+
+      default:
+        break;
+    }
+  }
+
+  return EFI_PROTOCOL_ERROR;
+}
+
+VOID
+PciExBarInitialization (
+  VOID
+  )
+{
+  union {
+    UINT64    Uint64;
+    UINT32    Uint32[2];
+  } PciExBarBase;
+
+  //
+  // We only support the 256MB size for the MMCONFIG area:
+  // 256 buses * 32 devices * 8 functions * 4096 bytes config space.
+  //
+  // The masks used below enforce the Q35 requirements that the MMCONFIG area
+  // be (a) correctly aligned -- here at 256 MB --, (b) located under 64 GB.
+  //
+  // Note that (b) also ensures that the minimum address width we have
+  // determined in AddressWidthInitialization(), i.e., 36 bits, will suffice
+  // for DXE's page tables to cover the MMCONFIG area.
+  //
+  PciExBarBase.Uint64 = FixedPcdGet64 (PcdPciExpressBaseAddress);
+  ASSERT ((PciExBarBase.Uint32[1] & MCH_PCIEXBAR_HIGHMASK) == 0);
+  ASSERT ((PciExBarBase.Uint32[0] & MCH_PCIEXBAR_LOWMASK) == 0);
+
+  //
+  // Clear the PCIEXBAREN bit first, before programming the high register.
+  //
+  PciWrite32 (DRAMC_REGISTER_Q35 (MCH_PCIEXBAR_LOW), 0);
+
+  //
+  // Program the high register. Then program the low register, setting the
+  // MMCONFIG area size and enabling decoding at once.
+  //
+  PciWrite32 (DRAMC_REGISTER_Q35 (MCH_PCIEXBAR_HIGH), PciExBarBase.Uint32[1]);
+  PciWrite32 (
+    DRAMC_REGISTER_Q35 (MCH_PCIEXBAR_LOW),
+    PciExBarBase.Uint32[0] | MCH_PCIEXBAR_BUS_FF | MCH_PCIEXBAR_EN
+    );
+}
+
+VOID
+MiscInitialization (
+  EFI_HOB_PLATFORM_INFO  *PlatformInfoHob,
+  BOOLEAN                *CfgSysStateDefault
+  )
+{
+  RETURN_STATUS         Status;
+  FIRMWARE_CONFIG_ITEM  FwCfgItem;
+  UINTN                 FwCfgSize;
+  UINTN                 PmCmd;
+  UINTN                 Pmba;
+  UINT32                PmbaAndVal;
+  UINT32                PmbaOrVal;
+  UINTN                 AcpiCtlReg;
+  UINT8                 AcpiEnBit;
+
+  //
+  // Disable A20 Mask
+  //
+  IoOr8 (0x92, BIT1);
+
+  //
+  // Determine platform type and save Host Bridge DID to PCD
+  //
+  switch (PlatformInfoHob->HostBridgePciDevId) {
+    case INTEL_82441_DEVICE_ID:
+      PmCmd      = POWER_MGMT_REGISTER_PIIX4 (PCI_COMMAND_OFFSET);
+      Pmba       = POWER_MGMT_REGISTER_PIIX4 (PIIX4_PMBA);
+      PmbaAndVal = ~(UINT32)PIIX4_PMBA_MASK;
+      PmbaOrVal  = PIIX4_PMBA_VALUE;
+      AcpiCtlReg = POWER_MGMT_REGISTER_PIIX4 (PIIX4_PMREGMISC);
+      AcpiEnBit  = PIIX4_PMREGMISC_PMIOSE;
+      break;
+    case INTEL_Q35_MCH_DEVICE_ID:
+      PmCmd      = POWER_MGMT_REGISTER_Q35 (PCI_COMMAND_OFFSET);
+      Pmba       = POWER_MGMT_REGISTER_Q35 (ICH9_PMBASE);
+      PmbaAndVal = ~(UINT32)ICH9_PMBASE_MASK;
+      PmbaOrVal  = ICH9_PMBASE_VALUE;
+      AcpiCtlReg = POWER_MGMT_REGISTER_Q35 (ICH9_ACPI_CNTL);
+      AcpiEnBit  = ICH9_ACPI_CNTL_ACPI_EN;
+      break;
+    default:
+      DEBUG ((
+        DEBUG_ERROR,
+        "%a: Unknown Host Bridge Device ID: 0x%04x\n",
+        __FUNCTION__,
+        PlatformInfoHob->HostBridgePciDevId
+        ));
+      ASSERT (FALSE);
+      return;
+  }
+
+  //
+  // If the appropriate IOspace enable bit is set, assume the ACPI PMBA
+  // has been configured and skip the setup here.
+  // This matches the logic in AcpiTimerLibConstructor ().
+  //
+  if ((PciRead8 (AcpiCtlReg) & AcpiEnBit) == 0) {
+    //
+    // The PEI phase should be exited with fully accessibe ACPI PM IO space:
+    // 1. set PMBA
+    //
+    PciAndThenOr32 (Pmba, PmbaAndVal, PmbaOrVal);
+
+    //
+    // 2. set PCICMD/IOSE
+    //
+    PciOr8 (PmCmd, EFI_PCI_COMMAND_IO_SPACE);
+
+    //
+    // 3. set ACPI PM IO enable bit (PMREGMISC:PMIOSE or ACPI_CNTL:ACPI_EN)
+    //
+    PciOr8 (AcpiCtlReg, AcpiEnBit);
+  }
+
+  if (PlatformInfoHob->HostBridgePciDevId == INTEL_Q35_MCH_DEVICE_ID) {
+    //
+    // Set Root Complex Register Block BAR
+    //
+    PciWrite32 (
+      POWER_MGMT_REGISTER_Q35 (ICH9_RCBA),
+      ICH9_ROOT_COMPLEX_BASE | ICH9_RCBA_EN
+      );
+
+    //
+    // Set PCI Express Register Range Base Address
+    //
+    PciExBarInitialization ();
+  }
+
+  //
+  // check for overrides
+  //
+  Status = QemuFwCfgFindFile ("etc/system-states", &FwCfgItem, &FwCfgSize);
+  if ((Status != RETURN_SUCCESS) || (FwCfgSize != sizeof PlatformInfoHob->SystemStates)) {
+    DEBUG ((DEBUG_INFO, "ACPI using S3/S4 defaults\n"));
+    *CfgSysStateDefault = TRUE;
+    return;
+  }
+
+  QemuFwCfgSelectItem (FwCfgItem);
+  QemuFwCfgReadBytes (sizeof PlatformInfoHob->SystemStates, PlatformInfoHob->SystemStates);
+}
+
+/**
+ * Perform Platform initialization.
+ *
+ * @param PlatformInfoHob       Pointer to the PlatformInfo Hob
+ * @param CfgSysStateDefault    Indicate if using the default SysState
+ * @param CfgNxForStackDefault  Indicate if using the default NxForStack
+ * @return VOID
+ */
+VOID
+EFIAPI
+TdxPlatformInitialize (
+  EFI_HOB_PLATFORM_INFO  *PlatformInfoHob,
+  BOOLEAN                *CfgSysStateDefault,
+  BOOLEAN                *CfgNxForStackDefault
+  )
+{
+  RETURN_STATUS  Status;
+
+  PlatformInfoHob->HostBridgePciDevId = PciRead16 (HOSTBRIDGE_DID);
+
+  if (PlatformInfoHob->HostBridgePciDevId == INTEL_Q35_MCH_DEVICE_ID) {
+    BuildResourceDescriptorHob (
+      EFI_RESOURCE_IO,
+      EFI_RESOURCE_ATTRIBUTE_PRESENT     |
+      EFI_RESOURCE_ATTRIBUTE_INITIALIZED,
+      0x6000,
+      0xa000
+      );
+  } else {
+    BuildResourceDescriptorHob (
+      EFI_RESOURCE_IO,
+      EFI_RESOURCE_ATTRIBUTE_PRESENT     |
+      EFI_RESOURCE_ATTRIBUTE_INITIALIZED,
+      0xc000,
+      0x4000
+      );
+  }
+
+  MiscInitialization (PlatformInfoHob, CfgSysStateDefault);
+
+  Status = GetNamedFwCfgBoolean ("opt/ovmf/PcdSetNxForStack", &PlatformInfoHob->SetNxForStack);
+  if (Status != RETURN_SUCCESS) {
+    DEBUG ((DEBUG_INFO, "NxForStack using defaults\n"));
+    *CfgNxForStackDefault = TRUE;
+  }
+}
diff --git a/OvmfPkg/IntelTdx/SecPlatformLibQemuTdx/TdxPlatformLib.inf b/OvmfPkg/IntelTdx/SecPlatformLibQemuTdx/TdxPlatformLib.inf
new file mode 100644
index 000000000000..23af0475f035
--- /dev/null
+++ b/OvmfPkg/IntelTdx/SecPlatformLibQemuTdx/TdxPlatformLib.inf
@@ -0,0 +1,49 @@
+## @file
+#
+#  Tdvf Platform Lib for the QEMU VMM
+#
+#  Copyright (C) 2013, Red Hat, Inc.
+#  Copyright (c) 2008 - 2012, Intel Corporation. All rights reserved.<BR>
+#  Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = SecPlatformLibQemuTdx
+  FILE_GUID                      = 44cabe70-fcfb-11ea-8b6e-0800200c9a66
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = TdxPlatformLib|SEC
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+#  VALID_ARCHITECTURES           = X64
+#
+
+[Sources]
+  Platform.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  UefiCpuPkg/UefiCpuPkg.dec
+  MdeModulePkg/MdeModulePkg.dec
+  OvmfPkg/OvmfPkg.dec
+
+[Guids]
+
+[LibraryClasses]
+  BaseLib
+  BaseMemoryLib
+  DebugLib
+  IoLib
+  PcdLib
+  HobLib
+  PciLib
+  QemuFwCfgLib
+
+[Pcd]
+  gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress
diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec
index 86138594b83b..3194b02d9d6b 100644
--- a/OvmfPkg/OvmfPkg.dec
+++ b/OvmfPkg/OvmfPkg.dec
@@ -117,6 +117,10 @@
   #
   TdxMailboxLib|Include/Library/TdxMailboxLib.h
 
+  ##  @libraryclass  TdxPlatformLib
+  #
+  TdxPlatformLib|Include/Library/TdxPlatformLib.h
+
 [Guids]
   gUefiOvmfPkgTokenSpaceGuid            = {0x93bb96af, 0xb9f2, 0x4eb8, {0x94, 0x62, 0xe0, 0xba, 0x74, 0x56, 0x42, 0x36}}
   gEfiXenInfoGuid                       = {0xd3b46f3b, 0xd441, 0x1244, {0x9a, 0x12, 0x0, 0x12, 0x27, 0x3f, 0xc1, 0x4d}}
-- 
2.29.2.windows.2


^ permalink raw reply related	[flat|nested] 37+ messages in thread

* [PATCH 06/10] OvmfPkg: Add TdxStartupLib
  2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
                   ` (4 preceding siblings ...)
  2021-12-14 13:41 ` [PATCH 05/10] OvmfPkg: Add SecPlatformLibQemuTdx Min Xu
@ 2021-12-14 13:41 ` Min Xu
  2021-12-15 10:09   ` Gerd Hoffmann
  2021-12-14 13:41 ` [PATCH 07/10] OvmfPkg: Update TdxDxe to set TDX PCDs Min Xu
                   ` (4 subsequent siblings)
  10 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2021-12-14 13:41 UTC (permalink / raw)
  To: devel
  Cc: Min Xu, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Gerd Hoffmann

RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429

TdxStarupLib provides a function (TdxStartup ()) which brings up the
Tdx guest from SEC phase to DXE phase. PEI phase is skipped because most
of the components in PEI phase is not needed for Tdx guest, for example,
MP Services, TPM etc. In this way, the attack surfaces are reduced as
much as possible.

TdxStartup() does below tasks:
1. Contruct the FW hoblist.
   Since PEI is skipped, we must find a memory region which is the
   largest one below 4GB. Then this memory region will be used as the
   firmware hoblist. Note: before TdxStartup() is called, some physical
   memory must be accepted so that these memory can be used as the
   hoblist.
2. Tranfer the Hoblist to the final Hoblist for DXE
3. Initialize the platform.
4. Build various Hobs, such as SecFv Hob, DxeFv Hob, Stack Hob, etc.
5. At last DXE Core is located / loaded and transfer control to it.

Plese be noted: this patch-set is to enable basic feature of Config-B.
So the measurement to the external input, such as HobList, is absent.
We will re-visit here in the patch-set for the advanced feature of
Config-B.

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Min Xu <min.m.xu@intel.com>
---
 OvmfPkg/Include/Library/TdxStartupLib.h       |  35 +
 OvmfPkg/IntelTdx/TdxStartupLib/DxeLoad.c      | 344 +++++++
 OvmfPkg/IntelTdx/TdxStartupLib/Hob.c          | 150 +++
 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartup.c   | 143 +++
 .../TdxStartupLib/TdxStartupInternal.h        |  68 ++
 .../IntelTdx/TdxStartupLib/TdxStartupLib.inf  |  85 ++
 .../TdxStartupLib/TdxStartupLibNull.inf       |  40 +
 .../IntelTdx/TdxStartupLib/TdxStartupNull.c   |  19 +
 .../IntelTdx/TdxStartupLib/X64/PageTables.h   | 206 ++++
 .../TdxStartupLib/X64/VirtualMemory.c         | 915 ++++++++++++++++++
 OvmfPkg/OvmfPkg.dec                           |   7 +
 11 files changed, 2012 insertions(+)
 create mode 100644 OvmfPkg/Include/Library/TdxStartupLib.h
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/DxeLoad.c
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/Hob.c
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartup.c
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupInternal.h
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLib.inf
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLibNull.inf
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupNull.c
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/X64/PageTables.h
 create mode 100644 OvmfPkg/IntelTdx/TdxStartupLib/X64/VirtualMemory.c

diff --git a/OvmfPkg/Include/Library/TdxStartupLib.h b/OvmfPkg/Include/Library/TdxStartupLib.h
new file mode 100644
index 000000000000..f24918c71c93
--- /dev/null
+++ b/OvmfPkg/Include/Library/TdxStartupLib.h
@@ -0,0 +1,35 @@
+/** @file
+
+  Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef TDX_STARTUP_LIB_H_
+#define TDX_STARTUP_LIB_H_
+
+#include <Library/BaseLib.h>
+#include <Uefi/UefiBaseType.h>
+#include <Uefi/UefiSpec.h>
+#include <Pi/PiPeiCis.h>
+#include <Library/DebugLib.h>
+#include <Protocol/DebugSupport.h>
+#include <IndustryStandard/Tpm20.h>
+
+/**
+ * This function brings up the Tdx guest from SEC phase to DXE phase.
+ * PEI phase is skipped because most of the components in PEI phase
+ * is not needed for Tdx guest, for example, MP Services, TPM etc.
+ * In this way, the attack surfaces are reduced as much as possible.
+ *
+ * @param Context   The pointer to the SecCoreData
+ * @return VOID     This function never returns
+ */
+VOID
+EFIAPI
+TdxStartup (
+  IN VOID  *Context
+  );
+
+#endif
diff --git a/OvmfPkg/IntelTdx/TdxStartupLib/DxeLoad.c b/OvmfPkg/IntelTdx/TdxStartupLib/DxeLoad.c
new file mode 100644
index 000000000000..1bac2338322d
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdxStartupLib/DxeLoad.c
@@ -0,0 +1,344 @@
+/** @file
+  Responsibility of this file is to load the DXE Core from a Firmware Volume.
+
+Copyright (c) 2016 HP Development Company, L.P.
+Copyright (c) 2006 - 2020, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "TdxStartupInternal.h"
+#include <Library/DebugLib.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/PcdLib.h>
+#include <Guid/MemoryTypeInformation.h>
+#include <Guid/MemoryAllocationHob.h>
+#include <Guid/PcdDataBaseSignatureGuid.h>
+#include <Register/Intel/Cpuid.h>
+#include <Library/PrePiLib.h>
+#include "X64/PageTables.h"
+#include <Library/ReportStatusCodeLib.h>
+
+#define PCD_PEIM_GUID  { \
+    0x9b3ada4f, 0xae56, 0x4c24, {0x8d, 0xea, 0xf0, 0x3b, 0x75, 0x58, 0xae, 0x50} \
+  }
+
+EFI_GUID  mPcdPeimGuid = PCD_PEIM_GUID;
+
+#define STACK_SIZE  0x20000
+
+EFI_MEMORY_TYPE_INFORMATION  mDefaultMemoryTypeInformation[] = {
+  { EfiACPIMemoryNVS,       0x004 },
+  { EfiACPIReclaimMemory,   0x008 },
+  { EfiReservedMemoryType,  0x004 },
+  { EfiRuntimeServicesData, 0x024 },
+  { EfiRuntimeServicesCode, 0x030 },
+  { EfiBootServicesCode,    0x180 },
+  { EfiBootServicesData,    0xF00 },
+  { EfiMaxMemoryType,       0x000 }
+};
+
+/**
+   Transfers control to DxeCore.
+
+   This function performs a CPU architecture specific operations to execute
+   the entry point of DxeCore
+
+   @param DxeCoreEntryPoint         The entry point of DxeCore.
+
+**/
+VOID
+HandOffToDxeCore (
+  IN EFI_PHYSICAL_ADDRESS  DxeCoreEntryPoint
+  )
+{
+  VOID   *BaseOfStack;
+  VOID   *TopOfStack;
+  UINTN  PageTables;
+
+  //
+  // Clear page 0 and mark it as allocated if NULL pointer detection is enabled.
+  //
+  if (IsNullDetectionEnabled ()) {
+    ClearFirst4KPage (GetHobList ());
+    BuildMemoryAllocationHob (0, EFI_PAGES_TO_SIZE (1), EfiBootServicesData);
+  }
+
+  //
+  // Allocate 128KB for the Stack
+  //
+  BaseOfStack = AllocatePages (EFI_SIZE_TO_PAGES (STACK_SIZE));
+  ASSERT (BaseOfStack != NULL);
+
+  //
+  // Compute the top of the stack we were allocated. Pre-allocate a UINTN
+  // for safety.
+  //
+  TopOfStack = (VOID *)((UINTN)BaseOfStack + EFI_SIZE_TO_PAGES (STACK_SIZE) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT);
+  TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);
+
+  DEBUG ((DEBUG_INFO, "BaseOfStack=0x%x, TopOfStack=0x%x\n", BaseOfStack, TopOfStack));
+
+  PageTables = 0;
+  if (FeaturePcdGet (PcdDxeIplBuildPageTables)) {
+    //
+    // Create page table and save PageMapLevel4 to CR3
+    //
+    PageTables = CreateIdentityMappingPageTables (
+                   (EFI_PHYSICAL_ADDRESS)(UINTN)BaseOfStack,
+                   STACK_SIZE
+                   );
+    if (PageTables == 0) {
+      DEBUG ((DEBUG_ERROR, "Failed to create idnetity mapping page tables.\n"));
+      CpuDeadLoop ();
+    }
+  } else {
+    //
+    // Set NX for stack feature also require PcdDxeIplBuildPageTables be TRUE
+    // for the DxeIpl and the DxeCore are both X64.
+    //
+    ASSERT (FixedPcdGetBool (PcdTdxSetNxForStack) == FALSE);
+    ASSERT (FixedPcdGetBool (PcdCpuStackGuard) == FALSE);
+  }
+
+  if (FeaturePcdGet (PcdDxeIplBuildPageTables)) {
+    AsmWriteCr3 (PageTables);
+  }
+
+  //
+  // Update the contents of BSP stack HOB to reflect the real stack info passed to DxeCore.
+  //
+  UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN)BaseOfStack, STACK_SIZE);
+
+  DEBUG ((DEBUG_INFO, "SwitchStack then Jump to DxeCore\n"));
+  //
+  // Transfer the control to the entry point of DxeCore.
+  //
+  SwitchStack (
+    (SWITCH_STACK_ENTRY_POINT)(UINTN)DxeCoreEntryPoint,
+    GetHobList (),
+    NULL,
+    TopOfStack
+    );
+}
+
+EFI_STATUS
+FindPcdPeim (
+  IN      INTN                 FvInstance,
+  IN OUT  EFI_PEI_FILE_HANDLE  *FileHandle
+  )
+{
+  EFI_STATUS         Status;
+  EFI_PEI_FV_HANDLE  VolumeHandle;
+
+  if ((FileHandle == NULL) || (FvInstance == -1)) {
+    ASSERT (FALSE);
+    return EFI_INVALID_PARAMETER;
+  }
+
+  *FileHandle = NULL;
+
+  //
+  // Caller passed in a specific FV to try, so only try that one
+  //
+  Status = FfsFindNextVolume (FvInstance, &VolumeHandle);
+  if (!EFI_ERROR (Status)) {
+    Status = FfsFindNextFile (EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE, VolumeHandle, FileHandle);
+
+    if (*FileHandle) {
+      // Assume the FV that contains multiple compressed FVs.
+      // So decompress the compressed FVs
+      Status = FfsProcessFvFile (*FileHandle);
+      ASSERT_EFI_ERROR (Status);
+
+      Status = FfsAnyFvFindFileByName (&mPcdPeimGuid, &VolumeHandle, FileHandle);
+    }
+  }
+
+  return Status;
+}
+
+EFI_STATUS
+EFIAPI
+InitPcdPeim (
+  IN INTN  FvInstance
+  )
+{
+  EFI_STATUS           Status;
+  PEI_PCD_DATABASE     *Database;
+  PEI_PCD_DATABASE     *PeiPcdDbBinary;
+  EFI_PEI_FILE_HANDLE  FileHandle;
+
+  //
+  // Find the PcdPeim and initialize the Pcd Database
+  //
+  Status = FindPcdPeim (FvInstance, &FileHandle);
+
+  if (EFI_ERROR (Status)) {
+    ASSERT (FALSE);
+    return Status;
+  }
+
+  Status = FfsFindSectionData (EFI_SECTION_RAW, FileHandle, (VOID **)(UINTN)&PeiPcdDbBinary);
+  if (EFI_ERROR (Status)) {
+    ASSERT (FALSE);
+    return Status;
+  }
+
+  Database = BuildGuidHob (&gPcdDataBaseHobGuid, PeiPcdDbBinary->Length + PeiPcdDbBinary->UninitDataBaseSize);
+
+  ZeroMem (Database, PeiPcdDbBinary->Length  + PeiPcdDbBinary->UninitDataBaseSize);
+
+  //
+  // PeiPcdDbBinary is smaller than Database
+  //
+  CopyMem (Database, PeiPcdDbBinary, PeiPcdDbBinary->Length);
+
+  return Status;
+}
+
+/**
+   Searches DxeCore in all firmware Volumes and loads the first
+   instance that contains DxeCore.
+
+   @return FileHandle of DxeCore to load DxeCore.
+
+**/
+EFI_STATUS
+FindDxeCore (
+  IN INTN                         FvInstance,
+  IN OUT     EFI_PEI_FILE_HANDLE  *FileHandle
+  )
+{
+  EFI_STATUS         Status;
+  EFI_PEI_FV_HANDLE  VolumeHandle;
+
+  if (FileHandle == NULL) {
+    ASSERT (FALSE);
+    return EFI_INVALID_PARAMETER;
+  }
+
+  *FileHandle = NULL;
+
+  if (FvInstance != -1) {
+    //
+    // Caller passed in a specific FV to try, so only try that one
+    //
+    Status = FfsFindNextVolume (FvInstance, &VolumeHandle);
+    if (!EFI_ERROR (Status)) {
+      Status = FfsFindNextFile (EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE, VolumeHandle, FileHandle);
+      if (*FileHandle) {
+        // Assume the FV that contains multiple compressed FVs.
+        // So decompress the compressed FVs
+        Status = FfsProcessFvFileEx (*FileHandle);
+        ASSERT_EFI_ERROR (Status);
+        Status = FfsAnyFvFindFirstFile (EFI_FV_FILETYPE_DXE_CORE, &VolumeHandle, FileHandle);
+      }
+    }
+  } else {
+    // Assume the FV that contains the SEC (our code) also contains a compressed FV.
+    Status = DecompressFirstFv ();
+    ASSERT_EFI_ERROR (Status);
+    Status = FfsAnyFvFindFirstFile (EFI_FV_FILETYPE_DXE_CORE, &VolumeHandle, FileHandle);
+  }
+
+  return Status;
+}
+
+/**
+   This function finds DXE Core in the firmware volume and transfer the control to
+   DXE core.
+
+   @return EFI_SUCCESS              DXE core was successfully loaded.
+   @return EFI_OUT_OF_RESOURCES     There are not enough resources to load DXE core.
+
+**/
+EFI_STATUS
+EFIAPI
+DxeLoadCore (
+  IN INTN  FvInstance
+  )
+{
+  EFI_STATUS            Status;
+  EFI_FV_FILE_INFO      DxeCoreFileInfo;
+  EFI_PHYSICAL_ADDRESS  DxeCoreAddress;
+  UINT64                DxeCoreSize;
+  EFI_PHYSICAL_ADDRESS  DxeCoreEntryPoint;
+  EFI_PEI_FILE_HANDLE   FileHandle;
+  VOID                  *PeCoffImage;
+
+  //
+  // Create Memory Type Information HOB
+  //
+  BuildGuidDataHob (
+    &gEfiMemoryTypeInformationGuid,
+    mDefaultMemoryTypeInformation,
+    sizeof (mDefaultMemoryTypeInformation)
+    );
+
+  //
+  // Look in all the FVs present and find the DXE Core FileHandle
+  //
+  Status = FindDxeCore (FvInstance, &FileHandle);
+
+  if (EFI_ERROR (Status)) {
+    ASSERT (FALSE);
+    return Status;
+  }
+
+  //
+  // Load the DXE Core from a Firmware Volume.
+  //
+  Status = FfsFindSectionData (EFI_SECTION_PE32, FileHandle, &PeCoffImage);
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  Status = LoadPeCoffImage (PeCoffImage, &DxeCoreAddress, &DxeCoreSize, &DxeCoreEntryPoint);
+  ASSERT_EFI_ERROR (Status);
+
+  //
+  // Extract the DxeCore GUID file name.
+  //
+  Status = FfsGetFileInfo (FileHandle, &DxeCoreFileInfo);
+  ASSERT_EFI_ERROR (Status);
+
+  //
+  // Add HOB for the DXE Core
+  //
+  BuildModuleHob (
+    &DxeCoreFileInfo.FileName,
+    DxeCoreAddress,
+    ALIGN_VALUE (DxeCoreSize, EFI_PAGE_SIZE),
+    DxeCoreEntryPoint
+    );
+
+  DEBUG ((
+    DEBUG_INFO | DEBUG_LOAD,
+    "Loading DXE CORE at 0x%11p EntryPoint=0x%11p\n",
+    (VOID *)(UINTN)DxeCoreAddress,
+    FUNCTION_ENTRY_POINT (DxeCoreEntryPoint)
+    ));
+
+  //
+  // Initialize PcdPeim database
+  //
+  Status = InitPcdPeim (FvInstance);
+  ASSERT (!EFI_ERROR (Status));
+
+  // Transfer control to the DXE Core
+  // The hand off state is simply a pointer to the HOB list
+  //
+  HandOffToDxeCore (DxeCoreEntryPoint);
+
+  //
+  // If we get here, then the DXE Core returned.  This is an error
+  // DxeCore should not return.
+  //
+  ASSERT (FALSE);
+  CpuDeadLoop ();
+
+  return EFI_OUT_OF_RESOURCES;
+}
diff --git a/OvmfPkg/IntelTdx/TdxStartupLib/Hob.c b/OvmfPkg/IntelTdx/TdxStartupLib/Hob.c
new file mode 100644
index 000000000000..a2f3d73e9dc6
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdxStartupLib/Hob.c
@@ -0,0 +1,150 @@
+/** @file
+  Main SEC phase code. Handles initial TDX Hob List Processing
+
+  Copyright (c) 2008, Intel Corporation. All rights reserved.<BR>
+  (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <PiPei.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/HobLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/PrePiLib.h>
+#include <Library/TdxPlatformLib.h>
+#include <Library/TpmMeasurementLib.h>
+#include <Library/QemuFwCfgLib.h>
+#include <IndustryStandard/Tdx.h>
+#include <IndustryStandard/UefiTcgPlatform.h>
+#include "TdxStartupInternal.h"
+
+/**
+ * This function is to find a memory region which is the largest one below 4GB.
+ * It will be used as the firmware hoblist.
+ *
+ * @param VmmHobList    Vmm passed hoblist which constains the memory information.
+ * @return EFI_SUCCESS  Successfully construct the firmware hoblist.
+ */
+EFI_STATUS
+EFIAPI
+ConstructFwHobList (
+  IN CONST VOID  *VmmHobList
+  )
+{
+  EFI_PEI_HOB_POINTERS  Hob;
+  EFI_PHYSICAL_ADDRESS  PhysicalEnd;
+  UINT64                ResourceLength;
+  EFI_PHYSICAL_ADDRESS  LowMemoryStart;
+  UINT64                LowMemoryLength;
+
+  ASSERT (VmmHobList != NULL);
+  Hob.Raw = (UINT8 *)VmmHobList;
+
+  LowMemoryLength = 0;
+  LowMemoryStart  = 0;
+
+  //
+  // Parse the HOB list until end of list or matching type is found.
+  //
+  while (!END_OF_HOB_LIST (Hob)) {
+    if (Hob.Header->HobType == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) {
+      if (Hob.ResourceDescriptor->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) {
+        PhysicalEnd    = Hob.ResourceDescriptor->PhysicalStart + Hob.ResourceDescriptor->ResourceLength;
+        ResourceLength = Hob.ResourceDescriptor->ResourceLength;
+
+        if (PhysicalEnd <= BASE_4GB) {
+          if (ResourceLength > LowMemoryLength) {
+            LowMemoryStart  = Hob.ResourceDescriptor->PhysicalStart;
+            LowMemoryLength = ResourceLength;
+          }
+        } else {
+          break;
+        }
+      }
+    }
+
+    Hob.Raw = GET_NEXT_HOB (Hob);
+  }
+
+  if (LowMemoryLength == 0) {
+    DEBUG ((DEBUG_ERROR, "Cannot find a memory region under 4GB for Fw hoblist.\n"));
+    return EFI_NOT_FOUND;
+  }
+
+  //
+  // HobLib doesn't like HobStart at address 0 so adjust is needed
+  //
+  if (LowMemoryStart == 0) {
+    LowMemoryStart  += EFI_PAGE_SIZE;
+    LowMemoryLength -= EFI_PAGE_SIZE;
+  }
+
+  DEBUG ((DEBUG_INFO, "LowMemory Start and End: %x, %x\n", LowMemoryStart, LowMemoryStart + LowMemoryLength));
+  HobConstructor (
+    (VOID *)LowMemoryStart,
+    LowMemoryLength,
+    (VOID *)LowMemoryStart,
+    (VOID *)(LowMemoryStart + LowMemoryLength)
+    );
+
+  SetHobList ((VOID *)(UINT64)LowMemoryStart);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Transfer the incoming HobList for the TD to the final HobList for Dxe
+
+  @param[in] VmmHobList    The Hoblist pass the firmware
+
+**/
+VOID
+EFIAPI
+TransferHobList (
+  IN CONST VOID  *VmmHobList
+  )
+{
+  EFI_PEI_HOB_POINTERS         Hob;
+  EFI_RESOURCE_ATTRIBUTE_TYPE  ResourceAttribute;
+  EFI_PHYSICAL_ADDRESS         PhysicalEnd;
+
+  Hob.Raw = (UINT8 *)VmmHobList;
+
+  Hob.Raw = (UINT8 *)VmmHobList;
+  while (!END_OF_HOB_LIST (Hob)) {
+    switch (Hob.Header->HobType) {
+      case EFI_HOB_TYPE_RESOURCE_DESCRIPTOR:
+        ResourceAttribute = Hob.ResourceDescriptor->ResourceAttribute;
+        PhysicalEnd       = Hob.ResourceDescriptor->PhysicalStart + Hob.ResourceDescriptor->ResourceLength;
+
+        if (Hob.ResourceDescriptor->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) {
+          ResourceAttribute |= EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_TESTED;
+
+          if (PhysicalEnd <= BASE_4GB) {
+            ResourceAttribute |= EFI_RESOURCE_ATTRIBUTE_ENCRYPTED;
+          }
+        }
+
+        BuildResourceDescriptorHob (
+          Hob.ResourceDescriptor->ResourceType,
+          ResourceAttribute,
+          Hob.ResourceDescriptor->PhysicalStart,
+          Hob.ResourceDescriptor->ResourceLength
+          );
+        break;
+
+      case EFI_HOB_TYPE_MEMORY_ALLOCATION:
+        BuildMemoryAllocationHob (
+          Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress,
+          Hob.MemoryAllocation->AllocDescriptor.MemoryLength,
+          Hob.MemoryAllocation->AllocDescriptor.MemoryType
+          );
+        break;
+    }
+
+    Hob.Raw = GET_NEXT_HOB (Hob);
+  }
+}
diff --git a/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartup.c b/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartup.c
new file mode 100644
index 000000000000..10d28269b5ba
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartup.c
@@ -0,0 +1,143 @@
+/** @file
+
+  Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <PiPei.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DebugLib.h>
+#include <Protocol/DebugSupport.h>
+#include <Library/TdxLib.h>
+#include <IndustryStandard/Tdx.h>
+#include <Library/TdxPlatformLib.h>
+#include <Library/PrePiLib.h>
+#include <Library/TdxStartupLib.h>
+#include "TdxStartupInternal.h"
+
+#define GET_GPAW_INIT_STATE(INFO)  ((UINT8) ((INFO) & 0x3f))
+
+/**
+ * This function brings up the Tdx guest from SEC phase to DXE phase.
+ * PEI phase is skipped because most of the components in PEI phase
+ * is not needed for Tdx guest, for example, MP Services, TPM etc.
+ * In this way, the attack surfaces are reduced as much as possible.
+ *
+ * @param Context   The pointer to the SecCoreData
+ * @return VOID     This function never returns
+ */
+VOID
+EFIAPI
+TdxStartup (
+  IN VOID  *Context
+  )
+{
+  EFI_SEC_PEI_HAND_OFF        *SecCoreData;
+  EFI_FIRMWARE_VOLUME_HEADER  *BootFv;
+  EFI_STATUS                  Status;
+  EFI_HOB_PLATFORM_INFO       PlatformInfoHob;
+  UINT32                      DxeCodeBase;
+  UINT32                      DxeCodeSize;
+  TD_RETURN_DATA              TdReturnData;
+  VOID                        *VmmHobList;
+  BOOLEAN                     CfgSysStateDefault;
+  BOOLEAN                     CfgNxStackDefault;
+
+  Status      = EFI_SUCCESS;
+  BootFv      = NULL;
+  SecCoreData = (EFI_SEC_PEI_HAND_OFF *)Context;
+  VmmHobList  = (VOID *)(UINTN)FixedPcdGet32 (PcdOvmfSecGhcbBase);
+
+  Status = TdCall (TDCALL_TDINFO, 0, 0, 0, &TdReturnData);
+  ASSERT (Status == EFI_SUCCESS);
+
+  DEBUG ((
+    EFI_D_INFO,
+    "Tdx started with(Hob: 0x%x, Gpaw: 0x%x, Cpus: %d)\n",
+    (UINT32)(UINTN)VmmHobList,
+    GET_GPAW_INIT_STATE (TdReturnData.TdInfo.Gpaw),
+    TdReturnData.TdInfo.NumVcpus
+    ));
+
+  ZeroMem (&PlatformInfoHob, sizeof (PlatformInfoHob));
+
+  //
+  // Construct the Fw hoblist.
+  //
+  Status = ConstructFwHobList (VmmHobList);
+  if (EFI_ERROR (Status)) {
+    ASSERT (FALSE);
+    CpuDeadLoop ();
+  }
+
+  //
+  // Tranfer the Hoblist to the final Hoblist for DXE
+  //
+  TransferHobList (VmmHobList);
+
+  //
+  // Initialize Platform
+  //
+  TdxPlatformInitialize (&PlatformInfoHob, &CfgSysStateDefault, &CfgNxStackDefault);
+
+  //
+  // TDVF must not use any CpuHob from input HobList.
+  // It must create its own using GPWA from VMM and 0 for SizeOfIoSpace
+  //
+  BuildCpuHob (GET_GPAW_INIT_STATE (TdReturnData.TdInfo.Gpaw), 16);
+
+  //
+  // SecFV
+  //
+  BootFv = (EFI_FIRMWARE_VOLUME_HEADER *)SecCoreData->BootFirmwareVolumeBase;
+  BuildFvHob ((UINTN)BootFv, BootFv->FvLength);
+
+  //
+  // DxeFV
+  //
+  DxeCodeBase = PcdGet32 (PcdBfvBase);
+  DxeCodeSize = PcdGet32 (PcdBfvRawDataSize) - (UINT32)BootFv->FvLength;
+  BuildFvHob (DxeCodeBase, DxeCodeSize);
+
+  DEBUG ((DEBUG_INFO, "SecFv : %p, 0x%x\n", BootFv, BootFv->FvLength));
+  DEBUG ((DEBUG_INFO, "DxeFv : %x, 0x%x\n", DxeCodeBase, DxeCodeSize));
+
+  BuildGuidDataHob (&gUefiOvmfPkgTdxPlatformGuid, &PlatformInfoHob, sizeof (EFI_HOB_PLATFORM_INFO));
+
+  BuildStackHob ((UINTN)SecCoreData->StackBase, SecCoreData->StackSize <<= 1);
+
+  BuildResourceDescriptorHob (
+    EFI_RESOURCE_SYSTEM_MEMORY,
+    EFI_RESOURCE_ATTRIBUTE_PRESENT |
+    EFI_RESOURCE_ATTRIBUTE_INITIALIZED |
+    EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE |
+    EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE |
+    EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE |
+    EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE |
+    EFI_RESOURCE_ATTRIBUTE_TESTED,
+    (UINT64)SecCoreData->TemporaryRamBase,
+    (UINT64)SecCoreData->TemporaryRamSize
+    );
+
+  BuildMemoryAllocationHob (
+    FixedPcdGet32 (PcdOvmfSecGhcbBackupBase),
+    FixedPcdGet32 (PcdOvmfSecGhcbBackupSize),
+    EfiACPIMemoryNVS
+    );
+
+  //
+  // Load the DXE Core and transfer control to it.
+  // DXE FV is the 1st FvInstance. (base 0)
+  //
+  Status = DxeLoadCore (1);
+
+  //
+  // Never arrive here.
+  //
+  ASSERT (FALSE);
+  CpuDeadLoop ();
+}
diff --git a/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupInternal.h b/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupInternal.h
new file mode 100644
index 000000000000..7a8c555b65ab
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupInternal.h
@@ -0,0 +1,68 @@
+/** @file
+
+  Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef TDX_STARTUP_INTERNAL_LIB_H_
+#define TDX_STARTUP_INTERNAL_LIB_H_
+
+#include <PiPei.h>
+#include <Library/BaseLib.h>
+#include <Uefi/UefiSpec.h>
+#include <Uefi/UefiBaseType.h>
+#include <IndustryStandard/Tpm20.h>
+#include <IndustryStandard/UefiTcgPlatform.h>
+#include <IndustryStandard/IntelTdx.h>
+
+#pragma pack (1)
+
+#define HANDOFF_TABLE_DESC  "TdxTable"
+typedef struct {
+  UINT8                      TableDescriptionSize;
+  UINT8                      TableDescription[sizeof (HANDOFF_TABLE_DESC)];
+  UINT64                     NumberOfTables;
+  EFI_CONFIGURATION_TABLE    TableEntry[1];
+} TDX_HANDOFF_TABLE_POINTERS2;
+#pragma pack()
+
+#define LOOPIT(X)  do {\
+  volatile int foo = (X); \
+  while (foo) ; \
+} while(0)
+
+EFI_STATUS
+EFIAPI
+DxeLoadCore (
+  IN INTN  FvInstance
+  );
+
+EFI_STATUS
+EFIAPI
+InitPcdPeim (
+  IN INTN  FvInstance
+  );
+
+VOID
+EFIAPI
+TransferHobList (
+  IN CONST VOID  *HobStart
+  );
+
+/**
+ * This function is to find a memory region which is the largest one below 4GB.
+ * It will be used as the firmware hoblist.
+ *
+ * @param VmmHobList        Vmm passed hoblist which constains the memory information.
+ * @return EFI_SUCCESS      Successfully construct the firmware hoblist.
+ * @return EFI_NOT_FOUND    Cannot find a memory region to be the fw hoblist.
+ */
+EFI_STATUS
+EFIAPI
+ConstructFwHobList (
+  IN CONST VOID  *VmmHobList
+  );
+
+#endif
diff --git a/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLib.inf b/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLib.inf
new file mode 100644
index 000000000000..15ccadd1e562
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLib.inf
@@ -0,0 +1,85 @@
+#/** @file
+# Component description file for TDX Pre PI Library
+#
+# LIbrary helps you build a platform that skips PEI and loads DXE Core
+# directly. Helps building HOBs, reading data from the FV, and doing
+# decompression.
+#
+#  Copyright (c) 2018, Intel Corporation. All rights reserved.<BR>
+#  Copyright (c) 2008, Apple Inc. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#
+#**/
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = TdxStartupLib
+  FILE_GUID                      = 8FA74135-F841-40A4-86C8-69C923D2E85F
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = TdxStartupLib|SEC
+
+#
+#  VALID_ARCHITECTURES           = X64
+#
+
+[Sources]
+  TdxStartup.c
+  Hob.c
+  DxeLoad.c
+
+[Sources.X64]
+  X64/VirtualMemory.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
+  UefiCpuPkg/UefiCpuPkg.dec
+  OvmfPkg/OvmfPkg.dec
+  EmbeddedPkg/EmbeddedPkg.dec
+
+[LibraryClasses]
+  BaseLib
+  DebugLib
+  BaseMemoryLib
+  PcdLib
+  UefiCpuLib
+  DebugAgentLib
+  IoLib
+  LocalApicLib
+  SynchronizationLib
+  HobLib
+  TdxLib
+  MemoryAllocationLib
+  TdxPlatformLib
+  PrePiLib
+  QemuFwCfgLib
+
+[Guids]
+  gEfiHobMemoryAllocModuleGuid
+  gEfiHobMemoryAllocStackGuid
+  gUefiOvmfPkgTdxPlatformGuid
+  gEfiMemoryTypeInformationGuid
+  gPcdDataBaseHobGuid
+
+[Pcd]
+  gUefiOvmfPkgTokenSpaceGuid.PcdCfvBase
+  gUefiOvmfPkgTokenSpaceGuid.PcdCfvRawDataOffset
+  gUefiOvmfPkgTokenSpaceGuid.PcdCfvRawDataSize
+  gUefiOvmfPkgTokenSpaceGuid.PcdBfvBase
+  gUefiOvmfPkgTokenSpaceGuid.PcdBfvRawDataOffset
+  gUefiOvmfPkgTokenSpaceGuid.PcdBfvRawDataSize
+  gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBackupBase
+  gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBackupSize
+  gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbSize
+  gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBase
+  gUefiOvmfPkgTokenSpaceGuid.PcdTdxSetNxForStack
+  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplBuildPageTables       ## CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard               ## CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable              ## SOMETIMES_CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy ## SOMETIMES_CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy       ## SOMETIMES_CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask    ## CONSUMES
diff --git a/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLibNull.inf b/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLibNull.inf
new file mode 100644
index 000000000000..e79d266d58ca
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLibNull.inf
@@ -0,0 +1,40 @@
+#/** @file
+# Component description file for TDX Pre PI Library
+#
+# LIbrary helps you build a platform that skips PEI and loads DXE Core
+# directly. Helps building HOBs, reading data from the FV, and doing
+# decompression.
+#
+#  Copyright (c) 2018, Intel Corporation. All rights reserved.<BR>
+#  Copyright (c) 2008, Apple Inc. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#
+#**/
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = TdxStartupLibNull
+  FILE_GUID                      = 79DD2160-D5E0-48CD-AA87-479EACEE8393
+  MODULE_TYPE                    = BASE
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = TdxStartupLib|SEC
+
+#
+#  VALID_ARCHITECTURES           = X64
+#
+
+[Sources]
+  TdxStartupNull.c
+
+[Packages]
+  MdePkg/MdePkg.dec
+  OvmfPkg/OvmfPkg.dec
+
+[LibraryClasses]
+  BaseLib
+  BaseMemoryLib
+  DebugLib
+
+[Pcd]
diff --git a/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupNull.c b/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupNull.c
new file mode 100644
index 000000000000..8c00e813c1f6
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupNull.c
@@ -0,0 +1,19 @@
+/** @file
+  Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/TdxStartupLib.h>
+
+VOID
+EFIAPI
+TdxStartup (
+  IN VOID  *Context
+  )
+{
+  ASSERT (FALSE);
+  CpuDeadLoop ();
+}
diff --git a/OvmfPkg/IntelTdx/TdxStartupLib/X64/PageTables.h b/OvmfPkg/IntelTdx/TdxStartupLib/X64/PageTables.h
new file mode 100644
index 000000000000..a0d0d3547bfa
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdxStartupLib/X64/PageTables.h
@@ -0,0 +1,206 @@
+/** @file
+  x64 Long Mode Virtual Memory Management Definitions
+
+  References:
+    1) IA-32 Intel(R) Architecture Software Developer's Manual Volume 1:Basic Architecture, Intel
+    2) IA-32 Intel(R) Architecture Software Developer's Manual Volume 2:Instruction Set Reference, Intel
+    3) IA-32 Intel(R) Architecture Software Developer's Manual Volume 3:System Programmer's Guide, Intel
+    4) AMD64 Architecture Programmer's Manual Volume 2: System Programming
+
+Copyright (c) 2006 - 2020, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
+
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef PAGE_TABLES_H_
+#define PAGE_TABLES_H_
+
+#define SYS_CODE64_SEL  0x38
+
+#pragma pack(1)
+
+typedef union {
+  struct {
+    UINT32    LimitLow    : 16;
+    UINT32    BaseLow     : 16;
+    UINT32    BaseMid     : 8;
+    UINT32    Type        : 4;
+    UINT32    System      : 1;
+    UINT32    Dpl         : 2;
+    UINT32    Present     : 1;
+    UINT32    LimitHigh   : 4;
+    UINT32    Software    : 1;
+    UINT32    Reserved    : 1;
+    UINT32    DefaultSize : 1;
+    UINT32    Granularity : 1;
+    UINT32    BaseHigh    : 8;
+  } Bits;
+  UINT64    Uint64;
+} IA32_GDT;
+
+typedef struct {
+  IA32_IDT_GATE_DESCRIPTOR    Ia32IdtEntry;
+  UINT32                      Offset32To63;
+  UINT32                      Reserved;
+} X64_IDT_GATE_DESCRIPTOR;
+
+//
+// Page-Map Level-4 Offset (PML4) and
+// Page-Directory-Pointer Offset (PDPE) entries 4K & 2MB
+//
+
+typedef union {
+  struct {
+    UINT64    Present              : 1;  // 0 = Not present in memory, 1 = Present in memory
+    UINT64    ReadWrite            : 1;  // 0 = Read-Only, 1= Read/Write
+    UINT64    UserSupervisor       : 1;  // 0 = Supervisor, 1=User
+    UINT64    WriteThrough         : 1;  // 0 = Write-Back caching, 1=Write-Through caching
+    UINT64    CacheDisabled        : 1;  // 0 = Cached, 1=Non-Cached
+    UINT64    Accessed             : 1;  // 0 = Not accessed, 1 = Accessed (set by CPU)
+    UINT64    Reserved             : 1;  // Reserved
+    UINT64    MustBeZero           : 2;  // Must Be Zero
+    UINT64    Available            : 3;  // Available for use by system software
+    UINT64    PageTableBaseAddress : 40; // Page Table Base Address
+    UINT64    AvabilableHigh       : 11; // Available for use by system software
+    UINT64    Nx                   : 1;  // No Execute bit
+  } Bits;
+  UINT64    Uint64;
+} PAGE_MAP_AND_DIRECTORY_POINTER;
+
+//
+// Page Table Entry 4KB
+//
+typedef union {
+  struct {
+    UINT64    Present              : 1;  // 0 = Not present in memory, 1 = Present in memory
+    UINT64    ReadWrite            : 1;  // 0 = Read-Only, 1= Read/Write
+    UINT64    UserSupervisor       : 1;  // 0 = Supervisor, 1=User
+    UINT64    WriteThrough         : 1;  // 0 = Write-Back caching, 1=Write-Through caching
+    UINT64    CacheDisabled        : 1;  // 0 = Cached, 1=Non-Cached
+    UINT64    Accessed             : 1;  // 0 = Not accessed, 1 = Accessed (set by CPU)
+    UINT64    Dirty                : 1;  // 0 = Not Dirty, 1 = written by processor on access to page
+    UINT64    PAT                  : 1;  //
+    UINT64    Global               : 1;  // 0 = Not global page, 1 = global page TLB not cleared on CR3 write
+    UINT64    Available            : 3;  // Available for use by system software
+    UINT64    PageTableBaseAddress : 40; // Page Table Base Address
+    UINT64    AvabilableHigh       : 11; // Available for use by system software
+    UINT64    Nx                   : 1;  // 0 = Execute Code, 1 = No Code Execution
+  } Bits;
+  UINT64    Uint64;
+} PAGE_TABLE_4K_ENTRY;
+
+//
+// Page Table Entry 2MB
+//
+typedef union {
+  struct {
+    UINT64    Present              : 1;  // 0 = Not present in memory, 1 = Present in memory
+    UINT64    ReadWrite            : 1;  // 0 = Read-Only, 1= Read/Write
+    UINT64    UserSupervisor       : 1;  // 0 = Supervisor, 1=User
+    UINT64    WriteThrough         : 1;  // 0 = Write-Back caching, 1=Write-Through caching
+    UINT64    CacheDisabled        : 1;  // 0 = Cached, 1=Non-Cached
+    UINT64    Accessed             : 1;  // 0 = Not accessed, 1 = Accessed (set by CPU)
+    UINT64    Dirty                : 1;  // 0 = Not Dirty, 1 = written by processor on access to page
+    UINT64    MustBe1              : 1;  // Must be 1
+    UINT64    Global               : 1;  // 0 = Not global page, 1 = global page TLB not cleared on CR3 write
+    UINT64    Available            : 3;  // Available for use by system software
+    UINT64    PAT                  : 1;  //
+    UINT64    MustBeZero           : 8;  // Must be zero;
+    UINT64    PageTableBaseAddress : 31; // Page Table Base Address
+    UINT64    AvabilableHigh       : 11; // Available for use by system software
+    UINT64    Nx                   : 1;  // 0 = Execute Code, 1 = No Code Execution
+  } Bits;
+  UINT64    Uint64;
+} PAGE_TABLE_ENTRY;
+
+//
+// Page Table Entry 1GB
+//
+typedef union {
+  struct {
+    UINT64    Present              : 1;  // 0 = Not present in memory, 1 = Present in memory
+    UINT64    ReadWrite            : 1;  // 0 = Read-Only, 1= Read/Write
+    UINT64    UserSupervisor       : 1;  // 0 = Supervisor, 1=User
+    UINT64    WriteThrough         : 1;  // 0 = Write-Back caching, 1=Write-Through caching
+    UINT64    CacheDisabled        : 1;  // 0 = Cached, 1=Non-Cached
+    UINT64    Accessed             : 1;  // 0 = Not accessed, 1 = Accessed (set by CPU)
+    UINT64    Dirty                : 1;  // 0 = Not Dirty, 1 = written by processor on access to page
+    UINT64    MustBe1              : 1;  // Must be 1
+    UINT64    Global               : 1;  // 0 = Not global page, 1 = global page TLB not cleared on CR3 write
+    UINT64    Available            : 3;  // Available for use by system software
+    UINT64    PAT                  : 1;  //
+    UINT64    MustBeZero           : 17; // Must be zero;
+    UINT64    PageTableBaseAddress : 22; // Page Table Base Address
+    UINT64    AvabilableHigh       : 11; // Available for use by system software
+    UINT64    Nx                   : 1;  // 0 = Execute Code, 1 = No Code Execution
+  } Bits;
+  UINT64    Uint64;
+} PAGE_TABLE_1G_ENTRY;
+
+#pragma pack()
+
+#define CR0_WP  BIT16
+
+#define IA32_PG_P   BIT0
+#define IA32_PG_RW  BIT1
+#define IA32_PG_PS  BIT7
+
+#define PAGING_PAE_INDEX_MASK  0x1FF
+
+#define PAGING_4K_ADDRESS_MASK_64  0x000FFFFFFFFFF000ull
+#define PAGING_2M_ADDRESS_MASK_64  0x000FFFFFFFE00000ull
+#define PAGING_1G_ADDRESS_MASK_64  0x000FFFFFC0000000ull
+
+#define PAGING_L1_ADDRESS_SHIFT  12
+#define PAGING_L2_ADDRESS_SHIFT  21
+#define PAGING_L3_ADDRESS_SHIFT  30
+#define PAGING_L4_ADDRESS_SHIFT  39
+
+#define PAGING_PML4E_NUMBER  4
+
+#define PAGE_TABLE_POOL_ALIGNMENT   BASE_2MB
+#define PAGE_TABLE_POOL_UNIT_SIZE   SIZE_2MB
+#define PAGE_TABLE_POOL_UNIT_PAGES  EFI_SIZE_TO_PAGES (PAGE_TABLE_POOL_UNIT_SIZE)
+#define PAGE_TABLE_POOL_ALIGN_MASK  \
+  (~(EFI_PHYSICAL_ADDRESS)(PAGE_TABLE_POOL_ALIGNMENT - 1))
+
+typedef struct {
+  VOID     *NextPool;
+  UINTN    Offset;
+  UINTN    FreePages;
+} PAGE_TABLE_POOL;
+
+UINTN
+CreateIdentityMappingPageTables (
+  IN EFI_PHYSICAL_ADDRESS  StackBase,
+  IN UINTN                 StackSize
+  );
+
+/**
+  Clear legacy memory located at the first 4K-page.
+
+  This function traverses the whole HOB list to check if memory from 0 to 4095
+  exists and has not been allocated, and then clear it if so.
+
+  @param HobStart         The start of HobList passed to DxeCore.
+
+**/
+VOID
+ClearFirst4KPage (
+  IN  VOID  *HobStart
+  );
+
+/**
+  Return configure status of NULL pointer detection feature.
+
+  @return TRUE   NULL pointer detection feature is enabled
+  @return FALSE  NULL pointer detection feature is disabled
+**/
+BOOLEAN
+IsNullDetectionEnabled (
+  VOID
+  );
+
+#endif
diff --git a/OvmfPkg/IntelTdx/TdxStartupLib/X64/VirtualMemory.c b/OvmfPkg/IntelTdx/TdxStartupLib/X64/VirtualMemory.c
new file mode 100644
index 000000000000..b7c21c519f59
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdxStartupLib/X64/VirtualMemory.c
@@ -0,0 +1,915 @@
+/** @file
+  x64-specifc functionality for Page Table Setup.
+
+Copyright (c) 2006 - 2020, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <Uefi/UefiBaseType.h>
+#include <Uefi/UefiSpec.h>
+#include <Pi/PiBootMode.h>
+#include <Pi/PiHob.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseLib.h>
+#include <Library/HobLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/PcdLib.h>
+#include <Guid/MemoryTypeInformation.h>
+#include <Guid/MemoryAllocationHob.h>
+#include <Register/Intel/Cpuid.h>
+#include "PageTables.h"
+
+//
+// Global variable to keep track current available memory used as page table.
+//
+PAGE_TABLE_POOL  *mPageTablePool = NULL;
+
+UINTN  mLevelShift[5] = {
+  0,
+  PAGING_L1_ADDRESS_SHIFT,
+  PAGING_L2_ADDRESS_SHIFT,
+  PAGING_L3_ADDRESS_SHIFT,
+  PAGING_L4_ADDRESS_SHIFT
+};
+
+UINT64  mLevelMask[5] = {
+  0,
+  PAGING_4K_ADDRESS_MASK_64,
+  PAGING_2M_ADDRESS_MASK_64,
+  PAGING_1G_ADDRESS_MASK_64,
+  PAGING_1G_ADDRESS_MASK_64
+};
+
+UINT64  mLevelSize[5] = {
+  0,
+  SIZE_4KB,
+  SIZE_2MB,
+  SIZE_1GB,
+  SIZE_512GB
+};
+
+/**
+  Clear legacy memory located at the first 4K-page, if available.
+
+  This function traverses the whole HOB list to check if memory from 0 to 4095
+  exists and has not been allocated, and then clear it if so.
+
+  @param HobStart                  The start of HobList passed to DxeCore.
+
+**/
+VOID
+ClearFirst4KPage (
+  IN  VOID  *HobStart
+  )
+{
+  EFI_PEI_HOB_POINTERS  RscHob;
+  EFI_PEI_HOB_POINTERS  MemHob;
+  BOOLEAN               DoClear;
+
+  RscHob.Raw = HobStart;
+  MemHob.Raw = HobStart;
+  DoClear    = FALSE;
+
+  //
+  // Check if page 0 exists and free
+  //
+  while ((RscHob.Raw = GetNextHob (
+                         EFI_HOB_TYPE_RESOURCE_DESCRIPTOR,
+                         RscHob.Raw
+                         )) != NULL)
+  {
+    if ((RscHob.ResourceDescriptor->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) &&
+        (RscHob.ResourceDescriptor->PhysicalStart == 0))
+    {
+      DoClear = TRUE;
+      //
+      // Make sure memory at 0-4095 has not been allocated.
+      //
+      while ((MemHob.Raw = GetNextHob (
+                             EFI_HOB_TYPE_MEMORY_ALLOCATION,
+                             MemHob.Raw
+                             )) != NULL)
+      {
+        if (MemHob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress
+            < EFI_PAGE_SIZE)
+        {
+          DoClear = FALSE;
+          break;
+        }
+
+        MemHob.Raw = GET_NEXT_HOB (MemHob);
+      }
+
+      break;
+    }
+
+    RscHob.Raw = GET_NEXT_HOB (RscHob);
+  }
+
+  if (DoClear) {
+    DEBUG ((DEBUG_INFO, "Clearing first 4K-page!\r\n"));
+    SetMem (NULL, EFI_PAGE_SIZE, 0);
+  }
+
+  return;
+}
+
+/**
+  Return configure status of NULL pointer detection feature.
+
+  @return TRUE   NULL pointer detection feature is enabled
+  @return FALSE  NULL pointer detection feature is disabled
+
+**/
+BOOLEAN
+IsNullDetectionEnabled (
+  VOID
+  )
+{
+  return ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT0) != 0);
+}
+
+/**
+  The function will check if Execute Disable Bit is available.
+
+  @retval TRUE      Execute Disable Bit is available.
+  @retval FALSE     Execute Disable Bit is not available.
+
+**/
+BOOLEAN
+IsExecuteDisableBitAvailable (
+  VOID
+  )
+{
+  UINT32   RegEax;
+  UINT32   RegEdx;
+  BOOLEAN  Available;
+
+  Available = FALSE;
+  AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);
+  if (RegEax >= 0x80000001) {
+    AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx);
+    if ((RegEdx & BIT20) != 0) {
+      //
+      // Bit 20: Execute Disable Bit available.
+      //
+      Available = TRUE;
+    }
+  }
+
+  return Available;
+}
+
+/**
+  Check if Execute Disable Bit (IA32_EFER.NXE) should be enabled or not.
+
+  @retval TRUE    IA32_EFER.NXE should be enabled.
+  @retval FALSE   IA32_EFER.NXE should not be enabled.
+
+**/
+BOOLEAN
+IsEnableNonExecNeeded (
+  VOID
+  )
+{
+  if (!IsExecuteDisableBitAvailable ()) {
+    return FALSE;
+  }
+
+  //
+  // XD flag (BIT63) in page table entry is only valid if IA32_EFER.NXE is set.
+  // Features controlled by Following PCDs need this feature to be enabled.
+  //
+  return (FixedPcdGetBool (PcdTdxSetNxForStack) ||
+          FixedPcdGet64 (PcdDxeNxMemoryProtectionPolicy) != 0 ||
+          PcdGet32 (PcdImageProtectionPolicy) != 0);
+}
+
+/**
+  Enable Execute Disable Bit.
+
+**/
+VOID
+EnableExecuteDisableBit (
+  VOID
+  )
+{
+  UINT64  MsrRegisters;
+
+  MsrRegisters  = AsmReadMsr64 (0xC0000080);
+  MsrRegisters |= BIT11;
+  AsmWriteMsr64 (0xC0000080, MsrRegisters);
+}
+
+/**
+  The function will check if page table entry should be splitted to smaller
+  granularity.
+
+  @param Address      Physical memory address.
+  @param Size         Size of the given physical memory.
+  @param StackBase    Base address of stack.
+  @param StackSize    Size of stack.
+
+  @retval TRUE      Page table should be split.
+  @retval FALSE     Page table should not be split.
+**/
+BOOLEAN
+ToSplitPageTable (
+  IN EFI_PHYSICAL_ADDRESS  Address,
+  IN UINTN                 Size,
+  IN EFI_PHYSICAL_ADDRESS  StackBase,
+  IN UINTN                 StackSize
+  )
+{
+  if (IsNullDetectionEnabled () && (Address == 0)) {
+    return TRUE;
+  }
+
+  if (FixedPcdGetBool (PcdCpuStackGuard)) {
+    if ((StackBase >= Address) && (StackBase < (Address + Size))) {
+      return TRUE;
+    }
+  }
+
+  if (FixedPcdGetBool (PcdTdxSetNxForStack)) {
+    if ((Address < StackBase + StackSize) && ((Address + Size) > StackBase)) {
+      return TRUE;
+    }
+  }
+
+  return FALSE;
+}
+
+/**
+  Initialize a buffer pool for page table use only.
+
+  To reduce the potential split operation on page table, the pages reserved for
+  page table should be allocated in the times of PAGE_TABLE_POOL_UNIT_PAGES and
+  at the boundary of PAGE_TABLE_POOL_ALIGNMENT. So the page pool is always
+  initialized with number of pages greater than or equal to the given PoolPages.
+
+  Once the pages in the pool are used up, this method should be called again to
+  reserve at least another PAGE_TABLE_POOL_UNIT_PAGES. But usually this won't
+  happen in practice.
+
+  @param PoolPages  The least page number of the pool to be created.
+
+  @retval TRUE    The pool is initialized successfully.
+  @retval FALSE   The memory is out of resource.
+**/
+BOOLEAN
+InitializePageTablePool (
+  IN UINTN  PoolPages
+  )
+{
+  VOID  *Buffer;
+
+  DEBUG ((DEBUG_INFO, "InitializePageTablePool PoolPages=%d\n", PoolPages));
+
+  //
+  // Always reserve at least PAGE_TABLE_POOL_UNIT_PAGES, including one page for
+  // header.
+  //
+  PoolPages += 1;   // Add one page for header.
+  PoolPages  = ((PoolPages - 1) / PAGE_TABLE_POOL_UNIT_PAGES + 1) *
+               PAGE_TABLE_POOL_UNIT_PAGES;
+  Buffer = AllocateAlignedPages (PoolPages, PAGE_TABLE_POOL_ALIGNMENT);
+  if (Buffer == NULL) {
+    DEBUG ((DEBUG_ERROR, "ERROR: Out of aligned pages\r\n"));
+    return FALSE;
+  }
+
+  //
+  // Link all pools into a list for easier track later.
+  //
+  if (mPageTablePool == NULL) {
+    mPageTablePool           = Buffer;
+    mPageTablePool->NextPool = mPageTablePool;
+  } else {
+    ((PAGE_TABLE_POOL *)Buffer)->NextPool = mPageTablePool->NextPool;
+    mPageTablePool->NextPool              = Buffer;
+    mPageTablePool                        = Buffer;
+  }
+
+  //
+  // Reserve one page for pool header.
+  //
+  mPageTablePool->FreePages = PoolPages - 1;
+  mPageTablePool->Offset    = EFI_PAGES_TO_SIZE (1);
+
+  return TRUE;
+}
+
+/**
+  This API provides a way to allocate memory for page table.
+
+  This API can be called more than once to allocate memory for page tables.
+
+  Allocates the number of 4KB pages and returns a pointer to the allocated
+  buffer. The buffer returned is aligned on a 4KB boundary.
+
+  If Pages is 0, then NULL is returned.
+  If there is not enough memory remaining to satisfy the request, then NULL is
+  returned.
+
+  @param  Pages                 The number of 4 KB pages to allocate.
+
+  @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+AllocatePageTableMemory (
+  IN UINTN  Pages
+  )
+{
+  VOID  *Buffer;
+
+  if (Pages == 0) {
+    return NULL;
+  }
+
+  DEBUG ((DEBUG_INFO, "AllocatePageTableMemory. mPageTablePool=%p, Pages=%d\n", mPageTablePool, Pages));
+  //
+  // Renew the pool if necessary.
+  //
+  if ((mPageTablePool == NULL) ||
+      (Pages > mPageTablePool->FreePages))
+  {
+    if (!InitializePageTablePool (Pages)) {
+      return NULL;
+    }
+  }
+
+  Buffer = (UINT8 *)mPageTablePool + mPageTablePool->Offset;
+
+  mPageTablePool->Offset    += EFI_PAGES_TO_SIZE (Pages);
+  mPageTablePool->FreePages -= Pages;
+
+  DEBUG ((
+    DEBUG_INFO,
+    "%a:%a: Buffer=0x%Lx Pages=%ld\n",
+    gEfiCallerBaseName,
+    __FUNCTION__,
+    Buffer,
+    Pages
+    ));
+
+  return Buffer;
+}
+
+/**
+  Split 2M page to 4K.
+
+  @param[in]      PhysicalAddress       Start physical address the 2M page covered.
+  @param[in, out] PageEntry2M           Pointer to 2M page entry.
+  @param[in]      StackBase             Stack base address.
+  @param[in]      StackSize             Stack size.
+
+**/
+VOID
+Split2MPageTo4K (
+  IN EFI_PHYSICAL_ADDRESS  PhysicalAddress,
+  IN OUT UINT64            *PageEntry2M,
+  IN EFI_PHYSICAL_ADDRESS  StackBase,
+  IN UINTN                 StackSize
+  )
+{
+  EFI_PHYSICAL_ADDRESS  PhysicalAddress4K;
+  UINTN                 IndexOfPageTableEntries;
+  PAGE_TABLE_4K_ENTRY   *PageTableEntry;
+
+  DEBUG ((DEBUG_INFO, "Split2MPageTo4K\n"));
+
+  PageTableEntry = AllocatePageTableMemory (1);
+
+  if (PageTableEntry == NULL) {
+    ASSERT (FALSE);
+    return;
+  }
+
+  //
+  // Fill in 2M page entry.
+  //
+  *PageEntry2M = (UINT64)(UINTN)PageTableEntry | IA32_PG_P | IA32_PG_RW;
+
+  PhysicalAddress4K = PhysicalAddress;
+  for (IndexOfPageTableEntries = 0; IndexOfPageTableEntries < 512; IndexOfPageTableEntries++, PageTableEntry++, PhysicalAddress4K += SIZE_4KB) {
+    //
+    // Fill in the Page Table entries
+    //
+    PageTableEntry->Uint64         = (UINT64)PhysicalAddress4K;
+    PageTableEntry->Bits.ReadWrite = 1;
+
+    if ((IsNullDetectionEnabled () && (PhysicalAddress4K == 0)) ||
+        (FixedPcdGetBool (PcdCpuStackGuard) && (PhysicalAddress4K == StackBase)))
+    {
+      PageTableEntry->Bits.Present = 0;
+    } else {
+      PageTableEntry->Bits.Present = 1;
+    }
+
+    if (  FixedPcdGetBool (PcdTdxSetNxForStack)
+       && (PhysicalAddress4K >= StackBase)
+       && (PhysicalAddress4K < StackBase + StackSize))
+    {
+      //
+      // Set Nx bit for stack.
+      //
+      PageTableEntry->Bits.Nx = 1;
+    }
+  }
+}
+
+/**
+  Split 1G page to 2M.
+
+  @param[in]      PhysicalAddress       Start physical address the 1G page covered.
+  @param[in, out] PageEntry1G           Pointer to 1G page entry.
+  @param[in]      StackBase             Stack base address.
+  @param[in]      StackSize             Stack size.
+
+**/
+VOID
+Split1GPageTo2M (
+  IN EFI_PHYSICAL_ADDRESS  PhysicalAddress,
+  IN OUT UINT64            *PageEntry1G,
+  IN EFI_PHYSICAL_ADDRESS  StackBase,
+  IN UINTN                 StackSize
+  )
+{
+  EFI_PHYSICAL_ADDRESS  PhysicalAddress2M;
+  UINTN                 IndexOfPageDirectoryEntries;
+  PAGE_TABLE_ENTRY      *PageDirectoryEntry;
+
+  PageDirectoryEntry = AllocatePageTableMemory (1);
+
+  if (PageDirectoryEntry == NULL) {
+    ASSERT (FALSE);
+    return;
+  }
+
+  //
+  // Fill in 1G page entry.
+  //
+  *PageEntry1G = (UINT64)(UINTN)PageDirectoryEntry | IA32_PG_P | IA32_PG_RW;
+
+  PhysicalAddress2M = PhysicalAddress;
+  for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectoryEntry++, PhysicalAddress2M += SIZE_2MB) {
+    if (ToSplitPageTable (PhysicalAddress2M, SIZE_2MB, StackBase, StackSize)) {
+      //
+      // Need to split this 2M page that covers NULL or stack range.
+      //
+      Split2MPageTo4K (PhysicalAddress2M, (UINT64 *)PageDirectoryEntry, StackBase, StackSize);
+    } else {
+      //
+      // Fill in the Page Directory entries
+      //
+      PageDirectoryEntry->Uint64         = (UINT64)PhysicalAddress2M;
+      PageDirectoryEntry->Bits.ReadWrite = 1;
+      PageDirectoryEntry->Bits.Present   = 1;
+      PageDirectoryEntry->Bits.MustBe1   = 1;
+    }
+  }
+}
+
+/**
+  Set one page of page table pool memory to be read-only.
+
+  @param[in] PageTableBase    Base address of page table (CR3).
+  @param[in] Address          Start address of a page to be set as read-only.
+  @param[in] Level4Paging     Level 4 paging flag.
+
+**/
+VOID
+SetPageTablePoolReadOnly (
+  IN  UINTN                 PageTableBase,
+  IN  EFI_PHYSICAL_ADDRESS  Address,
+  IN  BOOLEAN               Level4Paging
+  )
+{
+  UINTN                 Index;
+  UINTN                 EntryIndex;
+  EFI_PHYSICAL_ADDRESS  PhysicalAddress;
+  UINT64                *PageTable;
+  UINT64                *NewPageTable;
+  UINT64                PageAttr;
+  UINTN                 Level;
+  UINT64                PoolUnitSize;
+
+  if (PageTableBase == 0) {
+    ASSERT (FALSE);
+    return;
+  }
+
+  //
+  // Since the page table is always from page table pool, which is always
+  // located at the boundary of PcdPageTablePoolAlignment, we just need to
+  // set the whole pool unit to be read-only.
+  //
+  Address = Address & PAGE_TABLE_POOL_ALIGN_MASK;
+
+  PageTable    = (UINT64 *)(UINTN)PageTableBase;
+  PoolUnitSize = PAGE_TABLE_POOL_UNIT_SIZE;
+
+  for (Level = (Level4Paging) ? 4 : 3; Level > 0; --Level) {
+    Index  = ((UINTN)RShiftU64 (Address, mLevelShift[Level]));
+    Index &= PAGING_PAE_INDEX_MASK;
+
+    PageAttr = PageTable[Index];
+    if ((PageAttr & IA32_PG_PS) == 0) {
+      //
+      // Go to next level of table.
+      //
+      PageTable = (UINT64 *)(UINTN)(PageAttr & PAGING_4K_ADDRESS_MASK_64);
+      continue;
+    }
+
+    if (PoolUnitSize >= mLevelSize[Level]) {
+      //
+      // Clear R/W bit if current page granularity is not larger than pool unit
+      // size.
+      //
+      if ((PageAttr & IA32_PG_RW) != 0) {
+        while (PoolUnitSize > 0) {
+          //
+          // PAGE_TABLE_POOL_UNIT_SIZE and PAGE_TABLE_POOL_ALIGNMENT are fit in
+          // one page (2MB). Then we don't need to update attributes for pages
+          // crossing page directory. ASSERT below is for that purpose.
+          //
+          ASSERT (Index < EFI_PAGE_SIZE/sizeof (UINT64));
+
+          PageTable[Index] &= ~(UINT64)IA32_PG_RW;
+          PoolUnitSize     -= mLevelSize[Level];
+
+          ++Index;
+        }
+      }
+
+      break;
+    } else {
+      //
+      // The smaller granularity of page must be needed.
+      //
+      ASSERT (Level > 1);
+
+      NewPageTable = AllocatePageTableMemory (1);
+
+      if (NewPageTable == NULL) {
+        ASSERT (FALSE);
+        return;
+      }
+
+      PhysicalAddress = PageAttr & mLevelMask[Level];
+      for (EntryIndex = 0;
+           EntryIndex < EFI_PAGE_SIZE/sizeof (UINT64);
+           ++EntryIndex)
+      {
+        NewPageTable[EntryIndex] = PhysicalAddress |
+                                   IA32_PG_P | IA32_PG_RW;
+        if (Level > 2) {
+          NewPageTable[EntryIndex] |= IA32_PG_PS;
+        }
+
+        PhysicalAddress += mLevelSize[Level - 1];
+      }
+
+      PageTable[Index] = (UINT64)(UINTN)NewPageTable |
+                         IA32_PG_P | IA32_PG_RW;
+      PageTable = NewPageTable;
+    }
+  }
+}
+
+/**
+  Prevent the memory pages used for page table from been overwritten.
+
+  @param[in] PageTableBase    Base address of page table (CR3).
+  @param[in] Level4Paging     Level 4 paging flag.
+
+**/
+VOID
+EnablePageTableProtection (
+  IN  UINTN    PageTableBase,
+  IN  BOOLEAN  Level4Paging
+  )
+{
+  PAGE_TABLE_POOL       *HeadPool;
+  PAGE_TABLE_POOL       *Pool;
+  UINT64                PoolSize;
+  EFI_PHYSICAL_ADDRESS  Address;
+
+  DEBUG ((DEBUG_INFO, "EnablePageTableProtection\n"));
+
+  if (mPageTablePool == NULL) {
+    return;
+  }
+
+  //
+  // Disable write protection, because we need to mark page table to be write
+  // protected.
+  //
+  AsmWriteCr0 (AsmReadCr0 () & ~CR0_WP);
+
+  //
+  // SetPageTablePoolReadOnly might update mPageTablePool. It's safer to
+  // remember original one in advance.
+  //
+  HeadPool = mPageTablePool;
+  Pool     = HeadPool;
+  do {
+    Address  = (EFI_PHYSICAL_ADDRESS)(UINTN)Pool;
+    PoolSize = Pool->Offset + EFI_PAGES_TO_SIZE (Pool->FreePages);
+
+    //
+    // The size of one pool must be multiple of PAGE_TABLE_POOL_UNIT_SIZE, which
+    // is one of page size of the processor (2MB by default). Let's apply the
+    // protection to them one by one.
+    //
+    while (PoolSize > 0) {
+      SetPageTablePoolReadOnly (PageTableBase, Address, Level4Paging);
+      Address  += PAGE_TABLE_POOL_UNIT_SIZE;
+      PoolSize -= PAGE_TABLE_POOL_UNIT_SIZE;
+    }
+
+    Pool = Pool->NextPool;
+  } while (Pool != HeadPool);
+
+  //
+  // Enable write protection, after page table attribute updated.
+  //
+  AsmWriteCr0 (AsmReadCr0 () | CR0_WP);
+}
+
+/**
+  Allocates and fills in the Page Directory and Page Table Entries to
+  establish a 1:1 Virtual to Physical mapping.
+
+  @param[in] StackBase  Stack base address.
+  @param[in] StackSize  Stack size.
+
+  @return The address of 4 level page map.
+
+**/
+UINTN
+CreateIdentityMappingPageTables (
+  IN EFI_PHYSICAL_ADDRESS  StackBase,
+  IN UINTN                 StackSize
+  )
+{
+  UINT32                          RegEax;
+  UINT32                          RegEdx;
+  UINT8                           PhysicalAddressBits;
+  EFI_PHYSICAL_ADDRESS            PageAddress;
+  UINTN                           IndexOfPml5Entries;
+  UINTN                           IndexOfPml4Entries;
+  UINTN                           IndexOfPdpEntries;
+  UINTN                           IndexOfPageDirectoryEntries;
+  UINT32                          NumberOfPml5EntriesNeeded;
+  UINT32                          NumberOfPml4EntriesNeeded;
+  UINT32                          NumberOfPdpEntriesNeeded;
+  PAGE_MAP_AND_DIRECTORY_POINTER  *PageMapLevel5Entry;
+  PAGE_MAP_AND_DIRECTORY_POINTER  *PageMapLevel4Entry;
+  PAGE_MAP_AND_DIRECTORY_POINTER  *PageMap;
+  PAGE_MAP_AND_DIRECTORY_POINTER  *PageDirectoryPointerEntry;
+  PAGE_TABLE_ENTRY                *PageDirectoryEntry;
+  UINTN                           TotalPagesNum;
+  UINTN                           BigPageAddress;
+  VOID                            *Hob;
+  BOOLEAN                         Page5LevelSupport;
+  BOOLEAN                         Page1GSupport;
+  PAGE_TABLE_1G_ENTRY             *PageDirectory1GEntry;
+  IA32_CR4                        Cr4;
+
+  //
+  // Set PageMapLevel5Entry to suppress incorrect compiler/analyzer warnings
+  //
+  PageMapLevel5Entry = NULL;
+
+  Page1GSupport = FALSE;
+  if (FixedPcdGetBool (PcdUse1GPageTable)) {
+    AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);
+    if (RegEax >= 0x80000001) {
+      AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx);
+      if ((RegEdx & BIT26) != 0) {
+        Page1GSupport = TRUE;
+      }
+    }
+  }
+
+  //
+  // Get physical address bits supported.
+  //
+  Hob = GetFirstHob (EFI_HOB_TYPE_CPU);
+  if (Hob == NULL) {
+    ASSERT (FALSE);
+    return 0;
+  }
+
+  PhysicalAddressBits = ((EFI_HOB_CPU *)Hob)->SizeOfMemorySpace;
+
+  //
+  // CPU will already have LA57 enabled so just check CR4
+  Cr4.UintN         = AsmReadCr4 ();
+  Page5LevelSupport = (Cr4.Bits.LA57 ? TRUE : FALSE);
+
+  DEBUG ((
+    DEBUG_INFO,
+    "AddressBits=%u 5LevelPaging=%u 1GPage=%u \n",
+    PhysicalAddressBits,
+    Page5LevelSupport,
+    Page1GSupport
+    ));
+
+  //
+  // Calculate the table entries needed.
+  //
+  NumberOfPml5EntriesNeeded = 1;
+  if (PhysicalAddressBits > 48) {
+    NumberOfPml5EntriesNeeded = (UINT32)LShiftU64 (1, PhysicalAddressBits - 48);
+    PhysicalAddressBits       = 48;
+  }
+
+  NumberOfPml4EntriesNeeded = 1;
+  if (PhysicalAddressBits > 39) {
+    NumberOfPml4EntriesNeeded = (UINT32)LShiftU64 (1, PhysicalAddressBits - 39);
+    PhysicalAddressBits       = 39;
+  }
+
+  NumberOfPdpEntriesNeeded = 1;
+  ASSERT (PhysicalAddressBits > 30);
+  NumberOfPdpEntriesNeeded = (UINT32)LShiftU64 (1, PhysicalAddressBits - 30);
+
+  //
+  // Pre-allocate big pages to avoid later allocations.
+  //
+  if (!Page1GSupport) {
+    TotalPagesNum = ((NumberOfPdpEntriesNeeded + 1) * NumberOfPml4EntriesNeeded + 1) * NumberOfPml5EntriesNeeded + 1;
+  } else {
+    TotalPagesNum = (NumberOfPml4EntriesNeeded + 1) * NumberOfPml5EntriesNeeded + 1;
+  }
+
+  //
+  // Substract the one page occupied by PML5 entries if 5-Level Paging is disabled.
+  //
+  if (!Page5LevelSupport) {
+    TotalPagesNum--;
+  }
+
+  DEBUG ((
+    DEBUG_INFO,
+    "Pml5=%u Pml4=%u Pdp=%u TotalPage=%Lu\n",
+    NumberOfPml5EntriesNeeded,
+    NumberOfPml4EntriesNeeded,
+    NumberOfPdpEntriesNeeded,
+    (UINT64)TotalPagesNum
+    ));
+
+  BigPageAddress = (UINTN)AllocatePageTableMemory (TotalPagesNum);
+  if (BigPageAddress == 0) {
+    ASSERT (FALSE);
+    return 0;
+  }
+
+  DEBUG ((DEBUG_INFO, "BigPageAddress = 0x%llx\n", BigPageAddress));
+
+  //
+  // By architecture only one PageMapLevel4 exists - so lets allocate storage for it.
+  //
+  PageMap = (VOID *)BigPageAddress;
+  if (Page5LevelSupport) {
+    //
+    // By architecture only one PageMapLevel5 exists - so lets allocate storage for it.
+    //
+    PageMapLevel5Entry = PageMap;
+    BigPageAddress    += SIZE_4KB;
+  }
+
+  PageAddress = 0;
+
+  for ( IndexOfPml5Entries = 0
+        ; IndexOfPml5Entries < NumberOfPml5EntriesNeeded
+        ; IndexOfPml5Entries++)
+  {
+    //
+    // Each PML5 entry points to a page of PML4 entires.
+    // So lets allocate space for them and fill them in in the IndexOfPml4Entries loop.
+    // When 5-Level Paging is disabled, below allocation happens only once.
+    //
+    PageMapLevel4Entry = (VOID *)BigPageAddress;
+    BigPageAddress    += SIZE_4KB;
+
+    if (Page5LevelSupport) {
+      //
+      // Make a PML5 Entry
+      //
+      PageMapLevel5Entry->Uint64         = (UINT64)(UINTN)PageMapLevel4Entry;
+      PageMapLevel5Entry->Bits.ReadWrite = 1;
+      PageMapLevel5Entry->Bits.Present   = 1;
+      PageMapLevel5Entry++;
+    }
+
+    for ( IndexOfPml4Entries = 0
+          ; IndexOfPml4Entries < (NumberOfPml5EntriesNeeded == 1 ? NumberOfPml4EntriesNeeded : 512)
+          ; IndexOfPml4Entries++, PageMapLevel4Entry++)
+    {
+      //
+      // Each PML4 entry points to a page of Page Directory Pointer entires.
+      // So lets allocate space for them and fill them in in the IndexOfPdpEntries loop.
+      //
+      PageDirectoryPointerEntry = (VOID *)BigPageAddress;
+      BigPageAddress           += SIZE_4KB;
+
+      //
+      // Make a PML4 Entry
+      //
+      PageMapLevel4Entry->Uint64         = (UINT64)(UINTN)PageDirectoryPointerEntry;
+      PageMapLevel4Entry->Bits.ReadWrite = 1;
+      PageMapLevel4Entry->Bits.Present   = 1;
+
+      if (Page1GSupport) {
+        PageDirectory1GEntry = (VOID *)PageDirectoryPointerEntry;
+
+        for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectory1GEntry++, PageAddress += SIZE_1GB) {
+          if (ToSplitPageTable (PageAddress, SIZE_1GB, StackBase, StackSize)) {
+            Split1GPageTo2M (
+              PageAddress,
+              (UINT64 *)PageDirectory1GEntry,
+              StackBase,
+              StackSize
+              );
+          } else {
+            //
+            // Fill in the Page Directory entries
+            //
+            PageDirectory1GEntry->Uint64         = (UINT64)PageAddress;
+            PageDirectory1GEntry->Bits.ReadWrite = 1;
+            PageDirectory1GEntry->Bits.Present   = 1;
+            PageDirectory1GEntry->Bits.MustBe1   = 1;
+          }
+        }
+      } else {
+        for ( IndexOfPdpEntries = 0
+              ; IndexOfPdpEntries < (NumberOfPml4EntriesNeeded == 1 ? NumberOfPdpEntriesNeeded : 512)
+              ; IndexOfPdpEntries++, PageDirectoryPointerEntry++)
+        {
+          //
+          // Each Directory Pointer entries points to a page of Page Directory entires.
+          // So allocate space for them and fill them in in the IndexOfPageDirectoryEntries loop.
+          //
+          PageDirectoryEntry = (VOID *)BigPageAddress;
+          BigPageAddress    += SIZE_4KB;
+
+          //
+          // Fill in a Page Directory Pointer Entries
+          //
+          PageDirectoryPointerEntry->Uint64         = (UINT64)(UINTN)PageDirectoryEntry;
+          PageDirectoryPointerEntry->Bits.ReadWrite = 1;
+          PageDirectoryPointerEntry->Bits.Present   = 1;
+
+          for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectoryEntry++, PageAddress += SIZE_2MB) {
+            if (ToSplitPageTable (PageAddress, SIZE_2MB, StackBase, StackSize)) {
+              //
+              // Need to split this 2M page that covers NULL or stack range.
+              //
+              Split2MPageTo4K (PageAddress, (UINT64 *)PageDirectoryEntry, StackBase, StackSize);
+            } else {
+              //
+              // Fill in the Page Directory entries
+              //
+              PageDirectoryEntry->Uint64         = (UINT64)PageAddress;
+              PageDirectoryEntry->Bits.ReadWrite = 1;
+              PageDirectoryEntry->Bits.Present   = 1;
+              PageDirectoryEntry->Bits.MustBe1   = 1;
+            }
+          }
+        }
+
+        //
+        // Fill with null entry for unused PDPTE
+        //
+        ZeroMem (PageDirectoryPointerEntry, (512 - IndexOfPdpEntries) * sizeof (PAGE_MAP_AND_DIRECTORY_POINTER));
+      }
+    }
+
+    //
+    // For the PML4 entries we are not using fill in a null entry.
+    //
+    ZeroMem (PageMapLevel4Entry, (512 - IndexOfPml4Entries) * sizeof (PAGE_MAP_AND_DIRECTORY_POINTER));
+  }
+
+  if (Page5LevelSupport) {
+    //
+    // For the PML5 entries we are not using fill in a null entry.
+    //
+    ZeroMem (PageMapLevel5Entry, (512 - IndexOfPml5Entries) * sizeof (PAGE_MAP_AND_DIRECTORY_POINTER));
+  }
+
+  //
+  // Protect the page table by marking the memory used for page table to be
+  // read-only.
+  //
+  EnablePageTableProtection ((UINTN)PageMap, TRUE);
+
+  return (UINTN)PageMap;
+}
diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec
index 3194b02d9d6b..1bc2a547ee5c 100644
--- a/OvmfPkg/OvmfPkg.dec
+++ b/OvmfPkg/OvmfPkg.dec
@@ -121,6 +121,10 @@
   #
   TdxPlatformLib|Include/Library/TdxPlatformLib.h
 
+  ##  @libraryclass  TdxStartupLib
+  #
+  TdxStartupLib|Include/Library/TdxStartupLib.h
+
 [Guids]
   gUefiOvmfPkgTokenSpaceGuid            = {0x93bb96af, 0xb9f2, 0x4eb8, {0x94, 0x62, 0xe0, 0xba, 0x74, 0x56, 0x42, 0x36}}
   gEfiXenInfoGuid                       = {0xd3b46f3b, 0xd441, 0x1244, {0x9a, 0x12, 0x0, 0x12, 0x27, 0x3f, 0xc1, 0x4d}}
@@ -389,6 +393,9 @@
   ## The Tdx accept page size. 0x1000(4k),0x200000(2M)
   gUefiOvmfPkgTokenSpaceGuid.PcdTdxAcceptPageSize|0x1000|UINT32|0x66
 
+  ## Noexec settings for Tdx guest.
+  gUefiOvmfPkgTokenSpaceGuid.PcdTdxSetNxForStack|TRUE|BOOLEAN|0x67
+
 [PcdsDynamic, PcdsDynamicEx]
   gUefiOvmfPkgTokenSpaceGuid.PcdEmuVariableEvent|0|UINT64|2
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFlashVariablesEnable|FALSE|BOOLEAN|0x10
-- 
2.29.2.windows.2


^ permalink raw reply related	[flat|nested] 37+ messages in thread

* [PATCH 07/10] OvmfPkg: Update TdxDxe to set TDX PCDs
  2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
                   ` (5 preceding siblings ...)
  2021-12-14 13:41 ` [PATCH 06/10] OvmfPkg: Add TdxStartupLib Min Xu
@ 2021-12-14 13:41 ` Min Xu
  2021-12-14 13:41 ` [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B Min Xu
                   ` (3 subsequent siblings)
  10 siblings, 0 replies; 37+ messages in thread
From: Min Xu @ 2021-12-14 13:41 UTC (permalink / raw)
  To: devel
  Cc: Min Xu, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Gerd Hoffmann

RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429

These PCDs are set in PEI phase in Config-A. But in Config-B
PEI phase is skipped. So they're set here.

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Min Xu <min.m.xu@intel.com>
---
 OvmfPkg/Include/Library/TdxPlatformLib.h |  4 ++--
 OvmfPkg/TdxDxe/TdxDxe.c                  | 12 ++++++++++++
 OvmfPkg/TdxDxe/TdxDxe.inf                |  3 +++
 3 files changed, 17 insertions(+), 2 deletions(-)

diff --git a/OvmfPkg/Include/Library/TdxPlatformLib.h b/OvmfPkg/Include/Library/TdxPlatformLib.h
index a6118a0edd98..5463a6d7e55e 100644
--- a/OvmfPkg/Include/Library/TdxPlatformLib.h
+++ b/OvmfPkg/Include/Library/TdxPlatformLib.h
@@ -16,8 +16,8 @@
 #include <Library/HobLib.h>
 #include <IndustryStandard/IntelTdx.h>
 
-#define FW_CFG_NX_STACK_ITEM        "opt/ovmf/PcdSetNxForStack"
-#define FW_CFG_SYSTEM_STATE_ITEM    "etc/system-states"
+#define FW_CFG_NX_STACK_ITEM      "opt/ovmf/PcdSetNxForStack"
+#define FW_CFG_SYSTEM_STATE_ITEM  "etc/system-states"
 
 /**
  * Perform Platform initialization.
diff --git a/OvmfPkg/TdxDxe/TdxDxe.c b/OvmfPkg/TdxDxe/TdxDxe.c
index 36ef5c510771..63b069adefd3 100644
--- a/OvmfPkg/TdxDxe/TdxDxe.c
+++ b/OvmfPkg/TdxDxe/TdxDxe.c
@@ -24,6 +24,7 @@
 #include <Library/HobLib.h>
 #include <Protocol/Cpu.h>
 #include <Library/UefiBootServicesTableLib.h>
+#include <ConfidentialComputingGuestAttr.h>
 #include <IndustryStandard/Tdx.h>
 #include <IndustryStandard/IntelTdx.h>
 #include <Library/TdxLib.h>
@@ -181,6 +182,17 @@ TdxDxeEntryPoint (
 
   SetMmioSharedBit ();
 
+ #ifdef INTEL_TDX_FULL_FEATURE
+  PcdStatus = PcdSet64S (PcdConfidentialComputingGuestAttr, CCAttrIntelTdx);
+  ASSERT_RETURN_ERROR (PcdStatus);
+
+  PcdStatus = PcdSetBoolS (PcdIa32EferChangeAllowed, FALSE);
+  ASSERT_RETURN_ERROR (PcdStatus);
+
+  PcdStatus = PcdSet64S (PcdTdxSharedBitMask, TdSharedPageMask ());
+  ASSERT_RETURN_ERROR (PcdStatus);
+ #endif
+
   PlatformInfo = (EFI_HOB_PLATFORM_INFO *)GET_GUID_HOB_DATA (GuidHob);
 
   //
diff --git a/OvmfPkg/TdxDxe/TdxDxe.inf b/OvmfPkg/TdxDxe/TdxDxe.inf
index 077769bcf70c..b6335d86edbe 100644
--- a/OvmfPkg/TdxDxe/TdxDxe.inf
+++ b/OvmfPkg/TdxDxe/TdxDxe.inf
@@ -62,3 +62,6 @@
   gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber
   gUefiCpuPkgTokenSpaceGuid.PcdCpuLocalApicBaseAddress
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfFdBaseAddress
+  gEfiMdeModulePkgTokenSpaceGuid.PcdIa32EferChangeAllowed
+  gEfiMdePkgTokenSpaceGuid.PcdConfidentialComputingGuestAttr
+  gEfiMdeModulePkgTokenSpaceGuid.PcdTdxSharedBitMask
-- 
2.29.2.windows.2


^ permalink raw reply related	[flat|nested] 37+ messages in thread

* [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
                   ` (6 preceding siblings ...)
  2021-12-14 13:41 ` [PATCH 07/10] OvmfPkg: Update TdxDxe to set TDX PCDs Min Xu
@ 2021-12-14 13:41 ` Min Xu
  2021-12-15 10:27   ` Gerd Hoffmann
  2021-12-14 13:41 ` [PATCH 09/10] OvmfPkg: Update DxeAcpiTimerLib to read HostBridgeDevId in PlatformInfoHob Min Xu
                   ` (2 subsequent siblings)
  10 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2021-12-14 13:41 UTC (permalink / raw)
  To: devel
  Cc: Min Xu, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Gerd Hoffmann

RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429

Tdvf Config-B skip PEI phase to reduce attack surface. So instead of
jumping to SecStartupPhase2 (), TdxStartup () is called. This function
brings up Tdx guest from SEC phase to DXE phase.

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Min Xu <min.m.xu@intel.com>
---
 OvmfPkg/Sec/IntelTdx.c  |  7 ++++++-
 OvmfPkg/Sec/SecMain.c   | 17 +++++++++++++++++
 OvmfPkg/Sec/SecMain.inf |  2 ++
 3 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/OvmfPkg/Sec/IntelTdx.c b/OvmfPkg/Sec/IntelTdx.c
index d1d952e8d433..f9d44617b211 100644
--- a/OvmfPkg/Sec/IntelTdx.c
+++ b/OvmfPkg/Sec/IntelTdx.c
@@ -12,7 +12,7 @@
 #include <Uefi/UefiBaseType.h>
 #include <Library/BaseLib.h>
 #include <Library/DebugLib.h>
-#include <Library/HobLib.h>
+#include <Library/PrePiLib.h>
 #include <Library/BaseMemoryLib.h>
 #include <IndustryStandard/UefiTcgPlatform.h>
 #include <Library/MemoryAllocationLib.h>
@@ -25,6 +25,11 @@
 
 #define ALIGNED_2MB_MASK  0x1fffff
 
+#define GET_HOB_TYPE(Hob)     ((Hob).Header->HobType)
+#define GET_HOB_LENGTH(Hob)   ((Hob).Header->HobLength)
+#define GET_NEXT_HOB(Hob)     ((Hob).Raw + GET_HOB_LENGTH (Hob))
+#define END_OF_HOB_LIST(Hob)  (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_END_OF_HOB_LIST)
+
 /**
   Check TDX is enabled.
 
diff --git a/OvmfPkg/Sec/SecMain.c b/OvmfPkg/Sec/SecMain.c
index e2f3ede93901..c5dd066941fe 100644
--- a/OvmfPkg/Sec/SecMain.c
+++ b/OvmfPkg/Sec/SecMain.c
@@ -33,6 +33,10 @@
 #include "IntelTdx.h"
 #include "AmdSev.h"
 
+#ifdef INTEL_TDX_FULL_FEATURE
+  #include <Library/TdxStartupLib.h>
+#endif
+
 #define SEC_IDT_ENTRY_COUNT  34
 
 typedef struct _SEC_IDT_TABLE {
@@ -913,6 +917,19 @@ SecCoreStartupWithStack (
   InitializeApicTimer (0, MAX_UINT32, TRUE, 5);
   DisableApicTimerInterrupt ();
 
+ #ifdef INTEL_TDX_FULL_FEATURE
+  if (SecTdxIsEnabled ()) {
+    TdxStartup (&SecCoreData);
+
+    //
+    // Never arrived here
+    //
+    ASSERT (FALSE);
+    CpuDeadLoop ();
+  }
+
+ #endif
+
   //
   // Initialize Debug Agent to support source level debug in SEC/PEI phases before memory ready.
   //
diff --git a/OvmfPkg/Sec/SecMain.inf b/OvmfPkg/Sec/SecMain.inf
index 230ee5e465b9..05e49ab5ae81 100644
--- a/OvmfPkg/Sec/SecMain.inf
+++ b/OvmfPkg/Sec/SecMain.inf
@@ -38,6 +38,7 @@
   MdeModulePkg/MdeModulePkg.dec
   UefiCpuPkg/UefiCpuPkg.dec
   OvmfPkg/OvmfPkg.dec
+  EmbeddedPkg/EmbeddedPkg.dec
 
 [LibraryClasses]
   BaseLib
@@ -58,6 +59,7 @@
 
 [LibraryClasses.X64]
   TdxLib
+  TdxStartupLib
 
 [Ppis]
   gEfiTemporaryRamSupportPpiGuid                # PPI ALWAYS_PRODUCED
-- 
2.29.2.windows.2


^ permalink raw reply related	[flat|nested] 37+ messages in thread

* [PATCH 09/10] OvmfPkg: Update DxeAcpiTimerLib to read HostBridgeDevId in PlatformInfoHob
  2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
                   ` (7 preceding siblings ...)
  2021-12-14 13:41 ` [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B Min Xu
@ 2021-12-14 13:41 ` Min Xu
  2021-12-14 13:41 ` [PATCH 10/10] OvmfPkg: Add Tdx libs to prevent building broken Min Xu
  2021-12-15 10:41 ` [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Gerd Hoffmann
  10 siblings, 0 replies; 37+ messages in thread
From: Min Xu @ 2021-12-14 13:41 UTC (permalink / raw)
  To: devel
  Cc: Min Xu, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Gerd Hoffmann

RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429

The entrypoint of DxeAcpiTimerLib checks HostBridgeDevId by reading
PcdOvmfHostBridgePciDevId. If the DevId is not set, ASSERT is
triggered. Normally this DevId is set in PlatformPei which is executed
in PEI phase. But Tdvf Config-B skips PEI phase so there is no chance
to set this DevId.

A word-round is that in Tdx guest HostBridgeDevId is set in
PlatformInfoHob (in SecPlatformLibQemuTdx). So we can check if
PlatformInfoHob exists and if HostBridgeDevId is set in this Hob.

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Min Xu <min.m.xu@intel.com>
---
 .../Library/AcpiTimerLib/DxeAcpiTimerLib.c    | 23 ++++++++++++++++---
 .../Library/AcpiTimerLib/DxeAcpiTimerLib.inf  |  4 ++++
 2 files changed, 24 insertions(+), 3 deletions(-)

diff --git a/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.c b/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.c
index 115846187455..5c7011f2dd3d 100644
--- a/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.c
+++ b/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.c
@@ -6,10 +6,16 @@
   SPDX-License-Identifier: BSD-2-Clause-Patent
 **/
 
+#include <Uefi/UefiBaseType.h>
+#include <Uefi/UefiMultiPhase.h>
+#include <Pi/PiBootMode.h>
+#include <Pi/PiHob.h>
+#include <Library/HobLib.h>
 #include <Library/DebugLib.h>
 #include <Library/IoLib.h>
 #include <Library/PcdLib.h>
 #include <Library/PciLib.h>
+#include <IndustryStandard/IntelTdx.h>
 #include <OvmfPlatforms.h>
 
 //
@@ -36,13 +42,24 @@ AcpiTimerLibConstructor (
   VOID
   )
 {
-  UINT16  HostBridgeDevId;
-  UINTN   Pmba;
+  UINT16                 HostBridgeDevId;
+  UINTN                  Pmba;
+  EFI_HOB_GUID_TYPE      *GuidHob;
+  EFI_HOB_PLATFORM_INFO  *PlatformInfo = NULL;
 
   //
   // Query Host Bridge DID to determine platform type
+  // Tdx guest stores the HostBridgePciDevId in a GuidHob.
+  // So we first check if this HOB exists
   //
-  HostBridgeDevId = PcdGet16 (PcdOvmfHostBridgePciDevId);
+  GuidHob = GetFirstGuidHob (&gUefiOvmfPkgTdxPlatformGuid);
+  if (GuidHob != NULL) {
+    PlatformInfo    = (EFI_HOB_PLATFORM_INFO *)GET_GUID_HOB_DATA (GuidHob);
+    HostBridgeDevId = PlatformInfo->HostBridgePciDevId;
+  } else {
+    HostBridgeDevId = PcdGet16 (PcdOvmfHostBridgePciDevId);
+  }
+
   switch (HostBridgeDevId) {
     case INTEL_82441_DEVICE_ID:
       Pmba = POWER_MGMT_REGISTER_PIIX4 (PIIX4_PMBA);
diff --git a/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf b/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
index e29872add3c7..44a4423a9ddd 100644
--- a/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
+++ b/OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
@@ -33,3 +33,7 @@
   BaseLib
   PciLib
   IoLib
+  HobLib
+
+[Guids]
+  gUefiOvmfPkgTdxPlatformGuid                      ## CONSUMES
-- 
2.29.2.windows.2


^ permalink raw reply related	[flat|nested] 37+ messages in thread

* [PATCH 10/10] OvmfPkg: Add Tdx libs to prevent building broken
  2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
                   ` (8 preceding siblings ...)
  2021-12-14 13:41 ` [PATCH 09/10] OvmfPkg: Update DxeAcpiTimerLib to read HostBridgeDevId in PlatformInfoHob Min Xu
@ 2021-12-14 13:41 ` Min Xu
  2021-12-15 10:41 ` [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Gerd Hoffmann
  10 siblings, 0 replies; 37+ messages in thread
From: Min Xu @ 2021-12-14 13:41 UTC (permalink / raw)
  To: devel
  Cc: Min Xu, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Gerd Hoffmann

RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429

With the introduction of TDVF Config-B, some Tdx libs should be added
in below dsc to prevent the broken of building.
 - OvmfPkg/AmdSev/AmdSevX64.dsc
 - OvmfPkg/Bhyve/BhyveX64.dsc
 - OvmfPkg/Microvm/MicrovmX64.dsc
 - OvmfPkg/OvmfPkgX64.dsc
 - OvmfPkg/OvmfXen.dsc

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Brijesh Singh <brijesh.singh@amd.com>
Cc: Erdem Aktas <erdemaktas@google.com>
Cc: James Bottomley <jejb@linux.ibm.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Min Xu <min.m.xu@intel.com>
---
 OvmfPkg/AmdSev/AmdSevX64.dsc   | 3 +++
 OvmfPkg/Bhyve/BhyveX64.dsc     | 3 +++
 OvmfPkg/Microvm/MicrovmX64.dsc | 5 +++++
 OvmfPkg/OvmfPkgX64.dsc         | 1 +
 OvmfPkg/OvmfXen.dsc            | 3 +++
 5 files changed, 15 insertions(+)

diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc
index b2636febee3d..d4f3dac92c61 100644
--- a/OvmfPkg/AmdSev/AmdSevX64.dsc
+++ b/OvmfPkg/AmdSev/AmdSevX64.dsc
@@ -174,6 +174,7 @@
   CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
   FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
   BlobVerifierLib|OvmfPkg/AmdSev/BlobVerifierLibSevHashes/BlobVerifierLibSevHashes.inf
+  MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
 
 !if $(SOURCE_DEBUG_ENABLE) == TRUE
   PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
@@ -217,6 +218,8 @@
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
   VmgExitLib|OvmfPkg/Library/VmgExitLib/VmgExitLib.inf
+  TdxLib|MdePkg/Library/TdxLib/TdxLib.inf
+  TdxStartupLib|OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLibNull.inf
 
 [LibraryClasses.common.SEC]
   TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.inf
diff --git a/OvmfPkg/Bhyve/BhyveX64.dsc b/OvmfPkg/Bhyve/BhyveX64.dsc
index e833fc716b07..9c766f6f451e 100644
--- a/OvmfPkg/Bhyve/BhyveX64.dsc
+++ b/OvmfPkg/Bhyve/BhyveX64.dsc
@@ -169,6 +169,7 @@
   VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
   MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptSevLib.inf
   LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
+  MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
 
   CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
   FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
@@ -228,6 +229,8 @@
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
   VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf
+  TdxLib|MdePkg/Library/TdxLib/TdxLib.inf
+  TdxStartupLib|OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLibNull.inf
 
 [LibraryClasses.common.SEC]
 !ifdef $(DEBUG_ON_SERIAL_PORT)
diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc
index 7e5c131d39b3..9a45951dd56d 100644
--- a/OvmfPkg/Microvm/MicrovmX64.dsc
+++ b/OvmfPkg/Microvm/MicrovmX64.dsc
@@ -183,6 +183,7 @@
   LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
   CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
   FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
+  MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
 
 !if $(SOURCE_DEBUG_ENABLE) == TRUE
   PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
@@ -232,6 +233,10 @@
   VmgExitLib|OvmfPkg/Library/VmgExitLib/VmgExitLib.inf
   SerialPortLib|MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.inf
   PlatformHookLib|MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf
+  FdtLib|EmbeddedPkg/Library/FdtLib/FdtLib.inf
+  VirtioMmioDeviceLib|OvmfPkg/Library/VirtioMmioDeviceLib/VirtioMmioDeviceLib.inf
+  TdxLib|MdePkg/Library/TdxLib/TdxLib.inf
+  TdxStartupLib|OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLibNull.inf
 
 [LibraryClasses.common.SEC]
   QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index 771fa9da13e9..f468c4850bfd 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -276,6 +276,7 @@
 !endif
   VmgExitLib|OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf
   MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLib.inf
+  TdxStartupLib|OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLibNull.inf
 
 [LibraryClasses.common.PEI_CORE]
   HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf
diff --git a/OvmfPkg/OvmfXen.dsc b/OvmfPkg/OvmfXen.dsc
index f82c3adfe69c..e744a044efb9 100644
--- a/OvmfPkg/OvmfXen.dsc
+++ b/OvmfPkg/OvmfXen.dsc
@@ -170,6 +170,7 @@
   LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
   CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
   FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
+  MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
 
 !if $(SOURCE_DEBUG_ENABLE) == TRUE
   PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
@@ -227,6 +228,8 @@
 [LibraryClasses.common]
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
   VmgExitLib|UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf
+  TdxLib|MdePkg/Library/TdxLib/TdxLib.inf
+  TdxStartupLib|OvmfPkg/IntelTdx/TdxStartupLib/TdxStartupLibNull.inf
 
 [LibraryClasses.common.SEC]
   QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
-- 
2.29.2.windows.2


^ permalink raw reply related	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 03/10] EmbeddedPkg/MemoryAllocationLib: Add null stub for AllocateCopyPool
  2021-12-14 13:41 ` [PATCH 03/10] EmbeddedPkg/MemoryAllocationLib: Add null stub for AllocateCopyPool Min Xu
@ 2021-12-14 13:59   ` Ard Biesheuvel
  2021-12-16  3:08     ` Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Ard Biesheuvel @ 2021-12-14 13:59 UTC (permalink / raw)
  To: edk2-devel-groups-io, Min Xu
  Cc: Michael D Kinney, Brijesh Singh, Erdem Aktas, James Bottomley,
	Jiewen Yao, Tom Lendacky, Gerd Hoffmann, Leif Lindholm,
	Ard Biesheuvel, Abner Chang, Daniel Schaefer

On Tue, 14 Dec 2021 at 14:42, Min Xu <min.m.xu@intel.com> wrote:
>
> RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429
>
> This function is a null stub to make the build success.
>
> Cc: Michael D Kinney <michael.d.kinney@intel.com>
> Cc: Brijesh Singh <brijesh.singh@amd.com>
> Cc: Erdem Aktas <erdemaktas@google.com>
> Cc: James Bottomley <jejb@linux.ibm.com>
> Cc: Jiewen Yao <jiewen.yao@intel.com>
> Cc: Tom Lendacky <thomas.lendacky@amd.com>
> Cc: Gerd Hoffmann <kraxel@redhat.com>
> Cc: Leif Lindholm <leif@nuviainc.com>
> Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
> Cc: Abner Chang <abner.chang@hpe.com>
> Cc: Daniel Schaefer <daniel.schaefer@hpe.com>
> Signed-off-by: Min Xu <min.m.xu@intel.com>
> ---
>  .../MemoryAllocationLib.c                     | 28 +++++++++++++++++++
>  1 file changed, 28 insertions(+)
>

Why is it justified to implement a broken version of this routine?
This is not a NULL library class that only exists for build test
purposes, it is actually used in production builds.

If the TDVF code needs the symbol but does not actually call it,
perhaps there is another place where this should get fixed?


> diff --git a/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c b/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c
> index 78f8da5e9527..ddc27150c680 100644
> --- a/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c
> +++ b/EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c
> @@ -220,6 +220,34 @@ AllocateZeroPool (
>    return Buffer;
>  }
>
> +/**
> +  Copies a buffer to an allocated buffer of type EfiBootServicesData.
> +
> +  Allocates the number bytes specified by AllocationSize of type EfiBootServicesData, copies
> +  AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the
> +  allocated buffer.  If AllocationSize is 0, then a valid buffer of 0 size is returned.  If there
> +  is not enough memory remaining to satisfy the request, then NULL is returned.
> +
> +  If Buffer is NULL, then ASSERT().
> +  If AllocationSize is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT().
> +
> +  @param  AllocationSize        The number of bytes to allocate and zero.
> +  @param  Buffer                The buffer to copy to the allocated buffer.
> +
> +  @return A pointer to the allocated buffer or NULL if allocation fails.
> +
> +**/
> +VOID *
> +EFIAPI
> +AllocateCopyPool (
> +  IN UINTN       AllocationSize,
> +  IN CONST VOID  *Buffer
> +  )
> +{
> +  ASSERT (FALSE);
> +  return NULL;
> +}
> +
>  /**
>    Frees a buffer that was previously allocated with one of the pool allocation functions in the
>    Memory Allocation Library.
> --
> 2.29.2.windows.2
>
>
>
> 
>
>

^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 02/10] EmbeddedPkg/PrePiLib: Update PrePiLib
  2021-12-14 13:41 ` [PATCH 02/10] EmbeddedPkg/PrePiLib: Update PrePiLib Min Xu
@ 2021-12-14 14:00   ` Ard Biesheuvel
  2021-12-16  4:48     ` Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Ard Biesheuvel @ 2021-12-14 14:00 UTC (permalink / raw)
  To: edk2-devel-groups-io, Min Xu
  Cc: Michael D Kinney, Brijesh Singh, Erdem Aktas, James Bottomley,
	Jiewen Yao, Tom Lendacky, Gerd Hoffmann, Leif Lindholm,
	Ard Biesheuvel, Abner Chang, Daniel Schaefer

On Tue, 14 Dec 2021 at 14:42, Min Xu <min.m.xu@intel.com> wrote:
>
> RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429
>
> There are below new functions added in EmbeddedPkg/PrePiLib.
> 1. FfsAnyFvFindFileByName
>    This function is to find the file by name in the FvImage.
> 2. FfsDecompressSection
>    This function is to decompress a compressed section.
> 3. FfsProcessFvFileEx
>    This function is to decompress a compressed section and create
>    FvHob/Fv2Hob for all the FvImages.
>
> Cc: Michael D Kinney <michael.d.kinney@intel.com>
> Cc: Brijesh Singh <brijesh.singh@amd.com>
> Cc: Erdem Aktas <erdemaktas@google.com>
> Cc: James Bottomley <jejb@linux.ibm.com>
> Cc: Jiewen Yao <jiewen.yao@intel.com>
> Cc: Tom Lendacky <thomas.lendacky@amd.com>
> Cc: Gerd Hoffmann <kraxel@redhat.com>
> Cc: Leif Lindholm <leif@nuviainc.com>
> Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
> Cc: Abner Chang <abner.chang@hpe.com>
> Cc: Daniel Schaefer <daniel.schaefer@hpe.com>
> Signed-off-by: Min Xu <min.m.xu@intel.com>
> ---
>  EmbeddedPkg/Include/Library/PrePiLib.h |  21 +-
>  EmbeddedPkg/Library/PrePiLib/FwVol.c   | 399 ++++++++++++++++++++++++-
>  2 files changed, 418 insertions(+), 2 deletions(-)
>
> diff --git a/EmbeddedPkg/Include/Library/PrePiLib.h b/EmbeddedPkg/Include/Library/PrePiLib.h
> index 7b2cea296f1c..80698e559cdf 100644
> --- a/EmbeddedPkg/Include/Library/PrePiLib.h
> +++ b/EmbeddedPkg/Include/Library/PrePiLib.h
> @@ -180,6 +180,9 @@ FfsAnyFvFindFirstFile (
>
>  /**
>    Get Fv image from the FV type file, then add FV & FV2 Hob.
> +  This function can handle the situation that a compressed
> +  section contains multi-FvImages and create FV/FV2 Hob for
> +  all the FvImages.
>
>    @param FileHandle  File handle of a Fv type file.
>
> @@ -190,7 +193,7 @@ FfsAnyFvFindFirstFile (
>  **/
>  EFI_STATUS
>  EFIAPI
> -FfsProcessFvFile (
> +FfsProcessFvFileEx (
>    IN  EFI_PEI_FILE_HANDLE  FvFileHandle
>    );
>
> @@ -735,4 +738,20 @@ DecompressFirstFv (
>    VOID
>    );
>
> +/**
> + * This function find the file by GUID name from a FvImage.
> + *
> + * @param Name          GUID name of the file
> + * @param VolumeHandle  The handle of the Fv
> + * @param FileHandle    The handle of the File
> + * @return EFI_STATUS   Successfully find the file.
> + */
> +EFI_STATUS
> +EFIAPI
> +FfsAnyFvFindFileByName (
> +  IN  CONST EFI_GUID       *Name,
> +  OUT EFI_PEI_FV_HANDLE    *VolumeHandle,
> +  OUT EFI_PEI_FILE_HANDLE  *FileHandle
> +  );
> +
>  #endif
> diff --git a/EmbeddedPkg/Library/PrePiLib/FwVol.c b/EmbeddedPkg/Library/PrePiLib/FwVol.c
> index 92ae68f0d382..e714f4876ff5 100644
> --- a/EmbeddedPkg/Library/PrePiLib/FwVol.c
> +++ b/EmbeddedPkg/Library/PrePiLib/FwVol.c
> @@ -335,7 +335,7 @@ FfsProcessSection (
>
>          Status = UefiDecompressGetInfo (
>                     CompressedData,
> -                   CompressedDataLength,
> +                   (UINT32)CompressedDataLength,

How is this change related to the items listed in the commit log?

If there are code issues affecting this library, please fix them in a
separate patch.

>                     &DstBufferSize,
>                     &ScratchBufferSize
>                     );
> @@ -850,6 +850,403 @@ FfsProcessFvFile (
>      &FvImageInfo.FvName,
>      &(((EFI_FFS_FILE_HEADER *)FvFileHandle)->Name)
>      );
> +  return EFI_SUCCESS;
> +}
> +
> +/**
> + * This function find the file by GUID name from a FvImage.
> + *
> + * @param Name          GUID name of the file
> + * @param VolumeHandle  The handle of the Fv
> + * @param FileHandle    The handle of the File
> + * @return EFI_STATUS   Successfully find the file.
> + */
> +EFI_STATUS
> +EFIAPI
> +FfsAnyFvFindFileByName (
> +  IN  CONST EFI_GUID       *Name,
> +  OUT EFI_PEI_FV_HANDLE    *VolumeHandle,
> +  OUT EFI_PEI_FILE_HANDLE  *FileHandle
> +  )
> +{
> +  EFI_STATUS  Status;
> +  UINTN       Instance;
> +
> +  //
> +  // Search every FV for the file by name
> +  //
> +  Instance    = 0;
> +  *FileHandle = NULL;
> +
> +  while (1) {
> +    Status = FfsFindNextVolume (Instance++, VolumeHandle);
> +    if (EFI_ERROR (Status)) {
> +      break;
> +    }
> +
> +    Status = FfsFindFileByName (Name, *VolumeHandle, FileHandle);
> +    if (!EFI_ERROR (Status)) {
> +      break;
> +    }
> +  }
> +
> +  DEBUG ((DEBUG_INFO, "FfsAnyFvFindFileByName with name = %g, %r\n", Name, Status));
> +
> +  return Status;
> +}
> +
> +/**
> + * This function decompress the compressed section.
> + *
> + * @param FileHandle        File handle
> + * @param OutputBuffer      Pointer to the decompressed data
> + * @param OutputBufferSize  Pointer to the size of the decompressed data
> + * @return EFI_STATUS
> + */
> +EFI_STATUS
> +FfsDecompressSection (
> +  IN VOID     *FileHandle,
> +  OUT VOID    **OutputBuffer,
> +  OUT UINT32  *OutputBufferSize
> +  )
> +{
> +  EFI_STATUS                 Status;
> +  UINT32                     SectionLength;
> +  UINT32                     ParsedLength;
> +  EFI_COMPRESSION_SECTION    *CompressionSection;
> +  EFI_COMPRESSION_SECTION2   *CompressionSection2;
> +  UINT32                     DstBufferSize;
> +  VOID                       *ScratchBuffer;
> +  UINT32                     ScratchBufferSize;
> +  VOID                       *DstBuffer;
> +  UINT16                     SectionAttribute;
> +  UINT32                     AuthenticationStatus;
> +  CHAR8                      *CompressedData;
> +  UINTN                      CompressedDataLength;
> +  EFI_COMMON_SECTION_HEADER  *Section;
> +  UINT32                     SectionSize;
> +  EFI_FFS_FILE_HEADER        *FfsFileHeader;
> +
> +  *OutputBuffer     = NULL;
> +  *OutputBufferSize = 0;
> +  ParsedLength      = 0;
> +  Status            = EFI_NOT_FOUND;
> +
> +  FfsFileHeader = (EFI_FFS_FILE_HEADER *)(FileHandle);
> +  //
> +  // Size is 24 bits wide so mask upper 8 bits.
> +  // Does not include FfsFileHeader header size
> +  // FileSize is adjusted to FileOccupiedSize as it is 8 byte aligned.
> +  //
> +  Section      = (EFI_COMMON_SECTION_HEADER *)(FfsFileHeader + 1);
> +  SectionSize  = *(UINT32 *)(FfsFileHeader->Size) & 0x00FFFFFF;
> +  SectionSize -= sizeof (EFI_FFS_FILE_HEADER);
> +
> +  while (ParsedLength < SectionSize) {
> +    if (IS_SECTION2 (Section)) {
> +      ASSERT (SECTION2_SIZE (Section) > 0x00FFFFFF);
> +    }
> +
> +    DEBUG ((DEBUG_INFO, "Check section type=%x\n", Section->Type));
> +
> +    if ((Section->Type == EFI_SECTION_COMPRESSION) || (Section->Type == EFI_SECTION_GUID_DEFINED)) {
> +      DEBUG ((DEBUG_INFO, "It is a compressed section.\n"));
> +
> +      if (Section->Type == EFI_SECTION_COMPRESSION) {
> +        if (IS_SECTION2 (Section)) {
> +          CompressionSection2 = (EFI_COMPRESSION_SECTION2 *)Section;
> +          SectionLength       = SECTION2_SIZE (Section);
> +
> +          if (CompressionSection2->CompressionType != EFI_STANDARD_COMPRESSION) {
> +            return EFI_UNSUPPORTED;
> +          }
> +
> +          CompressedData       = (CHAR8 *)((EFI_COMPRESSION_SECTION2 *)Section + 1);
> +          CompressedDataLength = (UINT32)SectionLength - sizeof (EFI_COMPRESSION_SECTION2);
> +        } else {
> +          CompressionSection = (EFI_COMPRESSION_SECTION *)Section;
> +          SectionLength      = SECTION_SIZE (Section);
> +
> +          if (CompressionSection->CompressionType != EFI_STANDARD_COMPRESSION) {
> +            return EFI_UNSUPPORTED;
> +          }
> +
> +          CompressedData       = (CHAR8 *)((EFI_COMPRESSION_SECTION *)Section + 1);
> +          CompressedDataLength = (UINT32)SectionLength - sizeof (EFI_COMPRESSION_SECTION);
> +        }
> +
> +        Status = UefiDecompressGetInfo (
> +                   CompressedData,
> +                   (UINT32)CompressedDataLength,
> +                   &DstBufferSize,
> +                   &ScratchBufferSize
> +                   );
> +      } else if (Section->Type == EFI_SECTION_GUID_DEFINED) {
> +        Status = ExtractGuidedSectionGetInfo (
> +                   Section,
> +                   &DstBufferSize,
> +                   &ScratchBufferSize,
> +                   &SectionAttribute
> +                   );
> +      }
> +
> +      if (EFI_ERROR (Status)) {
> +        //
> +        // GetInfo failed
> +        //
> +        DEBUG ((DEBUG_ERROR, "Decompress GetInfo Failed - %r\n", Status));
> +        return EFI_NOT_FOUND;
> +      }
> +
> +      //
> +      // Allocate scratch buffer
> +      //
> +      ScratchBuffer = (VOID *)(UINTN)AllocatePages (EFI_SIZE_TO_PAGES (ScratchBufferSize));
> +      if (ScratchBuffer == NULL) {
> +        return EFI_OUT_OF_RESOURCES;
> +      }
> +
> +      //
> +      // Allocate destination buffer, extra one page for adjustment
> +      //
> +      DstBuffer = (VOID *)(UINTN)AllocatePages (EFI_SIZE_TO_PAGES (DstBufferSize) + 1);
> +      if (DstBuffer == NULL) {
> +        return EFI_OUT_OF_RESOURCES;
> +      }
> +
> +      //
> +      // DstBuffer still is one section. Adjust DstBuffer offset, skip EFI section header
> +      // to make section data at page alignment.
> +      //
> +      if (IS_SECTION2 (Section)) {
> +        DstBuffer = (UINT8 *)DstBuffer + EFI_PAGE_SIZE - sizeof (EFI_COMMON_SECTION_HEADER2);
> +      } else {
> +        DstBuffer = (UINT8 *)DstBuffer + EFI_PAGE_SIZE - sizeof (EFI_COMMON_SECTION_HEADER);
> +      }
> +
> +      //
> +      // Call decompress function
> +      //
> +      if (Section->Type == EFI_SECTION_COMPRESSION) {
> +        if (IS_SECTION2 (Section)) {
> +          CompressedData = (CHAR8 *)((EFI_COMPRESSION_SECTION2 *)Section + 1);
> +        } else {
> +          CompressedData = (CHAR8 *)((EFI_COMPRESSION_SECTION *)Section + 1);
> +        }
> +
> +        Status = UefiDecompress (
> +                   CompressedData,
> +                   DstBuffer,
> +                   ScratchBuffer
> +                   );
> +      } else if (Section->Type == EFI_SECTION_GUID_DEFINED) {
> +        Status = ExtractGuidedSectionDecode (
> +                   Section,
> +                   &DstBuffer,
> +                   ScratchBuffer,
> +                   &AuthenticationStatus
> +                   );
> +      }
> +
> +      if (EFI_ERROR (Status)) {
> +        //
> +        // Decompress failed
> +        //
> +        DEBUG ((DEBUG_ERROR, "Decompress Failed - %r\n", Status));
> +        return EFI_NOT_FOUND;
> +      } else {
> +        *OutputBuffer     = DstBuffer;
> +        *OutputBufferSize = DstBufferSize;
> +        DEBUG ((
> +          DEBUG_INFO,
> +          "Decompressed data is at %x, %x\n",
> +          DstBuffer,
> +          DstBufferSize
> +          ));
> +        return EFI_SUCCESS;
> +      }
> +    }
> +
> +    if (IS_SECTION2 (Section)) {
> +      SectionLength = SECTION2_SIZE (Section);
> +    } else {
> +      SectionLength = SECTION_SIZE (Section);
> +    }
> +
> +    //
> +    // SectionLength is adjusted it is 4 byte aligned.
> +    // Go to the next section
> +    //
> +    SectionLength = GET_OCCUPIED_SIZE (SectionLength, 4);
> +    ASSERT (SectionLength != 0);
> +    ParsedLength += SectionLength;
> +    Section       = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)Section + SectionLength);
> +    DEBUG ((DEBUG_INFO, "Go to next section.\n"));
> +  }
> +
> +  return EFI_NOT_FOUND;
> +}
> +
> +#define MAX_FV_IMAGES  8
> +/**
> +  Get Fv image from the FV type file, then add FV & FV2 Hob.
> +  This function can handle the situation that a compressed
> +  section contains multi-FvImages and create FV/FV2 Hob for
> +  all the FvImages.
> +
> +  We assume there are at most MAX_FV_IMAGES (8) FvImages in
> +  a compressed section. If it is not the case, it can be
> +  expanded to a larger one.
> +
> +  @param FileHandle  File handle of a Fv type file.
> +
> +
> +  @retval EFI_NOT_FOUND  FV image can't be found.
> +  @retval EFI_SUCCESS    Successfully to process it.
> +
> +**/
> +EFI_STATUS
> +EFIAPI
> +FfsProcessFvFileEx (
> +  IN  EFI_PEI_FILE_HANDLE  FvFileHandle
> +  )
> +{
> +  EFI_STATUS                    Status;
> +  EFI_FV_INFO                   FvImageInfo;
> +  UINT32                        FvAlignment;
> +  VOID                          *FvBuffer;
> +  EFI_PEI_HOB_POINTERS          HobFv2;
> +  UINT32                        ParsedLength;
> +  VOID                          *DecompressBuffer;
> +  UINT32                        DecompressBufferSize;
> +  UINT32                        FvImagesCnt;
> +  UINT32                        SectionLength;
> +  UINTN                         FvImageHandles[MAX_FV_IMAGES];
> +  UINT32                        Index;
> +  IN EFI_COMMON_SECTION_HEADER  *Section;
> +
> +  FvBuffer             = NULL;
> +  DecompressBuffer     = NULL;
> +  DecompressBufferSize = 0;
> +
> +  //
> +  // Check if this EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE file has already
> +  // been extracted.
> +  //
> +  HobFv2.Raw = GetHobList ();
> +  while ((HobFv2.Raw = GetNextHob (EFI_HOB_TYPE_FV2, HobFv2.Raw)) != NULL) {
> +    if (CompareGuid (&(((EFI_FFS_FILE_HEADER *)FvFileHandle)->Name), &HobFv2.FirmwareVolume2->FileName)) {
> +      //
> +      // this FILE has been dispatched, it will not be dispatched again.
> +      //
> +      return EFI_SUCCESS;
> +    }
> +
> +    HobFv2.Raw = GET_NEXT_HOB (HobFv2);
> +  }
> +
> +  //
> +  // Decompress section
> +  //
> +  Status = FfsDecompressSection (FvFileHandle, (VOID **)&DecompressBuffer, &DecompressBufferSize);
> +  if (EFI_ERROR (Status)) {
> +    DEBUG ((DEBUG_ERROR, "Failed to decompress section. %r\n", Status));
> +    ASSERT (FALSE);
> +    return Status;
> +  }
> +
> +  //
> +  // Find all the FvImages in the decompressed buffer
> +  //
> +  ParsedLength = 0;
> +  FvImagesCnt  = 0;
> +  Section      = (EFI_COMMON_SECTION_HEADER *)(DecompressBuffer);
> +
> +  while (ParsedLength < DecompressBufferSize && FvImagesCnt < MAX_FV_IMAGES) {
> +    if (IS_SECTION2 (Section)) {
> +      ASSERT (SECTION2_SIZE (Section) > 0x00FFFFFF);
> +    }
> +
> +    if (Section->Type == EFI_SECTION_FIRMWARE_VOLUME_IMAGE) {
> +      if (IS_SECTION2 (Section)) {
> +        FvImageHandles[FvImagesCnt++] = (UINTN)(VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER2));
> +      } else {
> +        FvImageHandles[FvImagesCnt++] = (UINTN)(VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER));
> +      }
> +    }
> +
> +    if (IS_SECTION2 (Section)) {
> +      SectionLength = SECTION2_SIZE (Section);
> +    } else {
> +      SectionLength = SECTION_SIZE (Section);
> +    }
> +
> +    //
> +    // SectionLength is adjusted it is 4 byte aligned.
> +    // Go to the next section
> +    //
> +    SectionLength = GET_OCCUPIED_SIZE (SectionLength, 4);
> +    ASSERT (SectionLength != 0);
> +    ParsedLength += SectionLength;
> +    Section       = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)Section + SectionLength);
> +  }
> +
> +  if (FvImagesCnt == 0) {
> +    ASSERT (FALSE);
> +    DEBUG ((DEBUG_ERROR, "Cannot find FvImages.\n"));
> +    return EFI_NOT_FOUND;
> +  }
> +
> +  DEBUG ((DEBUG_INFO, "Collect FvImageInfo\n"));
> +  for (Index = 0; Index < FvImagesCnt; Index++) {
> +    //
> +    // Collect FvImage Info.
> +    //
> +    ZeroMem (&FvImageInfo, sizeof (FvImageInfo));
> +    Status = FfsGetVolumeInfo ((VOID *)FvImageHandles[Index], &FvImageInfo);
> +    ASSERT_EFI_ERROR (Status);
> +    DEBUG ((DEBUG_INFO, "  Fv Name=%g, Format=%g, Size=0x%x\n", FvImageInfo.FvName, FvImageInfo.FvFormat, FvImageInfo.FvSize));
> +
> +    //
> +    // FvAlignment must be more than 8 bytes required by FvHeader structure.
> +    //
> +    FvAlignment = 1 << ((FvImageInfo.FvAttributes & EFI_FVB2_ALIGNMENT) >> 16);
> +    if (FvAlignment < 8) {
> +      FvAlignment = 8;
> +    }
> +
> +    //
> +    // Check FvImage
> +    //
> +    if ((UINTN)FvImageInfo.FvStart % FvAlignment != 0) {
> +      FvBuffer = AllocateAlignedPages (EFI_SIZE_TO_PAGES ((UINT32)FvImageInfo.FvSize), FvAlignment);
> +      if (FvBuffer == NULL) {
> +        return EFI_OUT_OF_RESOURCES;
> +      }
> +
> +      CopyMem (FvBuffer, FvImageInfo.FvStart, (UINTN)FvImageInfo.FvSize);
> +      //
> +      // Update FvImageInfo after reload FvImage to new aligned memory
> +      //
> +      FfsGetVolumeInfo ((EFI_PEI_FV_HANDLE)FvBuffer, &FvImageInfo);
> +    }
> +
> +    //
> +    // Inform HOB consumer phase, i.e. DXE core, the existence of this FV
> +    //
> +    BuildFvHob ((EFI_PHYSICAL_ADDRESS)(UINTN)FvImageInfo.FvStart, FvImageInfo.FvSize);
> +
> +    //
> +    // Makes the encapsulated volume show up in DXE phase to skip processing of
> +    // encapsulated file again.
> +    //
> +    BuildFv2Hob (
> +      (EFI_PHYSICAL_ADDRESS)(UINTN)FvImageInfo.FvStart,
> +      FvImageInfo.FvSize,
> +      &FvImageInfo.FvName,
> +      &(((EFI_FFS_FILE_HEADER *)FvFileHandle)->Name)
> +      );
> +  }
>
>    return EFI_SUCCESS;
>  }
> --
> 2.29.2.windows.2
>
>
>
> 
>
>

^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [PATCH 01/10] OvmfPkg: Introduce IntelTdxX64 for TDVF Config-B
  2021-12-14 13:41 ` [PATCH 01/10] OvmfPkg: Introduce IntelTdxX64 for TDVF Config-B Min Xu
@ 2021-12-15  9:32   ` Gerd Hoffmann
  0 siblings, 0 replies; 37+ messages in thread
From: Gerd Hoffmann @ 2021-12-15  9:32 UTC (permalink / raw)
  To: Min Xu
  Cc: devel, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky

  Hi,

>  - Remove unnecessary drivers to reduce attack surface, such as
>    network stack.

> +  #
> +  # Defines for default states.  These can be changed on the command line.
> +  # -D FLAG=VALUE
> +  #
> +  DEFINE SECURE_BOOT_ENABLE      = FALSE
> +  DEFINE SMM_REQUIRE             = FALSE
> +  DEFINE SOURCE_DEBUG_ENABLE     = FALSE
> +  DEFINE TPM_ENABLE              = FALSE
> +  DEFINE TPM_CONFIG_ENABLE       = FALSE
> +
> +  #
> +  # Network definition
> +  #
> +  DEFINE NETWORK_TLS_ENABLE             = FALSE
> +  DEFINE NETWORK_IP6_ENABLE             = FALSE
> +  DEFINE NETWORK_HTTP_BOOT_ENABLE       = FALSE
> +  DEFINE NETWORK_ALLOW_HTTP_CONNECTIONS = TRUE
> +  DEFINE NETWORK_ISCSI_ENABLE           = TRUE
> +
> +!include NetworkPkg/NetworkDefines.dsc.inc
> +

Hmm, that doesn't look very stripped down to me ...

take care,
  Gerd


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [PATCH 05/10] OvmfPkg: Add SecPlatformLibQemuTdx
  2021-12-14 13:41 ` [PATCH 05/10] OvmfPkg: Add SecPlatformLibQemuTdx Min Xu
@ 2021-12-15  9:48   ` Gerd Hoffmann
  2022-01-07  6:29     ` Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2021-12-15  9:48 UTC (permalink / raw)
  To: Min Xu
  Cc: devel, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky

  Hi,

> +#define FW_CFG_NX_STACK_ITEM        "opt/ovmf/PcdSetNxForStack"

Why this is needed?

> +//
> +// Values we program into the PM base address registers
> +//
> +#define PIIX4_PMBA_VALUE   0xB000
> +#define ICH9_PMBASE_VALUE  0x0600

They are in OvmfPkg/Include/OvmfPlatforms.h, no need to copy them over.

> +VOID
> +PciExBarInitialization (

> +VOID
> +MiscInitialization (

Cut+Paste from PlatformPei

Please refactor the code (move the functions needed to a Library?) so we
don't have multiple copies of the setup code.

take care,
  Gerd


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [PATCH 06/10] OvmfPkg: Add TdxStartupLib
  2021-12-14 13:41 ` [PATCH 06/10] OvmfPkg: Add TdxStartupLib Min Xu
@ 2021-12-15 10:09   ` Gerd Hoffmann
  2021-12-16 11:56     ` Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2021-12-15 10:09 UTC (permalink / raw)
  To: Min Xu
  Cc: devel, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky

  Hi,

> +  PageTables = 0;
> +  if (FeaturePcdGet (PcdDxeIplBuildPageTables)) {

Can this ever be false in a x64 build?

> +EFI_STATUS
> +FindDxeCore (
> +  IN INTN                         FvInstance,
> +  IN OUT     EFI_PEI_FILE_HANDLE  *FileHandle
> +  )
> +{

> +  if (FvInstance != -1) {
> +    //
> +    // Caller passed in a specific FV to try, so only try that one
> +    //
[ ... ]
> +  } else {
> +    // Assume the FV that contains the SEC (our code) also contains a compressed FV.

This branch never runs, FvInstance is explicity set to 1 by the caller.

> +++ b/OvmfPkg/IntelTdx/TdxStartupLib/X64/PageTables.h

There is OvmfPkg/Include/IndustryStandard/PageTable.h

> +VOID
> +Split2MPageTo4K (

Yet another copy of this.  Please don't.

take care,
  Gerd


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2021-12-14 13:41 ` [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B Min Xu
@ 2021-12-15 10:27   ` Gerd Hoffmann
  2021-12-16 12:21     ` [edk2-devel] " Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2021-12-15 10:27 UTC (permalink / raw)
  To: Min Xu
  Cc: devel, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky

On Tue, Dec 14, 2021 at 09:41:24PM +0800, Min Xu wrote:
> RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429
> 
> Tdvf Config-B skip PEI phase to reduce attack surface. So instead of
> jumping to SecStartupPhase2 (), TdxStartup () is called. This function
> brings up Tdx guest from SEC phase to DXE phase.

> + #ifdef INTEL_TDX_FULL_FEATURE
> +  if (SecTdxIsEnabled ()) {
> +    TdxStartup (&SecCoreData);
> +
> +    //
> +    // Never arrived here
> +    //
> +    ASSERT (FALSE);
> +    CpuDeadLoop ();
> +  }
> +
> + #endif

Oh, wow.  So you compile in PEI, then decide at runtime whenever you
use it or not?

No.  Please don't.  That's just silly.  If you don't want use PEI, ok,
fine, but please go the way then, remove PEI from the build and take
the PEI-less code path in all cases.

take care,
  Gerd


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg
  2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
                   ` (9 preceding siblings ...)
  2021-12-14 13:41 ` [PATCH 10/10] OvmfPkg: Add Tdx libs to prevent building broken Min Xu
@ 2021-12-15 10:41 ` Gerd Hoffmann
  2021-12-16 12:36   ` Min Xu
  10 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2021-12-15 10:41 UTC (permalink / raw)
  To: Min Xu
  Cc: devel, Michael D Kinney, Brijesh Singh, Erdem Aktas,
	James Bottomley, Jiewen Yao, Tom Lendacky, Leif Lindholm,
	Ard Biesheuvel, Abner Chang, Daniel Schaefer

  Hi,

> Patch 2/3:
> This patch-set leverage the PrePiLib and MemoryAllocationLib in
> EmbeddedPkg. Some new funtions are added to meet the Tdvf Config-B
> requirement.

Care to explain why this is needed?  How is tdvf different from other
pei-less platforms?  Could we just place DXEFV directly in the firmware
image, without wrapping it into FVMAIN_COMPACT for compression?

take care,
  Gerd


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 03/10] EmbeddedPkg/MemoryAllocationLib: Add null stub for AllocateCopyPool
  2021-12-14 13:59   ` [edk2-devel] " Ard Biesheuvel
@ 2021-12-16  3:08     ` Min Xu
  0 siblings, 0 replies; 37+ messages in thread
From: Min Xu @ 2021-12-16  3:08 UTC (permalink / raw)
  To: Ard Biesheuvel, edk2-devel-groups-io, Gerd Hoffmann
  Cc: Kinney, Michael D, Brijesh Singh, Aktas, Erdem, James Bottomley,
	Yao, Jiewen, Tom Lendacky, Leif Lindholm, Ard Biesheuvel,
	Chang, Abner, Schaefer, Daniel

On December 14, 2021 9:59 PM, Ard Biesheuvel wrote:
> On Tue, 14 Dec 2021 at 14:42, Min Xu <min.m.xu@intel.com> wrote:
> >
> > RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429
> >
> > This function is a null stub to make the build success.
> >
> > ---
> >  .../MemoryAllocationLib.c                     | 28 +++++++++++++++++++
> >  1 file changed, 28 insertions(+)
> >
> 
> Why is it justified to implement a broken version of this routine?
> This is not a NULL library class that only exists for build test purposes, it is
> actually used in production builds.
> 
> If the TDVF code needs the symbol but does not actually call it, perhaps there is
> another place where this should get fixed?
> 
PeiServicesLib (MdePkg/Library/PeiServicesLib/PeiServicesLib.inf) is imported in In OvmfPkg/Sec/SecMain.inf. In the implementation of this lib, AllocateCopyPool is used. AllocateCopyPool is implemented in MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf. 
With the introduction of TDVF Config-B, MemoryAllocationLib is changed to EmbeddedPkg/Library/PrePiMemoryAllocationLib/PrePiMemoryAllocationLib.inf. In this MemoryAllocationLib, AllocateCopyPool is not implemented.
So I have to add a null stub of AllocateCopyPool in EmbeddedPkg/Library/PrePiMemoryAllocationLib/MemoryAllocationLib.c

I carefully re-check the OvmfPkg/Sec and find PeiServicesLib is not needed. So PeiServiceLib is removed from SecMain.inf. This time AllocateCopyPool is not needed either. So this commit will be dropped in the next version. Thanks much for your reminder.

Min




^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 02/10] EmbeddedPkg/PrePiLib: Update PrePiLib
  2021-12-14 14:00   ` [edk2-devel] " Ard Biesheuvel
@ 2021-12-16  4:48     ` Min Xu
  0 siblings, 0 replies; 37+ messages in thread
From: Min Xu @ 2021-12-16  4:48 UTC (permalink / raw)
  To: devel@edk2.groups.io, ardb@kernel.org
  Cc: Kinney, Michael D, Brijesh Singh, Aktas, Erdem, James Bottomley,
	Yao, Jiewen, Tom Lendacky, Gerd Hoffmann, Leif Lindholm,
	Ard Biesheuvel, Chang, Abner, Schaefer, Daniel

On December 14, 2021 10:01 PM, Ard Biesheuvel wrote:
> On Tue, 14 Dec 2021 at 14:42, Min Xu <min.m.xu@intel.com> wrote:
> > --- a/EmbeddedPkg/Library/PrePiLib/FwVol.c
> > +++ b/EmbeddedPkg/Library/PrePiLib/FwVol.c
> > @@ -335,7 +335,7 @@ FfsProcessSection (
> >
> >          Status = UefiDecompressGetInfo (
> >                     CompressedData,
> > -                   CompressedDataLength,
> > +                   (UINT32)CompressedDataLength,
> 
> How is this change related to the items listed in the commit log?
> 
> If there are code issues affecting this library, please fix them in a separate
> patch.
> 
CompressedDataLength is declared as UINTN which is UINT64 in X64 arch. But the second parameter of UefiDecompressGetInfo() is declared as UINT32. So a build error is triggered.
  RETURN_STATUS
  EFIAPI
  UefiDecompressGetInfo (
    IN  CONST VOID  *Source,
    IN  UINT32      SourceSize,
    OUT UINT32      *DestinationSize,
    OUT UINT32      *ScratchSize
    );

I will fix it in a separate patch.

Thanks
Min

^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [PATCH 06/10] OvmfPkg: Add TdxStartupLib
  2021-12-15 10:09   ` Gerd Hoffmann
@ 2021-12-16 11:56     ` Min Xu
  2022-01-12  1:55       ` Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2021-12-16 11:56 UTC (permalink / raw)
  To: Gerd Hoffmann
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

On December 15, 2021 6:09 PM, Gerd Hoffmann wrote:
> > +  PageTables = 0;
> > +  if (FeaturePcdGet (PcdDxeIplBuildPageTables)) {
> 
> Can this ever be false in a x64 build?
You're right. This cannot be false in X64 build. I will refactor  it in the next version.
> 
> > +EFI_STATUS
> > +FindDxeCore (
> > +  IN INTN                         FvInstance,
> > +  IN OUT     EFI_PEI_FILE_HANDLE  *FileHandle
> > +  )
> > +{
> 
> > +  if (FvInstance != -1) {
> > +    //
> > +    // Caller passed in a specific FV to try, so only try that one
> > +    //
> [ ... ]
> > +  } else {
> > +    // Assume the FV that contains the SEC (our code) also contains a
> compressed FV.
> 
> This branch never runs, FvInstance is explicity set to 1 by the caller.
Thanks for reminder. It will be fixed in the next version.
> 
> > +++ b/OvmfPkg/IntelTdx/TdxStartupLib/X64/PageTables.h
> 
> There is OvmfPkg/Include/IndustryStandard/PageTable.h
> 
> > +VOID
> > +Split2MPageTo4K (
> 
> Yet another copy of this.  Please don't.
I will figure out a Page walker lib so that these duplicated code can be avoided. Thanks for reminder.

Thanks
Min

^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2021-12-15 10:27   ` Gerd Hoffmann
@ 2021-12-16 12:21     ` Min Xu
  2021-12-16 14:25       ` Gerd Hoffmann
  0 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2021-12-16 12:21 UTC (permalink / raw)
  To: devel@edk2.groups.io, kraxel@redhat.com
  Cc: Kinney, Michael D, Brijesh Singh, Aktas, Erdem, James Bottomley,
	Yao, Jiewen, Tom Lendacky

On December 15, 2021 6:28 PM, Gerd Hoffmann wrote:
> On Tue, Dec 14, 2021 at 09:41:24PM +0800, Min Xu wrote:
> > RFC: https://bugzilla.tianocore.org/show_bug.cgi?id=3429
> >
> > Tdvf Config-B skip PEI phase to reduce attack surface. So instead of
> > jumping to SecStartupPhase2 (), TdxStartup () is called. This function
> > brings up Tdx guest from SEC phase to DXE phase.
> 
> > + #ifdef INTEL_TDX_FULL_FEATURE
> > +  if (SecTdxIsEnabled ()) {
> > +    TdxStartup (&SecCoreData);
> > +
> > +    //
> > +    // Never arrived here
> > +    //
> > +    ASSERT (FALSE);
> > +    CpuDeadLoop ();
> > +  }
> > +
> > + #endif
> 
> Oh, wow.  So you compile in PEI, then decide at runtime whenever you use it
> or not?
Yes.
In OvmfPkgX64.dsc above code will not be built into the image. So it follows the SEC->PEI->DXE flow.
In IntelTdxX64.dsc, it if is Tdx guest, it jumps from SEC to DXE (see TdxStartup ()). Otherwise, it follows the SEC->PEI->DXE flow (Legacy guest, SEV guest, etc).
> 
> No.  Please don't.  That's just silly.  If you don't want use PEI, ok, fine, but
> please go the way then, remove PEI from the build and take the PEI-less code
> path in all cases.
In the first version TDVF, we do remove the PEI from the image. The image only contains the SEC and DXE, and only the components TDVF needs. It's a slim image.
Then the *ONE BINARY* requirement is proposed. It requires to bring up Legacy guest and Tdx guest with the same image. So PEI must be included in the build, and it probes Tdx guest in run-time so that it decides to go to the legacy flow (SEC->PEI->DXE) or Tdx flow (SEC->DXE).
Below are some of the links about the discussion.
https://edk2.groups.io/g/devel/message/76023  Laszlo
https://edk2.groups.io/g/devel/message/76024  Jiewen
https://edk2.groups.io/g/devel/message/76065  Laszlo
https://edk2.groups.io/g/devel/message/76339  Erdem Aktas
https://edk2.groups.io/g/devel/message/76367  Config-A & Config-B

Thanks
Min

^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg
  2021-12-15 10:41 ` [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Gerd Hoffmann
@ 2021-12-16 12:36   ` Min Xu
  0 siblings, 0 replies; 37+ messages in thread
From: Min Xu @ 2021-12-16 12:36 UTC (permalink / raw)
  To: Gerd Hoffmann
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky,
	Leif Lindholm, Ard Biesheuvel, Chang, Abner, Schaefer, Daniel

On December 15, 2021 6:42 PM, Gerd Hoffmann wrote:
> > Patch 2/3:
> > This patch-set leverage the PrePiLib and MemoryAllocationLib in
> > EmbeddedPkg. Some new funtions are added to meet the Tdvf Config-B
> > requirement.
> 
> Care to explain why this is needed?  How is tdvf different from other pei-less
> platforms?  Could we just place DXEFV directly in the firmware image, without
> wrapping it into FVMAIN_COMPACT for compression?
PrePiLib and MemoryAllocationLib in EmbeddedPkg can meet most of the requirement of TDVF Config-B, for example, the hob list functions, fw volume related functions, memory allocation functions, etc. 
But there are still TDVF specific function missed. For Example, EmbeddedPkg assumes the compressed section contains only one FV (DXE FV), so FfsProcessFvFile () can only handle this situation. But in TDVF's image, the compressed section contains 2 FV (PeiFV and DxeFV, this is because of *ONE BINARY* requirement). So FfsProcessFvFileEx () is added to handle this case.
I have to say, *ONE BINARY* requirement restricts us from changing the OVMF image layout, otherwise the current code (legacy guest, SEV guest, etc) will break.

Thanks
Min

^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2021-12-16 12:21     ` [edk2-devel] " Min Xu
@ 2021-12-16 14:25       ` Gerd Hoffmann
  2021-12-19  2:49         ` Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2021-12-16 14:25 UTC (permalink / raw)
  To: Xu, Min M
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

  Hi,

> > Oh, wow.  So you compile in PEI, then decide at runtime whenever you use it
> > or not?
> Yes.
> In OvmfPkgX64.dsc above code will not be built into the image. So it follows the SEC->PEI->DXE flow.
> In IntelTdxX64.dsc, it if is Tdx guest, it jumps from SEC to DXE (see TdxStartup ()). Otherwise, it follows the SEC->PEI->DXE flow (Legacy guest, SEV guest, etc).

> > No.  Please don't.  That's just silly.  If you don't want use PEI, ok, fine, but
> > please go the way then, remove PEI from the build and take the PEI-less code
> > path in all cases.

> In the first version TDVF, we do remove the PEI from the image. The
> image only contains the SEC and DXE, and only the components TDVF
> needs. It's a slim image.  Then the *ONE BINARY* requirement is
> proposed. It requires to bring up Legacy guest and Tdx guest with the
> same image. So PEI must be included in the build,

Why?  Booting non-tdx guests without PEI shouldn't be fundamentally
different from a TDX guest.  Memory detection needs fw_cfg instead of
the td_hob, and you have to skip some tdx setup steps, but that should
be it.  Code for all that exists in PlatformPei, it only needs to be
moved to a place where SEC can use it too.

Yes, you can't include a number of features which depend on PEI into the
build then.  But config-b wants be a stripped down build anyway, right?

One major advantage of having a single binary is that most aspects of
the SEC->DXE boot workflow can also be tested without TDX.  Easier for
developers.  Easier for CI coverage.  Especially now where we talk about
pre-production hardware support.

When builing a frankenstein image which uses SEC->DXE with TDX and
SEC->PEI->DXE without TDX you loose that advantage, because that is
effectively a two-in-one binary.

> and it probes Tdx
> guest in run-time so that it decides to go to the legacy flow
> (SEC->PEI->DXE) or Tdx flow (SEC->DXE).

Ok, so the state with wave-2 merged will be:

  * We have the ovmf build, which supports native/sev/tdx guests,
    with basic tdx support (aka config-a).

  * We have the amdsev variant (supports native/sev/not-sure-about-tdx),
    which is largely identical to the normal build, only unwanted
    drivers removed (no network etc), grub boot loader added and its own
    PlatformBootManagerLib to have a more strict boot policy (all dxe
    phase changes).

So, where to go from here?


I still think the best way forward would be to model the inteltdx build
(aka config-b) similar to the amdsev variant.  Just disable the stuff
you don't need, add support for the advanced tdx features (measurement
etc), but otherwise continue to use the same SEC->PEI->DXE boot
workflow.

Advantages:
  * It should be relatively easy to unify amdsev + inteltdx into one
    binary.
  * No quirks needed due to SEC/PEI differences.  SEC can't set PCDs,
    leading to patches like #9 of this series (and there was another
    similar one ...).


The other route (as preferred by Jiewen) would be to not use PEI in
inteltdx.  Requires some reorganization of the qemu platform
initialization code (probably move to lib) so we can run the same code
(without using cut+paste programming) in both sec and pei phase.
Clearly not my preference, but should work too.

A better solution for the PCD issue (and possibly other simliar issues
poping up later) would be good.  Can't we handle that early in
PlatformDxe?  So we have one single place for those quirks, and the dxe
drivers don't need to know about the SEC->DXE and SEC->PEI->DXE
differences?

take care,
  Gerd


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2021-12-16 14:25       ` Gerd Hoffmann
@ 2021-12-19  2:49         ` Min Xu
  2021-12-20 12:11           ` Gerd Hoffmann
  0 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2021-12-19  2:49 UTC (permalink / raw)
  To: devel@edk2.groups.io, kraxel@redhat.com
  Cc: Kinney, Michael D, Brijesh Singh, Aktas, Erdem, James Bottomley,
	Yao, Jiewen, Tom Lendacky

On December 16, 2021 10:25 PM, Gerd Hoffmann wrote:
> > > Oh, wow.  So you compile in PEI, then decide at runtime whenever you
> > > use it or not?
> > Yes.
> > In OvmfPkgX64.dsc above code will not be built into the image. So it follows
> the SEC->PEI->DXE flow.
> > In IntelTdxX64.dsc, it if is Tdx guest, it jumps from SEC to DXE (see TdxStartup
> ()). Otherwise, it follows the SEC->PEI->DXE flow (Legacy guest, SEV guest, etc).
> 
> > > No.  Please don't.  That's just silly.  If you don't want use PEI,
> > > ok, fine, but please go the way then, remove PEI from the build and
> > > take the PEI-less code path in all cases.
> 
> > In the first version TDVF, we do remove the PEI from the image. The
> > image only contains the SEC and DXE, and only the components TDVF
> > needs. It's a slim image.  Then the *ONE BINARY* requirement is
> > proposed. It requires to bring up Legacy guest and Tdx guest with the
> > same image. So PEI must be included in the build,
> 
> Why?  Booting non-tdx guests without PEI shouldn't be fundamentally
> different from a TDX guest.  Memory detection needs fw_cfg instead of the
> td_hob, and you have to skip some tdx setup steps, but that should be it.
> Code for all that exists in PlatformPei, it only needs to be moved to a place
> where SEC can use it too.
> 
> Yes, you can't include a number of features which depend on PEI into the build
> then.  But config-b wants be a stripped down build anyway, right?
> 
> One major advantage of having a single binary is that most aspects of the SEC-
> >DXE boot workflow can also be tested without TDX.  Easier for developers.
> Easier for CI coverage.  Especially now where we talk about pre-production
> hardware support.
> 
> When builing a frankenstein image which uses SEC->DXE with TDX and
> SEC->PEI->DXE without TDX you loose that advantage, because that is
> effectively a two-in-one binary.
> 
> > and it probes Tdx
> > guest in run-time so that it decides to go to the legacy flow
> > (SEC->PEI->DXE) or Tdx flow (SEC->DXE).
> 
> Ok, so the state with wave-2 merged will be:
> 
>   * We have the ovmf build, which supports native/sev/tdx guests,
>     with basic tdx support (aka config-a).
> 
>   * We have the amdsev variant (supports native/sev/not-sure-about-tdx),
>     which is largely identical to the normal build, only unwanted
>     drivers removed (no network etc), grub boot loader added and its own
>     PlatformBootManagerLib to have a more strict boot policy (all dxe
>     phase changes).
> 
> So, where to go from here?
> 
> 
> I still think the best way forward would be to model the inteltdx build (aka
> config-b) similar to the amdsev variant.  Just disable the stuff you don't need,
> add support for the advanced tdx features (measurement etc), but otherwise
> continue to use the same SEC->PEI->DXE boot workflow.
> 
> Advantages:
>   * It should be relatively easy to unify amdsev + inteltdx into one
>     binary.
>   * No quirks needed due to SEC/PEI differences.  SEC can't set PCDs,
>     leading to patches like #9 of this series (and there was another
>     similar one ...).
> 
> 
> The other route (as preferred by Jiewen) would be to not use PEI in inteltdx.
> Requires some reorganization of the qemu platform initialization code
> (probably move to lib) so we can run the same code (without using cut+paste
> programming) in both sec and pei phase.
> Clearly not my preference, but should work too.
> 
> A better solution for the PCD issue (and possibly other simliar issues poping up
> later) would be good.  Can't we handle that early in PlatformDxe?  So we have
> one single place for those quirks, and the dxe drivers don't need to know
> about the SEC->DXE and SEC->PEI->DXE differences?
> 
Thank Gerd for the review comments.
Yes, TDVF Config-B is a strip down and it is to be a more secure solution (because RTMR based measurement/measure boot is enabled, un-used drivers are excluded to reduce attack surface, sanity check/measure all external inputs, etc).

We would like to split TDVF Config-B into below stages.
1. Basic Config-B (wave-3)
1.1 A standalone IntelTdxX64.dsc/.fdf. Un-used drivers/libs are removed from the fdf, such as network components, SMM drivers, TPM drivers, etc.
1.2 PEI FV is excluded from the build. Only DxeFV is included.
1.3 Since PEI FV is excluded from the build, so Basic Config-B can only bring up Tdx guest. It *CAN NOT* bring up legacy guest.

2. Advanced Config-B (wave-4)
2.1 RTMR based measurement and measure boot are enabled
2.2 External input is checked and measured

3. Full feature Config-B (wave-5)
3.1 Add *basic* Ovmf feature without PEI, to achieve *ONE Binary* goal. (here basic means S3 is not supported without PEI)

@Gerd, What's your thought?

Thanks
Min


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2021-12-19  2:49         ` Min Xu
@ 2021-12-20 12:11           ` Gerd Hoffmann
  2021-12-24  3:02             ` Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2021-12-20 12:11 UTC (permalink / raw)
  To: Xu, Min M
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

  Hi,

> > Why?  Booting non-tdx guests without PEI shouldn't be fundamentally
> > different from a TDX guest.  Memory detection needs fw_cfg instead of the
> > td_hob, and you have to skip some tdx setup steps, but that should be it.
> > Code for all that exists in PlatformPei, it only needs to be moved to a place
> > where SEC can use it too.

> We would like to split TDVF Config-B into below stages.
> 1. Basic Config-B (wave-3)
> 1.1 A standalone IntelTdxX64.dsc/.fdf. Un-used drivers/libs are removed from the fdf, such as network components, SMM drivers, TPM drivers, etc.
> 1.2 PEI FV is excluded from the build. Only DxeFV is included.
> 1.3 Since PEI FV is excluded from the build, so Basic Config-B can only bring up Tdx guest. It *CAN NOT* bring up legacy guest.

What blocks legacy guest bringup?

See above, I think it should not be hard to do, and given that
TDX-capable hardware is not yet production ready I find it rather
important that testing the PEI-less boot workflow does not require
TDX.

It'll also make it much easier to add CI coverage.

> 3.1 Add *basic* Ovmf feature without PEI, to achieve *ONE Binary* goal. (here basic means S3 is not supported without PEI)

Sure, pei-less ovmf has to drop some features, that is perfectly fine.

take care,
  Gerd


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2021-12-20 12:11           ` Gerd Hoffmann
@ 2021-12-24  3:02             ` Min Xu
  2022-01-03  8:02               ` Gerd Hoffmann
  0 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2021-12-24  3:02 UTC (permalink / raw)
  To: devel@edk2.groups.io, kraxel@redhat.com
  Cc: Kinney, Michael D, Brijesh Singh, Aktas, Erdem, James Bottomley,
	Yao, Jiewen, Tom Lendacky

Hi
> 
> > > Why?  Booting non-tdx guests without PEI shouldn't be fundamentally
> > > different from a TDX guest.  Memory detection needs fw_cfg instead
> > > of the td_hob, and you have to skip some tdx setup steps, but that
> should be it.
> > > Code for all that exists in PlatformPei, it only needs to be moved
> > > to a place where SEC can use it too.
> 
> > We would like to split TDVF Config-B into below stages.
> > 1. Basic Config-B (wave-3)
> > 1.1 A standalone IntelTdxX64.dsc/.fdf. Un-used drivers/libs are removed
> from the fdf, such as network components, SMM drivers, TPM drivers, etc.
> > 1.2 PEI FV is excluded from the build. Only DxeFV is included.
> > 1.3 Since PEI FV is excluded from the build, so Basic Config-B can only bring
> up Tdx guest. It *CAN NOT* bring up legacy guest.
> 
> What blocks legacy guest bringup?
> 
> See above, I think it should not be hard to do, and given that TDX-capable
> hardware is not yet production ready I find it rather important that testing
> the PEI-less boot workflow does not require TDX.
Current PlatformPei does below tasks (no SMM, no S3):
1. Fetch the memory information from either e820 or CMOS, then create the ResourceDescriptorHob.
2. Create MemoryAllocationHob for PeiFV/DxeFV, create FvHob for DxeFV.
3. Read the CPU count from QEMU and set the PCDs.
4. Create the ResourceDescriptorHob for MMIO and set the PCDs
5. Other Hobs, such as MemTypeInfoHob, CpuHob
6. Set PCDs, such as PcdSetNxForStack, PcdOvmfHostBridgePciDevId, PcdPciIoBase, etc
7. Calculate the memory for PEI and PublishPeiMemory
8. InstallClearCacheCallback/InstallFeatureControlCallback

Task 7 is not needed in PEI-less boot up.
Task 8 is not needed either because it is for MP Services.

PCDs cannot be set in SEC phase, so the values should be saved in a Hob (for example, PLATFORM_INFO_HOB). In early DXE phase these values are set to the PCDs. This is how TdxDxe does today.

Other tasks can be done in SEC phase. I think there should be a lib (for example, PlatformPeiLib) to wrap these functions so that they can be re-used by OvmfPkg/PlatformPei. 

PEI-less booting up legacy guest doesn't support TPM.

So to boot up legacy guest without PEI phase, there will be below changes.
1. OvmfStartupLib:  (like TdxStartupLib)
    - Decompress DxeFv, locate DxeCore, create IdentityMappingPageTables, then jump to DxeCore.
2. PlatformPeiLib:
    - Wrap the functions to do memory initialization, etc. (see tasks 1-5)
3. OvmfLegacyDxe
    - Set the PCDs (see task 6)

Base upon above consideration, It's a big change. That's why we suggest implement Config-B in 3 stages.

I am also thinking about another option which includes PEI in build. (That's Config-B v1)
In this option, Ovmf image layout is kept unchanged. In run-time Tdx guest is probed. If it is Tdx guest, it goes to TdxStartup and brings up Tdx guest. Otherwise it follows normal Ovmf boot flow.
The advantages are:
1. The change is small.
2. It doesn't impact the current legacy guest, nor the SEV guest.

I know there are many discussions in above options. Can we follow below road map so that we can discuss 3 (How to achieve ONE Binary) in more details?
1. Basic Config-B (PEI-less and only Tdx guest)
2. Advanced Config-B (RTMR based measurement)
3. One Binary Config-B (support legacy guest)

> ... and given that TDX-capable
> hardware is not yet production ready I find it rather important that testing
> the PEI-less boot workflow does not require TDX.
> 
> It'll also make it much easier to add CI coverage.
I am thinking if SEV features are covered in CI? Because I want to make sure our changes don't impact SEV.

Thanks
Min

^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2021-12-24  3:02             ` Min Xu
@ 2022-01-03  8:02               ` Gerd Hoffmann
  2022-01-07  6:13                 ` Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2022-01-03  8:02 UTC (permalink / raw)
  To: Xu, Min M
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

  Hi,

> PCDs cannot be set in SEC phase, so the values should be saved in a
> Hob (for example, PLATFORM_INFO_HOB). In early DXE phase these values
> are set to the PCDs. This is how TdxDxe does today.
> 
> Other tasks can be done in SEC phase. I think there should be a lib
> (for example, PlatformPeiLib) to wrap these functions so that they can
> be re-used by OvmfPkg/PlatformPei. 

Yes, I think we need a PlatformLib for the platform initialization
code.  With PEI we would simply link the lib into PlatformPei, without
PEI we would link parts of the lib into SEC and parts of the lib into
DXE.

> PEI-less booting up legacy guest doesn't support TPM.
> 
> So to boot up legacy guest without PEI phase, there will be below changes.
> 1. OvmfStartupLib:  (like TdxStartupLib)
>     - Decompress DxeFv, locate DxeCore, create IdentityMappingPageTables, then jump to DxeCore.

Yes.  Basically rename TdxStartupLib to OvmfStartupLib and add some
IfTdx() checks.

> 2. PlatformPeiLib:
>     - Wrap the functions to do memory initialization, etc. (see tasks 1-5)

Yes.  Move code from PlatformPei to PlatformLib.  Might also need some
reorganization due to SEC restrictions.

> 3. OvmfLegacyDxe
>     - Set the PCDs (see task 6)

Well, in Tdx mode you have to set some PCDs too ...

Also not sure we actually need a new Dxe.  Can't we just handle
that in PlatformDxe in case of a PEI-less boot?

> I know there are many discussions in above options. Can we follow below road map so that we can discuss 3 (How to achieve ONE Binary) in more details?
> 1. Basic Config-B (PEI-less and only Tdx guest)
> 2. Advanced Config-B (RTMR based measurement)
> 3. One Binary Config-B (support legacy guest)

IMHO step #1 must be reorganizing the platform initialization code for
PEI-less boot (create PlatformLib as discussed above).

This patch series side-steps that by simply duplicating the code.  PCI
initialization for example.  Also setting the tdx PCDs.  Having two (or
even more) copies of the same code in the tree is a bad idea though.
It makes long-term maintenance harder for various reasons.

> > ... and given that TDX-capable
> > hardware is not yet production ready I find it rather important that testing
> > the PEI-less boot workflow does not require TDX.
> > 
> > It'll also make it much easier to add CI coverage.
> I am thinking if SEV features are covered in CI?
> Because I want to make sure our changes don't impact SEV.

AmdSevX64.dsc has build-test coverage.  There is no qemu boot test
because FlashRomImage() (in OvmfPkg/PlatformCI/PlatformBuildLib.py)
is not flexible enough for that.  Fixing that and adding a boot test
(in non-sev mode) shouldn't be that difficult though.

Same for IntelTdx.dsc: adding a CI boot test (in non-tdx mode) should be
easy, and it should help preventing regressions in PEI-less boot flow.

take care,
  Gerd


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2022-01-03  8:02               ` Gerd Hoffmann
@ 2022-01-07  6:13                 ` Min Xu
  2022-01-10  7:55                   ` Gerd Hoffmann
  0 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2022-01-07  6:13 UTC (permalink / raw)
  To: kraxel@redhat.com
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

On January 3, 2022 4:02 PM, Gerd Hoffmann wrote:
> 
> > PCDs cannot be set in SEC phase, so the values should be saved in a
> > Hob (for example, PLATFORM_INFO_HOB). In early DXE phase these values
> > are set to the PCDs. This is how TdxDxe does today.
> >
> > Other tasks can be done in SEC phase. I think there should be a lib
> > (for example, PlatformPeiLib) to wrap these functions so that they can
> > be re-used by OvmfPkg/PlatformPei.
> 
> Yes, I think we need a PlatformLib for the platform initialization code.  With
> PEI we would simply link the lib into PlatformPei, without PEI we would link
> parts of the lib into SEC and parts of the lib into DXE.
After carefully study the PlatformPei code and a quick PoC (PlatformInitLib which wraps the basic functions in PlatformPei), I found it's not a easy task for such a lib which can be used in both PlatformPei and Pei-less boot.
1. PlatformInitLib should work both in SEC and PEI. So it cannot use global variables between different functions. mHostBridgeDevId and mPhysMemAddressWidth are the examples. So these variables must be provided by the caller thru the input function parameters.
2. PlatformInitLib cannot set PCDs in the code. So a Guid hob should be created to store the PCDs and pass them to DXE phase. Then these PCDs will be set at the very beginning of DXE phase.
3. The pointer to the HobList should be saved somewhere so that HobLib functions can be called in SEC phase. In my PoC it is saved in OVMF_WORK_AREA.
4. In PlatformPei there are many if-else to check if it is SMM/S3/Microvm/Cloud-Hypervisor/SEV/TDX. There are also Bhyve and Xen PlatformPei variants. In the current PlatformPei those if-else check depends on the PCDs and global variables. Because of (1) it needs input parameters for all these if-else check. Maybe a big environment variable data structure is needed.
But anyway a complete functional PlatformInitLib is a big task. My suggestion is that in TDVF-Config-B we first propose a basic functional PlatformInitLib. This lib can boot up Tdx guest and legacy OVMF guest in TDVF-Config-B. OvmfPkg/PlatformPei is not refactored by this basic PlatformInitLib this time. This is because PlatformPei serves SMM/S3/Microvm/Cloud-Hypervisor/SEV/TDX. It is a big risk for such refactor. We can revisit PlatformPei in the future.
> 
> > PEI-less booting up legacy guest doesn't support TPM.
> >
> > So to boot up legacy guest without PEI phase, there will be below changes.
> > 1. OvmfStartupLib:  (like TdxStartupLib)
> >     - Decompress DxeFv, locate DxeCore, create IdentityMappingPageTables,
> then jump to DxeCore.
> 
> Yes.  Basically rename TdxStartupLib to OvmfStartupLib and add some
> IfTdx() checks.
Yes, agree.
> 
> > 2. PlatformPeiLib:
> >     - Wrap the functions to do memory initialization, etc. (see tasks
> > 1-5)
> 
> Yes.  Move code from PlatformPei to PlatformLib.  Might also need some
> reorganization due to SEC restrictions.
As I explained above, a basic PlatformInitLib is the first stage and some reorganization is needed.
> 
> > 3. OvmfLegacyDxe
> >     - Set the PCDs (see task 6)
> 
> Well, in Tdx mode you have to set some PCDs too ...
TdxDxe.inf can set the PCDs.
> 
> Also not sure we actually need a new Dxe.  Can't we just handle that in
> PlatformDxe in case of a PEI-less boot?
Do you mean "OvmfPkg/PlatformDxe/Platform.inf"? I am afraid PlatformDxe cannot do this task. 
It is not in APRIORI DXE list so it cannot be guaranteed to be loaded at the very beginning of DXE phase. While some PCDs are required in the very early stage of DXE phase.
> 
> > I know there are many discussions in above options. Can we follow below
> road map so that we can discuss 3 (How to achieve ONE Binary) in more
> details?
> > 1. Basic Config-B (PEI-less and only Tdx guest) 2. Advanced Config-B
> > (RTMR based measurement) 3. One Binary Config-B (support legacy guest)
> 
> IMHO step #1 must be reorganizing the platform initialization code for PEI-
> less boot (create PlatformLib as discussed above).
> 
> This patch series side-steps that by simply duplicating the code.  PCI
> initialization for example.  Also setting the tdx PCDs.  Having two (or even
> more) copies of the same code in the tree is a bad idea though.
> It makes long-term maintenance harder for various reasons.
As I explained above, a basic PlatformInitLib is the first stage. There will be an advanced PlatformInitLib in the future which implements more complicated functions.
> 
> > > ... and given that TDX-capable
> > > hardware is not yet production ready I find it rather important that
> > > testing the PEI-less boot workflow does not require TDX.
> > >
> > > It'll also make it much easier to add CI coverage.
> > I am thinking if SEV features are covered in CI?
> > Because I want to make sure our changes don't impact SEV.
> 
> AmdSevX64.dsc has build-test coverage.  There is no qemu boot test
> because FlashRomImage() (in OvmfPkg/PlatformCI/PlatformBuildLib.py)
> is not flexible enough for that.  Fixing that and adding a boot test (in non-sev
> mode) shouldn't be that difficult though.
> 
> Same for IntelTdx.dsc: adding a CI boot test (in non-tdx mode) should be
> easy, and it should help preventing regressions in PEI-less boot flow.
Agree. We will add a CI boot test (in non-tdx mode).

Thanks
Min

^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [PATCH 05/10] OvmfPkg: Add SecPlatformLibQemuTdx
  2021-12-15  9:48   ` Gerd Hoffmann
@ 2022-01-07  6:29     ` Min Xu
  0 siblings, 0 replies; 37+ messages in thread
From: Min Xu @ 2022-01-07  6:29 UTC (permalink / raw)
  To: Gerd Hoffmann
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

Hi,
> 
> > +#define FW_CFG_NX_STACK_ITEM        "opt/ovmf/PcdSetNxForStack"
> 
> Why this is needed?
> 
> > +//
> > +// Values we program into the PM base address registers //
> > +#define PIIX4_PMBA_VALUE   0xB000
> > +#define ICH9_PMBASE_VALUE  0x0600
> 
> They are in OvmfPkg/Include/OvmfPlatforms.h, no need to copy them over.
> 
> > +VOID
> > +PciExBarInitialization (
> 
> > +VOID
> > +MiscInitialization (
> 
> Cut+Paste from PlatformPei
> 
> Please refactor the code (move the functions needed to a Library?) so we
> don't have multiple copies of the setup code.
> 
As we're discussing the PlatformInitLib (which wraps the functions in PlatformPei), SecPlatformLibQemuTdx is deprecated.

Thanks
Min

^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2022-01-07  6:13                 ` Min Xu
@ 2022-01-10  7:55                   ` Gerd Hoffmann
  2022-01-11  2:24                     ` Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2022-01-10  7:55 UTC (permalink / raw)
  To: Xu, Min M
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

On Fri, Jan 07, 2022 at 06:13:37AM +0000, Xu, Min M wrote:
> On January 3, 2022 4:02 PM, Gerd Hoffmann wrote:
> > 
> > > PCDs cannot be set in SEC phase, so the values should be saved in a
> > > Hob (for example, PLATFORM_INFO_HOB). In early DXE phase these values
> > > are set to the PCDs. This is how TdxDxe does today.
> > >
> > > Other tasks can be done in SEC phase. I think there should be a lib
> > > (for example, PlatformPeiLib) to wrap these functions so that they can
> > > be re-used by OvmfPkg/PlatformPei.
> > 
> > Yes, I think we need a PlatformLib for the platform initialization code.  With
> > PEI we would simply link the lib into PlatformPei, without PEI we would link
> > parts of the lib into SEC and parts of the lib into DXE.

> After carefully study the PlatformPei code and a quick PoC
> (PlatformInitLib which wraps the basic functions in PlatformPei), I
> found it's not a easy task for such a lib which can be used in both
> PlatformPei and Pei-less boot.

> 1. PlatformInitLib should work both in SEC and PEI. So it cannot use
> global variables between different functions. mHostBridgeDevId and
> mPhysMemAddressWidth are the examples. So these variables must be
> provided by the caller thru the input function parameters.

> 2. PlatformInitLib cannot set PCDs in the code. So a Guid hob should
> be created to store the PCDs and pass them to DXE phase. Then these
> PCDs will be set at the very beginning of DXE phase.

Yes.  Your patches add a PlatformInitHob because of that.  I think right
now it only has some tdx-specific variables, but we can move more
variables into the hob to allow platform init code run in both SEC and
PEI phase.  I think it makes sense to have the hob in both PEI and
PEI-less mode to minimize the code differences.

> 4. In PlatformPei there are many if-else to check if it is
> SMM/S3/Microvm/Cloud-Hypervisor/SEV/TDX. There are also Bhyve and Xen
> PlatformPei variants. In the current PlatformPei those if-else check
> depends on the PCDs and global variables. Because of (1) it needs
> input parameters for all these if-else check. Maybe a big environment
> variable data structure is needed.

Use PlatformInitHob?

> But anyway a complete functional PlatformInitLib is a big task. My
> suggestion is that in TDVF-Config-B we first propose a basic
> functional PlatformInitLib. This lib can boot up Tdx guest and legacy
> OVMF guest in TDVF-Config-B. OvmfPkg/PlatformPei is not refactored by
> this basic PlatformInitLib this time.

Well.  The whole point of adding PlatformInitLib is to move over (and
refactor if needed) existing code in PlatformPei so we can avoid code
duplication.  Now you want add PlatformInitLib without touching
PlatformPei, probably by copying code.  That doesn't make sense at all.

> This is because PlatformPei serves
> SMM/S3/Microvm/Cloud-Hypervisor/SEV/TDX. It is a big risk for such
> refactor. We can revisit PlatformPei in the future.

Well, if you want avoid the refactoring because of the risk there is
still the option to have tdx config-b use the normal PEI boot flow.
Then revisit refactoring and adding support for PEI-less boot later.

take care,
  Gerd


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2022-01-10  7:55                   ` Gerd Hoffmann
@ 2022-01-11  2:24                     ` Min Xu
  2022-01-11  9:23                       ` Gerd Hoffmann
  0 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2022-01-11  2:24 UTC (permalink / raw)
  To: kraxel@redhat.com
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

On January 10, 2022 3:56 PM, Gerd Hoffmann wrote:
> On Fri, Jan 07, 2022 at 06:13:37AM +0000, Xu, Min M wrote:
> > On January 3, 2022 4:02 PM, Gerd Hoffmann wrote:
> > >
> > > > PCDs cannot be set in SEC phase, so the values should be saved in
> > > > a Hob (for example, PLATFORM_INFO_HOB). In early DXE phase these
> > > > values are set to the PCDs. This is how TdxDxe does today.
> > > >
> > > > Other tasks can be done in SEC phase. I think there should be a
> > > > lib (for example, PlatformPeiLib) to wrap these functions so that
> > > > they can be re-used by OvmfPkg/PlatformPei.
> > >
> > > Yes, I think we need a PlatformLib for the platform initialization
> > > code.  With PEI we would simply link the lib into PlatformPei,
> > > without PEI we would link parts of the lib into SEC and parts of the lib into
> DXE.
> 
> > After carefully study the PlatformPei code and a quick PoC
> > (PlatformInitLib which wraps the basic functions in PlatformPei), I
> > found it's not a easy task for such a lib which can be used in both
> > PlatformPei and Pei-less boot.
> 
> > 1. PlatformInitLib should work both in SEC and PEI. So it cannot use
> > global variables between different functions. mHostBridgeDevId and
> > mPhysMemAddressWidth are the examples. So these variables must be
> > provided by the caller thru the input function parameters.
> 
> > 2. PlatformInitLib cannot set PCDs in the code. So a Guid hob should
> > be created to store the PCDs and pass them to DXE phase. Then these
> > PCDs will be set at the very beginning of DXE phase.
> 
> Yes.  Your patches add a PlatformInitHob because of that.  I think right now it
> only has some tdx-specific variables, but we can move more variables into the
> hob to allow platform init code run in both SEC and PEI phase.  I think it makes
> sense to have the hob in both PEI and PEI-less mode to minimize the code
> differences.
Yes, we can use EFI_HOB_PLATFORM_INFO.
> 
> > 4. In PlatformPei there are many if-else to check if it is
> > SMM/S3/Microvm/Cloud-Hypervisor/SEV/TDX. There are also Bhyve and
> Xen
> > PlatformPei variants. In the current PlatformPei those if-else check
> > depends on the PCDs and global variables. Because of (1) it needs
> > input parameters for all these if-else check. Maybe a big environment
> > variable data structure is needed.
> 
> Use PlatformInitHob?
Yes, we can use this data structure.
> 
> > But anyway a complete functional PlatformInitLib is a big task. My
> > suggestion is that in TDVF-Config-B we first propose a basic
> > functional PlatformInitLib. This lib can boot up Tdx guest and legacy
> > OVMF guest in TDVF-Config-B. OvmfPkg/PlatformPei is not refactored by
> > this basic PlatformInitLib this time.
> 
> Well.  The whole point of adding PlatformInitLib is to move over (and refactor if
> needed) existing code in PlatformPei so we can avoid code duplication.  Now
> you want add PlatformInitLib without touching PlatformPei, probably by
> copying code.  That doesn't make sense at all.
> 
> > This is because PlatformPei serves
> > SMM/S3/Microvm/Cloud-Hypervisor/SEV/TDX. It is a big risk for such
> > refactor. We can revisit PlatformPei in the future.
> 
> Well, if you want avoid the refactoring because of the risk there is still the
> option to have tdx config-b use the normal PEI boot flow.
> Then revisit refactoring and adding support for PEI-less boot later.
> 
I think it still makes sense (Adding a basic PlatformInitLib which brings up tdx guest and legacy guest in Pei-less boot, but not touch PlatformPei).
1. The goal of TDVF-Config-B is to bring up tdx guest and legacy guest without PEI. So that attack surface can be reduced.
2. There are common functions when bring up tdx guest and legacy guest in Config-B. So PlatformInitLib is necessary.
3. As I explained there are many if-else checks in PlatformPei and the logics are rather complicated (because PlatformPei serves S3/SMM/SEV/TDX/Legacy/Microvm/CloudHypervisor, etc). To be honest I have not so much confidence to abstract PlatformPei's common function to PlatformInitLib.
4. But a basic version of PlatformInitLib is a good start. During the development and community review, we can understand better what functions should be wrapped into PlatformInitLib. After that PlatformInitLib can be evolved for OvmfPkg/PlatformPei, Bhyve/PlatformPei, XenPlatformPei.

Thanks
Min

^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2022-01-11  2:24                     ` Min Xu
@ 2022-01-11  9:23                       ` Gerd Hoffmann
  2022-01-14  2:17                         ` Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2022-01-11  9:23 UTC (permalink / raw)
  To: Xu, Min M
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

  Hi,

> > Well, if you want avoid the refactoring because of the risk there is still the
> > option to have tdx config-b use the normal PEI boot flow.
> > Then revisit refactoring and adding support for PEI-less boot later.
> > 
> I think it still makes sense (Adding a basic PlatformInitLib which
> brings up tdx guest and legacy guest in Pei-less boot, but not touch
> PlatformPei).

> 1. The goal of TDVF-Config-B is to bring up tdx guest and legacy guest
> without PEI. So that attack surface can be reduced.

Hmm?  Isn't the main goal of config-b to support the advanced tdx
features (attestation etc)?

I don't see that PEI-less boot is required for that.  Sure, when
stripping down the build and removing all the features which require
PEIMs there isn't much left to do for the PEI phase.  So it makes sense
to look into dropping PEI altogether.  But it's more a "nice to have"
than a hard requirement, no?

> 2. There are common functions when bring up tdx guest and legacy guest
> in Config-B. So PlatformInitLib is necessary.

Sure.

> 3. As I explained there are many if-else checks in PlatformPei and the
> logics are rather complicated (because PlatformPei serves
> S3/SMM/SEV/TDX/Legacy/Microvm/CloudHypervisor, etc). To be honest I
> have not so much confidence to abstract PlatformPei's common function
> to PlatformInitLib.

What is the problem with moving code?  After some preparing steps (add
platform info hob, move global variables to the hob) it should be
possible to move the code needed by config-b (memory detection via
fw_cfg or tdx hob, pci init, ...) from PlatformPei to PlatformInitLib
and (also) use it in the SEC phase.  Likewise for code which runs in DXE
in PEI-less mode (setting PCDs).

The code not needed by config-b (smm, s3, ...) can stay in PlatformPei.

> 4. But a basic version of PlatformInitLib is a good start.

Yes.  Having initially only the functions needed by config-b in
PlatformInitLib is perfectly fine, but this should be a code *move*
not a copy.

> During the development and community review, we can understand better
> what functions should be wrapped into PlatformInitLib. After that
> PlatformInitLib can be evolved for OvmfPkg/PlatformPei,
> Bhyve/PlatformPei, XenPlatformPei.

Yes, most likely there are a number of opportunities to reduce code
duplication in the three PlatformPei variants we have by moving code
to the (shared) PlatformInitLib.

That can be looked at later.

take care,
  Gerd


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [PATCH 06/10] OvmfPkg: Add TdxStartupLib
  2021-12-16 11:56     ` Min Xu
@ 2022-01-12  1:55       ` Min Xu
  0 siblings, 0 replies; 37+ messages in thread
From: Min Xu @ 2022-01-12  1:55 UTC (permalink / raw)
  To: Gerd Hoffmann
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky, Ni, Ray

Hi
> > > +VOID
> > > +Split2MPageTo4K (
> >
> > Yet another copy of this.  Please don't.
> I will figure out a Page walker lib so that these duplicated code can be
> avoided. Thanks for reminder.
After I implemented a PoC of PageTable library, I realized that there has already been a same feature requirement. https://bugzilla.tianocore.org/show_bug.cgi?id=847 
I discussed with the feature owner (Ni, Ray).  He said this feature is in his plan of 2022. He suggest I can wait for the library.

Thanks
Min
 


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2022-01-11  9:23                       ` Gerd Hoffmann
@ 2022-01-14  2:17                         ` Min Xu
  2022-01-14  8:32                           ` Gerd Hoffmann
  0 siblings, 1 reply; 37+ messages in thread
From: Min Xu @ 2022-01-14  2:17 UTC (permalink / raw)
  To: kraxel@redhat.com
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

On January 11, 2022 5:23 PM, Gerd Hoffmann wrote:
> 
> > > Well, if you want avoid the refactoring because of the risk there is
> > > still the option to have tdx config-b use the normal PEI boot flow.
> > > Then revisit refactoring and adding support for PEI-less boot later.
> > >
> > I think it still makes sense (Adding a basic PlatformInitLib which
> > brings up tdx guest and legacy guest in Pei-less boot, but not touch
> > PlatformPei).
> 
> > 1. The goal of TDVF-Config-B is to bring up tdx guest and legacy guest
> > without PEI. So that attack surface can be reduced.
> 
> Hmm?  Isn't the main goal of config-b to support the advanced tdx features
> (attestation etc)?
PEI-less boot is one of the main goal of Config-B. Actually PEI-less boot is in the original design of TDVF. RTMR-based measurement and measure boot are another important goals.
> 
> I don't see that PEI-less boot is required for that.  Sure, when stripping down
> the build and removing all the features which require PEIMs there isn't much
> left to do for the PEI phase.  So it makes sense to look into dropping PEI
> altogether.  But it's more a "nice to have"
> than a hard requirement, no?
No. I have to say PEI-less boot in Config-B is a hard requirement.
> 
> > 2. There are common functions when bring up tdx guest and legacy guest
> > in Config-B. So PlatformInitLib is necessary.
> 
> Sure.
> 
> > 3. As I explained there are many if-else checks in PlatformPei and the
> > logics are rather complicated (because PlatformPei serves
> > S3/SMM/SEV/TDX/Legacy/Microvm/CloudHypervisor, etc). To be honest I
> > have not so much confidence to abstract PlatformPei's common function
> > to PlatformInitLib.
> 
> What is the problem with moving code?  After some preparing steps (add
> platform info hob, move global variables to the hob) it should be possible to
> move the code needed by config-b (memory detection via fw_cfg or tdx hob,
> pci init, ...) from PlatformPei to PlatformInitLib and (also) use it in the SEC
> phase.  Likewise for code which runs in DXE in PEI-less mode (setting PCDs).
> 
> The code not needed by config-b (smm, s3, ...) can stay in PlatformPei.
Yes, PlatformPei can be refactored in this way.
> 
> > 4. But a basic version of PlatformInitLib is a good start.
> 
> Yes.  Having initially only the functions needed by config-b in PlatformInitLib
> is perfectly fine, but this should be a code *move* not a copy.
> 
> > During the development and community review, we can understand better
> > what functions should be wrapped into PlatformInitLib. After that
> > PlatformInitLib can be evolved for OvmfPkg/PlatformPei,
> > Bhyve/PlatformPei, XenPlatformPei.
> 
> Yes, most likely there are a number of opportunities to reduce code
> duplication in the three PlatformPei variants we have by moving code to the
> (shared) PlatformInitLib.
> 
> That can be looked at later.

So let me summarize the discussion about PlatformInitLib.
1. PlatformInitLib wraps the common functions in OvmfPkg/PlatformPei. These common functions covers the memory detection via fw_cfg, pci init, cmos, (MemDetect.c/Platform.c/Cmos.c). And PlatformInitLib will not handle the S3/SMM variants.
2. OvmfPkg/PlatformPei will be refactored with PlatformInitLib. The functions not needed by config-b stay in PlatformPei.
3. Config-B support PEI-less boot for both legacy guest and td guest.

If you agree, then I will update the patch-sets based on above discussions.

Thanks
Min

^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2022-01-14  2:17                         ` Min Xu
@ 2022-01-14  8:32                           ` Gerd Hoffmann
  2022-01-16  0:55                             ` Min Xu
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2022-01-14  8:32 UTC (permalink / raw)
  To: Xu, Min M
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

  Hi,

> > I don't see that PEI-less boot is required for that.  Sure, when stripping down
> > the build and removing all the features which require PEIMs there isn't much
> > left to do for the PEI phase.  So it makes sense to look into dropping PEI
> > altogether.  But it's more a "nice to have"
> > than a hard requirement, no?

> No. I have to say PEI-less boot in Config-B is a hard requirement.

I'm still wondering why though.  I have not yet seen a reason why
config-b can't use the PEI-based boot flow.

> > > 4. But a basic version of PlatformInitLib is a good start.
> > 
> > Yes.  Having initially only the functions needed by config-b in PlatformInitLib
> > is perfectly fine, but this should be a code *move* not a copy.
> > 
> > > During the development and community review, we can understand better
> > > what functions should be wrapped into PlatformInitLib. After that
> > > PlatformInitLib can be evolved for OvmfPkg/PlatformPei,
> > > Bhyve/PlatformPei, XenPlatformPei.
> > 
> > Yes, most likely there are a number of opportunities to reduce code
> > duplication in the three PlatformPei variants we have by moving code to the
> > (shared) PlatformInitLib.
> > 
> > That can be looked at later.
> 
> So let me summarize the discussion about PlatformInitLib.

> 1. PlatformInitLib wraps the common functions in OvmfPkg/PlatformPei.
> These common functions covers the memory detection via fw_cfg, pci
> init, cmos, (MemDetect.c/Platform.c/Cmos.c).

Yes.  Everything needed for PEI-less / config-b boot moves to
PlatformInitLib.

PlatformInitLib is added as dependency to OvmfPkg/PlatformPei, so
PlatformPei can call those functions when booting with PEI.

PEI-less boot will add PlatformInitLib to SEC (and DXE) instead
so the same code can be used then.

Not sure how to handle cmos best.  Not needed for memory detection on
qemu, but cloudhw depends on it so it is back for now.  Will cloudhw
support tdx too btw?

> And PlatformInitLib will
> not handle the S3/SMM variants.

At least not initially.  Maybe later when we move more code to the lib
to reduce code duplication in xen/bhyve/qemu PlatformPei variants.

> 2. OvmfPkg/PlatformPei will be refactored with PlatformInitLib. The
> functions not needed by config-b stay in PlatformPei.

> 3. Config-B support PEI-less boot for both legacy guest and td guest.

Yes.

take care,
  Gerd


^ permalink raw reply	[flat|nested] 37+ messages in thread

* Re: [edk2-devel] [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B
  2022-01-14  8:32                           ` Gerd Hoffmann
@ 2022-01-16  0:55                             ` Min Xu
  0 siblings, 0 replies; 37+ messages in thread
From: Min Xu @ 2022-01-16  0:55 UTC (permalink / raw)
  To: kraxel@redhat.com
  Cc: devel@edk2.groups.io, Kinney, Michael D, Brijesh Singh,
	Aktas, Erdem, James Bottomley, Yao, Jiewen, Tom Lendacky

On January 14, 2022 4:32 PM, Gerd Hoffmann wrote:
> > > I don't see that PEI-less boot is required for that.  Sure, when
> > > stripping down the build and removing all the features which require
> > > PEIMs there isn't much left to do for the PEI phase.  So it makes
> > > sense to look into dropping PEI altogether.  But it's more a "nice to have"
> > > than a hard requirement, no?
> 
> > No. I have to say PEI-less boot in Config-B is a hard requirement.
> 
> I'm still wondering why though.  I have not yet seen a reason why config-b
> can't use the PEI-based boot flow.
Hi, Gerd, I think Jiewen has discussed this (PEI-less boot in Config-B) in another mail thread. We can continue the discussion there. Let's first focus on the PlatformInitLib here. Thanks for your understanding.
> 
> > > > 4. But a basic version of PlatformInitLib is a good start.
> > >
> > > Yes.  Having initially only the functions needed by config-b in
> > > PlatformInitLib is perfectly fine, but this should be a code *move* not a
> copy.
> > >
> > > > During the development and community review, we can understand
> > > > better what functions should be wrapped into PlatformInitLib.
> > > > After that PlatformInitLib can be evolved for OvmfPkg/PlatformPei,
> > > > Bhyve/PlatformPei, XenPlatformPei.
> > >
> > > Yes, most likely there are a number of opportunities to reduce code
> > > duplication in the three PlatformPei variants we have by moving code
> > > to the
> > > (shared) PlatformInitLib.
> > >
> > > That can be looked at later.
> >
> > So let me summarize the discussion about PlatformInitLib.
> 
> > 1. PlatformInitLib wraps the common functions in OvmfPkg/PlatformPei.
> > These common functions covers the memory detection via fw_cfg, pci
> > init, cmos, (MemDetect.c/Platform.c/Cmos.c).
> 
> Yes.  Everything needed for PEI-less / config-b boot moves to PlatformInitLib.
> 
> PlatformInitLib is added as dependency to OvmfPkg/PlatformPei, so
> PlatformPei can call those functions when booting with PEI.
> 
> PEI-less boot will add PlatformInitLib to SEC (and DXE) instead so the same
> code can be used then.
> 
> Not sure how to handle cmos best.  Not needed for memory detection on
> qemu, but cloudhw depends on it so it is back for now.  Will cloudhw support
> tdx too btw?
Yes, Cloudhw support TDX too. Actually we have some PoC and plan to upstream it later.
BTW, cmos is needed in GetSystemMemorySizeBelow4gb which call CmosRead for 0x34/0x35.
> 
> > And PlatformInitLib will
> > not handle the S3/SMM variants.
> 
> At least not initially.  Maybe later when we move more code to the lib to
> reduce code duplication in xen/bhyve/qemu PlatformPei variants.
> 
> > 2. OvmfPkg/PlatformPei will be refactored with PlatformInitLib. The
> > functions not needed by config-b stay in PlatformPei.
> 
> > 3. Config-B support PEI-less boot for both legacy guest and td guest.
> 
> Yes.

Thanks
Min

^ permalink raw reply	[flat|nested] 37+ messages in thread

end of thread, other threads:[~2022-01-16  0:56 UTC | newest]

Thread overview: 37+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2021-12-14 13:41 [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Min Xu
2021-12-14 13:41 ` [PATCH 01/10] OvmfPkg: Introduce IntelTdxX64 for TDVF Config-B Min Xu
2021-12-15  9:32   ` Gerd Hoffmann
2021-12-14 13:41 ` [PATCH 02/10] EmbeddedPkg/PrePiLib: Update PrePiLib Min Xu
2021-12-14 14:00   ` [edk2-devel] " Ard Biesheuvel
2021-12-16  4:48     ` Min Xu
2021-12-14 13:41 ` [PATCH 03/10] EmbeddedPkg/MemoryAllocationLib: Add null stub for AllocateCopyPool Min Xu
2021-12-14 13:59   ` [edk2-devel] " Ard Biesheuvel
2021-12-16  3:08     ` Min Xu
2021-12-14 13:41 ` [PATCH 04/10] OvmfPkg: Add PrePiHobListPointerLibTdx Min Xu
2021-12-14 13:41 ` [PATCH 05/10] OvmfPkg: Add SecPlatformLibQemuTdx Min Xu
2021-12-15  9:48   ` Gerd Hoffmann
2022-01-07  6:29     ` Min Xu
2021-12-14 13:41 ` [PATCH 06/10] OvmfPkg: Add TdxStartupLib Min Xu
2021-12-15 10:09   ` Gerd Hoffmann
2021-12-16 11:56     ` Min Xu
2022-01-12  1:55       ` Min Xu
2021-12-14 13:41 ` [PATCH 07/10] OvmfPkg: Update TdxDxe to set TDX PCDs Min Xu
2021-12-14 13:41 ` [PATCH 08/10] OvmfPkg: Update Sec to support Tdvf Config-B Min Xu
2021-12-15 10:27   ` Gerd Hoffmann
2021-12-16 12:21     ` [edk2-devel] " Min Xu
2021-12-16 14:25       ` Gerd Hoffmann
2021-12-19  2:49         ` Min Xu
2021-12-20 12:11           ` Gerd Hoffmann
2021-12-24  3:02             ` Min Xu
2022-01-03  8:02               ` Gerd Hoffmann
2022-01-07  6:13                 ` Min Xu
2022-01-10  7:55                   ` Gerd Hoffmann
2022-01-11  2:24                     ` Min Xu
2022-01-11  9:23                       ` Gerd Hoffmann
2022-01-14  2:17                         ` Min Xu
2022-01-14  8:32                           ` Gerd Hoffmann
2022-01-16  0:55                             ` Min Xu
2021-12-14 13:41 ` [PATCH 09/10] OvmfPkg: Update DxeAcpiTimerLib to read HostBridgeDevId in PlatformInfoHob Min Xu
2021-12-14 13:41 ` [PATCH 10/10] OvmfPkg: Add Tdx libs to prevent building broken Min Xu
2021-12-15 10:41 ` [PATCH 00/10] Introduce TDVF Config-B (basic) in OvmfPkg Gerd Hoffmann
2021-12-16 12:36   ` Min Xu

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox