public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
From: "Min Xu" <min.m.xu@intel.com>
To: devel@edk2.groups.io
Cc: Min Xu <min.m.xu@intel.com>,
	Michael D Kinney <michael.d.kinney@intel.com>,
	Brijesh Singh <brijesh.singh@amd.com>,
	Erdem Aktas <erdemaktas@google.com>,
	James Bottomley <jejb@linux.ibm.com>,
	Jiewen Yao <jiewen.yao@intel.com>,
	Tom Lendacky <thomas.lendacky@amd.com>,
	Gerd Hoffmann <kraxel@redhat.com>
Subject: [PATCH 06/10] OvmfPkg: Add TdxStartupLib
Date: Tue, 14 Dec 2021 21:41:22 +0800	[thread overview]
Message-ID: <20211214134126.869-7-min.m.xu@intel.com> (raw)
In-Reply-To: <20211214134126.869-1-min.m.xu@intel.com>

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


  parent reply	other threads:[~2021-12-14 13:42 UTC|newest]

Thread overview: 37+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
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 ` Min Xu [this message]
2021-12-15 10:09   ` [PATCH 06/10] OvmfPkg: Add TdxStartupLib 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

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-list from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20211214134126.869-7-min.m.xu@intel.com \
    --to=devel@edk2.groups.io \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox