Date   

[PATCH V12 15/47] OvmfPkg: Add IntelTdx.h in OvmfPkg/Include/IndustryStandard

Min Xu
 

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

IntelTdx.h defines the defition used by TDX in OvmfPkg:
- Mailbox related defitions,such as the data structure, command code,
AP relocation defitions.

See Table 5.44 Multiprocessor Wakeup Mailbox Structure in below link.
https://uefi.org/specs/ACPI/6.4/05_ACPI_Software_Programming_Model/
ACPI_Software_Programming_Model.html#multiprocessor-wakeup-structure

Cc: Ard Biesheuvel <ardb+tianocore@...>
Cc: Jordan Justen <jordan.l.justen@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
OvmfPkg/Include/IndustryStandard/IntelTdx.h | 67 +++++++++++++++++++++
1 file changed, 67 insertions(+)
create mode 100644 OvmfPkg/Include/IndustryStandard/IntelTdx.h

diff --git a/OvmfPkg/Include/IndustryStandard/IntelTdx.h b/OvmfPkg/Include/IndustryStandard/IntelTdx.h
new file mode 100644
index 000000000000..cc849be2fb59
--- /dev/null
+++ b/OvmfPkg/Include/IndustryStandard/IntelTdx.h
@@ -0,0 +1,67 @@
+/** @file
+ Defines the defitions used by TDX in OvmfPkg.
+
+ Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef OVMF_INTEL_TDX_H_
+#define OVMF_INTEL_TDX_H_
+
+#include <PiPei.h>
+#include <Library/BaseLib.h>
+#include <Uefi/UefiSpec.h>
+#include <Uefi/UefiBaseType.h>
+
+#define MP_CPU_PROTECTED_MODE_MAILBOX_APICID_INVALID 0xFFFFFFFF
+#define MP_CPU_PROTECTED_MODE_MAILBOX_APICID_BROADCAST 0xFFFFFFFE
+
+typedef enum {
+ MpProtectedModeWakeupCommandNoop = 0,
+ MpProtectedModeWakeupCommandWakeup = 1,
+ MpProtectedModeWakeupCommandSleep = 2,
+ MpProtectedModeWakeupCommandAcceptPages = 3,
+} MP_CPU_PROTECTED_MODE_WAKEUP_CMD;
+
+#pragma pack(1)
+
+//
+// Describes the CPU MAILBOX control structure use to
+// wakeup cpus spinning in long mode
+//
+typedef struct {
+ UINT16 Command;
+ UINT16 Resv;
+ UINT32 ApicId;
+ UINT64 WakeUpVector;
+ UINT8 ResvForOs[2032];
+ //
+ // Arguments available for wakeup code
+ //
+ UINT64 WakeUpArgs1;
+ UINT64 WakeUpArgs2;
+ UINT64 WakeUpArgs3;
+ UINT64 WakeUpArgs4;
+ UINT8 Pad1[0xe0];
+ UINT64 NumCpusArriving;
+ UINT8 Pad2[0xf8];
+ UINT64 NumCpusExiting;
+ UINT32 Tallies[256];
+ UINT8 Errors[256];
+ UINT8 Pad3[0xf8];
+} MP_WAKEUP_MAILBOX;
+
+//
+// AP relocation code information including code address and size,
+// this structure will be shared be C code and assembly code.
+// It is natural aligned by design.
+//
+typedef struct {
+ UINT8 *RelocateApLoopFuncAddress;
+ UINTN RelocateApLoopFuncSize;
+} MP_RELOCATION_MAP;
+
+#pragma pack()
+
+#endif
--
2.29.2.windows.2


[PATCH V12 16/47] OvmfPkg: Add TdxMailboxLib

Min Xu
 

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

In Tdx BSP may issues commands to APs for some task, for example, to
accept pages paralelly. BSP also need to wait until all the APs have
done the task. TdxMailboxLib wraps these common funtions for BSP.

Cc: Ard Biesheuvel <ardb+tianocore@...>
Cc: Jordan Justen <jordan.l.justen@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
OvmfPkg/Include/Library/TdxMailboxLib.h | 76 ++++++++++
OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c | 141 ++++++++++++++++++
.../Library/TdxMailboxLib/TdxMailboxLib.inf | 52 +++++++
.../Library/TdxMailboxLib/TdxMailboxNull.c | 85 +++++++++++
OvmfPkg/OvmfPkg.dec | 4 +
5 files changed, 358 insertions(+)
create mode 100644 OvmfPkg/Include/Library/TdxMailboxLib.h
create mode 100644 OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c
create mode 100644 OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf
create mode 100644 OvmfPkg/Library/TdxMailboxLib/TdxMailboxNull.c

diff --git a/OvmfPkg/Include/Library/TdxMailboxLib.h b/OvmfPkg/Include/Library/TdxMailboxLib.h
new file mode 100644
index 000000000000..166cab43bc02
--- /dev/null
+++ b/OvmfPkg/Include/Library/TdxMailboxLib.h
@@ -0,0 +1,76 @@
+/** @file
+
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef TDX_MAILBOX_LIB_H_
+#define TDX_MAILBOX_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>
+
+/**
+ This function will be called by BSP to get the CPU number.
+
+ @retval CPU number
+**/
+UINT32
+EFIAPI
+GetCpusNum (
+ VOID
+ );
+
+/**
+ Get the address of Td mailbox.
+**/
+volatile VOID *
+EFIAPI
+GetTdxMailBox (
+ VOID
+ );
+
+/**
+ This function will be called by BSP to wakeup APs the are spinning on mailbox
+ in protected mode
+
+ @param[in] Command Command to send APs
+ @param[in] WakeupVector If used, address for APs to start executing
+ @param[in] WakeArgsX Args to pass to APs for excuting commands
+**/
+VOID
+EFIAPI
+MpSendWakeupCommand (
+ IN UINT16 Command,
+ IN UINT64 WakeupVector,
+ IN UINT64 WakeupArgs1,
+ IN UINT64 WakeupArgs2,
+ IN UINT64 WakeupArgs3,
+ IN UINT64 WakeupArgs4
+ );
+
+/**
+ BSP wait until all the APs arriving. It means the task triggered by BSP is started.
+**/
+VOID
+EFIAPI
+MpSerializeStart (
+ VOID
+ );
+
+/**
+ BSP wait until all the APs arriving. It means the task triggered by BSP is ended.
+**/
+VOID
+EFIAPI
+MpSerializeEnd (
+ VOID
+ );
+
+#endif
diff --git a/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c b/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c
new file mode 100644
index 000000000000..74cb55611fe3
--- /dev/null
+++ b/OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c
@@ -0,0 +1,141 @@
+/** @file
+
+ 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 <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/PcdLib.h>
+#include <Library/UefiCpuLib.h>
+#include <Library/SynchronizationLib.h>
+#include <Uefi/UefiBaseType.h>
+#include <Library/TdxLib.h>
+#include <IndustryStandard/IntelTdx.h>
+#include <IndustryStandard/Tdx.h>
+#include <Library/TdxMailboxLib.h>
+
+volatile VOID *mMailBox = NULL;
+UINT32 mNumOfCpus = 0;
+
+/**
+ This function will be called by BSP to get the CPU number.
+
+ @retval CPU number
+**/
+UINT32
+EFIAPI
+GetCpusNum (
+ VOID
+ )
+{
+ if (mNumOfCpus == 0) {
+ mNumOfCpus = TdVCpuNum ();
+ }
+
+ return mNumOfCpus;
+}
+
+/**
+ Get the address of Td mailbox.
+**/
+volatile VOID *
+EFIAPI
+GetTdxMailBox (
+ VOID
+ )
+{
+ if (mMailBox == NULL) {
+ mMailBox = (VOID *)(UINTN)PcdGet32 (PcdOvmfSecGhcbBackupBase);
+ }
+
+ return mMailBox;
+}
+
+/**
+ This function will be called by BSP to wakeup APs the are spinning on mailbox
+ in protected mode
+
+ @param[in] Command Command to send APs
+ @param[in] WakeupVector If used, address for APs to start executing
+ @param[in] WakeArgsX Args to pass to APs for excuting commands
+**/
+VOID
+EFIAPI
+MpSendWakeupCommand (
+ IN UINT16 Command,
+ IN UINT64 WakeupVector,
+ IN UINT64 WakeupArgs1,
+ IN UINT64 WakeupArgs2,
+ IN UINT64 WakeupArgs3,
+ IN UINT64 WakeupArgs4
+ )
+{
+ volatile MP_WAKEUP_MAILBOX *MailBox;
+
+ MailBox = (volatile MP_WAKEUP_MAILBOX *)GetTdxMailBox ();
+ MailBox->ApicId = MP_CPU_PROTECTED_MODE_MAILBOX_APICID_INVALID;
+ MailBox->WakeUpVector = 0;
+ MailBox->Command = MpProtectedModeWakeupCommandNoop;
+ MailBox->ApicId = MP_CPU_PROTECTED_MODE_MAILBOX_APICID_BROADCAST;
+ MailBox->WakeUpVector = WakeupVector;
+ MailBox->WakeUpArgs1 = WakeupArgs1;
+ MailBox->WakeUpArgs2 = WakeupArgs2;
+ MailBox->WakeUpArgs3 = WakeupArgs3;
+ MailBox->WakeUpArgs4 = WakeupArgs4;
+ AsmCpuid (0x01, NULL, NULL, NULL, NULL);
+ MailBox->Command = Command;
+ AsmCpuid (0x01, NULL, NULL, NULL, NULL);
+ return;
+}
+
+/**
+ BSP wait until all the APs arriving. It means the task triggered by BSP is started.
+**/
+VOID
+EFIAPI
+MpSerializeStart (
+ VOID
+ )
+{
+ volatile MP_WAKEUP_MAILBOX *MailBox;
+ UINT32 NumOfCpus;
+
+ NumOfCpus = GetCpusNum ();
+ MailBox = (volatile MP_WAKEUP_MAILBOX *)GetTdxMailBox ();
+
+ DEBUG ((DEBUG_VERBOSE, "Waiting for APs to arriving. NumOfCpus=%d, MailBox=%p\n", NumOfCpus, MailBox));
+ while (MailBox->NumCpusArriving != (NumOfCpus -1)) {
+ CpuPause ();
+ }
+
+ DEBUG ((DEBUG_VERBOSE, "Releasing APs\n"));
+ MailBox->NumCpusExiting = NumOfCpus;
+ InterlockedIncrement ((UINT32 *)&MailBox->NumCpusArriving);
+}
+
+/**
+ BSP wait until all the APs arriving. It means the task triggered by BSP is ended.
+**/
+VOID
+EFIAPI
+MpSerializeEnd (
+ VOID
+ )
+{
+ volatile MP_WAKEUP_MAILBOX *MailBox;
+
+ MailBox = (volatile MP_WAKEUP_MAILBOX *)GetTdxMailBox ();
+ DEBUG ((DEBUG_VERBOSE, "Waiting for APs to finish\n"));
+ while (MailBox->NumCpusExiting != 1 ) {
+ CpuPause ();
+ }
+
+ DEBUG ((DEBUG_VERBOSE, "Restarting APs\n"));
+ MailBox->Command = MpProtectedModeWakeupCommandNoop;
+ MailBox->NumCpusArriving = 0;
+ InterlockedDecrement ((UINT32 *)&MailBox->NumCpusExiting);
+}
diff --git a/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf
new file mode 100644
index 000000000000..3cf3690a16c7
--- /dev/null
+++ b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf
@@ -0,0 +1,52 @@
+#/** @file
+#
+# TBD
+#
+# 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 = TdxMailboxLib
+ FILE_GUID = 2F81A9BA-748E-4519-BB11-A63A039D561E
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = TdxMailboxLib
+
+#
+# VALID_ARCHITECTURES = X64 IA32
+#
+
+[Sources.IA32]
+ TdxMailboxNull.c
+
+[Sources.X64]
+ TdxMailbox.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ UefiCpuPkg/UefiCpuPkg.dec
+ OvmfPkg/OvmfPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ DebugLib
+ BaseMemoryLib
+ PcdLib
+ UefiCpuLib
+ DebugAgentLib
+ IoLib
+ SynchronizationLib
+ MemoryAllocationLib
+
+[Guids]
+
+[Pcd]
+ gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBackupBase
+ gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBackupSize
diff --git a/OvmfPkg/Library/TdxMailboxLib/TdxMailboxNull.c b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxNull.c
new file mode 100644
index 000000000000..35b070361eb1
--- /dev/null
+++ b/OvmfPkg/Library/TdxMailboxLib/TdxMailboxNull.c
@@ -0,0 +1,85 @@
+/** @file
+
+ 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 <Library/DebugLib.h>
+#include <Library/TdxMailboxLib.h>
+
+/**
+ This function will be called by BSP to get the CPU number.
+
+ @retval CPU number
+**/
+UINT32
+EFIAPI
+GetCpusNum (
+ VOID
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Get the address of Td mailbox.
+**/
+volatile VOID *
+EFIAPI
+GetTdxMailBox (
+ VOID
+ )
+{
+ ASSERT (FALSE);
+ return (volatile VOID *)NULL;
+}
+
+/**
+ This function will be called by BSP to wakeup APs the are spinning on mailbox
+ in protected mode
+
+ @param[in] Command Command to send APs
+ @param[in] WakeupVector If used, address for APs to start executing
+ @param[in] WakeArgsX Args to pass to APs for excuting commands
+**/
+VOID
+EFIAPI
+MpSendWakeupCommand (
+ IN UINT16 Command,
+ IN UINT64 WakeupVector,
+ IN UINT64 WakeupArgs1,
+ IN UINT64 WakeupArgs2,
+ IN UINT64 WakeupArgs3,
+ IN UINT64 WakeupArgs4
+ )
+{
+ ASSERT (FALSE);
+}
+
+/**
+ BSP wait until all the APs arriving. It means the task triggered by BSP is started.
+**/
+VOID
+EFIAPI
+MpSerializeStart (
+ VOID
+ )
+{
+ ASSERT (FALSE);
+}
+
+/**
+ BSP wait until all the APs arriving. It means the task triggered by BSP is ended.
+**/
+VOID
+EFIAPI
+MpSerializeEnd (
+ VOID
+ )
+{
+ ASSERT (FALSE);
+}
diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec
index 7aa94ca02863..d373b5d6042e 100644
--- a/OvmfPkg/OvmfPkg.dec
+++ b/OvmfPkg/OvmfPkg.dec
@@ -109,6 +109,10 @@
#
XenPlatformLib|Include/Library/XenPlatformLib.h

+ ## @libraryclass TdxMailboxLib
+ #
+ TdxMailboxLib|Include/Library/TdxMailboxLib.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


[PATCH V12 14/47] UefiCpuPkg: Enable Tdx support in MpInitLib

Min Xu
 

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

In TDVF BSP and APs are simplified. BSP is the vCPU-0, while the others
are treated as APs.

So MP intialization is rather simple. ApWorker is not supported, BSP is
always the working processor, while the APs are just in a
wait-for-precedure state.

Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Eric Dong <eric.dong@...>
Cc: Ray Ni <ray.ni@...>
Cc: Rahul Kumar <rahul1.kumar@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf | 3 +
UefiCpuPkg/Library/MpInitLib/MpIntelTdx.h | 69 ++++++++++++
UefiCpuPkg/Library/MpInitLib/MpLib.c | 63 ++++++++++-
UefiCpuPkg/Library/MpInitLib/MpLibTdx.c | 106 ++++++++++++++++++
UefiCpuPkg/Library/MpInitLib/MpLibTdxNull.c | 69 ++++++++++++
UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf | 3 +
6 files changed, 308 insertions(+), 5 deletions(-)
create mode 100644 UefiCpuPkg/Library/MpInitLib/MpIntelTdx.h
create mode 100644 UefiCpuPkg/Library/MpInitLib/MpLibTdx.c
create mode 100644 UefiCpuPkg/Library/MpInitLib/MpLibTdxNull.c

diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf
index e1cd0b350008..159b4d16ed0e 100644
--- a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf
+++ b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf
@@ -24,10 +24,12 @@
[Sources.IA32]
Ia32/AmdSev.c
Ia32/MpFuncs.nasm
+ MpLibTdxNull.c

[Sources.X64]
X64/AmdSev.c
X64/MpFuncs.nasm
+ MpLibTdx.c

[Sources.common]
AmdSev.c
@@ -36,6 +38,7 @@
MpLib.c
MpLib.h
Microcode.c
+ MpIntelTdx.h

[Packages]
MdePkg/MdePkg.dec
diff --git a/UefiCpuPkg/Library/MpInitLib/MpIntelTdx.h b/UefiCpuPkg/Library/MpInitLib/MpIntelTdx.h
new file mode 100644
index 000000000000..8a26f6c19fc4
--- /dev/null
+++ b/UefiCpuPkg/Library/MpInitLib/MpIntelTdx.h
@@ -0,0 +1,69 @@
+/** @file
+ CPU MP Initialize Library header file for Td guest.
+
+ Copyright (c) 2020 - 2022, Intel Corporation. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef MP_INTEL_TDX_H_
+#define MP_INTEL_TDX_H_
+
+#include <PiPei.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Uefi/UefiBaseType.h>
+#include <Protocol/MpService.h>
+
+/**
+ Gets detailed MP-related information on the requested processor at the
+ instant this call is made. This service may only be called from the BSP.
+
+ @param[in] ProcessorNumber The handle number of processor.
+ @param[out] ProcessorInfoBuffer A pointer to the buffer where information for
+ the requested processor is deposited.
+ @param[out] HealthData Return processor health data.
+
+ @retval EFI_SUCCESS Processor information was returned.
+ @retval EFI_DEVICE_ERROR The calling processor is an AP.
+ @retval EFI_INVALID_PARAMETER ProcessorInfoBuffer is NULL.
+ @retval EFI_NOT_FOUND The processor with the handle specified by
+ ProcessorNumber does not exist in the platform.
+ @retval EFI_NOT_READY MP Initialize Library is not initialized.
+
+**/
+EFI_STATUS
+TdxMpInitLibGetProcessorInfo (
+ IN UINTN ProcessorNumber,
+ OUT EFI_PROCESSOR_INFORMATION *ProcessorInfoBuffer,
+ OUT EFI_HEALTH_FLAGS *HealthData OPTIONAL
+ );
+
+/**
+ Retrieves the number of logical processor in the platform and the number of
+ those logical processors that are enabled on this boot. This service may only
+ be called from the BSP.
+
+ @param[out] NumberOfProcessors Pointer to the total number of logical
+ processors in the system, including the BSP
+ and disabled APs.
+ @param[out] NumberOfEnabledProcessors Pointer to the number of enabled logical
+ processors that exist in system, including
+ the BSP.
+
+ @retval EFI_SUCCESS The number of logical processors and enabled
+ logical processors was retrieved.
+ @retval EFI_DEVICE_ERROR The calling processor is an AP.
+ @retval EFI_INVALID_PARAMETER NumberOfProcessors is NULL and NumberOfEnabledProcessors
+ is NULL.
+ @retval EFI_NOT_READY MP Initialize Library is not initialized.
+
+**/
+EFI_STATUS
+TdxMpInitLibGetNumberOfProcessors (
+ OUT UINTN *NumberOfProcessors, OPTIONAL
+ OUT UINTN *NumberOfEnabledProcessors OPTIONAL
+ );
+
+#endif
diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.c b/UefiCpuPkg/Library/MpInitLib/MpLib.c
index 4a73787ee43a..91c7afaeb2ad 100644
--- a/UefiCpuPkg/Library/MpInitLib/MpLib.c
+++ b/UefiCpuPkg/Library/MpInitLib/MpLib.c
@@ -9,9 +9,11 @@
**/

#include "MpLib.h"
+#include "MpIntelTdx.h"
#include <Library/VmgExitLib.h>
#include <Register/Amd/Fam17Msr.h>
#include <Register/Amd/Ghcb.h>
+#include <ConfidentialComputingGuestAttr.h>

EFI_GUID mCpuInitMpLibHobGuid = CPU_INIT_MP_LIB_HOB_GUID;

@@ -1803,6 +1805,10 @@ MpInitLibInitialize (
UINTN BackupBufferAddr;
UINTN ApIdtBase;

+ if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) {
+ return EFI_SUCCESS;
+ }
+
OldCpuMpData = GetCpuMpDataFromGuidedHob ();
if (OldCpuMpData == NULL) {
MaxLogicalProcessorNumber = PcdGet32 (PcdCpuMaxLogicalProcessorNumber);
@@ -2073,6 +2079,10 @@ MpInitLibGetProcessorInfo (
CPU_INFO_IN_HOB *CpuInfoInHob;
UINTN OriginalProcessorNumber;

+ if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) {
+ return TdxMpInitLibGetProcessorInfo (ProcessorNumber, ProcessorInfoBuffer, HealthData);
+ }
+
CpuMpData = GetCpuMpData ();
CpuInfoInHob = (CPU_INFO_IN_HOB *)(UINTN)CpuMpData->CpuInfoInHob;

@@ -2167,6 +2177,10 @@ SwitchBSPWorker (
BOOLEAN OldInterruptState;
BOOLEAN OldTimerInterruptState;

+ if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) {
+ return EFI_UNSUPPORTED;
+ }
+
//
// Save and Disable Local APIC timer interrupt
//
@@ -2307,6 +2321,10 @@ EnableDisableApWorker (
CPU_MP_DATA *CpuMpData;
UINTN CallerNumber;

+ if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) {
+ return EFI_UNSUPPORTED;
+ }
+
CpuMpData = GetCpuMpData ();

//
@@ -2367,6 +2385,11 @@ MpInitLibWhoAmI (
return EFI_INVALID_PARAMETER;
}

+ if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) {
+ *ProcessorNumber = 0;
+ return EFI_SUCCESS;
+ }
+
CpuMpData = GetCpuMpData ();

return GetProcessorNumber (CpuMpData, ProcessorNumber);
@@ -2405,12 +2428,16 @@ MpInitLibGetNumberOfProcessors (
UINTN EnabledProcessorNumber;
UINTN Index;

- CpuMpData = GetCpuMpData ();
-
if ((NumberOfProcessors == NULL) && (NumberOfEnabledProcessors == NULL)) {
return EFI_INVALID_PARAMETER;
}

+ if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) {
+ return TdxMpInitLibGetNumberOfProcessors (NumberOfProcessors, NumberOfEnabledProcessors);
+ }
+
+ CpuMpData = GetCpuMpData ();
+
//
// Check whether caller processor is BSP
//
@@ -2490,13 +2517,16 @@ StartupAllCPUsWorker (
BOOLEAN HasEnabledAp;
CPU_STATE ApState;

- CpuMpData = GetCpuMpData ();
-
if (FailedCpuList != NULL) {
*FailedCpuList = NULL;
}

- if ((CpuMpData->CpuCount == 1) && ExcludeBsp) {
+ Status = MpInitLibGetNumberOfProcessors (&ProcessorCount, NULL);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ if ((ProcessorCount == 1) && ExcludeBsp) {
return EFI_NOT_STARTED;
}

@@ -2504,6 +2534,22 @@ StartupAllCPUsWorker (
return EFI_INVALID_PARAMETER;
}

+ if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) {
+ //
+ // For Td guest ExcludeBsp must be FALSE. Otherwise it will return in above checks.
+ //
+ ASSERT (!ExcludeBsp);
+
+ //
+ // Start BSP.
+ //
+ Procedure (ProcedureArgument);
+
+ return EFI_SUCCESS;
+ }
+
+ CpuMpData = GetCpuMpData ();
+
//
// Check whether caller processor is BSP
//
@@ -2643,6 +2689,13 @@ StartupThisAPWorker (
CPU_AP_DATA *CpuData;
UINTN CallerNumber;

+ //
+ // In Td guest, startup of AP is not supported in current stage.
+ //
+ if (CC_GUEST_IS_TDX (PcdGet64 (PcdConfidentialComputingGuestAttr))) {
+ return EFI_UNSUPPORTED;
+ }
+
CpuMpData = GetCpuMpData ();

if (Finished != NULL) {
diff --git a/UefiCpuPkg/Library/MpInitLib/MpLibTdx.c b/UefiCpuPkg/Library/MpInitLib/MpLibTdx.c
new file mode 100644
index 000000000000..fdb58fba9323
--- /dev/null
+++ b/UefiCpuPkg/Library/MpInitLib/MpLibTdx.c
@@ -0,0 +1,106 @@
+/** @file
+ CPU MP Initialize Library common functions for Td guest.
+
+ Copyright (c) 2020 - 2022, Intel Corporation. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "MpLib.h"
+#include "MpIntelTdx.h"
+
+/**
+ Gets detailed MP-related information on the requested processor at the
+ instant this call is made. This service may only be called from the BSP.
+
+ In current stage only the BSP is workable. So ProcessorNumber should be 0.
+
+ @param[in] ProcessorNumber The handle number of processor.
+ @param[out] ProcessorInfoBuffer A pointer to the buffer where information for
+ the requested processor is deposited.
+ @param[out] HealthData Return processor health data.
+
+ @retval EFI_SUCCESS Processor information was returned.
+ @retval EFI_DEVICE_ERROR The calling processor is an AP.
+ @retval EFI_INVALID_PARAMETER ProcessorInfoBuffer is NULL or ProcessorNumber is not 0.
+ @retval EFI_NOT_FOUND The processor with the handle specified by
+ ProcessorNumber does not exist in the platform.
+ @retval EFI_NOT_READY MP Initialize Library is not initialized.
+
+**/
+EFI_STATUS
+TdxMpInitLibGetProcessorInfo (
+ IN UINTN ProcessorNumber,
+ OUT EFI_PROCESSOR_INFORMATION *ProcessorInfoBuffer,
+ OUT EFI_HEALTH_FLAGS *HealthData OPTIONAL
+ )
+{
+ UINTN OriginalProcessorNumber;
+
+ //
+ // Lower 24 bits contains the actual processor number.
+ //
+ OriginalProcessorNumber = ProcessorNumber;
+ ProcessorNumber &= BIT24 - 1;
+
+ if ((ProcessorInfoBuffer == NULL) || (ProcessorNumber != 0)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ ProcessorInfoBuffer->ProcessorId = 0;
+ ProcessorInfoBuffer->StatusFlag = PROCESSOR_AS_BSP_BIT | PROCESSOR_ENABLED_BIT;
+ ZeroMem (&ProcessorInfoBuffer->Location, sizeof (EFI_CPU_PHYSICAL_LOCATION));
+
+ if ((OriginalProcessorNumber & CPU_V2_EXTENDED_TOPOLOGY) != 0) {
+ ZeroMem (&ProcessorInfoBuffer->ExtendedInformation.Location2, sizeof (EFI_CPU_PHYSICAL_LOCATION2));
+ }
+
+ if (HealthData != NULL) {
+ HealthData->Uint32 = 0;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Retrieves the number of logical processor in the platform and the number of
+ those logical processors that are enabled on this boot. This service may only
+ be called from the BSP.
+
+ @param[out] NumberOfProcessors Pointer to the total number of logical
+ processors in the system, including the BSP
+ and disabled APs.
+ @param[out] NumberOfEnabledProcessors Pointer to the number of enabled logical
+ processors that exist in system, including
+ the BSP.
+
+ @retval EFI_SUCCESS The number of logical processors and enabled
+ logical processors was retrieved.
+ @retval EFI_DEVICE_ERROR The calling processor is an AP.
+ @retval EFI_INVALID_PARAMETER NumberOfProcessors is NULL and NumberOfEnabledProcessors
+ is NULL.
+ @retval EFI_NOT_READY MP Initialize Library is not initialized.
+
+**/
+EFI_STATUS
+TdxMpInitLibGetNumberOfProcessors (
+ OUT UINTN *NumberOfProcessors, OPTIONAL
+ OUT UINTN *NumberOfEnabledProcessors OPTIONAL
+ )
+{
+ ASSERT (NumberOfProcessors != NULL || NumberOfEnabledProcessors != NULL);
+ //
+ // In current stage only the BSP is workable. So NumberOfProcessors
+ // & NumberOfEnableddProcessors are both 1.
+ //
+ if (NumberOfProcessors != NULL) {
+ *NumberOfProcessors = 1;
+ }
+
+ if (NumberOfEnabledProcessors != NULL) {
+ *NumberOfEnabledProcessors = 1;
+ }
+
+ return EFI_SUCCESS;
+}
diff --git a/UefiCpuPkg/Library/MpInitLib/MpLibTdxNull.c b/UefiCpuPkg/Library/MpInitLib/MpLibTdxNull.c
new file mode 100644
index 000000000000..b5aaf6df283f
--- /dev/null
+++ b/UefiCpuPkg/Library/MpInitLib/MpLibTdxNull.c
@@ -0,0 +1,69 @@
+/** @file
+ CPU MP Initialize Library common functions (NULL instance) for Td guest.
+
+ Copyright (c) 2020 - 2022, Intel Corporation. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "MpLib.h"
+#include "MpIntelTdx.h"
+
+/**
+ Gets detailed MP-related information on the requested processor at the
+ instant this call is made. This service may only be called from the BSP.
+
+ @param[in] ProcessorNumber The handle number of processor.
+ @param[out] ProcessorInfoBuffer A pointer to the buffer where information for
+ the requested processor is deposited.
+ @param[out] HealthData Return processor health data.
+
+ @retval EFI_SUCCESS Processor information was returned.
+ @retval EFI_DEVICE_ERROR The calling processor is an AP.
+ @retval EFI_INVALID_PARAMETER ProcessorInfoBuffer is NULL.
+ @retval EFI_NOT_FOUND The processor with the handle specified by
+ ProcessorNumber does not exist in the platform.
+ @retval EFI_NOT_READY MP Initialize Library is not initialized.
+
+**/
+EFI_STATUS
+TdxMpInitLibGetProcessorInfo (
+ IN UINTN ProcessorNumber,
+ OUT EFI_PROCESSOR_INFORMATION *ProcessorInfoBuffer,
+ OUT EFI_HEALTH_FLAGS *HealthData OPTIONAL
+ )
+{
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Retrieves the number of logical processor in the platform and the number of
+ those logical processors that are enabled on this boot. This service may only
+ be called from the BSP.
+
+ @param[out] NumberOfProcessors Pointer to the total number of logical
+ processors in the system, including the BSP
+ and disabled APs.
+ @param[out] NumberOfEnabledProcessors Pointer to the number of enabled logical
+ processors that exist in system, including
+ the BSP.
+
+ @retval EFI_SUCCESS The number of logical processors and enabled
+ logical processors was retrieved.
+ @retval EFI_DEVICE_ERROR The calling processor is an AP.
+ @retval EFI_INVALID_PARAMETER NumberOfProcessors is NULL and NumberOfEnabledProcessors
+ is NULL.
+ @retval EFI_NOT_READY MP Initialize Library is not initialized.
+
+**/
+EFI_STATUS
+TdxMpInitLibGetNumberOfProcessors (
+ OUT UINTN *NumberOfProcessors, OPTIONAL
+ OUT UINTN *NumberOfEnabledProcessors OPTIONAL
+ )
+{
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+}
diff --git a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf
index 5facf4db9499..894be0f8daab 100644
--- a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf
+++ b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf
@@ -24,10 +24,12 @@
[Sources.IA32]
Ia32/AmdSev.c
Ia32/MpFuncs.nasm
+ MpLibTdxNull.c

[Sources.X64]
X64/AmdSev.c
X64/MpFuncs.nasm
+ MpLibTdx.c

[Sources.common]
AmdSev.c
@@ -36,6 +38,7 @@
MpLib.c
MpLib.h
Microcode.c
+ MpIntelTdx.h

[Packages]
MdePkg/MdePkg.dec
--
2.29.2.windows.2


[PATCH V12 13/47] MdePkg: Add macro to check SEV / TDX guest

Min Xu
 

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

Add macros CC_GUEST_IS_SEV / CC_GUEST_IS_TDX to check SEV / TDX guest.

Cc: Michael Roth <michael.roth@...>
Cc: Ray Ni <ray.ni@...>
Cc: Rahul Kumar <rahul1.kumar@...>
Cc: Eric Dong <eric.dong@...>
Cc: James Bottomley <jejb@...>
Cc: Min Xu <min.m.xu@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Jordan Justen <jordan.l.justen@...>
Cc: Ard Biesheuvel <ardb+tianocore@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: Gerd Hoffmann <kraxel@...>
Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Reviewed-by: Liming Gao <gaoliming@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
MdePkg/Include/ConfidentialComputingGuestAttr.h | 3 +++
1 file changed, 3 insertions(+)

diff --git a/MdePkg/Include/ConfidentialComputingGuestAttr.h b/MdePkg/Include/ConfidentialComputingGuestAttr.h
index 6a1301801519..dd2541c6dcdf 100644
--- a/MdePkg/Include/ConfidentialComputingGuestAttr.h
+++ b/MdePkg/Include/ConfidentialComputingGuestAttr.h
@@ -22,4 +22,7 @@ typedef enum {
CCAttrIntelTdx = 0x200,
} CONFIDENTIAL_COMPUTING_GUEST_ATTR;

+#define CC_GUEST_IS_TDX(x) ((x) == CCAttrIntelTdx)
+#define CC_GUEST_IS_SEV(x) ((x) == CCAttrAmdSev || (x) == CCAttrAmdSevEs || (x) == CCAttrAmdSevSnp)
+
#endif
--
2.29.2.windows.2


[PATCH V12 12/47] UefiCpuPkg: Support TDX in BaseXApicX2ApicLib

Min Xu
 

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

MSR is accessed in BaseXApicX2ApicLib. In TDX some MSRs are accessed
directly from/to CPU. Some should be accessed via explicit requests
from the host VMM using TDCALL(TDG.VP.VMCALL). This is done by the
help of TdxLib.

Please refer to [TDX] Section 18.1
TDX: https://software.intel.com/content/dam/develop/external/us/en/
documents/tdx-module-1.0-public-spec-v0.931.pdf

Cc: Eric Dong <eric.dong@...>
Cc: Ray Ni <ray.ni@...>
Cc: Rahul Kumar <rahul1.kumar@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Reviewed-by: Ray Ni <ray.ni@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
.../BaseXApicX2ApicLib/BaseXApicX2ApicLib.c | 160 +++++++++++++++++-
1 file changed, 152 insertions(+), 8 deletions(-)

diff --git a/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.c b/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.c
index aaa42ff8450b..2d17177df12b 100644
--- a/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.c
+++ b/UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.c
@@ -23,11 +23,155 @@
#include <Library/TimerLib.h>
#include <Library/PcdLib.h>
#include <Library/UefiCpuLib.h>
+#include <IndustryStandard/Tdx.h>

//
// Library internal functions
//

+/**
+ Some MSRs in TDX are accessed via TdCall.
+ Some are directly read/write from/to CPU.
+
+ @param MsrIndex Index of the MSR
+ @retval TRUE MSR accessed via TdCall.
+ @retval FALSE MSR accessed not via TdCall.
+
+**/
+BOOLEAN
+AccessMsrTdxCall (
+ IN UINT32 MsrIndex
+ )
+{
+ if (!TdIsEnabled ()) {
+ return FALSE;
+ }
+
+ switch (MsrIndex) {
+ case MSR_IA32_X2APIC_TPR:
+ case MSR_IA32_X2APIC_PPR:
+ case MSR_IA32_X2APIC_EOI:
+ case MSR_IA32_X2APIC_ISR0:
+ case MSR_IA32_X2APIC_ISR1:
+ case MSR_IA32_X2APIC_ISR2:
+ case MSR_IA32_X2APIC_ISR3:
+ case MSR_IA32_X2APIC_ISR4:
+ case MSR_IA32_X2APIC_ISR5:
+ case MSR_IA32_X2APIC_ISR6:
+ case MSR_IA32_X2APIC_ISR7:
+ case MSR_IA32_X2APIC_TMR0:
+ case MSR_IA32_X2APIC_TMR1:
+ case MSR_IA32_X2APIC_TMR2:
+ case MSR_IA32_X2APIC_TMR3:
+ case MSR_IA32_X2APIC_TMR4:
+ case MSR_IA32_X2APIC_TMR5:
+ case MSR_IA32_X2APIC_TMR6:
+ case MSR_IA32_X2APIC_TMR7:
+ case MSR_IA32_X2APIC_IRR0:
+ case MSR_IA32_X2APIC_IRR1:
+ case MSR_IA32_X2APIC_IRR2:
+ case MSR_IA32_X2APIC_IRR3:
+ case MSR_IA32_X2APIC_IRR4:
+ case MSR_IA32_X2APIC_IRR5:
+ case MSR_IA32_X2APIC_IRR6:
+ case MSR_IA32_X2APIC_IRR7:
+ return FALSE;
+ default:
+ break;
+ }
+
+ return TRUE;
+}
+
+/**
+ Read MSR value.
+
+ @param MsrIndex Index of the MSR to read
+ @retval 64-bit Value of MSR.
+
+**/
+UINT64
+LocalApicReadMsrReg64 (
+ IN UINT32 MsrIndex
+ )
+{
+ UINT64 Val;
+ UINT64 Status;
+
+ if (AccessMsrTdxCall (MsrIndex)) {
+ Status = TdVmCall (TDVMCALL_RDMSR, (UINT64)MsrIndex, 0, 0, 0, &Val);
+ if (Status != 0) {
+ TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0);
+ }
+ } else {
+ Val = AsmReadMsr64 (MsrIndex);
+ }
+
+ return Val;
+}
+
+/**
+ Write to MSR.
+
+ @param MsrIndex Index of the MSR to write to
+ @param Value Value to be written to the MSR
+
+ @return Value
+
+**/
+UINT64
+LocalApicWriteMsrReg64 (
+ IN UINT32 MsrIndex,
+ IN UINT64 Value
+ )
+{
+ UINT64 Status;
+
+ if (AccessMsrTdxCall (MsrIndex)) {
+ Status = TdVmCall (TDVMCALL_WRMSR, (UINT64)MsrIndex, Value, 0, 0, 0);
+ if (Status != 0) {
+ TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0);
+ }
+ } else {
+ AsmWriteMsr64 (MsrIndex, Value);
+ }
+
+ return Value;
+}
+
+/**
+ Read MSR value.
+
+ @param MsrIndex Index of the MSR to read
+ @retval 32-bit Value of MSR.
+
+**/
+UINT32
+LocalApicReadMsrReg32 (
+ IN UINT32 MsrIndex
+ )
+{
+ return (UINT32)LocalApicReadMsrReg64 (MsrIndex);
+}
+
+/**
+ Write to MSR.
+
+ @param MsrIndex Index of the MSR to write to
+ @param Value Value to be written to the MSR
+
+ @return Value
+
+**/
+UINT32
+LocalApicWriteMsrReg32 (
+ IN UINT32 MsrIndex,
+ IN UINT32 Value
+ )
+{
+ return (UINT32)LocalApicWriteMsrReg64 (MsrIndex, Value);
+}
+
/**
Determine if the CPU supports the Local APIC Base Address MSR.

@@ -78,7 +222,7 @@ GetLocalApicBaseAddress (
return PcdGet32 (PcdCpuLocalApicBaseAddress);
}

- ApicBaseMsr.Uint64 = AsmReadMsr64 (MSR_IA32_APIC_BASE);
+ ApicBaseMsr.Uint64 = LocalApicReadMsrReg64 (MSR_IA32_APIC_BASE);

return (UINTN)(LShiftU64 ((UINT64)ApicBaseMsr.Bits.ApicBaseHi, 32)) +
(((UINTN)ApicBaseMsr.Bits.ApicBase) << 12);
@@ -109,12 +253,12 @@ SetLocalApicBaseAddress (
return;
}

- ApicBaseMsr.Uint64 = AsmReadMsr64 (MSR_IA32_APIC_BASE);
+ ApicBaseMsr.Uint64 = LocalApicReadMsrReg64 (MSR_IA32_APIC_BASE);

ApicBaseMsr.Bits.ApicBase = (UINT32)(BaseAddress >> 12);
ApicBaseMsr.Bits.ApicBaseHi = (UINT32)(RShiftU64 ((UINT64)BaseAddress, 32));

- AsmWriteMsr64 (MSR_IA32_APIC_BASE, ApicBaseMsr.Uint64);
+ LocalApicWriteMsrReg64 (MSR_IA32_APIC_BASE, ApicBaseMsr.Uint64);
}

/**
@@ -154,7 +298,7 @@ ReadLocalApicReg (
ASSERT (MmioOffset != XAPIC_ICR_HIGH_OFFSET);

MsrIndex = (UINT32)(MmioOffset >> 4) + X2APIC_MSR_BASE_ADDRESS;
- return AsmReadMsr32 (MsrIndex);
+ return LocalApicReadMsrReg32 (MsrIndex);
}
}

@@ -203,7 +347,7 @@ WriteLocalApicReg (
// Use memory fence here to force the serializing semantics to be consisent with xAPIC mode.
//
MemoryFence ();
- AsmWriteMsr32 (MsrIndex, Value);
+ LocalApicWriteMsrReg32 (MsrIndex, Value);
}
}

@@ -309,7 +453,7 @@ GetApicMode (
return LOCAL_APIC_MODE_XAPIC;
}

- ApicBaseMsr.Uint64 = AsmReadMsr64 (MSR_IA32_APIC_BASE);
+ ApicBaseMsr.Uint64 = LocalApicReadMsrReg64 (MSR_IA32_APIC_BASE);
//
// Local APIC should have been enabled
//
@@ -354,9 +498,9 @@ SetApicMode (
case LOCAL_APIC_MODE_XAPIC:
break;
case LOCAL_APIC_MODE_X2APIC:
- ApicBaseMsr.Uint64 = AsmReadMsr64 (MSR_IA32_APIC_BASE);
+ ApicBaseMsr.Uint64 = LocalApicReadMsrReg64 (MSR_IA32_APIC_BASE);
ApicBaseMsr.Bits.EXTD = 1;
- AsmWriteMsr64 (MSR_IA32_APIC_BASE, ApicBaseMsr.Uint64);
+ LocalApicWriteMsrReg64 (MSR_IA32_APIC_BASE, ApicBaseMsr.Uint64);
break;
default:
ASSERT (FALSE);
--
2.29.2.windows.2


[PATCH V12 11/47] MdePkg: Support IoRead/IoWrite for Tdx guest in BaseIoLibIntrinsic

Min Xu
 

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

This commit supports IoRead/IoWrite for SEV/TDX/Legacy guest in one
binary. It checks the guest type in runtime and then call corresponding
functions.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Reviewed-by: Liming Gao <gaoliming@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
MdePkg/Library/BaseIoLibIntrinsic/IoLibGcc.c | 51 ++++++++++++--
MdePkg/Library/BaseIoLibIntrinsic/IoLibMsc.c | 73 +++++++++++++++-----
2 files changed, 99 insertions(+), 25 deletions(-)

diff --git a/MdePkg/Library/BaseIoLibIntrinsic/IoLibGcc.c b/MdePkg/Library/BaseIoLibIntrinsic/IoLibGcc.c
index 5c791289c469..05a739085967 100644
--- a/MdePkg/Library/BaseIoLibIntrinsic/IoLibGcc.c
+++ b/MdePkg/Library/BaseIoLibIntrinsic/IoLibGcc.c
@@ -16,6 +16,7 @@
**/

#include "BaseIoLibIntrinsicInternal.h"
+#include "IoLibTdx.h"

/**
Reads an 8-bit I/O port.
@@ -24,7 +25,9 @@
This function must guarantee that all I/O read and write operations are
serialized.

- If 8-bit I/O port operations are not supported, then ASSERT().
+ If 8-bit I/O port operations are not supported, then ASSERT()
+
+ For Td guest TDVMCALL_IO is invoked to read I/O port.

@param Port The I/O port to read.

@@ -42,7 +45,11 @@ IoRead8 (

Flag = FilterBeforeIoRead (FilterWidth8, Port, &Data);
if (Flag) {
- __asm__ __volatile__ ("inb %w1,%b0" : "=a" (Data) : "d" ((UINT16)Port));
+ if (IsTdxGuest ()) {
+ Data = TdIoRead8 (Port);
+ } else {
+ __asm__ __volatile__ ("inb %w1,%b0" : "=a" (Data) : "d" ((UINT16)Port));
+ }
}

FilterAfterIoRead (FilterWidth8, Port, &Data);
@@ -59,6 +66,8 @@ IoRead8 (

If 8-bit I/O port operations are not supported, then ASSERT().

+ For Td guest TDVMCALL_IO is invoked to write I/O port.
+
@param Port The I/O port to write.
@param Value The value to write to the I/O port.

@@ -76,7 +85,11 @@ IoWrite8 (

Flag = FilterBeforeIoWrite (FilterWidth8, Port, &Value);
if (Flag) {
- __asm__ __volatile__ ("outb %b0,%w1" : : "a" (Value), "d" ((UINT16)Port));
+ if (IsTdxGuest ()) {
+ TdIoWrite8 (Port, Value);
+ } else {
+ __asm__ __volatile__ ("outb %b0,%w1" : : "a" (Value), "d" ((UINT16)Port));
+ }
}

FilterAfterIoWrite (FilterWidth8, Port, &Value);
@@ -94,6 +107,8 @@ IoWrite8 (
If 16-bit I/O port operations are not supported, then ASSERT().
If Port is not aligned on a 16-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_IO is invoked to read I/O port.
+
@param Port The I/O port to read.

@return The value read.
@@ -112,7 +127,11 @@ IoRead16 (

Flag = FilterBeforeIoRead (FilterWidth16, Port, &Data);
if (Flag) {
- __asm__ __volatile__ ("inw %w1,%w0" : "=a" (Data) : "d" ((UINT16)Port));
+ if (IsTdxGuest ()) {
+ Data = TdIoRead16 (Port);
+ } else {
+ __asm__ __volatile__ ("inw %w1,%w0" : "=a" (Data) : "d" ((UINT16)Port));
+ }
}

FilterAfterIoRead (FilterWidth16, Port, &Data);
@@ -130,6 +149,8 @@ IoRead16 (
If 16-bit I/O port operations are not supported, then ASSERT().
If Port is not aligned on a 16-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_IO is invoked to write I/O port.
+
@param Port The I/O port to write.
@param Value The value to write to the I/O port.

@@ -149,7 +170,11 @@ IoWrite16 (

Flag = FilterBeforeIoWrite (FilterWidth16, Port, &Value);
if (Flag) {
- __asm__ __volatile__ ("outw %w0,%w1" : : "a" (Value), "d" ((UINT16)Port));
+ if (IsTdxGuest ()) {
+ TdIoWrite16 (Port, Value);
+ } else {
+ __asm__ __volatile__ ("outw %w0,%w1" : : "a" (Value), "d" ((UINT16)Port));
+ }
}

FilterAfterIoWrite (FilterWidth16, Port, &Value);
@@ -167,6 +192,8 @@ IoWrite16 (
If 32-bit I/O port operations are not supported, then ASSERT().
If Port is not aligned on a 32-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_IO is invoked to read I/O port.
+
@param Port The I/O port to read.

@return The value read.
@@ -185,7 +212,11 @@ IoRead32 (

Flag = FilterBeforeIoRead (FilterWidth32, Port, &Data);
if (Flag) {
- __asm__ __volatile__ ("inl %w1,%0" : "=a" (Data) : "d" ((UINT16)Port));
+ if (IsTdxGuest ()) {
+ Data = TdIoRead32 (Port);
+ } else {
+ __asm__ __volatile__ ("inl %w1,%0" : "=a" (Data) : "d" ((UINT16)Port));
+ }
}

FilterAfterIoRead (FilterWidth32, Port, &Data);
@@ -203,6 +234,8 @@ IoRead32 (
If 32-bit I/O port operations are not supported, then ASSERT().
If Port is not aligned on a 32-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_IO is invoked to write I/O port.
+
@param Port The I/O port to write.
@param Value The value to write to the I/O port.

@@ -222,7 +255,11 @@ IoWrite32 (

Flag = FilterBeforeIoWrite (FilterWidth32, Port, &Value);
if (Flag) {
- __asm__ __volatile__ ("outl %0,%w1" : : "a" (Value), "d" ((UINT16)Port));
+ if (IsTdxGuest ()) {
+ TdIoWrite32 (Port, Value);
+ } else {
+ __asm__ __volatile__ ("outl %0,%w1" : : "a" (Value), "d" ((UINT16)Port));
+ }
}

FilterAfterIoWrite (FilterWidth32, Port, &Value);
diff --git a/MdePkg/Library/BaseIoLibIntrinsic/IoLibMsc.c b/MdePkg/Library/BaseIoLibIntrinsic/IoLibMsc.c
index 9f225a6b5d39..f1b7d51a7245 100644
--- a/MdePkg/Library/BaseIoLibIntrinsic/IoLibMsc.c
+++ b/MdePkg/Library/BaseIoLibIntrinsic/IoLibMsc.c
@@ -14,6 +14,7 @@
**/

#include "BaseIoLibIntrinsicInternal.h"
+#include "IoLibTdx.h"

//
// Microsoft Visual Studio 7.1 Function Prototypes for I/O Intrinsics.
@@ -82,6 +83,8 @@ _ReadWriteBarrier (

If 8-bit I/O port operations are not supported, then ASSERT().

+ For Td guest TDVMCALL_IO is invoked to read I/O port.
+
@param Port The I/O port to read.

@return The value read.
@@ -98,9 +101,13 @@ IoRead8 (

Flag = FilterBeforeIoRead (FilterWidth8, Port, &Value);
if (Flag) {
- _ReadWriteBarrier ();
- Value = (UINT8)_inp ((UINT16)Port);
- _ReadWriteBarrier ();
+ if (IsTdxGuest ()) {
+ Value = TdIoRead8 (Port);
+ } else {
+ _ReadWriteBarrier ();
+ Value = (UINT8)_inp ((UINT16)Port);
+ _ReadWriteBarrier ();
+ }
}

FilterAfterIoRead (FilterWidth8, Port, &Value);
@@ -117,6 +124,8 @@ IoRead8 (

If 8-bit I/O port operations are not supported, then ASSERT().

+ For Td guest TDVMCALL_IO is invoked to write I/O port.
+
@param Port The I/O port to write.
@param Value The value to write to the I/O port.

@@ -134,9 +143,13 @@ IoWrite8 (

Flag = FilterBeforeIoWrite (FilterWidth8, Port, &Value);
if (Flag) {
- _ReadWriteBarrier ();
- (UINT8)_outp ((UINT16)Port, Value);
- _ReadWriteBarrier ();
+ if (IsTdxGuest ()) {
+ TdIoWrite8 (Port, Value);
+ } else {
+ _ReadWriteBarrier ();
+ (UINT8)_outp ((UINT16)Port, Value);
+ _ReadWriteBarrier ();
+ }
}

FilterAfterIoWrite (FilterWidth8, Port, &Value);
@@ -154,6 +167,8 @@ IoWrite8 (
If 16-bit I/O port operations are not supported, then ASSERT().
If Port is not aligned on a 16-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_IO is invoked to read I/O port.
+
@param Port The I/O port to read.

@return The value read.
@@ -172,9 +187,13 @@ IoRead16 (

Flag = FilterBeforeIoRead (FilterWidth16, Port, &Value);
if (Flag) {
- _ReadWriteBarrier ();
- Value = _inpw ((UINT16)Port);
- _ReadWriteBarrier ();
+ if (IsTdxGuest ()) {
+ Value = TdIoRead16 (Port);
+ } else {
+ _ReadWriteBarrier ();
+ Value = _inpw ((UINT16)Port);
+ _ReadWriteBarrier ();
+ }
}

FilterBeforeIoRead (FilterWidth16, Port, &Value);
@@ -192,6 +211,8 @@ IoRead16 (
If 16-bit I/O port operations are not supported, then ASSERT().
If Port is not aligned on a 16-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_IO is invoked to write I/O port.
+
@param Port The I/O port to write.
@param Value The value to write to the I/O port.

@@ -211,9 +232,13 @@ IoWrite16 (

Flag = FilterBeforeIoWrite (FilterWidth16, Port, &Value);
if (Flag) {
- _ReadWriteBarrier ();
- _outpw ((UINT16)Port, Value);
- _ReadWriteBarrier ();
+ if (IsTdxGuest ()) {
+ TdIoWrite16 (Port, Value);
+ } else {
+ _ReadWriteBarrier ();
+ _outpw ((UINT16)Port, Value);
+ _ReadWriteBarrier ();
+ }
}

FilterAfterIoWrite (FilterWidth16, Port, &Value);
@@ -231,6 +256,8 @@ IoWrite16 (
If 32-bit I/O port operations are not supported, then ASSERT().
If Port is not aligned on a 32-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_IO is invoked to read I/O port.
+
@param Port The I/O port to read.

@return The value read.
@@ -249,9 +276,13 @@ IoRead32 (

Flag = FilterBeforeIoRead (FilterWidth32, Port, &Value);
if (Flag) {
- _ReadWriteBarrier ();
- Value = _inpd ((UINT16)Port);
- _ReadWriteBarrier ();
+ if (IsTdxGuest ()) {
+ Value = TdIoRead32 (Port);
+ } else {
+ _ReadWriteBarrier ();
+ Value = _inpd ((UINT16)Port);
+ _ReadWriteBarrier ();
+ }
}

FilterAfterIoRead (FilterWidth32, Port, &Value);
@@ -269,6 +300,8 @@ IoRead32 (
If 32-bit I/O port operations are not supported, then ASSERT().
If Port is not aligned on a 32-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_IO is invoked to write I/O port.
+
@param Port The I/O port to write.
@param Value The value to write to the I/O port.

@@ -288,9 +321,13 @@ IoWrite32 (

Flag = FilterBeforeIoWrite (FilterWidth32, Port, &Value);
if (Flag) {
- _ReadWriteBarrier ();
- _outpd ((UINT16)Port, Value);
- _ReadWriteBarrier ();
+ if (IsTdxGuest ()) {
+ TdIoWrite32 (Port, Value);
+ } else {
+ _ReadWriteBarrier ();
+ _outpd ((UINT16)Port, Value);
+ _ReadWriteBarrier ();
+ }
}

FilterAfterIoWrite (FilterWidth32, Port, &Value);
--
2.29.2.windows.2


[PATCH V12 10/47] MdePkg: Support IoFifo for Tdx guest in BaseIoLibIntrinsic

Min Xu
 

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

Previously IoFifo functions are in X64/IoFifoSev.nasm which supports
both SEV guest and Legacy guest. IoLibFifo.c is introduced to support
SEV/TDX/Legacy guest in one binary. It checks the guest type in runtime
and call corresponding functions then.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Reviewed-by: Liming Gao <gaoliming@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
.../BaseIoLibIntrinsicSev.inf | 2 +
MdePkg/Library/BaseIoLibIntrinsic/IoLibFifo.c | 217 ++++++++++++++++++
MdePkg/Library/BaseIoLibIntrinsic/IoLibSev.h | 166 ++++++++++++++
.../BaseIoLibIntrinsic/X64/IoFifoSev.nasm | 34 +--
4 files changed, 402 insertions(+), 17 deletions(-)
create mode 100644 MdePkg/Library/BaseIoLibIntrinsic/IoLibFifo.c
create mode 100644 MdePkg/Library/BaseIoLibIntrinsic/IoLibSev.h

diff --git a/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf b/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
index a74e54bee8b5..7fe1c60f046e 100644
--- a/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
+++ b/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
@@ -31,6 +31,7 @@
BaseIoLibIntrinsicInternal.h
IoHighLevel.c
IoLibTdx.h
+ IoLibSev.h

[Sources.IA32]
IoLibGcc.c | GCC
@@ -44,6 +45,7 @@
IoLibMsc.c | MSFT
IoLib.c
IoLibInternalTdx.c
+ IoLibFifo.c
X64/IoFifoSev.nasm

[Packages]
diff --git a/MdePkg/Library/BaseIoLibIntrinsic/IoLibFifo.c b/MdePkg/Library/BaseIoLibIntrinsic/IoLibFifo.c
new file mode 100644
index 000000000000..9a94bc6a054c
--- /dev/null
+++ b/MdePkg/Library/BaseIoLibIntrinsic/IoLibFifo.c
@@ -0,0 +1,217 @@
+/** @file
+ IoFifo read/write routines.
+
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "BaseIoLibIntrinsicInternal.h"
+#include "IoLibSev.h"
+#include "IoLibTdx.h"
+#include <Uefi/UefiBaseType.h>
+#include <Library/TdxLib.h>
+
+/**
+ Reads an 8-bit I/O port fifo into a block of memory.
+
+ Reads the 8-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoRead8 is invoked to read the I/O port fifo.
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+IoReadFifo8 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ )
+{
+ if (IsTdxGuest ()) {
+ TdIoReadFifo8 (Port, Count, Buffer);
+ } else {
+ SevIoReadFifo8 (Port, Count, Buffer);
+ }
+}
+
+/**
+ Writes a block of memory into an 8-bit I/O port fifo.
+
+ Writes the 8-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoWrite8 is invoked to write data to the I/O port.
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+IoWriteFifo8 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ if (IsTdxGuest ()) {
+ TdIoWriteFifo8 (Port, Count, Buffer);
+ } else {
+ SevIoWriteFifo8 (Port, Count, Buffer);
+ }
+}
+
+/**
+ Reads a 16-bit I/O port fifo into a block of memory.
+
+ Reads the 16-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 16-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoRead16 is invoked to read data from the I/O port.
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+IoReadFifo16 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ )
+{
+ if (IsTdxGuest ()) {
+ TdIoReadFifo16 (Port, Count, Buffer);
+ } else {
+ SevIoReadFifo16 (Port, Count, Buffer);
+ }
+}
+
+/**
+ Writes a block of memory into a 16-bit I/O port fifo.
+
+ Writes the 16-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 16-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoWrite16 is invoked to write data to the I/O port.
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+IoWriteFifo16 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ if (IsTdxGuest ()) {
+ TdIoWriteFifo16 (Port, Count, Buffer);
+ } else {
+ SevIoWriteFifo16 (Port, Count, Buffer);
+ }
+}
+
+/**
+ Reads a 32-bit I/O port fifo into a block of memory.
+
+ Reads the 32-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 32-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoRead32 is invoked to read data from the I/O port.
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+IoReadFifo32 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ )
+{
+ if (IsTdxGuest ()) {
+ TdIoReadFifo32 (Port, Count, Buffer);
+ } else {
+ SevIoReadFifo32 (Port, Count, Buffer);
+ }
+}
+
+/**
+ Writes a block of memory into a 32-bit I/O port fifo.
+
+ Writes the 32-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 32-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoWrite32 is invoked to write data to the I/O port.
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+IoWriteFifo32 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ if (IsTdxGuest ()) {
+ TdIoWriteFifo32 (Port, Count, Buffer);
+ } else {
+ SevIoWriteFifo32 (Port, Count, Buffer);
+ }
+}
diff --git a/MdePkg/Library/BaseIoLibIntrinsic/IoLibSev.h b/MdePkg/Library/BaseIoLibIntrinsic/IoLibSev.h
new file mode 100644
index 000000000000..6d7cafcff27a
--- /dev/null
+++ b/MdePkg/Library/BaseIoLibIntrinsic/IoLibSev.h
@@ -0,0 +1,166 @@
+/** @file
+ Header file for SEV IO library.
+
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#ifndef IOLIB_SEV_H_
+#define IOLIB_SEV_H_
+
+#include <Base.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+
+/**
+ Reads an 8-bit I/O port fifo into a block of memory.
+
+ Reads the 8-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+SevIoReadFifo8 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ );
+
+/**
+ Writes a block of memory into an 8-bit I/O port fifo.
+
+ Writes the 8-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+SevIoWriteFifo8 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ );
+
+/**
+ Reads an 8-bit I/O port fifo into a block of memory.
+
+ Reads the 8-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+SevIoReadFifo16 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ );
+
+/**
+ Writes a block of memory into an 8-bit I/O port fifo.
+
+ Writes the 8-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+SevIoWriteFifo16 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ );
+
+/**
+ Reads an 8-bit I/O port fifo into a block of memory.
+
+ Reads the 8-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+SevIoReadFifo32 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ );
+
+/**
+ Writes a block of memory into an 8-bit I/O port fifo.
+
+ Writes the 8-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+SevIoWriteFifo32 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ );
+
+#endif
diff --git a/MdePkg/Library/BaseIoLibIntrinsic/X64/IoFifoSev.nasm b/MdePkg/Library/BaseIoLibIntrinsic/X64/IoFifoSev.nasm
index 106f8881c55c..d02286b4d518 100644
--- a/MdePkg/Library/BaseIoLibIntrinsic/X64/IoFifoSev.nasm
+++ b/MdePkg/Library/BaseIoLibIntrinsic/X64/IoFifoSev.nasm
@@ -67,14 +67,14 @@ ASM_PFX(SevNoRepIo):
;------------------------------------------------------------------------------
; VOID
; EFIAPI
-; IoReadFifo8 (
+; SevIoReadFifo8 (
; IN UINTN Port, // rcx
; IN UINTN Size, // rdx
; OUT VOID *Buffer // r8
; );
;------------------------------------------------------------------------------
-global ASM_PFX(IoReadFifo8)
-ASM_PFX(IoReadFifo8):
+global ASM_PFX(SevIoReadFifo8)
+ASM_PFX(SevIoReadFifo8):
xchg rcx, rdx
xchg rdi, r8 ; rdi: buffer address; r8: save rdi

@@ -103,14 +103,14 @@ ASM_PFX(IoReadFifo8):
;------------------------------------------------------------------------------
; VOID
; EFIAPI
-; IoReadFifo16 (
+; SevIoReadFifo16 (
; IN UINTN Port, // rcx
; IN UINTN Size, // rdx
; OUT VOID *Buffer // r8
; );
;------------------------------------------------------------------------------
-global ASM_PFX(IoReadFifo16)
-ASM_PFX(IoReadFifo16):
+global ASM_PFX(SevIoReadFifo16)
+ASM_PFX(SevIoReadFifo16):
xchg rcx, rdx
xchg rdi, r8 ; rdi: buffer address; r8: save rdi

@@ -139,14 +139,14 @@ ASM_PFX(IoReadFifo16):
;------------------------------------------------------------------------------
; VOID
; EFIAPI
-; IoReadFifo32 (
+; SevIoReadFifo32 (
; IN UINTN Port, // rcx
; IN UINTN Size, // rdx
; OUT VOID *Buffer // r8
; );
;------------------------------------------------------------------------------
-global ASM_PFX(IoReadFifo32)
-ASM_PFX(IoReadFifo32):
+global ASM_PFX(SevIoReadFifo32)
+ASM_PFX(SevIoReadFifo32):
xchg rcx, rdx
xchg rdi, r8 ; rdi: buffer address; r8: save rdi

@@ -181,8 +181,8 @@ ASM_PFX(IoReadFifo32):
; IN VOID *Buffer // r8
; );
;------------------------------------------------------------------------------
-global ASM_PFX(IoWriteFifo8)
-ASM_PFX(IoWriteFifo8):
+global ASM_PFX(SevIoWriteFifo8)
+ASM_PFX(SevIoWriteFifo8):
xchg rcx, rdx
xchg rsi, r8 ; rsi: buffer address; r8: save rsi

@@ -211,14 +211,14 @@ ASM_PFX(IoWriteFifo8):
;------------------------------------------------------------------------------
; VOID
; EFIAPI
-; IoWriteFifo16 (
+; SevIoWriteFifo16 (
; IN UINTN Port, // rcx
; IN UINTN Size, // rdx
; IN VOID *Buffer // r8
; );
;------------------------------------------------------------------------------
-global ASM_PFX(IoWriteFifo16)
-ASM_PFX(IoWriteFifo16):
+global ASM_PFX(SevIoWriteFifo16)
+ASM_PFX(SevIoWriteFifo16):
xchg rcx, rdx
xchg rsi, r8 ; rsi: buffer address; r8: save rsi

@@ -247,14 +247,14 @@ ASM_PFX(IoWriteFifo16):
;------------------------------------------------------------------------------
; VOID
; EFIAPI
-; IoWriteFifo32 (
+; SevIoWriteFifo32 (
; IN UINTN Port, // rcx
; IN UINTN Size, // rdx
; IN VOID *Buffer // r8
; );
;------------------------------------------------------------------------------
-global ASM_PFX(IoWriteFifo32)
-ASM_PFX(IoWriteFifo32):
+global ASM_PFX(SevIoWriteFifo32)
+ASM_PFX(SevIoWriteFifo32):
xchg rcx, rdx
xchg rsi, r8 ; rsi: buffer address; r8: save rsi

--
2.29.2.windows.2


[PATCH V12 09/47] MdePkg: Support mmio for Tdx guest in BaseIoLibIntrinsic

Min Xu
 

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

TDVF access MMIO with TDG.VP.VMCALL to invoke VMM provided emulation
functions. If the access to MMIO fails, it fall backs to the direct
access.

BaseIoLibIntrinsic.inf is the IoLib used by other packages. It will
not support I/O in Td guest. But some files are shared between
BaseIoLibIntrinsic and BaseIoLibIntrinsicSev (IoLib.c is the example). So
IoLibInternalTdxNull.c (which holds the null stub of the Td I/O routines)
is included in BaseIoLibIntrinsic.inf. BaseIoLibIntrinsic.inf doesn't
import TdxLib so that the Pkgs which include BaseIoLibIntrinsic.inf
need not include TdxLib.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Reviewed-by: Liming Gao <gaoliming@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
.../BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf | 2 +
.../BaseIoLibIntrinsicSev.inf | 3 +
MdePkg/Library/BaseIoLibIntrinsic/IoLib.c | 81 +++++++++++++++++--
3 files changed, 78 insertions(+), 8 deletions(-)

diff --git a/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf b/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
index 97eeada0656e..27b15d9ae256 100644
--- a/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
+++ b/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
@@ -34,6 +34,8 @@
IoLibMmioBuffer.c
BaseIoLibIntrinsicInternal.h
IoHighLevel.c
+ IoLibInternalTdxNull.c
+ IoLibTdx.h

[Sources.IA32]
IoLibGcc.c | GCC
diff --git a/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf b/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
index 336d79736d9a..a74e54bee8b5 100644
--- a/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
+++ b/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
@@ -30,17 +30,20 @@
IoLibMmioBuffer.c
BaseIoLibIntrinsicInternal.h
IoHighLevel.c
+ IoLibTdx.h

[Sources.IA32]
IoLibGcc.c | GCC
IoLibMsc.c | MSFT
IoLib.c
+ IoLibInternalTdxNull.c
Ia32/IoFifoSev.nasm

[Sources.X64]
IoLibGcc.c | GCC
IoLibMsc.c | MSFT
IoLib.c
+ IoLibInternalTdx.c
X64/IoFifoSev.nasm

[Packages]
diff --git a/MdePkg/Library/BaseIoLibIntrinsic/IoLib.c b/MdePkg/Library/BaseIoLibIntrinsic/IoLib.c
index 9d42e21a691c..5bd02b56a1fa 100644
--- a/MdePkg/Library/BaseIoLibIntrinsic/IoLib.c
+++ b/MdePkg/Library/BaseIoLibIntrinsic/IoLib.c
@@ -7,6 +7,7 @@
**/

#include "BaseIoLibIntrinsicInternal.h"
+#include "IoLibTdx.h"

/**
Reads a 64-bit I/O port.
@@ -69,6 +70,8 @@ IoWrite64 (

If 8-bit MMIO register operations are not supported, then ASSERT().

+ For Td guest TDVMCALL_MMIO is invoked to read MMIO registers.
+
@param Address The MMIO register to read.

@return The value read.
@@ -86,7 +89,13 @@ MmioRead8 (
Flag = FilterBeforeMmIoRead (FilterWidth8, Address, &Value);
if (Flag) {
MemoryFence ();
- Value = *(volatile UINT8 *)Address;
+
+ if (IsTdxGuest ()) {
+ Value = TdMmioRead8 (Address);
+ } else {
+ Value = *(volatile UINT8 *)Address;
+ }
+
MemoryFence ();
}

@@ -104,6 +113,8 @@ MmioRead8 (

If 8-bit MMIO register operations are not supported, then ASSERT().

+ For Td guest TDVMCALL_MMIO is invoked to write MMIO registers.
+
@param Address The MMIO register to write.
@param Value The value to write to the MMIO register.

@@ -122,7 +133,13 @@ MmioWrite8 (
Flag = FilterBeforeMmIoWrite (FilterWidth8, Address, &Value);
if (Flag) {
MemoryFence ();
- *(volatile UINT8 *)Address = Value;
+
+ if (IsTdxGuest ()) {
+ TdMmioWrite8 (Address, Value);
+ } else {
+ *(volatile UINT8 *)Address = Value;
+ }
+
MemoryFence ();
}

@@ -141,6 +158,8 @@ MmioWrite8 (
If 16-bit MMIO register operations are not supported, then ASSERT().
If Address is not aligned on a 16-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_MMIO is invoked to read MMIO registers.
+
@param Address The MMIO register to read.

@return The value read.
@@ -159,7 +178,13 @@ MmioRead16 (
Flag = FilterBeforeMmIoRead (FilterWidth16, Address, &Value);
if (Flag) {
MemoryFence ();
- Value = *(volatile UINT16 *)Address;
+
+ if (IsTdxGuest ()) {
+ Value = TdMmioRead16 (Address);
+ } else {
+ Value = *(volatile UINT16 *)Address;
+ }
+
MemoryFence ();
}

@@ -178,6 +203,8 @@ MmioRead16 (
If 16-bit MMIO register operations are not supported, then ASSERT().
If Address is not aligned on a 16-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_MMIO is invoked to write MMIO registers.
+
@param Address The MMIO register to write.
@param Value The value to write to the MMIO register.

@@ -198,7 +225,13 @@ MmioWrite16 (
Flag = FilterBeforeMmIoWrite (FilterWidth16, Address, &Value);
if (Flag) {
MemoryFence ();
- *(volatile UINT16 *)Address = Value;
+
+ if (IsTdxGuest ()) {
+ TdMmioWrite16 (Address, Value);
+ } else {
+ *(volatile UINT16 *)Address = Value;
+ }
+
MemoryFence ();
}

@@ -217,6 +250,8 @@ MmioWrite16 (
If 32-bit MMIO register operations are not supported, then ASSERT().
If Address is not aligned on a 32-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_MMIO is invoked to read MMIO registers.
+
@param Address The MMIO register to read.

@return The value read.
@@ -236,7 +271,13 @@ MmioRead32 (
Flag = FilterBeforeMmIoRead (FilterWidth32, Address, &Value);
if (Flag) {
MemoryFence ();
- Value = *(volatile UINT32 *)Address;
+
+ if (IsTdxGuest ()) {
+ Value = TdMmioRead32 (Address);
+ } else {
+ Value = *(volatile UINT32 *)Address;
+ }
+
MemoryFence ();
}

@@ -255,6 +296,8 @@ MmioRead32 (
If 32-bit MMIO register operations are not supported, then ASSERT().
If Address is not aligned on a 32-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_MMIO is invoked to write MMIO registers.
+
@param Address The MMIO register to write.
@param Value The value to write to the MMIO register.

@@ -275,7 +318,13 @@ MmioWrite32 (
Flag = FilterBeforeMmIoWrite (FilterWidth32, Address, &Value);
if (Flag) {
MemoryFence ();
- *(volatile UINT32 *)Address = Value;
+
+ if (IsTdxGuest ()) {
+ TdMmioWrite32 (Address, Value);
+ } else {
+ *(volatile UINT32 *)Address = Value;
+ }
+
MemoryFence ();
}

@@ -294,6 +343,8 @@ MmioWrite32 (
If 64-bit MMIO register operations are not supported, then ASSERT().
If Address is not aligned on a 64-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_MMIO is invoked to read MMIO registers.
+
@param Address The MMIO register to read.

@return The value read.
@@ -313,7 +364,13 @@ MmioRead64 (
Flag = FilterBeforeMmIoRead (FilterWidth64, Address, &Value);
if (Flag) {
MemoryFence ();
- Value = *(volatile UINT64 *)Address;
+
+ if (IsTdxGuest ()) {
+ Value = TdMmioRead64 (Address);
+ } else {
+ Value = *(volatile UINT64 *)Address;
+ }
+
MemoryFence ();
}

@@ -332,6 +389,8 @@ MmioRead64 (
If 64-bit MMIO register operations are not supported, then ASSERT().
If Address is not aligned on a 64-bit boundary, then ASSERT().

+ For Td guest TDVMCALL_MMIO is invoked to write MMIO registers.
+
@param Address The MMIO register to write.
@param Value The value to write to the MMIO register.

@@ -350,7 +409,13 @@ MmioWrite64 (
Flag = FilterBeforeMmIoWrite (FilterWidth64, Address, &Value);
if (Flag) {
MemoryFence ();
- *(volatile UINT64 *)Address = Value;
+
+ if (IsTdxGuest ()) {
+ TdMmioWrite64 (Address, Value);
+ } else {
+ *(volatile UINT64 *)Address = Value;
+ }
+
MemoryFence ();
}

--
2.29.2.windows.2


[PATCH V12 08/47] MdePkg: Add helper functions for Tdx guest in BaseIoLibIntrinsic

Min Xu
 

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

Intel TDX architecture does not prescribe a specific software convention
to perform I/O from the guest TD. Guest TD providers have many choices to
provide I/O to the guest. The common I/O models are emulated devices,
para-virtualized devices, SRIOV devices and Direct Device assignments.

TDVF chooses para-virtualized I/O (Choice-A) which use the TDG.VP.VMCALL
function to invoke the funtions provided by the host VMM to perform I/O.
Another choice (Choice-B) is the emulation performed by the #VE handler.

There are 2 benefits of para-virtualized I/O:
1. Performance.
VMEXIT/VMENTRY is skipped so that the performance is better than #VE
handler.
2. De-couple with #VE handler.
Choice-B depends on the #VE handler which means I/O is not available
until #VE handler is installed. For example, in PEI phase #VE handler
is installed in CpuMpPei, while communication with Qemu (via I/O port)
happen earlier than it.

IoLibInternalTdx.c provides the helper functions for Tdx guest.
IoLibInternalTdxNull.c provides the null version of the helper functions.
It is included in the Non-X64 IoLib so that the build will not be broken.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Reviewed-by: Liming Gao <gaoliming@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
.../BaseIoLibIntrinsicSev.inf | 2 +
.../BaseIoLibIntrinsic/IoLibInternalTdx.c | 674 ++++++++++++++++++
.../BaseIoLibIntrinsic/IoLibInternalTdxNull.c | 497 +++++++++++++
MdePkg/Library/BaseIoLibIntrinsic/IoLibTdx.h | 410 +++++++++++
4 files changed, 1583 insertions(+)
create mode 100644 MdePkg/Library/BaseIoLibIntrinsic/IoLibInternalTdx.c
create mode 100644 MdePkg/Library/BaseIoLibIntrinsic/IoLibInternalTdxNull.c
create mode 100644 MdePkg/Library/BaseIoLibIntrinsic/IoLibTdx.h

diff --git a/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf b/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
index 34f9d1d1062f..336d79736d9a 100644
--- a/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
+++ b/MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
@@ -51,3 +51,5 @@
BaseLib
RegisterFilterLib

+[LibraryClasses.X64]
+ TdxLib
diff --git a/MdePkg/Library/BaseIoLibIntrinsic/IoLibInternalTdx.c b/MdePkg/Library/BaseIoLibIntrinsic/IoLibInternalTdx.c
new file mode 100644
index 000000000000..1e539dbfbbad
--- /dev/null
+++ b/MdePkg/Library/BaseIoLibIntrinsic/IoLibInternalTdx.c
@@ -0,0 +1,674 @@
+/** @file
+ TDX I/O Library routines.
+
+ Copyright (c) 2020-2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#include "BaseIoLibIntrinsicInternal.h"
+#include <Uefi/UefiBaseType.h>
+#include <Include/IndustryStandard/Tdx.h>
+#include <Library/TdxLib.h>
+#include <Register/Intel/Cpuid.h>
+#include "IoLibTdx.h"
+
+// Size of TDVMCALL Access, including IO and MMIO
+#define TDVMCALL_ACCESS_SIZE_1 1
+#define TDVMCALL_ACCESS_SIZE_2 2
+#define TDVMCALL_ACCESS_SIZE_4 4
+#define TDVMCALL_ACCESS_SIZE_8 8
+
+// Direction of TDVMCALL Access, including IO and MMIO
+#define TDVMCALL_ACCESS_READ 0
+#define TDVMCALL_ACCESS_WRITE 1
+
+BOOLEAN mTdxEnabled = FALSE;
+BOOLEAN mTdxProbed = FALSE;
+
+/**
+ Check if it is Tdx guest.
+
+ @return TRUE It is Tdx guest
+ @return FALSE It is not Tdx guest
+
+**/
+BOOLEAN
+EFIAPI
+IsTdxGuest (
+ VOID
+ )
+{
+ if (mTdxProbed) {
+ return mTdxEnabled;
+ }
+
+ mTdxEnabled = TdIsEnabled ();
+ mTdxProbed = TRUE;
+
+ return mTdxEnabled;
+}
+
+/**
+ Reads an 8-bit I/O port.
+
+ TDVMCALL_IO is invoked to read I/O port.
+
+ @param Port The I/O port to read.
+
+ @return The value read.
+
+**/
+UINT8
+EFIAPI
+TdIoRead8 (
+ IN UINTN Port
+ )
+{
+ UINT64 Status;
+ UINT64 Val;
+
+ Status = TdVmCall (TDVMCALL_IO, TDVMCALL_ACCESS_SIZE_1, TDVMCALL_ACCESS_READ, Port, 0, &Val);
+ if (Status != 0) {
+ TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0);
+ }
+
+ return (UINT8)Val;
+}
+
+/**
+ Reads a 16-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to read.
+
+ @return The value read.
+
+**/
+UINT16
+EFIAPI
+TdIoRead16 (
+ IN UINTN Port
+ )
+{
+ UINT64 Status;
+ UINT64 Val;
+
+ ASSERT ((Port & 1) == 0);
+
+ Status = TdVmCall (TDVMCALL_IO, TDVMCALL_ACCESS_SIZE_2, TDVMCALL_ACCESS_READ, Port, 0, &Val);
+ if (Status != 0) {
+ TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0);
+ }
+
+ return (UINT16)Val;
+}
+
+/**
+ Reads a 32-bit I/O port.
+
+ TDVMCALL_IO is invoked to read I/O port.
+
+ @param Port The I/O port to read.
+
+ @return The value read.
+
+**/
+UINT32
+EFIAPI
+TdIoRead32 (
+ IN UINTN Port
+ )
+{
+ UINT64 Status;
+ UINT64 Val;
+
+ ASSERT ((Port & 3) == 0);
+
+ Status = TdVmCall (TDVMCALL_IO, TDVMCALL_ACCESS_SIZE_4, TDVMCALL_ACCESS_READ, Port, 0, &Val);
+ if (Status != 0) {
+ TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0);
+ }
+
+ return (UINT32)Val;
+}
+
+/**
+ Writes an 8-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to write.
+ @param Value The value to write to the I/O port.
+
+ @return The value written the I/O port.
+
+**/
+UINT8
+EFIAPI
+TdIoWrite8 (
+ IN UINTN Port,
+ IN UINT8 Value
+ )
+{
+ UINT64 Status;
+ UINT64 Val;
+
+ Val = Value;
+ Status = TdVmCall (TDVMCALL_IO, TDVMCALL_ACCESS_SIZE_1, TDVMCALL_ACCESS_WRITE, Port, Val, 0);
+ if (Status != 0) {
+ TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0);
+ }
+
+ return Value;
+}
+
+/**
+ Writes a 16-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to write.
+ @param Value The value to write to the I/O port.
+
+ @return The value written the I/O port.
+
+**/
+UINT16
+EFIAPI
+TdIoWrite16 (
+ IN UINTN Port,
+ IN UINT16 Value
+ )
+{
+ UINT64 Status;
+ UINT64 Val;
+
+ ASSERT ((Port & 1) == 0);
+ Val = Value;
+ Status = TdVmCall (TDVMCALL_IO, TDVMCALL_ACCESS_SIZE_2, TDVMCALL_ACCESS_WRITE, Port, Val, 0);
+ if (Status != 0) {
+ TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0);
+ }
+
+ return Value;
+}
+
+/**
+ Writes a 32-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to write.
+ @param Value The value to write to the I/O port.
+
+ @return The value written the I/O port.
+
+**/
+UINT32
+EFIAPI
+TdIoWrite32 (
+ IN UINTN Port,
+ IN UINT32 Value
+ )
+{
+ UINT64 Status;
+ UINT64 Val;
+
+ ASSERT ((Port & 3) == 0);
+ Val = Value;
+ Status = TdVmCall (TDVMCALL_IO, TDVMCALL_ACCESS_SIZE_4, TDVMCALL_ACCESS_WRITE, Port, Val, 0);
+ if (Status != 0) {
+ TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0);
+ }
+
+ return Value;
+}
+
+/**
+ Reads an 8-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT8
+EFIAPI
+TdMmioRead8 (
+ IN UINTN Address
+ )
+{
+ UINT64 Value;
+ UINT64 Status;
+
+ Status = TdVmCall (TDVMCALL_MMIO, TDVMCALL_ACCESS_SIZE_1, TDVMCALL_ACCESS_READ, Address | TdSharedPageMask (), 0, &Value);
+ if (Status != 0) {
+ Value = *(volatile UINT64 *)Address;
+ }
+
+ return (UINT8)Value;
+}
+
+/**
+ Writes an 8-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read write registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+ @return Value.
+
+**/
+UINT8
+EFIAPI
+TdMmioWrite8 (
+ IN UINTN Address,
+ IN UINT8 Value
+ )
+{
+ UINT64 Val;
+ UINT64 Status;
+
+ Val = Value;
+ Status = TdVmCall (TDVMCALL_MMIO, TDVMCALL_ACCESS_SIZE_1, TDVMCALL_ACCESS_WRITE, Address | TdSharedPageMask (), Val, 0);
+ if (Status != 0) {
+ *(volatile UINT8 *)Address = Value;
+ }
+
+ return Value;
+}
+
+/**
+ Reads a 16-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT16
+EFIAPI
+TdMmioRead16 (
+ IN UINTN Address
+ )
+{
+ UINT64 Value;
+ UINT64 Status;
+
+ Status = TdVmCall (TDVMCALL_MMIO, TDVMCALL_ACCESS_SIZE_2, TDVMCALL_ACCESS_READ, Address | TdSharedPageMask (), 0, &Value);
+ if (Status != 0) {
+ Value = *(volatile UINT64 *)Address;
+ }
+
+ return (UINT16)Value;
+}
+
+/**
+ Writes a 16-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to write MMIO registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+ @return Value.
+
+**/
+UINT16
+EFIAPI
+TdMmioWrite16 (
+ IN UINTN Address,
+ IN UINT16 Value
+ )
+{
+ UINT64 Val;
+ UINT64 Status;
+
+ ASSERT ((Address & 1) == 0);
+
+ Val = Value;
+ Status = TdVmCall (TDVMCALL_MMIO, TDVMCALL_ACCESS_SIZE_2, TDVMCALL_ACCESS_WRITE, Address | TdSharedPageMask (), Val, 0);
+ if (Status != 0) {
+ *(volatile UINT16 *)Address = Value;
+ }
+
+ return Value;
+}
+
+/**
+ Reads a 32-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT32
+EFIAPI
+TdMmioRead32 (
+ IN UINTN Address
+ )
+{
+ UINT64 Value;
+ UINT64 Status;
+
+ Status = TdVmCall (TDVMCALL_MMIO, TDVMCALL_ACCESS_SIZE_4, TDVMCALL_ACCESS_READ, Address | TdSharedPageMask (), 0, &Value);
+ if (Status != 0) {
+ Value = *(volatile UINT64 *)Address;
+ }
+
+ return (UINT32)Value;
+}
+
+/**
+ Writes a 32-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to write MMIO registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+ @return Value.
+
+**/
+UINT32
+EFIAPI
+TdMmioWrite32 (
+ IN UINTN Address,
+ IN UINT32 Value
+ )
+{
+ UINT64 Val;
+ UINT64 Status;
+
+ ASSERT ((Address & 3) == 0);
+
+ Val = Value;
+ Status = TdVmCall (TDVMCALL_MMIO, TDVMCALL_ACCESS_SIZE_4, TDVMCALL_ACCESS_WRITE, Address | TdSharedPageMask (), Val, 0);
+ if (Status != 0) {
+ *(volatile UINT32 *)Address = Value;
+ }
+
+ return Value;
+}
+
+/**
+ Reads a 64-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT64
+EFIAPI
+TdMmioRead64 (
+ IN UINTN Address
+ )
+{
+ UINT64 Value;
+ UINT64 Status;
+
+ Status = TdVmCall (TDVMCALL_MMIO, TDVMCALL_ACCESS_SIZE_8, TDVMCALL_ACCESS_READ, Address | TdSharedPageMask (), 0, &Value);
+ if (Status != 0) {
+ Value = *(volatile UINT64 *)Address;
+ }
+
+ return Value;
+}
+
+/**
+ Writes a 64-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to write MMIO registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+**/
+UINT64
+EFIAPI
+TdMmioWrite64 (
+ IN UINTN Address,
+ IN UINT64 Value
+ )
+{
+ UINT64 Status;
+ UINT64 Val;
+
+ ASSERT ((Address & 7) == 0);
+
+ Val = Value;
+ Status = TdVmCall (TDVMCALL_MMIO, TDVMCALL_ACCESS_SIZE_8, TDVMCALL_ACCESS_WRITE, Address | TdSharedPageMask (), Val, 0);
+ if (Status != 0) {
+ *(volatile UINT64 *)Address = Value;
+ }
+
+ return Value;
+}
+
+/**
+ Reads an 8-bit I/O port fifo into a block of memory.
+
+ Reads the 8-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoRead8 is invoked to read the I/O port fifo.
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+TdIoReadFifo8 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ )
+{
+ UINT8 *Buf8;
+ UINTN Index;
+
+ Buf8 = (UINT8 *)Buffer;
+ for (Index = 0; Index < Count; Index++) {
+ Buf8[Index] = TdIoRead8 (Port);
+ }
+}
+
+/**
+ Writes a block of memory into an 8-bit I/O port fifo.
+
+ Writes the 8-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoWrite8 is invoked to write data to the I/O port.
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+TdIoWriteFifo8 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ UINT8 *Buf8;
+ UINTN Index;
+
+ Buf8 = (UINT8 *)Buffer;
+ for (Index = 0; Index < Count; Index++) {
+ TdIoWrite8 (Port, Buf8[Index]);
+ }
+}
+
+/**
+ Reads a 16-bit I/O port fifo into a block of memory.
+
+ Reads the 16-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 16-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoRead16 is invoked to read data from the I/O port.
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+TdIoReadFifo16 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ )
+{
+ UINT16 *Buf16;
+ UINTN Index;
+
+ Buf16 = (UINT16 *)Buffer;
+ for (Index = 0; Index < Count; Index++) {
+ Buf16[Index] = TdIoRead16 (Port);
+ }
+}
+
+/**
+ Writes a block of memory into a 16-bit I/O port fifo.
+
+ Writes the 16-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 16-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoWrite16 is invoked to write data to the I/O port.
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+TdIoWriteFifo16 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ UINT16 *Buf16;
+ UINTN Index;
+
+ Buf16 = (UINT16 *)Buffer;
+ for (Index = 0; Index < Count; Index++) {
+ TdIoWrite16 (Port, Buf16[Index]);
+ }
+}
+
+/**
+ Reads a 32-bit I/O port fifo into a block of memory.
+
+ Reads the 32-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 32-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoRead32 is invoked to read data from the I/O port.
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+TdIoReadFifo32 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ )
+{
+ UINT32 *Buf32;
+ UINTN Index;
+
+ Buf32 = (UINT32 *)Buffer;
+ for (Index = 0; Index < Count; Index++) {
+ Buf32[Index] = TdIoRead32 (Port);
+ }
+}
+
+/**
+ Writes a block of memory into a 32-bit I/O port fifo.
+
+ Writes the 32-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 32-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoWrite32 is invoked to write data to the I/O port.
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+TdIoWriteFifo32 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ UINT32 *Buf32;
+ UINTN Index;
+
+ Buf32 = (UINT32 *)Buffer;
+ for (Index = 0; Index < Count; Index++) {
+ TdIoWrite32 (Port, Buf32[Index]);
+ }
+}
diff --git a/MdePkg/Library/BaseIoLibIntrinsic/IoLibInternalTdxNull.c b/MdePkg/Library/BaseIoLibIntrinsic/IoLibInternalTdxNull.c
new file mode 100644
index 000000000000..7262704d6b14
--- /dev/null
+++ b/MdePkg/Library/BaseIoLibIntrinsic/IoLibInternalTdxNull.c
@@ -0,0 +1,497 @@
+/** @file
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseLib.h>
+#include "BaseIoLibIntrinsicInternal.h"
+#include "IoLibTdx.h"
+
+/**
+ Check if it is Tdx guest.
+
+ @return TRUE It is Tdx guest
+ @return FALSE It is not Tdx guest
+
+**/
+BOOLEAN
+EFIAPI
+IsTdxGuest (
+ VOID
+ )
+{
+ return FALSE;
+}
+
+/**
+ Reads an 8-bit I/O port.
+
+ TDVMCALL_IO is invoked to read I/O port.
+
+ @param Port The I/O port to read.
+
+ @return The value read.
+
+**/
+UINT8
+EFIAPI
+TdIoRead8 (
+ IN UINTN Port
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Reads a 16-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to read.
+
+ @return The value read.
+
+**/
+UINT16
+EFIAPI
+TdIoRead16 (
+ IN UINTN Port
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Reads a 32-bit I/O port.
+
+ TDVMCALL_IO is invoked to read I/O port.
+
+ @param Port The I/O port to read.
+
+ @return The value read.
+
+**/
+UINT32
+EFIAPI
+TdIoRead32 (
+ IN UINTN Port
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Writes an 8-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to write.
+ @param Value The value to write to the I/O port.
+
+ @return The value written the I/O port.
+
+**/
+UINT8
+EFIAPI
+TdIoWrite8 (
+ IN UINTN Port,
+ IN UINT8 Value
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Writes a 16-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to write.
+ @param Value The value to write to the I/O port.
+
+ @return The value written the I/O port.
+
+**/
+UINT16
+EFIAPI
+TdIoWrite16 (
+ IN UINTN Port,
+ IN UINT16 Value
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Writes a 32-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to write.
+ @param Value The value to write to the I/O port.
+
+ @return The value written the I/O port.
+
+**/
+UINT32
+EFIAPI
+TdIoWrite32 (
+ IN UINTN Port,
+ IN UINT32 Value
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Reads an 8-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT8
+EFIAPI
+TdMmioRead8 (
+ IN UINTN Address
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Writes an 8-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read write registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+ @return Value.
+
+**/
+UINT8
+EFIAPI
+TdMmioWrite8 (
+ IN UINTN Address,
+ IN UINT8 Val
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Reads a 16-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT16
+EFIAPI
+TdMmioRead16 (
+ IN UINTN Address
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Writes a 16-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to write MMIO registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+ @return Value.
+
+**/
+UINT16
+EFIAPI
+TdMmioWrite16 (
+ IN UINTN Address,
+ IN UINT16 Val
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Reads a 32-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT32
+EFIAPI
+TdMmioRead32 (
+ IN UINTN Address
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Writes a 32-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to write MMIO registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+ @return Value.
+
+**/
+UINT32
+EFIAPI
+TdMmioWrite32 (
+ IN UINTN Address,
+ IN UINT32 Val
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Reads a 64-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT64
+EFIAPI
+TdMmioRead64 (
+ IN UINTN Address
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Writes a 64-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to write MMIO registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+**/
+UINT64
+EFIAPI
+TdMmioWrite64 (
+ IN UINTN Address,
+ IN UINT64 Value
+ )
+{
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Reads an 8-bit I/O port fifo into a block of memory.
+
+ Reads the 8-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoRead8 is invoked to read the I/O port fifo.
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+TdIoReadFifo8 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ )
+{
+ ASSERT (FALSE);
+}
+
+/**
+ Writes a block of memory into an 8-bit I/O port fifo.
+
+ Writes the 8-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoWrite8 is invoked to write data to the I/O port.
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+TdIoWriteFifo8 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ ASSERT (FALSE);
+}
+
+/**
+ Reads a 16-bit I/O port fifo into a block of memory.
+
+ Reads the 16-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 16-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoRead16 is invoked to read data from the I/O port.
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+TdIoReadFifo16 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ )
+{
+ ASSERT (FALSE);
+}
+
+/**
+ Writes a block of memory into a 16-bit I/O port fifo.
+
+ Writes the 16-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 16-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoWrite16 is invoked to write data to the I/O port.
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+TdIoWriteFifo16 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ ASSERT (FALSE);
+}
+
+/**
+ Reads a 32-bit I/O port fifo into a block of memory.
+
+ Reads the 32-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 32-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoRead32 is invoked to read data from the I/O port.
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+TdIoReadFifo32 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ )
+{
+ ASSERT (FALSE);
+}
+
+/**
+ Writes a block of memory into a 32-bit I/O port fifo.
+
+ Writes the 32-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 32-bit I/O port operations are not supported, then ASSERT().
+
+ In TDX a serial of TdIoWrite32 is invoked to write data to the I/O port.
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+TdIoWriteFifo32 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ )
+{
+ ASSERT (FALSE);
+}
diff --git a/MdePkg/Library/BaseIoLibIntrinsic/IoLibTdx.h b/MdePkg/Library/BaseIoLibIntrinsic/IoLibTdx.h
new file mode 100644
index 000000000000..ab2fa771f6c8
--- /dev/null
+++ b/MdePkg/Library/BaseIoLibIntrinsic/IoLibTdx.h
@@ -0,0 +1,410 @@
+/** @file
+ Header file for Tdx IO library.
+
+ Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#ifndef IOLIB_TDX_H_
+#define IOLIB_TDX_H_
+
+/**
+ Check if it is Tdx guest.
+
+ @return TRUE It is Tdx guest
+ @return FALSE It is not Tdx guest
+
+**/
+BOOLEAN
+EFIAPI
+IsTdxGuest (
+ VOID
+ );
+
+/**
+ Reads an 8-bit I/O port.
+
+ TDVMCALL_IO is invoked to read I/O port.
+
+ @param Port The I/O port to read.
+
+ @return The value read.
+
+**/
+UINT8
+EFIAPI
+TdIoRead8 (
+ IN UINTN Port
+ );
+
+/**
+ Reads a 16-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to read.
+
+ @return The value read.
+
+**/
+UINT16
+EFIAPI
+TdIoRead16 (
+ IN UINTN Port
+ );
+
+/**
+ Reads a 32-bit I/O port.
+
+ TDVMCALL_IO is invoked to read I/O port.
+
+ @param Port The I/O port to read.
+
+ @return The value read.
+
+**/
+UINT32
+EFIAPI
+TdIoRead32 (
+ IN UINTN Port
+ );
+
+/**
+ Writes an 8-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to write.
+ @param Value The value to write to the I/O port.
+
+ @return The value written the I/O port.
+
+**/
+UINT8
+EFIAPI
+TdIoWrite8 (
+ IN UINTN Port,
+ IN UINT8 Value
+ );
+
+/**
+ Writes a 16-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to write.
+ @param Value The value to write to the I/O port.
+
+ @return The value written the I/O port.
+
+**/
+UINT16
+EFIAPI
+TdIoWrite16 (
+ IN UINTN Port,
+ IN UINT16 Value
+ );
+
+/**
+ Writes a 32-bit I/O port.
+
+ TDVMCALL_IO is invoked to write I/O port.
+
+ @param Port The I/O port to write.
+ @param Value The value to write to the I/O port.
+
+ @return The value written the I/O port.
+
+**/
+UINT32
+EFIAPI
+TdIoWrite32 (
+ IN UINTN Port,
+ IN UINT32 Value
+ );
+
+/**
+ Reads an 8-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT8
+EFIAPI
+TdMmioRead8 (
+ IN UINTN Address
+ );
+
+/**
+ Writes an 8-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read write registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+ @return Value.
+
+**/
+UINT8
+EFIAPI
+TdMmioWrite8 (
+ IN UINTN Address,
+ IN UINT8 Val
+ );
+
+/**
+ Reads a 16-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT16
+EFIAPI
+TdMmioRead16 (
+ IN UINTN Address
+ );
+
+/**
+ Writes a 16-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to write MMIO registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+ @return Value.
+
+**/
+UINT16
+EFIAPI
+TdMmioWrite16 (
+ IN UINTN Address,
+ IN UINT16 Val
+ );
+
+/**
+ Reads a 32-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT32
+EFIAPI
+TdMmioRead32 (
+ IN UINTN Address
+ );
+
+/**
+ Writes a 32-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to write MMIO registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+ @return Value.
+
+**/
+UINT32
+EFIAPI
+TdMmioWrite32 (
+ IN UINTN Address,
+ IN UINT32 Val
+ );
+
+/**
+ Reads a 64-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to read MMIO registers.
+
+ @param Address The MMIO register to read.
+
+ @return The value read.
+
+**/
+UINT64
+EFIAPI
+TdMmioRead64 (
+ IN UINTN Address
+ );
+
+/**
+ Writes a 64-bit MMIO register.
+
+ TDVMCALL_MMIO is invoked to write MMIO registers.
+
+ @param Address The MMIO register to write.
+ @param Value The value to write to the MMIO register.
+
+**/
+UINT64
+EFIAPI
+TdMmioWrite64 (
+ IN UINTN Address,
+ IN UINT64 Value
+ );
+
+/**
+ Reads an 8-bit I/O port fifo into a block of memory in Tdx.
+
+ Reads the 8-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+TdIoReadFifo8 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ );
+
+/**
+ Writes a block of memory into an 8-bit I/O port fifo in Tdx.
+
+ Writes the 8-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 8-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+TdIoWriteFifo8 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ );
+
+/**
+ Reads a 16-bit I/O port fifo into a block of memory in Tdx.
+
+ Reads the 16-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 16-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+TdIoReadFifo16 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ );
+
+/**
+ Writes a block of memory into a 16-bit I/O port fifo in Tdx.
+
+ Writes the 16-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 16-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+TdIoWriteFifo16 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ );
+
+/**
+ Reads a 32-bit I/O port fifo into a block of memory in Tdx.
+
+ Reads the 32-bit I/O fifo port specified by Port.
+ The port is read Count times, and the read data is
+ stored in the provided Buffer.
+
+ This function must guarantee that all I/O read and write operations are
+ serialized.
+
+ If 32-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to read.
+ @param Count The number of times to read I/O port.
+ @param Buffer The buffer to store the read data into.
+
+**/
+VOID
+EFIAPI
+TdIoReadFifo32 (
+ IN UINTN Port,
+ IN UINTN Count,
+ OUT VOID *Buffer
+ );
+
+/**
+ Writes a block of memory into a 32-bit I/O port fifo in Tdx.
+
+ Writes the 32-bit I/O fifo port specified by Port.
+ The port is written Count times, and the write data is
+ retrieved from the provided Buffer.
+
+ This function must guarantee that all I/O write and write operations are
+ serialized.
+
+ If 32-bit I/O port operations are not supported, then ASSERT().
+
+ @param Port The I/O port to write.
+ @param Count The number of times to write I/O port.
+ @param Buffer The buffer to retrieve the write data from.
+
+**/
+VOID
+EFIAPI
+TdIoWriteFifo32 (
+ IN UINTN Port,
+ IN UINTN Count,
+ IN VOID *Buffer
+ );
+
+#endif
--
2.29.2.windows.2


[PATCH V12 07/47] UefiCpuPkg/CpuExceptionHandler: Add base support for the #VE exception #ve

Min Xu
 

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

Add base support to handle #VE exceptions. Update the common exception
handlers to invoke the VmTdExitHandleVe () function of the VmgExitLib
library when a #VE is encountered. A non-zero return code will propagate
to the targeted exception handler.

Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Eric Dong <eric.dong@...>
Cc: Ray Ni <ray.ni@...>
Cc: Rahul Kumar <rahul1.kumar@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Reviewed-by: Ray Ni <ray.ni@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
.../PeiDxeSmmCpuException.c | 53 ++++++++++++-----
.../SecPeiCpuException.c | 57 +++++++++++++------
2 files changed, 79 insertions(+), 31 deletions(-)

diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c
index 762ea2460f91..f47a80dcab8f 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiDxeSmmCpuException.c
@@ -24,25 +24,48 @@ CommonExceptionHandlerWorker (
IN EXCEPTION_HANDLER_DATA *ExceptionHandlerData
)
{
+ EFI_STATUS Status;
EXCEPTION_HANDLER_CONTEXT *ExceptionHandlerContext;
RESERVED_VECTORS_DATA *ReservedVectors;
EFI_CPU_INTERRUPT_HANDLER *ExternalInterruptHandler;

- if (ExceptionType == VC_EXCEPTION) {
- EFI_STATUS Status;
- //
- // #VC needs to be handled immediately upon enabling exception handling
- // and therefore can't use the RegisterCpuInterruptHandler() interface.
- //
- // Handle the #VC:
- // On EFI_SUCCESS - Exception has been handled, return
- // On other - ExceptionType contains (possibly new) exception
- // value
- //
- Status = VmgExitHandleVc (&ExceptionType, SystemContext);
- if (!EFI_ERROR (Status)) {
- return;
- }
+ switch (ExceptionType) {
+ case VC_EXCEPTION:
+ //
+ // #VC needs to be handled immediately upon enabling exception handling
+ // and therefore can't use the RegisterCpuInterruptHandler() interface.
+ //
+ // Handle the #VC:
+ // On EFI_SUCCESS - Exception has been handled, return
+ // On other - ExceptionType contains (possibly new) exception
+ // value
+ //
+ Status = VmgExitHandleVc (&ExceptionType, SystemContext);
+ if (!EFI_ERROR (Status)) {
+ return;
+ }
+
+ break;
+
+ case VE_EXCEPTION:
+ //
+ // #VE needs to be handled immediately upon enabling exception handling
+ // and therefore can't use the RegisterCpuInterruptHandler() interface.
+ //
+ // Handle the #VE:
+ // On EFI_SUCCESS - Exception has been handled, return
+ // On other - ExceptionType contains (possibly new) exception
+ // value
+ //
+ Status = VmTdExitHandleVe (&ExceptionType, SystemContext);
+ if (!EFI_ERROR (Status)) {
+ return;
+ }
+
+ break;
+
+ default:
+ break;
}

ExceptionHandlerContext = (EXCEPTION_HANDLER_CONTEXT *)(UINTN)(SystemContext.SystemContextIa32);
diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c
index c614d5b0b6f1..6e5216380da8 100644
--- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c
+++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuException.c
@@ -25,22 +25,47 @@ CommonExceptionHandler (
IN EFI_SYSTEM_CONTEXT SystemContext
)
{
- if (ExceptionType == VC_EXCEPTION) {
- EFI_STATUS Status;
- //
- // #VC needs to be handled immediately upon enabling exception handling
- // and therefore can't use the RegisterCpuInterruptHandler() interface
- // (which isn't supported under Sec and Pei anyway).
- //
- // Handle the #VC:
- // On EFI_SUCCESS - Exception has been handled, return
- // On other - ExceptionType contains (possibly new) exception
- // value
- //
- Status = VmgExitHandleVc (&ExceptionType, SystemContext);
- if (!EFI_ERROR (Status)) {
- return;
- }
+ EFI_STATUS Status;
+
+ switch (ExceptionType) {
+ case VC_EXCEPTION:
+ //
+ // #VC needs to be handled immediately upon enabling exception handling
+ // and therefore can't use the RegisterCpuInterruptHandler() interface
+ // (which isn't supported under Sec and Pei anyway).
+ //
+ // Handle the #VC:
+ // On EFI_SUCCESS - Exception has been handled, return
+ // On other - ExceptionType contains (possibly new) exception
+ // value
+ //
+ Status = VmgExitHandleVc (&ExceptionType, SystemContext);
+ if (!EFI_ERROR (Status)) {
+ return;
+ }
+
+ break;
+
+ case VE_EXCEPTION:
+ //
+ // #VE needs to be handled immediately upon enabling exception handling
+ // and therefore can't use the RegisterCpuInterruptHandler() interface
+ // (which isn't supported under Sec and Pei anyway).
+ //
+ // Handle the #VE:
+ // On EFI_SUCCESS - Exception has been handled, return
+ // On other - ExceptionType contains (possibly new) exception
+ // value
+ //
+ Status = VmTdExitHandleVe (&ExceptionType, SystemContext);
+ if (!EFI_ERROR (Status)) {
+ return;
+ }
+
+ break;
+
+ default:
+ break;
}

//
--
2.29.2.windows.2


[PATCH V12 06/47] OvmfPkg: Extend VmgExitLib to handle #VE exception #ve

Min Xu
 

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

The base VmgExitLib library provides a default limited interface to
handle #VE exception. To provide full support, the OVMF version of
VmgExitLib is extended to provide full support of #VE handler.

Cc: Ard Biesheuvel <ardb+tianocore@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Jordan Justen <jordan.l.justen@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf | 3 +-
OvmfPkg/Library/VmgExitLib/VmTdExitHandler.h | 32 +
.../Library/VmgExitLib/VmTdExitVeHandler.c | 559 ++++++++++++++++++
OvmfPkg/Library/VmgExitLib/VmgExitLib.inf | 2 +
.../Library/VmgExitLib/X64/TdVmcallCpuid.nasm | 146 +++++
5 files changed, 741 insertions(+), 1 deletion(-)
create mode 100644 OvmfPkg/Library/VmgExitLib/VmTdExitHandler.h
create mode 100644 OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c
create mode 100644 OvmfPkg/Library/VmgExitLib/X64/TdVmcallCpuid.nasm

diff --git a/OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf b/OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf
index 78207fa0f9c9..f9bd4974f6dc 100644
--- a/OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf
+++ b/OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf
@@ -25,6 +25,8 @@
VmgExitVcHandler.c
VmgExitVcHandler.h
SecVmgExitVcHandler.c
+ VmTdExitVeHandler.c
+ X64/TdVmcallCpuid.nasm

[Packages]
MdePkg/MdePkg.dec
@@ -44,4 +46,3 @@
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecGhcbBackupSize
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfCpuidBase
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfCpuidSize
-
diff --git a/OvmfPkg/Library/VmgExitLib/VmTdExitHandler.h b/OvmfPkg/Library/VmgExitLib/VmTdExitHandler.h
new file mode 100644
index 000000000000..7eacd0872f46
--- /dev/null
+++ b/OvmfPkg/Library/VmgExitLib/VmTdExitHandler.h
@@ -0,0 +1,32 @@
+/** @file
+
+ Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef VMTD_EXIT_HANDLER_H_
+#define VMTD_EXIT_HANDLER_H_
+
+#include <Base.h>
+#include <Uefi.h>
+
+/**
+ This function enable the TD guest to request the VMM to emulate CPUID
+ operation, especially for non-architectural, CPUID leaves.
+
+ @param[in] Eax Main leaf of the CPUID
+ @param[in] Ecx Sub-leaf of the CPUID
+ @param[out] Results Returned result of CPUID operation
+
+ @return EFI_SUCCESS
+**/
+EFI_STATUS
+EFIAPI
+TdVmCallCpuid (
+ IN UINT64 Eax,
+ IN UINT64 Ecx,
+ OUT VOID *Results
+ );
+
+#endif
diff --git a/OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c b/OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c
new file mode 100644
index 000000000000..b73e877c093b
--- /dev/null
+++ b/OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c
@@ -0,0 +1,559 @@
+/** @file
+
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include "VmTdExitHandler.h"
+#include <Library/VmgExitLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <IndustryStandard/Tdx.h>
+#include <IndustryStandard/InstructionParsing.h>
+
+typedef union {
+ struct {
+ UINT32 Eax;
+ UINT32 Edx;
+ } Regs;
+ UINT64 Val;
+} MSR_DATA;
+
+typedef union {
+ UINT8 Val;
+ struct {
+ UINT8 B : 1;
+ UINT8 X : 1;
+ UINT8 R : 1;
+ UINT8 W : 1;
+ } Bits;
+} REX;
+
+typedef union {
+ UINT8 Val;
+ struct {
+ UINT8 Rm : 3;
+ UINT8 Reg : 3;
+ UINT8 Mod : 2;
+ } Bits;
+} MODRM;
+
+typedef struct {
+ UINT64 Regs[4];
+} CPUID_DATA;
+
+/**
+ Handle an CPUID event.
+
+ Use the TDVMCALL instruction to handle cpuid #ve
+
+ @param[in, out] Regs x64 processor context
+ @param[in] Veinfo VE Info
+
+ @retval 0 Event handled successfully
+ @return New exception value to propagate
+**/
+STATIC
+UINT64
+EFIAPI
+CpuIdExit (
+ IN EFI_SYSTEM_CONTEXT_X64 *Regs,
+ IN TDCALL_VEINFO_RETURN_DATA *Veinfo
+ )
+{
+ CPUID_DATA CpuIdData;
+ UINT64 Status;
+
+ Status = TdVmCallCpuid (Regs->Rax, Regs->Rcx, &CpuIdData);
+
+ if (Status == 0) {
+ Regs->Rax = CpuIdData.Regs[0];
+ Regs->Rbx = CpuIdData.Regs[1];
+ Regs->Rcx = CpuIdData.Regs[2];
+ Regs->Rdx = CpuIdData.Regs[3];
+ }
+
+ return Status;
+}
+
+/**
+ Handle an IO event.
+
+ Use the TDVMCALL instruction to handle either an IO read or an IO write.
+
+ @param[in, out] Regs x64 processor context
+ @param[in] Veinfo VE Info
+
+ @retval 0 Event handled successfully
+ @return New exception value to propagate
+**/
+STATIC
+UINT64
+EFIAPI
+IoExit (
+ IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs,
+ IN TDCALL_VEINFO_RETURN_DATA *Veinfo
+ )
+{
+ BOOLEAN Write;
+ UINTN Size;
+ UINTN Port;
+ UINT64 Val;
+ UINT64 RepCnt;
+ UINT64 Status;
+
+ Val = 0;
+ Write = Veinfo->ExitQualification.Io.Direction ? FALSE : TRUE;
+ Size = Veinfo->ExitQualification.Io.Size + 1;
+ Port = Veinfo->ExitQualification.Io.Port;
+
+ if (Veinfo->ExitQualification.Io.String) {
+ //
+ // If REP is set, get rep-cnt from Rcx
+ //
+ RepCnt = Veinfo->ExitQualification.Io.Rep ? Regs->Rcx : 1;
+
+ while (RepCnt) {
+ Val = 0;
+ if (Write == TRUE) {
+ CopyMem (&Val, (VOID *)Regs->Rsi, Size);
+ Regs->Rsi += Size;
+ }
+
+ Status = TdVmCall (EXIT_REASON_IO_INSTRUCTION, Size, Write, Port, Val, (Write ? NULL : &Val));
+ if (Status != 0) {
+ break;
+ }
+
+ if (Write == FALSE) {
+ CopyMem ((VOID *)Regs->Rdi, &Val, Size);
+ Regs->Rdi += Size;
+ }
+
+ if (Veinfo->ExitQualification.Io.Rep) {
+ Regs->Rcx -= 1;
+ }
+
+ RepCnt -= 1;
+ }
+ } else {
+ if (Write == TRUE) {
+ CopyMem (&Val, (VOID *)&Regs->Rax, Size);
+ }
+
+ Status = TdVmCall (EXIT_REASON_IO_INSTRUCTION, Size, Write, Port, Val, (Write ? NULL : &Val));
+ if ((Status == 0) && (Write == FALSE)) {
+ CopyMem ((VOID *)&Regs->Rax, &Val, Size);
+ }
+ }
+
+ return Status;
+}
+
+/**
+ Handle an READ MSR event.
+
+ Use the TDVMCALL instruction to handle msr read
+
+ @param[in, out] Regs x64 processor context
+ @param[in] Veinfo VE Info
+
+ @retval 0 Event handled successfully
+ @return New exception value to propagate
+**/
+STATIC
+UINT64
+ReadMsrExit (
+ IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs,
+ IN TDCALL_VEINFO_RETURN_DATA *Veinfo
+ )
+{
+ MSR_DATA Data;
+ UINT64 Status;
+
+ Status = TdVmCall (EXIT_REASON_MSR_READ, Regs->Rcx, 0, 0, 0, &Data);
+ if (Status == 0) {
+ Regs->Rax = Data.Regs.Eax;
+ Regs->Rdx = Data.Regs.Edx;
+ }
+
+ return Status;
+}
+
+/**
+ Handle an WRITE MSR event.
+
+ Use the TDVMCALL instruction to handle msr write
+
+ @param[in, out] Regs x64 processor context
+ @param[in] Veinfo VE Info
+
+ @retval 0 Event handled successfully
+ @return New exception value to propagate
+**/
+STATIC
+UINT64
+WriteMsrExit (
+ IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs,
+ IN TDCALL_VEINFO_RETURN_DATA *Veinfo
+ )
+{
+ UINT64 Status;
+ MSR_DATA Data;
+
+ Data.Regs.Eax = (UINT32)Regs->Rax;
+ Data.Regs.Edx = (UINT32)Regs->Rdx;
+
+ Status = TdVmCall (EXIT_REASON_MSR_WRITE, Regs->Rcx, Data.Val, 0, 0, NULL);
+
+ return Status;
+}
+
+STATIC
+VOID
+EFIAPI
+TdxDecodeInstruction (
+ IN UINT8 *Rip
+ )
+{
+ UINTN i;
+
+ DEBUG ((DEBUG_INFO, "TDX: #TD[EPT] instruction (%p):", Rip));
+ for (i = 0; i < 15; i++) {
+ DEBUG ((DEBUG_INFO, "%02x:", Rip[i]));
+ }
+
+ DEBUG ((DEBUG_INFO, "\n"));
+}
+
+#define TDX_DECODER_BUG_ON(x) \
+ if ((x)) { \
+ TdxDecodeInstruction(Rip); \
+ TdVmCall(TDVMCALL_HALT, 0, 0, 0, 0, 0); \
+ }
+
+STATIC
+UINT64 *
+EFIAPI
+GetRegFromContext (
+ IN EFI_SYSTEM_CONTEXT_X64 *Regs,
+ IN UINTN RegIndex
+ )
+{
+ switch (RegIndex) {
+ case 0: return &Regs->Rax;
+ break;
+ case 1: return &Regs->Rcx;
+ break;
+ case 2: return &Regs->Rdx;
+ break;
+ case 3: return &Regs->Rbx;
+ break;
+ case 4: return &Regs->Rsp;
+ break;
+ case 5: return &Regs->Rbp;
+ break;
+ case 6: return &Regs->Rsi;
+ break;
+ case 7: return &Regs->Rdi;
+ break;
+ case 8: return &Regs->R8;
+ break;
+ case 9: return &Regs->R9;
+ break;
+ case 10: return &Regs->R10;
+ break;
+ case 11: return &Regs->R11;
+ break;
+ case 12: return &Regs->R12;
+ break;
+ case 13: return &Regs->R13;
+ break;
+ case 14: return &Regs->R14;
+ break;
+ case 15: return &Regs->R15;
+ break;
+ }
+
+ return NULL;
+}
+
+/**
+ Handle an MMIO event.
+
+ Use the TDVMCALL instruction to handle either an mmio read or an mmio write.
+
+ @param[in, out] Regs x64 processor context
+ @param[in] Veinfo VE Info
+
+ @retval 0 Event handled successfully
+ @return New exception value to propagate
+**/
+STATIC
+INTN
+EFIAPI
+MmioExit (
+ IN OUT EFI_SYSTEM_CONTEXT_X64 *Regs,
+ IN TDCALL_VEINFO_RETURN_DATA *Veinfo
+ )
+{
+ UINT64 Status;
+ UINT32 MmioSize;
+ UINT32 RegSize;
+ UINT8 OpCode;
+ BOOLEAN SeenRex;
+ UINT64 *Reg;
+ UINT8 *Rip;
+ UINT64 Val;
+ UINT32 OpSize;
+ MODRM ModRm;
+ REX Rex;
+
+ Rip = (UINT8 *)Regs->Rip;
+ Val = 0;
+ Rex.Val = 0;
+ SeenRex = FALSE;
+
+ //
+ // Default to 32bit transfer
+ //
+ OpSize = 4;
+
+ do {
+ OpCode = *Rip++;
+ if (OpCode == 0x66) {
+ OpSize = 2;
+ } else if ((OpCode == 0x64) || (OpCode == 0x65) || (OpCode == 0x67)) {
+ continue;
+ } else if ((OpCode >= 0x40) && (OpCode <= 0x4f)) {
+ SeenRex = TRUE;
+ Rex.Val = OpCode;
+ } else {
+ break;
+ }
+ } while (TRUE);
+
+ //
+ // We need to have at least 2 more bytes for this instruction
+ //
+ TDX_DECODER_BUG_ON (((UINT64)Rip - Regs->Rip) > 13);
+
+ OpCode = *Rip++;
+ //
+ // Two-byte opecode, get next byte
+ //
+ if (OpCode == 0x0F) {
+ OpCode = *Rip++;
+ }
+
+ switch (OpCode) {
+ case 0x88:
+ case 0x8A:
+ case 0xB6:
+ MmioSize = 1;
+ break;
+ case 0xB7:
+ MmioSize = 2;
+ break;
+ default:
+ MmioSize = Rex.Bits.W ? 8 : OpSize;
+ break;
+ }
+
+ /* Punt on AH/BH/CH/DH unless it shows up. */
+ ModRm.Val = *Rip++;
+ TDX_DECODER_BUG_ON (MmioSize == 1 && ModRm.Bits.Reg > 4 && !SeenRex && OpCode != 0xB6);
+ Reg = GetRegFromContext (Regs, ModRm.Bits.Reg | ((int)Rex.Bits.R << 3));
+ TDX_DECODER_BUG_ON (!Reg);
+
+ if (ModRm.Bits.Rm == 4) {
+ ++Rip; /* SIB byte */
+ }
+
+ if ((ModRm.Bits.Mod == 2) || ((ModRm.Bits.Mod == 0) && (ModRm.Bits.Rm == 5))) {
+ Rip += 4; /* DISP32 */
+ } else if (ModRm.Bits.Mod == 1) {
+ ++Rip; /* DISP8 */
+ }
+
+ switch (OpCode) {
+ case 0x88:
+ case 0x89:
+ CopyMem ((void *)&Val, Reg, MmioSize);
+ Status = TdVmCall (TDVMCALL_MMIO, MmioSize, 1, Veinfo->GuestPA, Val, 0);
+ break;
+ case 0xC7:
+ CopyMem ((void *)&Val, Rip, OpSize);
+ Status = TdVmCall (TDVMCALL_MMIO, MmioSize, 1, Veinfo->GuestPA, Val, 0);
+ Rip += OpSize;
+ default:
+ //
+ // 32-bit write registers are zero extended to the full register
+ // Hence 'MOVZX r[32/64], r/m16' is
+ // hardcoded to reg size 8, and the straight MOV case has a reg
+ // size of 8 in the 32-bit read case.
+ //
+ switch (OpCode) {
+ case 0xB6:
+ RegSize = Rex.Bits.W ? 8 : OpSize;
+ break;
+ case 0xB7:
+ RegSize = 8;
+ break;
+ default:
+ RegSize = MmioSize == 4 ? 8 : MmioSize;
+ break;
+ }
+
+ Status = TdVmCall (TDVMCALL_MMIO, MmioSize, 0, Veinfo->GuestPA, 0, &Val);
+ if (Status == 0) {
+ ZeroMem (Reg, RegSize);
+ CopyMem (Reg, (void *)&Val, MmioSize);
+ }
+ }
+
+ if (Status == 0) {
+ TDX_DECODER_BUG_ON (((UINT64)Rip - Regs->Rip) > 15);
+
+ //
+ // We change instruction length to reflect true size so handler can
+ // bump rip
+ //
+ Veinfo->ExitInstructionLength = (UINT32)((UINT64)Rip - Regs->Rip);
+ }
+
+ return Status;
+}
+
+/**
+ Handle a #VE exception.
+
+ Performs the necessary processing to handle a #VE exception.
+
+ @param[in, out] ExceptionType Pointer to an EFI_EXCEPTION_TYPE to be set
+ as value to use on error.
+ @param[in, out] SystemContext Pointer to EFI_SYSTEM_CONTEXT
+
+ @retval EFI_SUCCESS Exception handled
+ @retval EFI_UNSUPPORTED #VE not supported, (new) exception value to
+ propagate provided
+ @retval EFI_PROTOCOL_ERROR #VE handling failed, (new) exception value to
+ propagate provided
+
+**/
+EFI_STATUS
+EFIAPI
+VmTdExitHandleVe (
+ IN OUT EFI_EXCEPTION_TYPE *ExceptionType,
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ UINT64 Status;
+ TD_RETURN_DATA ReturnData;
+ EFI_SYSTEM_CONTEXT_X64 *Regs;
+
+ Regs = SystemContext.SystemContextX64;
+ Status = TdCall (TDCALL_TDGETVEINFO, 0, 0, 0, &ReturnData);
+ ASSERT (Status == 0);
+ if (Status != 0) {
+ DEBUG ((DEBUG_ERROR, "#VE happened. TDGETVEINFO failed with Status = 0x%llx\n", Status));
+ TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0);
+ }
+
+ switch (ReturnData.VeInfo.ExitReason) {
+ case EXIT_REASON_CPUID:
+ Status = CpuIdExit (Regs, &ReturnData.VeInfo);
+ DEBUG ((
+ DEBUG_VERBOSE,
+ "CPUID #VE happened, ExitReasion is %d, ExitQualification = 0x%x.\n",
+ ReturnData.VeInfo.ExitReason,
+ ReturnData.VeInfo.ExitQualification.Val
+ ));
+ break;
+
+ case EXIT_REASON_HLT:
+ Status = TdVmCall (EXIT_REASON_HLT, 0, 0, 0, 0, 0);
+ break;
+
+ case EXIT_REASON_IO_INSTRUCTION:
+ Status = IoExit (Regs, &ReturnData.VeInfo);
+ DEBUG ((
+ DEBUG_VERBOSE,
+ "IO_Instruction #VE happened, ExitReasion is %d, ExitQualification = 0x%x.\n",
+ ReturnData.VeInfo.ExitReason,
+ ReturnData.VeInfo.ExitQualification.Val
+ ));
+ break;
+
+ case EXIT_REASON_MSR_READ:
+ Status = ReadMsrExit (Regs, &ReturnData.VeInfo);
+ DEBUG ((
+ DEBUG_VERBOSE,
+ "RDMSR #VE happened, ExitReasion is %d, ExitQualification = 0x%x. Regs->Rcx=0x%llx, Status = 0x%llx\n",
+ ReturnData.VeInfo.ExitReason,
+ ReturnData.VeInfo.ExitQualification.Val,
+ Regs->Rcx,
+ Status
+ ));
+ break;
+
+ case EXIT_REASON_MSR_WRITE:
+ Status = WriteMsrExit (Regs, &ReturnData.VeInfo);
+ DEBUG ((
+ DEBUG_VERBOSE,
+ "WRMSR #VE happened, ExitReasion is %d, ExitQualification = 0x%x. Regs->Rcx=0x%llx, Status = 0x%llx\n",
+ ReturnData.VeInfo.ExitReason,
+ ReturnData.VeInfo.ExitQualification.Val,
+ Regs->Rcx,
+ Status
+ ));
+ break;
+
+ case EXIT_REASON_EPT_VIOLATION:
+ Status = MmioExit (Regs, &ReturnData.VeInfo);
+ DEBUG ((
+ DEBUG_VERBOSE,
+ "MMIO #VE happened, ExitReasion is %d, ExitQualification = 0x%x.\n",
+ ReturnData.VeInfo.ExitReason,
+ ReturnData.VeInfo.ExitQualification.Val
+ ));
+ break;
+
+ case EXIT_REASON_VMCALL:
+ case EXIT_REASON_MWAIT_INSTRUCTION:
+ case EXIT_REASON_MONITOR_INSTRUCTION:
+ case EXIT_REASON_WBINVD:
+ case EXIT_REASON_RDPMC:
+ /* Handle as nops. */
+ break;
+
+ default:
+ DEBUG ((
+ DEBUG_ERROR,
+ "Unsupported #VE happened, ExitReason is %d, ExitQualification = 0x%x.\n",
+ ReturnData.VeInfo.ExitReason,
+ ReturnData.VeInfo.ExitQualification.Val
+ ));
+
+ ASSERT (FALSE);
+ CpuDeadLoop ();
+ }
+
+ if (Status) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "#VE Error (0x%llx) returned from host, ExitReason is %d, ExitQualification = 0x%x.\n",
+ Status,
+ ReturnData.VeInfo.ExitReason,
+ ReturnData.VeInfo.ExitQualification.Val
+ ));
+
+ TdVmCall (TDVMCALL_HALT, 0, 0, 0, 0, 0);
+ }
+
+ SystemContext.SystemContextX64->Rip += ReturnData.VeInfo.ExitInstructionLength;
+ return EFI_SUCCESS;
+}
diff --git a/OvmfPkg/Library/VmgExitLib/VmgExitLib.inf b/OvmfPkg/Library/VmgExitLib/VmgExitLib.inf
index 7963670e7d30..255b0c1a2f7f 100644
--- a/OvmfPkg/Library/VmgExitLib/VmgExitLib.inf
+++ b/OvmfPkg/Library/VmgExitLib/VmgExitLib.inf
@@ -25,6 +25,8 @@
VmgExitVcHandler.c
VmgExitVcHandler.h
PeiDxeVmgExitVcHandler.c
+ VmTdExitVeHandler.c
+ X64/TdVmcallCpuid.nasm

[Packages]
MdePkg/MdePkg.dec
diff --git a/OvmfPkg/Library/VmgExitLib/X64/TdVmcallCpuid.nasm b/OvmfPkg/Library/VmgExitLib/X64/TdVmcallCpuid.nasm
new file mode 100644
index 000000000000..fa86440904fe
--- /dev/null
+++ b/OvmfPkg/Library/VmgExitLib/X64/TdVmcallCpuid.nasm
@@ -0,0 +1,146 @@
+;------------------------------------------------------------------------------
+;*
+;* Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+;* SPDX-License-Identifier: BSD-2-Clause-Patent
+;*
+;*
+;------------------------------------------------------------------------------
+
+DEFAULT REL
+SECTION .text
+
+%define TDVMCALL_EXPOSE_REGS_MASK 0xffec
+%define TDVMCALL 0x0
+%define EXIT_REASON_CPUID 0xa
+
+%macro tdcall 0
+ db 0x66,0x0f,0x01,0xcc
+%endmacro
+
+%macro tdcall_push_regs 0
+ push rbp
+ mov rbp, rsp
+ push r15
+ push r14
+ push r13
+ push r12
+ push rbx
+ push rsi
+ push rdi
+%endmacro
+
+%macro tdcall_pop_regs 0
+ pop rdi
+ pop rsi
+ pop rbx
+ pop r12
+ pop r13
+ pop r14
+ pop r15
+ pop rbp
+%endmacro
+
+%define number_of_regs_pushed 8
+%define number_of_parameters 4
+
+;
+; Keep these in sync for push_regs/pop_regs, code below
+; uses them to find 5th or greater parameters
+;
+%define first_variable_on_stack_offset \
+ ((number_of_regs_pushed * 8) + (number_of_parameters * 8) + 8)
+%define second_variable_on_stack_offset \
+ ((first_variable_on_stack_offset) + 8)
+
+%macro tdcall_regs_preamble 2
+ mov rax, %1
+
+ xor rcx, rcx
+ mov ecx, %2
+
+ ; R10 = 0 (standard TDVMCALL)
+
+ xor r10d, r10d
+
+ ; Zero out unused (for standard TDVMCALL) registers to avoid leaking
+ ; secrets to the VMM.
+
+ xor ebx, ebx
+ xor esi, esi
+ xor edi, edi
+
+ xor edx, edx
+ xor ebp, ebp
+ xor r8d, r8d
+ xor r9d, r9d
+ xor r14, r14
+ xor r15, r15
+%endmacro
+
+%macro tdcall_regs_postamble 0
+ xor ebx, ebx
+ xor esi, esi
+ xor edi, edi
+
+ xor ecx, ecx
+ xor edx, edx
+ xor r8d, r8d
+ xor r9d, r9d
+ xor r10d, r10d
+ xor r11d, r11d
+%endmacro
+
+;------------------------------------------------------------------------------
+; 0 => RAX = TDCALL leaf / TDVMCALL
+; M => RCX = TDVMCALL register behavior
+; 0xa => R11 = TDVMCALL function / CPUID
+; RCX => R12 = p1
+; RDX => R13 = p2
+;
+; UINT64
+; EFIAPI
+; TdVmCallCpuid (
+; UINT64 EaxIn, // Rcx
+; UINT64 EcxIn, // Rdx
+; UINT64 *Results // R8
+; )
+global ASM_PFX(TdVmCallCpuid)
+ASM_PFX(TdVmCallCpuid):
+ tdcall_push_regs
+
+ mov r11, EXIT_REASON_CPUID
+ mov r12, rcx
+ mov r13, rdx
+
+ ; Save *results pointers
+ push r8
+
+ tdcall_regs_preamble TDVMCALL, TDVMCALL_EXPOSE_REGS_MASK
+
+ tdcall
+
+ ; ignore return data if TDCALL reports failure.
+ test rax, rax
+ jnz .no_return_data
+
+ ; Propagate TDVMCALL success/failure to return value.
+ mov rax, r10
+ test rax, rax
+ jnz .no_return_data
+
+ ; Retrieve *Results
+ pop r8
+ test r8, r8
+ jz .no_return_data
+ ; Caller pass in buffer so store results r12-r15 contains eax-edx
+ mov [r8 + 0], r12
+ mov [r8 + 8], r13
+ mov [r8 + 16], r14
+ mov [r8 + 24], r15
+
+.no_return_data:
+ tdcall_regs_postamble
+
+ tdcall_pop_regs
+
+ ret
--
2.29.2.windows.2


[PATCH V12 05/47] UefiCpuPkg: Extend VmgExitLibNull to handle #VE exception #ve

Min Xu
 

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

VmgExitLib performs the necessary processing to handle a #VC exception.
VmgExitLibNull is a NULL instance of VmgExitLib which provides a
default limited interface. In this commit VmgExitLibNull is extended to
handle a #VE exception with a default limited interface. A full feature
version of #VE handler will be created later.

Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Eric Dong <eric.dong@...>
Cc: Ray Ni <ray.ni@...>
Cc: Rahul Kumar <rahul1.kumar@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Reviewed-by: Ray Ni <ray.ni@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
UefiCpuPkg/Include/Library/VmgExitLib.h | 28 ++++++++++++++
.../Library/VmgExitLibNull/VmTdExitNull.c | 38 +++++++++++++++++++
.../Library/VmgExitLibNull/VmgExitLibNull.inf | 1 +
3 files changed, 67 insertions(+)
create mode 100644 UefiCpuPkg/Library/VmgExitLibNull/VmTdExitNull.c

diff --git a/UefiCpuPkg/Include/Library/VmgExitLib.h b/UefiCpuPkg/Include/Library/VmgExitLib.h
index ebda1c3d907c..f9f911099a7b 100644
--- a/UefiCpuPkg/Include/Library/VmgExitLib.h
+++ b/UefiCpuPkg/Include/Library/VmgExitLib.h
@@ -15,6 +15,8 @@
#include <Protocol/DebugSupport.h>
#include <Register/Amd/Ghcb.h>

+#define VE_EXCEPTION 20
+
/**
Perform VMGEXIT.

@@ -142,4 +144,30 @@ VmgExitHandleVc (
IN OUT EFI_SYSTEM_CONTEXT SystemContext
);

+/**
+ Handle a #VE exception.
+
+ Performs the necessary processing to handle a #VE exception.
+
+ The base library function returns an error equal to VE_EXCEPTION,
+ to be propagated to the standard exception handling stack.
+
+ @param[in, out] ExceptionType Pointer to an EFI_EXCEPTION_TYPE to be set
+ as value to use on error.
+ @param[in, out] SystemContext Pointer to EFI_SYSTEM_CONTEXT
+
+ @retval EFI_SUCCESS Exception handled
+ @retval EFI_UNSUPPORTED #VE not supported, (new) exception value to
+ propagate provided
+ @retval EFI_PROTOCOL_ERROR #VE handling failed, (new) exception value to
+ propagate provided
+
+**/
+EFI_STATUS
+EFIAPI
+VmTdExitHandleVe (
+ IN OUT EFI_EXCEPTION_TYPE *ExceptionType,
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ );
+
#endif
diff --git a/UefiCpuPkg/Library/VmgExitLibNull/VmTdExitNull.c b/UefiCpuPkg/Library/VmgExitLibNull/VmTdExitNull.c
new file mode 100644
index 000000000000..6a4e8087cb89
--- /dev/null
+++ b/UefiCpuPkg/Library/VmgExitLibNull/VmTdExitNull.c
@@ -0,0 +1,38 @@
+/** @file
+
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#include <Base.h>
+#include <Uefi.h>
+#include <Library/VmgExitLib.h>
+
+/**
+ Handle a #VE exception.
+
+ Performs the necessary processing to handle a #VE exception.
+
+ @param[in, out] ExceptionType Pointer to an EFI_EXCEPTION_TYPE to be set
+ as value to use on error.
+ @param[in, out] SystemContext Pointer to EFI_SYSTEM_CONTEXT
+
+ @retval EFI_SUCCESS Exception handled
+ @retval EFI_UNSUPPORTED #VE not supported, (new) exception value to
+ propagate provided
+ @retval EFI_PROTOCOL_ERROR #VE handling failed, (new) exception value to
+ propagate provided
+
+**/
+EFI_STATUS
+EFIAPI
+VmTdExitHandleVe (
+ IN OUT EFI_EXCEPTION_TYPE *ExceptionType,
+ IN OUT EFI_SYSTEM_CONTEXT SystemContext
+ )
+{
+ *ExceptionType = VE_EXCEPTION;
+
+ return EFI_UNSUPPORTED;
+}
diff --git a/UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf b/UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf
index d8770a21c355..4aab601939ff 100644
--- a/UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf
+++ b/UefiCpuPkg/Library/VmgExitLibNull/VmgExitLibNull.inf
@@ -17,6 +17,7 @@

[Sources.common]
VmgExitLibNull.c
+ VmTdExitNull.c

[Packages]
MdePkg/MdePkg.dec
--
2.29.2.windows.2


[PATCH V12 04/47] MdePkg: Add TdxLib to wrap Tdx operations

Min Xu
 

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

TdxLib is created with functions to perform the related Tdx operation.
This includes functions for:
- TdAcceptPages : Accept pending private pages and initialize the pages
to all-0 using the TD ephemeral private key.
- TdExtendRtmr : Extend measurement to one of the RTMR registers.
- TdSharedPageMask: Get the Td guest shared page mask which indicates it
is a Shared or Private page.
- TdMaxVCpuNum : Get the maximum number of virtual CPUs.
- TdVCpuNum : Get the number of virtual CPUs.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Reviewed-by: Liming Gao <gaoliming@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
MdePkg/Include/Library/TdxLib.h | 92 ++++++++++++++
MdePkg/Library/TdxLib/AcceptPages.c | 181 ++++++++++++++++++++++++++++
MdePkg/Library/TdxLib/Rtmr.c | 84 +++++++++++++
MdePkg/Library/TdxLib/TdInfo.c | 115 ++++++++++++++++++
MdePkg/Library/TdxLib/TdxLib.inf | 37 ++++++
MdePkg/Library/TdxLib/TdxLibNull.c | 106 ++++++++++++++++
MdePkg/MdePkg.dec | 3 +
MdePkg/MdePkg.dsc | 1 +
8 files changed, 619 insertions(+)
create mode 100644 MdePkg/Include/Library/TdxLib.h
create mode 100644 MdePkg/Library/TdxLib/AcceptPages.c
create mode 100644 MdePkg/Library/TdxLib/Rtmr.c
create mode 100644 MdePkg/Library/TdxLib/TdInfo.c
create mode 100644 MdePkg/Library/TdxLib/TdxLib.inf
create mode 100644 MdePkg/Library/TdxLib/TdxLibNull.c

diff --git a/MdePkg/Include/Library/TdxLib.h b/MdePkg/Include/Library/TdxLib.h
new file mode 100644
index 000000000000..55f0436cca1f
--- /dev/null
+++ b/MdePkg/Include/Library/TdxLib.h
@@ -0,0 +1,92 @@
+/** @file
+ TdxLib definitions
+
+ Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef TDX_LIB_H_
+#define TDX_LIB_H_
+
+/**
+ This function accepts a pending private page, and initialize the page to
+ all-0 using the TD ephemeral private key.
+
+ @param[in] StartAddress Guest physical address of the private page
+ to accept. [63:52] and [11:0] must be 0.
+ @param[in] NumberOfPages Number of the pages to be accepted.
+ @param[in] PageSize GPA page size. Accept 2M/4K page size.
+
+ @return EFI_SUCCESS
+**/
+EFI_STATUS
+EFIAPI
+TdAcceptPages (
+ IN UINT64 StartAddress,
+ IN UINT64 NumberOfPages,
+ IN UINT32 PageSize
+ );
+
+/**
+ This function extends one of the RTMR measurement register
+ in TDCS with the provided extension data in memory.
+ RTMR extending supports SHA384 which length is 48 bytes.
+
+ @param[in] Data Point to the data to be extended
+ @param[in] DataLen Length of the data. Must be 48
+ @param[in] Index RTMR index
+
+ @return EFI_SUCCESS
+ @return EFI_INVALID_PARAMETER
+ @return EFI_DEVICE_ERROR
+
+**/
+EFI_STATUS
+EFIAPI
+TdExtendRtmr (
+ IN UINT32 *Data,
+ IN UINT32 DataLen,
+ IN UINT8 Index
+ );
+
+/**
+ This function gets the Td guest shared page mask.
+
+ The guest indicates if a page is shared using the Guest Physical Address
+ (GPA) Shared (S) bit. If the GPA Width(GPAW) is 48, the S-bit is bit-47.
+ If the GPAW is 52, the S-bit is bit-51.
+
+ @return Shared page bit mask
+**/
+UINT64
+EFIAPI
+TdSharedPageMask (
+ VOID
+ );
+
+/**
+ This function gets the maximum number of Virtual CPUs that are usable for
+ Td Guest.
+
+ @return maximum Virtual CPUs number
+**/
+UINT32
+EFIAPI
+TdMaxVCpuNum (
+ VOID
+ );
+
+/**
+ This function gets the number of Virtual CPUs that are usable for Td
+ Guest.
+
+ @return Virtual CPUs number
+**/
+UINT32
+EFIAPI
+TdVCpuNum (
+ VOID
+ );
+
+#endif
diff --git a/MdePkg/Library/TdxLib/AcceptPages.c b/MdePkg/Library/TdxLib/AcceptPages.c
new file mode 100644
index 000000000000..3a2182e95f47
--- /dev/null
+++ b/MdePkg/Library/TdxLib/AcceptPages.c
@@ -0,0 +1,181 @@
+/** @file
+
+ Unaccepted memory is a special type of private memory. In Td guest
+ TDCALL [TDG.MEM.PAGE.ACCEPT] is invoked to accept the unaccepted
+ memory before use it.
+
+ 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 <IndustryStandard/Tdx.h>
+#include <Uefi/UefiBaseType.h>
+#include <Library/TdxLib.h>
+#include <Library/BaseMemoryLib.h>
+
+UINT64 mNumberOfDuplicatedAcceptedPages;
+
+#define TDX_ACCEPTPAGE_MAX_RETRIED 3
+
+// PageSize is mapped to PageLevel like below:
+// 4KB - 0, 2MB - 1
+UINT32 mTdxAcceptPageLevelMap[2] = {
+ SIZE_4KB,
+ SIZE_2MB
+};
+
+#define INVALID_ACCEPT_PAGELEVEL ARRAY_SIZE(mTdxAcceptPageLevelMap)
+
+/**
+ This function gets the PageLevel according to the input page size.
+
+ @param[in] PageSize Page size
+
+ @return UINT32 The mapped page level
+**/
+UINT32
+GetGpaPageLevel (
+ UINT32 PageSize
+ )
+{
+ UINT32 Index;
+
+ for (Index = 0; Index < ARRAY_SIZE (mTdxAcceptPageLevelMap); Index++) {
+ if (mTdxAcceptPageLevelMap[Index] == PageSize) {
+ break;
+ }
+ }
+
+ return Index;
+}
+
+/**
+ This function accept a pending private page, and initialize the page to
+ all-0 using the TD ephemeral private key.
+
+ Sometimes TDCALL [TDG.MEM.PAGE.ACCEPT] may return
+ TDX_EXIT_REASON_PAGE_SIZE_MISMATCH. It indicates the input PageLevel is
+ not workable. In this case we need to try to fallback to a smaller
+ PageLevel if possible.
+
+ @param[in] StartAddress Guest physical address of the private
+ page to accept. [63:52] and [11:0] must be 0.
+ @param[in] NumberOfPages Number of the pages to be accepted.
+ @param[in] PageSize GPA page size. Only accept 2M/4K size.
+
+ @return EFI_SUCCESS Accept successfully
+ @return others Indicate other errors
+**/
+EFI_STATUS
+EFIAPI
+TdAcceptPages (
+ IN UINT64 StartAddress,
+ IN UINT64 NumberOfPages,
+ IN UINT32 PageSize
+ )
+{
+ EFI_STATUS Status;
+ UINT64 Address;
+ UINT64 TdxStatus;
+ UINT64 Index;
+ UINT32 GpaPageLevel;
+ UINT32 PageSize2;
+ UINTN Retried;
+
+ Retried = 0;
+
+ if ((StartAddress & ~0xFFFFFFFFFF000ULL) != 0) {
+ ASSERT (FALSE);
+ DEBUG ((DEBUG_ERROR, "Accept page address(0x%llx) is not valid. [63:52] and [11:0] must be 0\n", StartAddress));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Address = StartAddress;
+
+ GpaPageLevel = GetGpaPageLevel (PageSize);
+ if (GpaPageLevel == INVALID_ACCEPT_PAGELEVEL) {
+ ASSERT (FALSE);
+ DEBUG ((DEBUG_ERROR, "Accept page size must be 4K/2M. Invalid page size - 0x%llx\n", PageSize));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Status = EFI_SUCCESS;
+ for (Index = 0; Index < NumberOfPages; Index++) {
+ Retried = 0;
+
+DoAcceptPage:
+ TdxStatus = TdCall (TDCALL_TDACCEPTPAGE, Address | GpaPageLevel, 0, 0, 0);
+ if (TdxStatus != TDX_EXIT_REASON_SUCCESS) {
+ if ((TdxStatus & ~0xFFFFULL) == TDX_EXIT_REASON_PAGE_ALREADY_ACCEPTED) {
+ //
+ // Already accepted
+ //
+ mNumberOfDuplicatedAcceptedPages++;
+ DEBUG ((DEBUG_WARN, "Page at Address (0x%llx) has already been accepted. - %d\n", Address, mNumberOfDuplicatedAcceptedPages));
+ } else if ((TdxStatus & ~0xFFFFULL) == TDX_EXIT_REASON_PAGE_SIZE_MISMATCH) {
+ //
+ // GpaPageLevel is mismatch, fall back to a smaller GpaPageLevel if possible
+ //
+ DEBUG ((DEBUG_VERBOSE, "Address %llx cannot be accepted in PageLevel of %d\n", Address, GpaPageLevel));
+
+ if (GpaPageLevel == 0) {
+ //
+ // Cannot fall back to smaller page level
+ //
+ DEBUG ((DEBUG_ERROR, "AcceptPage cannot fallback from PageLevel %d\n", GpaPageLevel));
+ Status = EFI_INVALID_PARAMETER;
+ break;
+ } else {
+ //
+ // Fall back to a smaller page size
+ //
+ PageSize2 = mTdxAcceptPageLevelMap[GpaPageLevel - 1];
+ Status = TdAcceptPages (Address, 512, PageSize2);
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ }
+ } else if ((TdxStatus & ~0xFFFFULL) == TDX_EXIT_REASON_OPERAND_BUSY) {
+ //
+ // Concurrent TDG.MEM.PAGE.ACCEPT is using the same Secure EPT entry
+ // So try it again. There is a max retried count. If Retried exceeds the max count,
+ // report the error and quit.
+ //
+ Retried += 1;
+ if (Retried > TDX_ACCEPTPAGE_MAX_RETRIED) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "Address %llx (%d) failed to be accepted because of OPERAND_BUSY. Retried %d time.\n",
+ Address,
+ Index,
+ Retried
+ ));
+ Status = EFI_INVALID_PARAMETER;
+ break;
+ } else {
+ goto DoAcceptPage;
+ }
+ } else {
+ //
+ // Other errors
+ //
+ DEBUG ((
+ DEBUG_ERROR,
+ "Address %llx (%d) failed to be accepted. Error = 0x%llx\n",
+ Address,
+ Index,
+ TdxStatus
+ ));
+ Status = EFI_INVALID_PARAMETER;
+ break;
+ }
+ }
+
+ Address += PageSize;
+ }
+
+ return Status;
+}
diff --git a/MdePkg/Library/TdxLib/Rtmr.c b/MdePkg/Library/TdxLib/Rtmr.c
new file mode 100644
index 000000000000..a0283966b353
--- /dev/null
+++ b/MdePkg/Library/TdxLib/Rtmr.c
@@ -0,0 +1,84 @@
+/** @file
+
+ Extends one of the RTMR measurement registers in TDCS with the provided
+ extension data in memory.
+
+ 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 <Uefi/UefiBaseType.h>
+#include <Library/TdxLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <IndustryStandard/Tpm20.h>
+#include <IndustryStandard/Tdx.h>
+
+#define RTMR_COUNT 4
+#define TD_EXTEND_BUFFER_LEN (64 + 48)
+
+UINT8 mExtendBuffer[TD_EXTEND_BUFFER_LEN];
+
+/**
+ This function extends one of the RTMR measurement register
+ in TDCS with the provided extension data in memory.
+ RTMR extending supports SHA384 which length is 48 bytes.
+
+ @param[in] Data Point to the data to be extended
+ @param[in] DataLen Length of the data. Must be 48
+ @param[in] Index RTMR index
+
+ @return EFI_SUCCESS
+ @return EFI_INVALID_PARAMETER
+ @return EFI_DEVICE_ERROR
+
+**/
+EFI_STATUS
+EFIAPI
+TdExtendRtmr (
+ IN UINT32 *Data,
+ IN UINT32 DataLen,
+ IN UINT8 Index
+ )
+{
+ EFI_STATUS Status;
+ UINT64 TdCallStatus;
+ UINT8 *ExtendBuffer;
+
+ Status = EFI_SUCCESS;
+
+ ASSERT (Data != NULL);
+ ASSERT (DataLen == SHA384_DIGEST_SIZE);
+ ASSERT (Index >= 0 && Index < RTMR_COUNT);
+
+ if ((Data == NULL) || (DataLen != SHA384_DIGEST_SIZE) || (Index >= RTMR_COUNT)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // TD.RTMR.EXTEND requires 64B-aligned guest physical address of
+ // 48B-extension data. We use ALIGN_POINTER(Pointer, 64) to get
+ // the 64B-aligned guest physical address.
+ ExtendBuffer = ALIGN_POINTER (mExtendBuffer, 64);
+ ASSERT (((UINTN)ExtendBuffer & 0x3f) == 0);
+
+ ZeroMem (ExtendBuffer, SHA384_DIGEST_SIZE);
+ CopyMem (ExtendBuffer, Data, SHA384_DIGEST_SIZE);
+
+ TdCallStatus = TdCall (TDCALL_TDEXTENDRTMR, (UINT64)(UINTN)ExtendBuffer, Index, 0, 0);
+
+ if (TdCallStatus == TDX_EXIT_REASON_SUCCESS) {
+ Status = EFI_SUCCESS;
+ } else if (TdCallStatus == TDX_EXIT_REASON_OPERAND_INVALID) {
+ Status = EFI_INVALID_PARAMETER;
+ } else {
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ if (Status != EFI_SUCCESS) {
+ DEBUG ((DEBUG_ERROR, "Error returned from TdExtendRtmr call - 0x%lx\n", TdCallStatus));
+ }
+
+ return Status;
+}
diff --git a/MdePkg/Library/TdxLib/TdInfo.c b/MdePkg/Library/TdxLib/TdInfo.c
new file mode 100644
index 000000000000..3c5689f1d8c6
--- /dev/null
+++ b/MdePkg/Library/TdxLib/TdInfo.c
@@ -0,0 +1,115 @@
+/** @file
+
+ Fetch the Tdx info.
+
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <IndustryStandard/Tdx.h>
+#include <Uefi/UefiBaseType.h>
+#include <Library/TdxLib.h>
+#include <Library/BaseMemoryLib.h>
+
+UINT64 mTdSharedPageMask = 0;
+UINT32 mTdMaxVCpuNum = 0;
+UINT32 mTdVCpuNum = 0;
+BOOLEAN mTdDataReturned = FALSE;
+
+/**
+ This function call TDCALL_TDINFO to get the TD_RETURN_DATA.
+ If the TDCALL is successful, populate below variables:
+ - mTdSharedPageMask
+ - mTdMaxVCpunum
+ - mTdVCpuNum
+ - mTdDataReturned
+
+ @return TRUE The TDCALL is successful and above variables are populated.
+ @return FALSE The TDCALL is failed. Above variables are not set.
+**/
+BOOLEAN
+GetTdInfo (
+ VOID
+ )
+{
+ UINT64 Status;
+ TD_RETURN_DATA TdReturnData;
+ UINT8 Gpaw;
+
+ Status = TdCall (TDCALL_TDINFO, 0, 0, 0, &TdReturnData);
+ if (Status == TDX_EXIT_REASON_SUCCESS) {
+ Gpaw = (UINT8)(TdReturnData.TdInfo.Gpaw & 0x3f);
+ mTdSharedPageMask = 1ULL << (Gpaw - 1);
+ mTdMaxVCpuNum = TdReturnData.TdInfo.MaxVcpus;
+ mTdVCpuNum = TdReturnData.TdInfo.NumVcpus;
+ mTdDataReturned = TRUE;
+ } else {
+ DEBUG ((DEBUG_ERROR, "Failed call TDCALL_TDINFO. %llx\n", Status));
+ mTdDataReturned = FALSE;
+ }
+
+ return mTdDataReturned;
+}
+
+/**
+ This function gets the Td guest shared page mask.
+
+ The guest indicates if a page is shared using the Guest Physical Address
+ (GPA) Shared (S) bit. If the GPA Width(GPAW) is 48, the S-bit is bit-47.
+ If the GPAW is 52, the S-bit is bit-51.
+
+ @return Shared page bit mask
+**/
+UINT64
+EFIAPI
+TdSharedPageMask (
+ VOID
+ )
+{
+ if (mTdDataReturned) {
+ return mTdSharedPageMask;
+ }
+
+ return GetTdInfo () ? mTdSharedPageMask : 0;
+}
+
+/**
+ This function gets the maximum number of Virtual CPUs that are usable for
+ Td Guest.
+
+ @return maximum Virtual CPUs number
+**/
+UINT32
+EFIAPI
+TdMaxVCpuNum (
+ VOID
+ )
+{
+ if (mTdDataReturned) {
+ return mTdMaxVCpuNum;
+ }
+
+ return GetTdInfo () ? mTdMaxVCpuNum : 0;
+}
+
+/**
+ This function gets the number of Virtual CPUs that are usable for Td
+ Guest.
+
+ @return Virtual CPUs number
+**/
+UINT32
+EFIAPI
+TdVCpuNum (
+ VOID
+ )
+{
+ if (mTdDataReturned) {
+ return mTdVCpuNum;
+ }
+
+ return GetTdInfo () ? mTdVCpuNum : 0;
+}
diff --git a/MdePkg/Library/TdxLib/TdxLib.inf b/MdePkg/Library/TdxLib/TdxLib.inf
new file mode 100644
index 000000000000..442e63d079da
--- /dev/null
+++ b/MdePkg/Library/TdxLib/TdxLib.inf
@@ -0,0 +1,37 @@
+## @file
+# Tdx library
+#
+# Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = TdxLib
+ FILE_GUID = 032A8E0D-0C27-40C0-9CAA-23B731C1B223
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = TdxLib
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64
+#
+
+[Sources.IA32]
+ TdxLibNull.c
+
+[Sources.X64]
+ AcceptPages.c
+ Rtmr.c
+ TdInfo.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ DebugLib
diff --git a/MdePkg/Library/TdxLib/TdxLibNull.c b/MdePkg/Library/TdxLib/TdxLibNull.c
new file mode 100644
index 000000000000..29b2fe7ae775
--- /dev/null
+++ b/MdePkg/Library/TdxLib/TdxLibNull.c
@@ -0,0 +1,106 @@
+/** @file
+
+ Null stub of TdxLib
+
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Uefi/UefiBaseType.h>
+#include <Library/TdxLib.h>
+
+/**
+ This function accepts a pending private page, and initialize the page to
+ all-0 using the TD ephemeral private key.
+
+ @param[in] StartAddress Guest physical address of the private page
+ to accept.
+ @param[in] NumberOfPages Number of the pages to be accepted.
+ @param[in] PageSize GPA page size. Accept 1G/2M/4K page size.
+
+ @return EFI_SUCCESS
+**/
+EFI_STATUS
+EFIAPI
+TdAcceptPages (
+ IN UINT64 StartAddress,
+ IN UINT64 NumberOfPages,
+ IN UINT32 PageSize
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ This function extends one of the RTMR measurement register
+ in TDCS with the provided extension data in memory.
+ RTMR extending supports SHA384 which length is 48 bytes.
+
+ @param[in] Data Point to the data to be extended
+ @param[in] DataLen Length of the data. Must be 48
+ @param[in] Index RTMR index
+
+ @return EFI_SUCCESS
+ @return EFI_INVALID_PARAMETER
+ @return EFI_DEVICE_ERROR
+
+**/
+EFI_STATUS
+EFIAPI
+TdExtendRtmr (
+ IN UINT32 *Data,
+ IN UINT32 DataLen,
+ IN UINT8 Index
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ This function gets the Td guest shared page mask.
+
+ The guest indicates if a page is shared using the Guest Physical Address
+ (GPA) Shared (S) bit. If the GPA Width(GPAW) is 48, the S-bit is bit-47.
+ If the GPAW is 52, the S-bit is bit-51.
+
+ @return Shared page bit mask
+**/
+UINT64
+EFIAPI
+TdSharedPageMask (
+ VOID
+ )
+{
+ return 0;
+}
+
+/**
+ This function gets the maximum number of Virtual CPUs that are usable for
+ Td Guest.
+
+ @return maximum Virtual CPUs number
+**/
+UINT32
+EFIAPI
+TdMaxVCpuNum (
+ VOID
+ )
+{
+ return 0;
+}
+
+/**
+ This function gets the number of Virtual CPUs that are usable for Td
+ Guest.
+
+ @return Virtual CPUs number
+**/
+UINT32
+EFIAPI
+TdVCpuNum (
+ VOID
+ )
+{
+ return 0;
+}
diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec
index 59b405928bf8..1934c9840423 100644
--- a/MdePkg/MdePkg.dec
+++ b/MdePkg/MdePkg.dec
@@ -296,6 +296,9 @@
## @libraryclass Provides services to log the SMI handler registration.
SmiHandlerProfileLib|Include/Library/SmiHandlerProfileLib.h

+ ## @libraryclass Provides function to support TDX processing.
+ TdxLib|Include/Library/TdxLib.h
+
[Guids]
#
# GUID defined in UEFI2.1/UEFI2.0/EFI1.1
diff --git a/MdePkg/MdePkg.dsc b/MdePkg/MdePkg.dsc
index a94959169b2f..d6a7af412be7 100644
--- a/MdePkg/MdePkg.dsc
+++ b/MdePkg/MdePkg.dsc
@@ -175,6 +175,7 @@
MdePkg/Library/SmiHandlerProfileLibNull/SmiHandlerProfileLibNull.inf
MdePkg/Library/MmServicesTableLib/MmServicesTableLib.inf
MdePkg/Library/MmUnblockMemoryLib/MmUnblockMemoryLibNull.inf
+ MdePkg/Library/TdxLib/TdxLib.inf

[Components.EBC]
MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
--
2.29.2.windows.2


[PATCH V12 03/47] MdePkg: Introduce basic Tdx functions in BaseLib

Min Xu
 

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

Introduce basic Tdx functions in BaseLib:
- TdCall ()
- TdVmCall ()
- TdIsEnabled ()

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Gerd Hoffmann <kraxel@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Reviewed-by: Liming Gao <gaoliming@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
MdePkg/Include/Library/BaseLib.h | 66 +++++++++++
MdePkg/Library/BaseLib/BaseLib.inf | 4 +
MdePkg/Library/BaseLib/IntelTdxNull.c | 83 +++++++++++++
MdePkg/Library/BaseLib/X64/TdCall.nasm | 85 +++++++++++++
MdePkg/Library/BaseLib/X64/TdProbe.c | 63 ++++++++++
MdePkg/Library/BaseLib/X64/TdVmcall.nasm | 145 +++++++++++++++++++++++
6 files changed, 446 insertions(+)
create mode 100644 MdePkg/Library/BaseLib/IntelTdxNull.c
create mode 100644 MdePkg/Library/BaseLib/X64/TdCall.nasm
create mode 100644 MdePkg/Library/BaseLib/X64/TdProbe.c
create mode 100644 MdePkg/Library/BaseLib/X64/TdVmcall.nasm

diff --git a/MdePkg/Include/Library/BaseLib.h b/MdePkg/Include/Library/BaseLib.h
index 6aa0d972186e..9d58a7c4ad13 100644
--- a/MdePkg/Include/Library/BaseLib.h
+++ b/MdePkg/Include/Library/BaseLib.h
@@ -4759,6 +4759,72 @@ SpeculationBarrier (
VOID
);

+#if defined (MDE_CPU_X64) || defined (MDE_CPU_IA32)
+
+/**
+ The TDCALL instruction causes a VM exit to the Intel TDX module. It is
+ used to call guest-side Intel TDX functions, either local or a TD exit
+ to the host VMM, as selected by Leaf.
+
+ @param[in] Leaf Leaf number of TDCALL instruction
+ @param[in] Arg1 Arg1
+ @param[in] Arg2 Arg2
+ @param[in] Arg3 Arg3
+ @param[in,out] Results Returned result of the Leaf function
+
+ @return 0 A successful call
+ @return Other See individual leaf functions
+**/
+UINTN
+EFIAPI
+TdCall (
+ IN UINT64 Leaf,
+ IN UINT64 Arg1,
+ IN UINT64 Arg2,
+ IN UINT64 Arg3,
+ IN OUT VOID *Results
+ );
+
+/**
+ TDVMALL is a leaf function 0 for TDCALL. It helps invoke services from the
+ host VMM to pass/receive information.
+
+ @param[in] Leaf Number of sub-functions
+ @param[in] Arg1 Arg1
+ @param[in] Arg2 Arg2
+ @param[in] Arg3 Arg3
+ @param[in] Arg4 Arg4
+ @param[in,out] Results Returned result of the sub-function
+
+ @return 0 A successful call
+ @return Other See individual sub-functions
+
+**/
+UINTN
+EFIAPI
+TdVmCall (
+ IN UINT64 Leaf,
+ IN UINT64 Arg1,
+ IN UINT64 Arg2,
+ IN UINT64 Arg3,
+ IN UINT64 Arg4,
+ IN OUT VOID *Results
+ );
+
+/**
+ Probe if TD is enabled.
+
+ @return TRUE TD is enabled.
+ @return FALSE TD is not enabled.
+**/
+BOOLEAN
+EFIAPI
+TdIsEnabled (
+ VOID
+ );
+
+#endif
+
#if defined (MDE_CPU_X64)
//
// The page size for the PVALIDATE instruction
diff --git a/MdePkg/Library/BaseLib/BaseLib.inf b/MdePkg/Library/BaseLib/BaseLib.inf
index cebda3b210c1..16b7ac391705 100644
--- a/MdePkg/Library/BaseLib/BaseLib.inf
+++ b/MdePkg/Library/BaseLib/BaseLib.inf
@@ -210,6 +210,7 @@
X86RdRand.c
X86PatchInstruction.c
X86SpeculationBarrier.c
+ IntelTdxNull.c

[Sources.X64]
X64/Thunk16.nasm
@@ -293,6 +294,9 @@
X64/ReadCr0.nasm| MSFT
X64/ReadEflags.nasm| MSFT

+ X64/TdCall.nasm
+ X64/TdVmcall.nasm
+ X64/TdProbe.c

X64/Non-existing.c
Math64.c
diff --git a/MdePkg/Library/BaseLib/IntelTdxNull.c b/MdePkg/Library/BaseLib/IntelTdxNull.c
new file mode 100644
index 000000000000..ec95470bd43e
--- /dev/null
+++ b/MdePkg/Library/BaseLib/IntelTdxNull.c
@@ -0,0 +1,83 @@
+/** @file
+
+ Null stub of TdxLib
+
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseLib.h>
+#include <Uefi/UefiBaseType.h>
+
+/**
+ The TDCALL instruction causes a VM exit to the Intel TDX module. It is
+ used to call guest-side Intel TDX functions, either local or a TD exit
+ to the host VMM, as selected by Leaf.
+ Leaf functions are described at <https://software.intel.com/content/
+ www/us/en/develop/articles/intel-trust-domain-extensions.html>
+
+ @param[in] Leaf Leaf number of TDCALL instruction
+ @param[in] Arg1 Arg1
+ @param[in] Arg2 Arg2
+ @param[in] Arg3 Arg3
+ @param[in,out] Results Returned result of the Leaf function
+
+ @return EFI_SUCCESS
+ @return Other See individual leaf functions
+**/
+UINTN
+EFIAPI
+TdCall (
+ IN UINT64 Leaf,
+ IN UINT64 Arg1,
+ IN UINT64 Arg2,
+ IN UINT64 Arg3,
+ IN OUT VOID *Results
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ TDVMALL is a leaf function 0 for TDCALL. It helps invoke services from the
+ host VMM to pass/receive information.
+
+ @param[in] Leaf Number of sub-functions
+ @param[in] Arg1 Arg1
+ @param[in] Arg2 Arg2
+ @param[in] Arg3 Arg3
+ @param[in] Arg4 Arg4
+ @param[in,out] Results Returned result of the sub-function
+
+ @return EFI_SUCCESS
+ @return Other See individual sub-functions
+
+**/
+UINTN
+EFIAPI
+TdVmCall (
+ IN UINT64 Leaf,
+ IN UINT64 Arg1,
+ IN UINT64 Arg2,
+ IN UINT64 Arg3,
+ IN UINT64 Arg4,
+ IN OUT VOID *Results
+ )
+{
+ return EFI_UNSUPPORTED;
+}
+
+/**
+ Probe if TD is enabled.
+
+ @return TRUE TD is enabled.
+ @return FALSE TD is not enabled.
+**/
+BOOLEAN
+EFIAPI
+TdIsEnabled (
+ )
+{
+ return FALSE;
+}
diff --git a/MdePkg/Library/BaseLib/X64/TdCall.nasm b/MdePkg/Library/BaseLib/X64/TdCall.nasm
new file mode 100644
index 000000000000..e8a094b0eb3f
--- /dev/null
+++ b/MdePkg/Library/BaseLib/X64/TdCall.nasm
@@ -0,0 +1,85 @@
+;------------------------------------------------------------------------------
+;*
+;* Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+;* SPDX-License-Identifier: BSD-2-Clause-Patent
+;*
+;*
+;------------------------------------------------------------------------------
+
+DEFAULT REL
+SECTION .text
+
+%macro tdcall 0
+ db 0x66,0x0f,0x01,0xcc
+%endmacro
+
+%macro tdcall_push_regs 0
+ push rbp
+ mov rbp, rsp
+ push r15
+ push r14
+ push r13
+ push r12
+ push rbx
+ push rsi
+ push rdi
+%endmacro
+
+%macro tdcall_pop_regs 0
+ pop rdi
+ pop rsi
+ pop rbx
+ pop r12
+ pop r13
+ pop r14
+ pop r15
+ pop rbp
+%endmacro
+
+%define number_of_regs_pushed 8
+%define number_of_parameters 4
+
+;
+; Keep these in sync for push_regs/pop_regs, code below
+; uses them to find 5th or greater parameters
+;
+%define first_variable_on_stack_offset \
+ ((number_of_regs_pushed * 8) + (number_of_parameters * 8) + 8)
+%define second_variable_on_stack_offset \
+ ((first_variable_on_stack_offset) + 8)
+
+; TdCall (
+; UINT64 Leaf, // Rcx
+; UINT64 P1, // Rdx
+; UINT64 P2, // R8
+; UINT64 P3, // R9
+; UINT64 Results, // rsp + 0x28
+; )
+global ASM_PFX(TdCall)
+ASM_PFX(TdCall):
+ tdcall_push_regs
+
+ mov rax, rcx
+ mov rcx, rdx
+ mov rdx, r8
+ mov r8, r9
+
+ tdcall
+
+ ; exit if tdcall reports failure.
+ test rax, rax
+ jnz .exit
+
+ ; test if caller wanted results
+ mov r12, [rsp + first_variable_on_stack_offset ]
+ test r12, r12
+ jz .exit
+ mov [r12 + 0 ], rcx
+ mov [r12 + 8 ], rdx
+ mov [r12 + 16], r8
+ mov [r12 + 24], r9
+ mov [r12 + 32], r10
+ mov [r12 + 40], r11
+.exit:
+ tdcall_pop_regs
+ ret
diff --git a/MdePkg/Library/BaseLib/X64/TdProbe.c b/MdePkg/Library/BaseLib/X64/TdProbe.c
new file mode 100644
index 000000000000..b893c0a004d5
--- /dev/null
+++ b/MdePkg/Library/BaseLib/X64/TdProbe.c
@@ -0,0 +1,63 @@
+/** @file
+
+ Copyright (c) 2020-2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseLib.h>
+#include <Register/Intel/Cpuid.h>
+
+/**
+ Probe if TD is enabled.
+
+ @return TRUE TD is enabled.
+ @return FALSE TD is not enabled.
+**/
+BOOLEAN
+EFIAPI
+TdIsEnabled (
+ )
+{
+ UINT32 Eax;
+ UINT32 Ebx;
+ UINT32 Ecx;
+ UINT32 Edx;
+ UINT32 LargestEax;
+ BOOLEAN TdEnabled;
+ CPUID_VERSION_INFO_ECX CpuIdVersionInfoEcx;
+
+ TdEnabled = FALSE;
+
+ do {
+ AsmCpuid (CPUID_SIGNATURE, &LargestEax, &Ebx, &Ecx, &Edx);
+
+ if ( (Ebx != CPUID_SIGNATURE_GENUINE_INTEL_EBX)
+ || (Edx != CPUID_SIGNATURE_GENUINE_INTEL_EDX)
+ || (Ecx != CPUID_SIGNATURE_GENUINE_INTEL_ECX))
+ {
+ break;
+ }
+
+ AsmCpuid (CPUID_VERSION_INFO, NULL, NULL, &CpuIdVersionInfoEcx.Uint32, NULL);
+ if (CpuIdVersionInfoEcx.Bits.ParaVirtualized == 0) {
+ break;
+ }
+
+ if (LargestEax < CPUID_GUESTTD_RUNTIME_ENVIRONMENT) {
+ break;
+ }
+
+ AsmCpuidEx (CPUID_GUESTTD_RUNTIME_ENVIRONMENT, 0, &Eax, &Ebx, &Ecx, &Edx);
+ if ( (Ebx != CPUID_GUESTTD_SIGNATURE_GENUINE_INTEL_EBX)
+ || (Edx != CPUID_GUESTTD_SIGNATURE_GENUINE_INTEL_EDX)
+ || (Ecx != CPUID_GUESTTD_SIGNATURE_GENUINE_INTEL_ECX))
+ {
+ break;
+ }
+
+ TdEnabled = TRUE;
+ } while (FALSE);
+
+ return TdEnabled;
+}
diff --git a/MdePkg/Library/BaseLib/X64/TdVmcall.nasm b/MdePkg/Library/BaseLib/X64/TdVmcall.nasm
new file mode 100644
index 000000000000..5ecc10b17193
--- /dev/null
+++ b/MdePkg/Library/BaseLib/X64/TdVmcall.nasm
@@ -0,0 +1,145 @@
+;------------------------------------------------------------------------------
+;*
+;* Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+;* SPDX-License-Identifier: BSD-2-Clause-Patent
+;*
+;*
+;------------------------------------------------------------------------------
+
+DEFAULT REL
+SECTION .text
+
+%define TDVMCALL_EXPOSE_REGS_MASK 0xffec
+%define TDVMCALL 0x0
+
+%macro tdcall 0
+ db 0x66,0x0f,0x01,0xcc
+%endmacro
+
+%macro tdcall_push_regs 0
+ push rbp
+ mov rbp, rsp
+ push r15
+ push r14
+ push r13
+ push r12
+ push rbx
+ push rsi
+ push rdi
+%endmacro
+
+%macro tdcall_pop_regs 0
+ pop rdi
+ pop rsi
+ pop rbx
+ pop r12
+ pop r13
+ pop r14
+ pop r15
+ pop rbp
+%endmacro
+
+%define number_of_regs_pushed 8
+%define number_of_parameters 4
+
+;
+; Keep these in sync for push_regs/pop_regs, code below
+; uses them to find 5th or greater parameters
+;
+%define first_variable_on_stack_offset \
+ ((number_of_regs_pushed * 8) + (number_of_parameters * 8) + 8)
+%define second_variable_on_stack_offset \
+ ((first_variable_on_stack_offset) + 8)
+
+%macro tdcall_regs_preamble 2
+ mov rax, %1
+
+ xor rcx, rcx
+ mov ecx, %2
+
+ ; R10 = 0 (standard TDVMCALL)
+
+ xor r10d, r10d
+
+ ; Zero out unused (for standard TDVMCALL) registers to avoid leaking
+ ; secrets to the VMM.
+
+ xor ebx, ebx
+ xor esi, esi
+ xor edi, edi
+
+ xor edx, edx
+ xor ebp, ebp
+ xor r8d, r8d
+ xor r9d, r9d
+%endmacro
+
+%macro tdcall_regs_postamble 0
+ xor ebx, ebx
+ xor esi, esi
+ xor edi, edi
+
+ xor ecx, ecx
+ xor edx, edx
+ xor r8d, r8d
+ xor r9d, r9d
+ xor r10d, r10d
+ xor r11d, r11d
+%endmacro
+
+;------------------------------------------------------------------------------
+; 0 => RAX = TDCALL leaf
+; M => RCX = TDVMCALL register behavior
+; 1 => R10 = standard vs. vendor
+; RDI => R11 = TDVMCALL function / nr
+; RSI = R12 = p1
+; RDX => R13 = p2
+; RCX => R14 = p3
+; R8 => R15 = p4
+
+; UINT64
+; EFIAPI
+; TdVmCall (
+; UINT64 Leaf, // Rcx
+; UINT64 P1, // Rdx
+; UINT64 P2, // R8
+; UINT64 P3, // R9
+; UINT64 P4, // rsp + 0x28
+; UINT64 *Val // rsp + 0x30
+; )
+global ASM_PFX(TdVmCall)
+ASM_PFX(TdVmCall):
+ tdcall_push_regs
+
+ mov r11, rcx
+ mov r12, rdx
+ mov r13, r8
+ mov r14, r9
+ mov r15, [rsp + first_variable_on_stack_offset ]
+
+ tdcall_regs_preamble TDVMCALL, TDVMCALL_EXPOSE_REGS_MASK
+
+ tdcall
+
+ ; ignore return dataif TDCALL reports failure.
+ test rax, rax
+ jnz .no_return_data
+
+ ; Propagate TDVMCALL success/failure to return value.
+ mov rax, r10
+
+ ; Retrieve the Val pointer.
+ mov r9, [rsp + second_variable_on_stack_offset ]
+ test r9, r9
+ jz .no_return_data
+
+ ; On success, propagate TDVMCALL output value to output param
+ test rax, rax
+ jnz .no_return_data
+ mov [r9], r11
+.no_return_data:
+ tdcall_regs_postamble
+
+ tdcall_pop_regs
+
+ ret
--
2.29.2.windows.2


[PATCH V12 02/47] MdePkg: Update Cpuid.h for Tdx

Min Xu
 

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

Guest software can be designed to run either as a TD, as a legacy virtual
machine, or directly on the CPU, based on enumeration of its run-time
environment. [TDX-Module] Chap 10.2 defines the flow and the new CPUID
leaf 0x21.

[TDX-Module] Architecture Specification: Intel(R) Trust Domain Extensions
Module, Chap 10.2, 344425-003US, August 2021
https://www.intel.com/content/dam/develop/external/us/en/documents/
tdx-module-1.0-public-spec-v0.931.pdf

Cc: Ray Ni <ray.ni@...>
Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Gerd Hoffmann <kraxel@...>
Reviewed-by: Liming Gao <gaoliming@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
MdePkg/Include/Register/Intel/Cpuid.h | 35 +++++++++++++++++++++++++--
1 file changed, 33 insertions(+), 2 deletions(-)

diff --git a/MdePkg/Include/Register/Intel/Cpuid.h b/MdePkg/Include/Register/Intel/Cpuid.h
index bd6349d7940d..350bf60252e1 100644
--- a/MdePkg/Include/Register/Intel/Cpuid.h
+++ b/MdePkg/Include/Register/Intel/Cpuid.h
@@ -12,6 +12,8 @@
@par Specification Reference:
Intel(R) 64 and IA-32 Architectures Software Developer's Manual, Volume 2A,
November 2018, CPUID instruction.
+ Architecture Specification: Intel(R) Trust Domain Extensions Module, Chap 10.2
+ 344425-003US, August 2021

**/

@@ -321,9 +323,9 @@ typedef union {
///
UINT32 RDRAND : 1;
///
- /// [Bit 31] Always returns 0.
+ /// [Bit 31] A value of 1 indicates that processor is in Para-Virtualized.
///
- UINT32 NotUsed : 1;
+ UINT32 ParaVirtualized : 1;
} Bits;
///
/// All bit fields as a 32-bit value
@@ -3689,6 +3691,35 @@ typedef union {
/// @}
///

+/**
+ CPUID Guest TD Run Time Environment Enumeration Leaf
+
+ @note
+ Guest software can be designed to run either as a TD, as a legacy virtual machine,
+ or directly on the CPU, based on enumeration of its run-time environment.
+ CPUID leaf 21H emulation is done by the Intel TDX module. Sub-leaf 0 returns the values
+ shown below. Other sub-leaves return 0 in EAX/EBX/ECX/EDX.
+ EAX: 0x00000000
+ EBX: 0x65746E49 "Inte"
+ ECX: 0x20202020 " "
+ EDX: 0x5844546C "lTDX"
+
+ @param EAX CPUID_GUESTTD_RUNTIME_ENVIRONMENT (0x21)
+ @param ECX Level number
+
+**/
+#define CPUID_GUESTTD_RUNTIME_ENVIRONMENT 0x21
+
+///
+/// @{ CPUID Guest TD signature values returned by Intel processors
+///
+#define CPUID_GUESTTD_SIGNATURE_GENUINE_INTEL_EBX SIGNATURE_32 ('I', 'n', 't', 'e')
+#define CPUID_GUESTTD_SIGNATURE_GENUINE_INTEL_ECX SIGNATURE_32 (' ', ' ', ' ', ' ')
+#define CPUID_GUESTTD_SIGNATURE_GENUINE_INTEL_EDX SIGNATURE_32 ('l', 'T', 'D', 'X')
+///
+/// @}
+///
+
/**
CPUID Extended Function

--
2.29.2.windows.2


[PATCH V12 01/47] MdePkg: Add Tdx.h

Min Xu
 

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

Tdx.h includes the Intel Trust Domain Extension definitions.

Detailed information can be found in below document:
https://software.intel.com/content/dam/develop/external/us/en/
documents/tdx-module-1eas-v0.85.039.pdf

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Gerd Hoffmann <kraxel@...>
Cc: Jiewen Yao <jiewen.yao@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Reviewed-by: Liming Gao <gaoliming@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
MdePkg/Include/IndustryStandard/Tdx.h | 203 ++++++++++++++++++++++++++
1 file changed, 203 insertions(+)
create mode 100644 MdePkg/Include/IndustryStandard/Tdx.h

diff --git a/MdePkg/Include/IndustryStandard/Tdx.h b/MdePkg/Include/IndustryStandard/Tdx.h
new file mode 100644
index 000000000000..81df1361842b
--- /dev/null
+++ b/MdePkg/Include/IndustryStandard/Tdx.h
@@ -0,0 +1,203 @@
+/** @file
+ Intel Trust Domain Extension definitions
+ Detailed information is in below document:
+ https://software.intel.com/content/dam/develop/external/us/en/documents
+ /tdx-module-1eas-v0.85.039.pdf
+
+ Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef MDE_PKG_TDX_H_
+#define MDE_PKG_TDX_H_
+
+#define EXIT_REASON_EXTERNAL_INTERRUPT 1
+#define EXIT_REASON_TRIPLE_FAULT 2
+
+#define EXIT_REASON_PENDING_INTERRUPT 7
+#define EXIT_REASON_NMI_WINDOW 8
+#define EXIT_REASON_TASK_SWITCH 9
+#define EXIT_REASON_CPUID 10
+#define EXIT_REASON_HLT 12
+#define EXIT_REASON_INVD 13
+#define EXIT_REASON_INVLPG 14
+#define EXIT_REASON_RDPMC 15
+#define EXIT_REASON_RDTSC 16
+#define EXIT_REASON_VMCALL 18
+#define EXIT_REASON_VMCLEAR 19
+#define EXIT_REASON_VMLAUNCH 20
+#define EXIT_REASON_VMPTRLD 21
+#define EXIT_REASON_VMPTRST 22
+#define EXIT_REASON_VMREAD 23
+#define EXIT_REASON_VMRESUME 24
+#define EXIT_REASON_VMWRITE 25
+#define EXIT_REASON_VMOFF 26
+#define EXIT_REASON_VMON 27
+#define EXIT_REASON_CR_ACCESS 28
+#define EXIT_REASON_DR_ACCESS 29
+#define EXIT_REASON_IO_INSTRUCTION 30
+#define EXIT_REASON_MSR_READ 31
+#define EXIT_REASON_MSR_WRITE 32
+#define EXIT_REASON_INVALID_STATE 33
+#define EXIT_REASON_MSR_LOAD_FAIL 34
+#define EXIT_REASON_MWAIT_INSTRUCTION 36
+#define EXIT_REASON_MONITOR_TRAP_FLAG 37
+#define EXIT_REASON_MONITOR_INSTRUCTION 39
+#define EXIT_REASON_PAUSE_INSTRUCTION 40
+#define EXIT_REASON_MCE_DURING_VMENTRY 41
+#define EXIT_REASON_TPR_BELOW_THRESHOLD 43
+#define EXIT_REASON_APIC_ACCESS 44
+#define EXIT_REASON_EOI_INDUCED 45
+#define EXIT_REASON_GDTR_IDTR 46
+#define EXIT_REASON_LDTR_TR 47
+#define EXIT_REASON_EPT_VIOLATION 48
+#define EXIT_REASON_EPT_MISCONFIG 49
+#define EXIT_REASON_INVEPT 50
+#define EXIT_REASON_RDTSCP 51
+#define EXIT_REASON_PREEMPTION_TIMER 52
+#define EXIT_REASON_INVVPID 53
+#define EXIT_REASON_WBINVD 54
+#define EXIT_REASON_XSETBV 55
+#define EXIT_REASON_APIC_WRITE 56
+#define EXIT_REASON_RDRAND 57
+#define EXIT_REASON_INVPCID 58
+#define EXIT_REASON_VMFUNC 59
+#define EXIT_REASON_ENCLS 60
+#define EXIT_REASON_RDSEED 61
+#define EXIT_REASON_PML_FULL 62
+#define EXIT_REASON_XSAVES 63
+#define EXIT_REASON_XRSTORS 64
+
+// TDCALL API Function Completion Status Codes
+#define TDX_EXIT_REASON_SUCCESS 0x0000000000000000
+#define TDX_EXIT_REASON_PAGE_ALREADY_ACCEPTED 0x00000B0A00000000
+#define TDX_EXIT_REASON_PAGE_SIZE_MISMATCH 0xC0000B0B00000000
+#define TDX_EXIT_REASON_OPERAND_INVALID 0xC000010000000000
+#define TDX_EXIT_REASON_OPERAND_BUSY 0x8000020000000000
+
+// TDCALL [TDG.MEM.PAGE.ACCEPT] page size
+#define TDCALL_ACCEPT_PAGE_SIZE_4K 0
+#define TDCALL_ACCEPT_PAGE_SIZE_2M 1
+#define TDCALL_ACCEPT_PAGE_SIZE_1G 2
+
+#define TDCALL_TDVMCALL 0
+#define TDCALL_TDINFO 1
+#define TDCALL_TDEXTENDRTMR 2
+#define TDCALL_TDGETVEINFO 3
+#define TDCALL_TDREPORT 4
+#define TDCALL_TDSETCPUIDVE 5
+#define TDCALL_TDACCEPTPAGE 6
+
+#define TDVMCALL_CPUID 0x0000a
+#define TDVMCALL_HALT 0x0000c
+#define TDVMCALL_IO 0x0001e
+#define TDVMCALL_RDMSR 0x0001f
+#define TDVMCALL_WRMSR 0x00020
+#define TDVMCALL_MMIO 0x00030
+#define TDVMCALL_PCONFIG 0x00041
+
+#define TDVMCALL_GET_TDVMCALL_INFO 0x10000
+#define TDVMCALL_MAPGPA 0x10001
+#define TDVMCALL_GET_QUOTE 0x10002
+#define TDVMCALL_REPORT_FATAL_ERR 0x10003
+#define TDVMCALL_SETUP_EVENT_NOTIFY 0x10004
+
+#pragma pack(1)
+typedef struct {
+ UINT64 Data[6];
+} TDCALL_GENERIC_RETURN_DATA;
+
+typedef struct {
+ UINT64 Gpaw;
+ UINT64 Attributes;
+ UINT32 MaxVcpus;
+ UINT32 NumVcpus;
+ UINT64 Resv[3];
+} TDCALL_INFO_RETURN_DATA;
+
+typedef union {
+ UINT64 Val;
+ struct {
+ UINT32 Size : 3;
+ UINT32 Direction : 1;
+ UINT32 String : 1;
+ UINT32 Rep : 1;
+ UINT32 Encoding : 1;
+ UINT32 Resv : 9;
+ UINT32 Port : 16;
+ UINT32 Resv2;
+ } Io;
+} VMX_EXIT_QUALIFICATION;
+
+typedef struct {
+ UINT32 ExitReason;
+ UINT32 Resv;
+ VMX_EXIT_QUALIFICATION ExitQualification;
+ UINT64 GuestLA;
+ UINT64 GuestPA;
+ UINT32 ExitInstructionLength;
+ UINT32 ExitInstructionInfo;
+ UINT32 Resv1;
+} TDCALL_VEINFO_RETURN_DATA;
+
+typedef union {
+ TDCALL_GENERIC_RETURN_DATA Generic;
+ TDCALL_INFO_RETURN_DATA TdInfo;
+ TDCALL_VEINFO_RETURN_DATA VeInfo;
+} TD_RETURN_DATA;
+
+/* data structure used in TDREPORT_STRUCT */
+typedef struct {
+ UINT8 Type;
+ UINT8 Subtype;
+ UINT8 Version;
+ UINT8 Rsvd;
+} TD_REPORT_TYPE;
+
+typedef struct {
+ TD_REPORT_TYPE ReportType;
+ UINT8 Rsvd1[12];
+ UINT8 CpuSvn[16];
+ UINT8 TeeTcbInfoHash[48];
+ UINT8 TeeInfoHash[48];
+ UINT8 ReportData[64];
+ UINT8 Rsvd2[32];
+ UINT8 Mac[32];
+} REPORTMACSTRUCT;
+
+typedef struct {
+ UINT8 Seam[2];
+ UINT8 Rsvd[14];
+} TEE_TCB_SVN;
+
+typedef struct {
+ UINT8 Valid[8];
+ TEE_TCB_SVN TeeTcbSvn;
+ UINT8 Mrseam[48];
+ UINT8 Mrsignerseam[48];
+ UINT8 Attributes[8];
+ UINT8 Rsvd[111];
+} TEE_TCB_INFO;
+
+typedef struct {
+ UINT8 Attributes[8];
+ UINT8 Xfam[8];
+ UINT8 Mrtd[48];
+ UINT8 Mrconfigid[48];
+ UINT8 Mrowner[48];
+ UINT8 Mrownerconfig[48];
+ UINT8 Rtmrs[4][48];
+ UINT8 Rsvd[112];
+} TDINFO;
+
+typedef struct {
+ REPORTMACSTRUCT ReportMacStruct;
+ TEE_TCB_INFO TeeTcbInfo;
+ UINT8 Rsvd[17];
+ TDINFO Tdinfo;
+} TDREPORT_STRUCT;
+
+#pragma pack()
+
+#endif
--
2.29.2.windows.2


[PATCH V12 00/47] Enable Intel TDX in OvmfPkg (Config-A)

Min Xu
 

REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3249

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 Config-A in OvmfPkg.
- Merge the *basic* TDVF feature to existing OvmfX64Pkg.dsc. (Align
with existing SEV)
- Threat model: VMM is NOT out of TCB. (We don’t make things worse.)
- The OvmfX64Pkg.dsc includes SEV/TDX/normal OVMF basic boot capability.
The final binary can run on SEV/TDX/normal OVMF
- No changes to existing OvmfPkgX64 image layout.
- No need to add additional security features if they do not exist today
- No need to remove features if they exist today.
- RTMR is not supported
- PEI phase is NOT skipped in either Td or Non-Td

Patch 01 - 33 are changes in SEC phase. Also some libraries in these
patches are workable in SEC/PEI/DXE.

Patch 16 - 29 extract the common codes from OvmfPkg/PlatformPei to a new
PlatformInitLib. After that OvmfPkg/PlatformPei is refactored with this
lib. These 14 patches are currently reviewed in another separate
patch-set. https://edk2.groups.io/g/devel/message/87327

Patch 34 - 39 are changes in PEI phase.

Patch 40 - 44 are changes in DXE phase.

Patch 45 - 47 are for local Apic timer DXE driver.

[TDX]: https://software.intel.com/content/dam/develop/external/us/en/
documents/tdx-whitepaper-final9-17.pdf

[TDX-Module]: https://software.intel.com/content/dam/develop/external/
us/en/documents/tdx-module-1.0-public-spec-v0.931.pdf

[TDVF]: https://software.intel.com/content/dam/develop/external/us/en/
documents/tdx-virtual-firmware-design-guide-rev-1.pdf

[GCHI]: https://software.intel.com/content/dam/develop/external/us/en/
documents/intel-tdx-guest-hypervisor-communication-interface-1.0-344426-002.pdf

Code is at https://github.com/mxu9/edk2/tree/tdvf_wave2.v12

v12 changes:
- Update MpInitLib based on the review feedbacks. Please see
https://edk2.groups.io/g/devel/message/88173.
- Update the code base to 2b4b8013fe45.

v11 changes:
- Update MpInitlib based on the review comments. Please see
https://edk2.groups.io/g/devel/message/88089
- Update the code base to 3ef2071927fa.

v10 changes:
- Update MpInitLib based on the review comments. Please see the
discussion: https://edk2.groups.io/g/devel/message/87902
- Update the code base to ec0b54849b23.

v9 changes:
- Move the definition of EFI_RESOURCE_MEMORY_UNACCEPTED from MdePkg
to OvmfPkg as in internal implementation. Because it has not been
added in PI spec. After the definition is added in PI spec, it can
be moved to MdePkg.
- Add definition of new CPUID leaf 0x21 in
MdePkg/Include/Register/Intel/Cpuid.h.
- Use switch-case to hanle VC/VE handling together in
CpuExceptionHandlerLib.
- Refactor changes for Tdx guest in MpInitLib.
- Refine the comments in BaseLib and PlatformInitLib.
- Other minor updates and changes.

v8 changes:
- Based on the comments of PlatformInitLib and OvmfPkg/PlatformPei,
a separte patch-set is created for the changes. It is now under review
https://edk2.groups.io/g/devel/message/87327
- Based on the comments, TdCall/TdVmCall/TdIsEnabled is wrapped with
MDE_CPU_IA32 and MDE_CPU_X64.
- EFI_RESOURCE_ATTRIBUTE_ENCRYPTED is removed based on the TDVF Spec
update. Instead EFI_RESOURCE_MEMORY_UNACCEPTED is added to indicate
the memory which to be accepted in TDVF. The corresponding logic
of AcceptMemory is updated as well. Please see Patch 31.
- PcdIa32EferChangeAllowed is deleted. Because for Td guest
IA32_EFER.NXE is set by default. So we only need check whether it has
been set before it is to be set again. See Patch 35.
- Based on comments PcdTdxSharedBitMask is defined in
[PcdsFixedAtBuild, PcdsPatchableInModule, PcdsDynamic, PcdsDynamicEx]
- Delete un-necessary header files in TdxLib.h.
- Other minor updates and changes.

v7 changes:
- Based on the comments from last review, 8 PlatformInitLib patches
are squashed into 4 patches (#17-#20). These 4 patches are not
related to Tdx guest. Tdx related codes of PlatformInitLib is
in #21.
- gUefiOvmfPkgTdxPlatformGuid is renamed as gUefiOvmfPkgPlatformInfoGuid.
Because this GUID is used not only by Tdx guest, but also by
Legacy guest.
- PlatformInitLibNull is deleted.
- In PlatformPei Pml4Entries is cap at 512 entries when
mPhysMemAddressWidth > 48.

v7 not-addressed comments
- Comments in MpInitLib have not been addressed yet. It will be
addressed in the following version.
- Thanks much for your understanding.

v6 changes:
- PlatformInitLib and OvmfPkg/PlatformPei refactoring are covered in
patch from 17 - 24. These patches are not related to Tdx guest. Tdx
related codes of PlatformInitLib is in patch 25.
- In the previous patch-sets, TdHob is processed in
OvmfPkg/Sec/IntelTdx.c. Per Gerd's suggestion they are now moved
to PlatformInitLib/IntelTdx.c. So that they can be reused in Config-B.
- The default Accept page size is changed from 4K to 2M.
- The BspAcceptMemoryResourceRange is refactored according to Gerd's
comment.
- In ApRunLoop.nasm command field is set to zero as acknowledgement.
This is a fix based on the ACPI Spec v6.4,Sec titled "Multiprocessor
Wakeup Structure".

v6 not-addressed comments
- Comments in MpInitLib have not been addressed yet. It will be
addressed in the following version.
- Thanks much for your understanding.

v5 changes:
- PlatformInitLib is introduced which wraps the common functions in
OvmfPkg/PlatformPei. It is because there are a lot of duplicated
codes for Platform initialization in PEI phase and there are at least
3 variants of PlatformPei. Another reason is that in TDVF Config-B
PEI-less boot needs the similar initiliazation as PlatformPei. Based
on the discussion with the community, PlatformInitLib is introduced.
As the first stage OvmfPkg/PlatformPei is refactored with this lib.
In the future the other 2 PlatformPei variants will be refactored
as well.
- PcdIgnoreVeHalt is deprecated.
- Add spec link for Mailbox.
- Other minor changes, such as comments, uncrustify formats, etc.

v5 not-addressed comments
- Comments in MpInitLib have not been addressed yet. It will be
addressed in the following version.
- Some comments may be missed. I will re-visit the review emails.
- Thanks much for your understanding.

v4 changes:
- Split the TdxLib into 2 libraries. The TDX basic functions
(TdCall / TdVmCall / TdIsEnabled) are moved to BaseLib (#2).
The other functions are in TdxLib. (#3)
- Based on above changes (TdCall/TdVmCall/TdIsEnabled in BaseLib)
the TdxLib.inf is not necessary in some Pkgs, such as
UefiPayloadPkg. The duplicated source code are deleted (BaseIoLib
is the sample).
- Drop the Accepting pages with TDX MP service. Instead only BSP
accepts pages. There maybe boot performance issue. There are some
mitigations to it, such as 2M accept page size, lazy accept, etc.
We will re-visit this issue in a separate patch-set.
- Relocate Mailbox in TdxDxe driver instead of in PlatformPei. This
is to keep consistence with Config-B (PEI is skipped in Config-B).
- SetMmioSharedBit in TdxDxe driver instead of in DxeIplPeim after
CreateIdentityMappingPageTables. This is to keep consistence with
Config-B (PEI is skipped in Config-B).
- Some other minor changes, such as switch-case indention.
- Rebase the code base (commit: 8c06c53b585a) and update the code with
uncrustify.

v4 not-addressed comments:
- Comments in MpInitLib have not been addressed yet. It will be
addressed in the next version.
- BaseMemEncryptTdxLib is suggested to be merged with
BaseMemEncryptSevLib. It will be addressed in the next version.
- Gerd suggests a generic page table walker which is able to set
and clear bits for a given memory range in both SEV and TDX guest.
This suggestion will be addressed in the next version.
- Some comments may be missed. I will re-visit the review emails.
- Thanks much for your understanding.

v3 changes:
- LocalApicTimerDxe is split out to be a separate patch-series.
- VmTdExitLibNull/VmgExitLib are removed. Instead the VmgExitLib
is extended to handle #VE exception. (Patch 3-5)
- Split the Tdx support of base IoLib into 4 commits. (Patch 6-9)
- Alter of MADT table is updated. In previous version it was
created from scratch. Now it gets the installed table, copy
it to a larger buffer and append the ACPI_MADT_MPWK to it.
(Patch 25)
- Changes in BaseXApicX2ApicLib is refined based on the
feedbacks. (Add spec link of MSR access definition, rename
some funtion name, etc.) (Patch 11)
- Use PcdConfidentialComputingGuestAttr to probe TDX guest instead
of CPUID. But in some cases PcdConfidentialComputingGuestAttr
cannot be used because it has not been set yet.
- Some other minor changes.

v3 not-addressed comments:
- Some of the comments have not been addressed. This is because I
need more time to consider how to address these comments.
At the same time I want to submit a new version based on the above
changes so that community can review in a more efficient way.
(v2 is the version one month ago).
- Comments in MpInitLib have not been addressed yet. It will be
addressed in v4.
- BaseMemEncryptTdxLib should be merged with BaseMemEncryptSevLib.
It will be addressed in v4.
- Some comments may be missed. I will re-visit the review emails.
- Thanks much for your understanding.

v2 changes:
- Remove TdxProbeLib. It is to reduce the depencies of the lib.
- In v1 a new function (AllocatePagesWithMemoryType) is added in
PeiMemoryAllocationLib. This function is not necessary. It can
be replaced by PeiServicesAllocatePages.
- IoLibFifo.c is added in BaseIoLibIntrinsic. This file includes
the functions of read/write of I/O port fifo. These functions
will call TdIoReadFifo or SevIoReadFifo by checking TDX or SEV
in run-time.
- DXE related patches are added. (Patch 22-28)
- Fix typo in commit/comment message, or some minor changes.
- Rebase the edk2 code base. (4cc1458dbe00)

Cc: Brijesh Singh <brijesh.singh@...>
Cc: Eric Dong <eric.dong@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: Hao A Wu <hao.a.wu@...>
Cc: Jian J Wang <jian.j.wang@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Liming Gao <gaoliming@...>
Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Ray Ni <ray.ni@...>
Cc: Rahul Kumar <rahul1.kumar@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>

Min Xu (47):
MdePkg: Add Tdx.h
MdePkg: Update Cpuid.h for Tdx
MdePkg: Introduce basic Tdx functions in BaseLib
MdePkg: Add TdxLib to wrap Tdx operations
UefiCpuPkg: Extend VmgExitLibNull to handle #VE exception
OvmfPkg: Extend VmgExitLib to handle #VE exception
UefiCpuPkg/CpuExceptionHandler: Add base support for the #VE exception
MdePkg: Add helper functions for Tdx guest in BaseIoLibIntrinsic
MdePkg: Support mmio for Tdx guest in BaseIoLibIntrinsic
MdePkg: Support IoFifo for Tdx guest in BaseIoLibIntrinsic
MdePkg: Support IoRead/IoWrite for Tdx guest in BaseIoLibIntrinsic
UefiCpuPkg: Support TDX in BaseXApicX2ApicLib
MdePkg: Add macro to check SEV / TDX guest
UefiCpuPkg: Enable Tdx support in MpInitLib
OvmfPkg: Add IntelTdx.h in OvmfPkg/Include/IndustryStandard
OvmfPkg: Add TdxMailboxLib
OvmfPkg: Create initial version of PlatformInitLib
OvmfPkg/PlatformInitLib: Add hob functions
OvmfPkg/PlatformPei: Move global variables to PlatformInfoHob
OvmfPkg/PlatformPei: Refactor MiscInitialization
OvmfPkg/PlatformPei: Refactor MiscInitialization for CloudHV
OvmfPkg/PlatformPei: Refactor AddressWidthInitialization
OvmfPkg/PlatformPei: Refactor MaxCpuCountInitialization
OvmfPkg/PlatformPei: Refactor QemuUc32BaseInitialization
OvmfPkg/PlatformPei: Refactor InitializeRamRegions
OvmfPkg/PlatformPei: Refactor MemMapInitialization
OvmfPkg/PlatformPei: Refactor NoexecDxeInitialization
OvmfPkg/PlatformPei: Refactor MiscInitialization
OvmfPkg/PlatformInitLib: Create MemDetect.c
OvmfPkg/PlatformInitLib: Move functions to Platform.c
OvmfPkg: Update PlatformInitLib to process Tdx hoblist
OvmfPkg/Sec: Declare local variable as volatile in
SecCoreStartupWithStack
OvmfPkg: Update Sec to support Tdx
OvmfPkg: Check Tdx in QemuFwCfgPei to avoid DMA operation
MdeModulePkg: Skip setting IA32_ERER.NXE if it has already been set
MdeModulePkg: Add PcdTdxSharedBitMask
UefiCpuPkg: Update AddressEncMask in CpuPageTable
OvmfPkg: Update PlatformInitLib for Tdx guest
OvmfPkg: Update PlatformPei to support Tdx guest
OvmfPkg: Update AcpiPlatformDxe to alter MADT table
OvmfPkg/BaseMemEncryptTdxLib: Add TDX helper library
OvmfPkg: Add TdxDxe driver
OvmfPkg/QemuFwCfgLib: Support Tdx in QemuFwCfgDxe
OvmfPkg: Update IoMmuDxe to support TDX
OvmfPkg: Rename XenTimerDxe to LocalApicTimerDxe
UefiCpuPkg: Setting initial-count register as the last step
OvmfPkg: Switch timer in build time for OvmfPkg

.../Core/DxeIplPeim/X64/VirtualMemory.c | 8 +-
MdeModulePkg/MdeModulePkg.dec | 4 +
.../Include/ConfidentialComputingGuestAttr.h | 3 +
MdePkg/Include/IndustryStandard/Tdx.h | 203 ++++
MdePkg/Include/Library/BaseLib.h | 66 ++
MdePkg/Include/Library/TdxLib.h | 92 ++
MdePkg/Include/Register/Intel/Cpuid.h | 35 +-
.../BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf | 2 +
.../BaseIoLibIntrinsicSev.inf | 7 +
MdePkg/Library/BaseIoLibIntrinsic/IoLib.c | 81 +-
MdePkg/Library/BaseIoLibIntrinsic/IoLibFifo.c | 217 ++++
MdePkg/Library/BaseIoLibIntrinsic/IoLibGcc.c | 51 +-
.../BaseIoLibIntrinsic/IoLibInternalTdx.c | 674 +++++++++++++
.../BaseIoLibIntrinsic/IoLibInternalTdxNull.c | 497 +++++++++
MdePkg/Library/BaseIoLibIntrinsic/IoLibMsc.c | 73 +-
MdePkg/Library/BaseIoLibIntrinsic/IoLibSev.h | 166 +++
MdePkg/Library/BaseIoLibIntrinsic/IoLibTdx.h | 410 ++++++++
.../BaseIoLibIntrinsic/X64/IoFifoSev.nasm | 34 +-
MdePkg/Library/BaseLib/BaseLib.inf | 4 +
MdePkg/Library/BaseLib/IntelTdxNull.c | 83 ++
MdePkg/Library/BaseLib/X64/TdCall.nasm | 85 ++
MdePkg/Library/BaseLib/X64/TdProbe.c | 63 ++
MdePkg/Library/BaseLib/X64/TdVmcall.nasm | 145 +++
MdePkg/Library/TdxLib/AcceptPages.c | 181 ++++
MdePkg/Library/TdxLib/Rtmr.c | 84 ++
MdePkg/Library/TdxLib/TdInfo.c | 115 +++
MdePkg/Library/TdxLib/TdxLib.inf | 37 +
MdePkg/Library/TdxLib/TdxLibNull.c | 106 ++
MdePkg/MdePkg.dec | 3 +
MdePkg/MdePkg.dsc | 1 +
OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf | 1 +
OvmfPkg/AcpiPlatformDxe/QemuFwCfgAcpi.c | 14 +-
OvmfPkg/AmdSev/AmdSevX64.dsc | 11 +-
OvmfPkg/AmdSev/AmdSevX64.fdf | 3 +-
OvmfPkg/Bhyve/BhyveX64.dsc | 5 +
OvmfPkg/CloudHv/CloudHvX64.dsc | 8 +-
OvmfPkg/CloudHv/CloudHvX64.fdf | 2 +-
OvmfPkg/Include/IndustryStandard/IntelTdx.h | 67 ++
OvmfPkg/Include/Library/MemEncryptTdxLib.h | 81 ++
OvmfPkg/Include/Library/PlatformInitLib.h | 237 +++++
OvmfPkg/Include/Library/TdxMailboxLib.h | 76 ++
.../Include/Protocol/QemuAcpiTableNotify.h | 27 +
OvmfPkg/Include/TdxCommondefs.inc | 51 +
OvmfPkg/IoMmuDxe/AmdSevIoMmu.c | 103 +-
OvmfPkg/IoMmuDxe/AmdSevIoMmu.h | 6 +-
OvmfPkg/IoMmuDxe/IoMmuDxe.c | 6 +-
OvmfPkg/IoMmuDxe/IoMmuDxe.inf | 5 +
.../BaseMemEncryptTdxLib.inf | 44 +
.../BaseMemEncryptTdxLibNull.inf | 35 +
.../BaseMemoryEncryptionNull.c | 90 ++
.../BaseMemEncryptTdxLib/MemoryEncryption.c | 948 ++++++++++++++++++
.../BaseMemEncryptTdxLib/VirtualMemory.h | 181 ++++
.../PlatformInitLib}/Cmos.c | 32 +-
OvmfPkg/Library/PlatformInitLib/IntelTdx.c | 563 +++++++++++
.../Library/PlatformInitLib/IntelTdxNull.c | 46 +
OvmfPkg/Library/PlatformInitLib/MemDetect.c | 856 ++++++++++++++++
OvmfPkg/Library/PlatformInitLib/Platform.c | 573 +++++++++++
.../PlatformInitLib/PlatformInitLib.inf | 98 ++
OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxe.c | 9 +-
.../Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf | 1 +
.../QemuFwCfgLib/QemuFwCfgLibInternal.h | 11 +
OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPei.c | 32 +
.../Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf | 2 +
OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c | 141 +++
.../Library/TdxMailboxLib/TdxMailboxLib.inf | 52 +
.../Library/TdxMailboxLib/TdxMailboxNull.c | 85 ++
OvmfPkg/Library/VmgExitLib/SecVmgExitLib.inf | 3 +-
OvmfPkg/Library/VmgExitLib/VmTdExitHandler.h | 32 +
.../Library/VmgExitLib/VmTdExitVeHandler.c | 559 +++++++++++
OvmfPkg/Library/VmgExitLib/VmgExitLib.inf | 2 +
.../Library/VmgExitLib/X64/TdVmcallCpuid.nasm | 146 +++
.../LocalApicTimerDxe.c} | 4 +-
.../LocalApicTimerDxe.h} | 4 +-
.../LocalApicTimerDxe.inf} | 7 +-
OvmfPkg/Microvm/MicrovmX64.dsc | 8 +-
OvmfPkg/Microvm/MicrovmX64.fdf | 2 +-
OvmfPkg/OvmfPkg.dec | 17 +
OvmfPkg/OvmfPkgIa32.dsc | 15 +-
OvmfPkg/OvmfPkgIa32.fdf | 8 +-
OvmfPkg/OvmfPkgIa32X64.dsc | 15 +-
OvmfPkg/OvmfPkgIa32X64.fdf | 8 +-
OvmfPkg/OvmfPkgX64.dsc | 32 +-
OvmfPkg/OvmfPkgX64.fdf | 11 +-
OvmfPkg/OvmfXen.dsc | 7 +-
OvmfPkg/OvmfXen.fdf | 2 +-
OvmfPkg/PlatformPei/AmdSev.c | 8 +-
OvmfPkg/PlatformPei/Cmos.h | 48 -
OvmfPkg/PlatformPei/FeatureControl.c | 7 +-
OvmfPkg/PlatformPei/Fv.c | 4 +-
OvmfPkg/PlatformPei/IntelTdx.c | 51 +
OvmfPkg/PlatformPei/MemDetect.c | 889 ++--------------
OvmfPkg/PlatformPei/MemTypeInfo.c | 2 +-
OvmfPkg/PlatformPei/Platform.c | 631 ++----------
OvmfPkg/PlatformPei/Platform.h | 97 +-
OvmfPkg/PlatformPei/PlatformPei.inf | 6 +-
OvmfPkg/Sec/SecMain.c | 44 +-
OvmfPkg/Sec/SecMain.inf | 3 +
OvmfPkg/Sec/X64/SecEntry.nasm | 82 ++
OvmfPkg/TdxDxe/TdxAcpiTable.c | 213 ++++
OvmfPkg/TdxDxe/TdxAcpiTable.h | 60 ++
OvmfPkg/TdxDxe/TdxDxe.c | 261 +++++
OvmfPkg/TdxDxe/TdxDxe.inf | 64 ++
OvmfPkg/TdxDxe/X64/ApRunLoop.nasm | 90 ++
UefiCpuPkg/CpuDxe/CpuDxe.inf | 1 +
UefiCpuPkg/CpuDxe/CpuPageTable.c | 3 +
UefiCpuPkg/Include/Library/VmgExitLib.h | 28 +
.../BaseXApicX2ApicLib/BaseXApicX2ApicLib.c | 170 +++-
.../PeiDxeSmmCpuException.c | 53 +-
.../SecPeiCpuException.c | 57 +-
UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf | 3 +
UefiCpuPkg/Library/MpInitLib/MpIntelTdx.h | 69 ++
UefiCpuPkg/Library/MpInitLib/MpLib.c | 63 +-
UefiCpuPkg/Library/MpInitLib/MpLibTdx.c | 106 ++
UefiCpuPkg/Library/MpInitLib/MpLibTdxNull.c | 69 ++
UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf | 3 +
.../Library/VmgExitLibNull/VmTdExitNull.c | 38 +
.../Library/VmgExitLibNull/VmgExitLibNull.inf | 1 +
117 files changed, 10472 insertions(+), 1666 deletions(-)
create mode 100644 MdePkg/Include/IndustryStandard/Tdx.h
create mode 100644 MdePkg/Include/Library/TdxLib.h
create mode 100644 MdePkg/Library/BaseIoLibIntrinsic/IoLibFifo.c
create mode 100644 MdePkg/Library/BaseIoLibIntrinsic/IoLibInternalTdx.c
create mode 100644 MdePkg/Library/BaseIoLibIntrinsic/IoLibInternalTdxNull.c
create mode 100644 MdePkg/Library/BaseIoLibIntrinsic/IoLibSev.h
create mode 100644 MdePkg/Library/BaseIoLibIntrinsic/IoLibTdx.h
create mode 100644 MdePkg/Library/BaseLib/IntelTdxNull.c
create mode 100644 MdePkg/Library/BaseLib/X64/TdCall.nasm
create mode 100644 MdePkg/Library/BaseLib/X64/TdProbe.c
create mode 100644 MdePkg/Library/BaseLib/X64/TdVmcall.nasm
create mode 100644 MdePkg/Library/TdxLib/AcceptPages.c
create mode 100644 MdePkg/Library/TdxLib/Rtmr.c
create mode 100644 MdePkg/Library/TdxLib/TdInfo.c
create mode 100644 MdePkg/Library/TdxLib/TdxLib.inf
create mode 100644 MdePkg/Library/TdxLib/TdxLibNull.c
create mode 100644 OvmfPkg/Include/IndustryStandard/IntelTdx.h
create mode 100644 OvmfPkg/Include/Library/MemEncryptTdxLib.h
create mode 100644 OvmfPkg/Include/Library/PlatformInitLib.h
create mode 100644 OvmfPkg/Include/Library/TdxMailboxLib.h
create mode 100644 OvmfPkg/Include/Protocol/QemuAcpiTableNotify.h
create mode 100644 OvmfPkg/Include/TdxCommondefs.inc
create mode 100644 OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
create mode 100644 OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLibNull.inf
create mode 100644 OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemoryEncryptionNull.c
create mode 100644 OvmfPkg/Library/BaseMemEncryptTdxLib/MemoryEncryption.c
create mode 100644 OvmfPkg/Library/BaseMemEncryptTdxLib/VirtualMemory.h
rename OvmfPkg/{PlatformPei => Library/PlatformInitLib}/Cmos.c (61%)
create mode 100644 OvmfPkg/Library/PlatformInitLib/IntelTdx.c
create mode 100644 OvmfPkg/Library/PlatformInitLib/IntelTdxNull.c
create mode 100644 OvmfPkg/Library/PlatformInitLib/MemDetect.c
create mode 100644 OvmfPkg/Library/PlatformInitLib/Platform.c
create mode 100644 OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf
create mode 100644 OvmfPkg/Library/TdxMailboxLib/TdxMailbox.c
create mode 100644 OvmfPkg/Library/TdxMailboxLib/TdxMailboxLib.inf
create mode 100644 OvmfPkg/Library/TdxMailboxLib/TdxMailboxNull.c
create mode 100644 OvmfPkg/Library/VmgExitLib/VmTdExitHandler.h
create mode 100644 OvmfPkg/Library/VmgExitLib/VmTdExitVeHandler.c
create mode 100644 OvmfPkg/Library/VmgExitLib/X64/TdVmcallCpuid.nasm
rename OvmfPkg/{XenTimerDxe/XenTimerDxe.c => LocalApicTimerDxe/LocalApicTimerDxe.c} (95%)
rename OvmfPkg/{XenTimerDxe/XenTimerDxe.h => LocalApicTimerDxe/LocalApicTimerDxe.h} (96%)
rename OvmfPkg/{XenTimerDxe/XenTimerDxe.inf => LocalApicTimerDxe/LocalApicTimerDxe.inf} (80%)
delete mode 100644 OvmfPkg/PlatformPei/Cmos.h
create mode 100644 OvmfPkg/PlatformPei/IntelTdx.c
create mode 100644 OvmfPkg/TdxDxe/TdxAcpiTable.c
create mode 100644 OvmfPkg/TdxDxe/TdxAcpiTable.h
create mode 100644 OvmfPkg/TdxDxe/TdxDxe.c
create mode 100644 OvmfPkg/TdxDxe/TdxDxe.inf
create mode 100644 OvmfPkg/TdxDxe/X64/ApRunLoop.nasm
create mode 100644 UefiCpuPkg/Library/MpInitLib/MpIntelTdx.h
create mode 100644 UefiCpuPkg/Library/MpInitLib/MpLibTdx.c
create mode 100644 UefiCpuPkg/Library/MpInitLib/MpLibTdxNull.c
create mode 100644 UefiCpuPkg/Library/VmgExitLibNull/VmTdExitNull.c

--
2.29.2.windows.2


Re: CryptoPkg build broken using XCODE5 (Availability.h not found)

Andrew Fish
 

Rebecca,

I got it to compile by doing this

diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf
index cdeed0d073eb..72dbeb2795e8 100644
--- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf
+++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf
@@ -595,8 +595,8 @@ [BuildOptions]
   # 3017: <entity> may be used before being set (NOTE: This was fixed in OpenSSL 1.1 HEAD with
   #       commit d9b8b89bec4480de3a10bdaf9425db371c19145b, and can be dropped then.)
   RVCT:*_*_ARM_CC_FLAGS     = $(OPENSSL_FLAGS) --library_interface=aeabi_clib99 --diag_suppress=1296,1295,550,1293,111,68,177,223,144,513,188,128,546,1,3017 -JCryptoPkg/Include
-  XCODE:*_*_IA32_CC_FLAGS   = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -w -std=c99 -Wno-error=uninitialized
-  XCODE:*_*_X64_CC_FLAGS    = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -w -std=c99 -Wno-error=uninitialized
+  XCODE:*_*_IA32_CC_FLAGS   = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM
+  XCODE:*_*_X64_CC_FLAGS    = -mmmx -msse -U_WIN32 -U_WIN64 $(OPENSSL_FLAGS) -w -std=c99 -Wno-error=uninitialized -DOPENSSL_NO_APPLE_CRYPTO_RANDOM

 

   #
   # AARCH64 uses strict alignment and avoids SIMD registers for code that may execute


Thanks,

Andrew Fish

On Mar 29, 2022, at 10:33 AM, Rebecca Cran <quic_rcran@...> wrote:

A build of CryptoPkg with XCODE5 on macOS is now trying to include Availability.h, which isn't found:

In file included from /Users/bcran/src/uefi/edk2/CryptoPkg/Library/OpensslLib/openssl/crypto/init.c:13:
/Users/bcran/src/uefi/edk2/CryptoPkg/Library/OpensslLib/openssl/include/crypto/rand.h:24:12: fatal error: 'Availability.h' file not found
#  include <Availability.h>
           ^~~~~~~~~~~~~~~~

This is because of the following in CryptoPkg/Library/OpensslLib/openssl/include/crypto/rand.h

# if defined(__APPLE__) && !defined(OPENSSL_NO_APPLE_CRYPTO_RANDOM)
#  include <Availability.h>
#  if (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) || \
     (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000)
#   define OPENSSL_APPLE_CRYPTO_RANDOM 1
#   include <CommonCrypto/CommonCryptoError.h>
#   include <CommonCrypto/CommonRandom.h>
#  endif
# endif

--
Rebecca Cran







Re: [PATCH 3/3] Basetools: turn off gcc12 warning

Andrew Fish
 



On Mar 29, 2022, at 2:38 PM, Andrew Fish via groups.io <afish@...> wrote:



On Mar 29, 2022, at 11:14 AM, grant@... wrote:

While I can't test this myself, the following does appear to result in a successful build using the same clang version:


diff --git a/BaseTools/Source/C/DevicePath/GNUmakefile b/BaseTools/Source/C/DevicePath/GNUmakefile

index b05d2bddfa..81aa35aa31 100644

--- a/BaseTools/Source/C/DevicePath/GNUmakefile

+++ b/BaseTools/Source/C/DevicePath/GNUmakefile

@@ -14,7 +14,9 @@ OBJECTS = DevicePath.o UefiDevicePathLib.o DevicePathFromText.o  DevicePathUtili

 include $(MAKEROOT)/Makefiles/app.makefile

 

 # gcc 12 trips over device path handling

-BUILD_CFLAGS += -Wno-error=stringop-overflow

+ifeq($(CC), gcc)

+  BUILD_CFLAGS += -Wno-error=stringop-overflow

+endif

 

Gerd,

I’m not sure if this was caused by my email client but your fix did not work for me.
GNUmakefile:17: *** missing separator.  Stop.


Sorry I forgot to mention I was using an Xcode clang on macOS. 

Thanks,

Andrew Fish

I had to add a space after `ifeq` to get it to work.
diff --git a/BaseTools/Source/C/DevicePath/GNUmakefile b/BaseTools/Source/C/DevicePath/GNUmakefile
index b05d2bddfa68..ebab1d3e2617 100644
--- a/BaseTools/Source/C/DevicePath/GNUmakefile
+++ b/BaseTools/Source/C/DevicePath/GNUmakefile
@@ -14,7 +14,9 @@ OBJECTS = DevicePath.o UefiDevicePathLib.o DevicePathFromText.o  DevicePathUtili
 include $(MAKEROOT)/Makefiles/app.makefile
 
 # gcc 12 trips over device path handling
-BUILD_CFLAGS += -Wno-error=stringop-overflow
+ifeq ($(CC), gcc)
+  BUILD_CFLAGS += -Wno-error=stringop-overflow
+endif
 
 LIBS = -lCommon
 ifeq ($(CYGWIN), CYGWIN)


I had been working around like this previously (I’m not sure about the portability of -Wno-unknown-warning-option):

diff --git a/BaseTools/Source/C/DevicePath/GNUmakefile b/BaseTools/Source/C/DevicePath/GNUmakefile
index b05d2bddfa68..d08588a81f80 100644
--- a/BaseTools/Source/C/DevicePath/GNUmakefile
+++ b/BaseTools/Source/C/DevicePath/GNUmakefile
@@ -14,7 +14,7 @@ OBJECTS = DevicePath.o UefiDevicePathLib.o DevicePathFromText.o  DevicePathUtili
 include $(MAKEROOT)/Makefiles/app.makefile
 
 # gcc 12 trips over device path handling
-BUILD_CFLAGS += -Wno-error=stringop-overflow
+BUILD_CFLAGS += -Wno-error=stringop-overflow -Wno-unknown-warning-option
 
 LIBS = -lCommon
 ifeq ($(CYGWIN), CYGWIN)

Thanks,

Andrew Fish

 LIBS = -lCommon

 ifeq ($(CYGWIN), CYGWIN)




Re: [PATCH 3/3] Basetools: turn off gcc12 warning

Andrew Fish
 



On Mar 29, 2022, at 11:14 AM, grant@... wrote:

While I can't test this myself, the following does appear to result in a successful build using the same clang version:


diff --git a/BaseTools/Source/C/DevicePath/GNUmakefile b/BaseTools/Source/C/DevicePath/GNUmakefile

index b05d2bddfa..81aa35aa31 100644

--- a/BaseTools/Source/C/DevicePath/GNUmakefile

+++ b/BaseTools/Source/C/DevicePath/GNUmakefile

@@ -14,7 +14,9 @@ OBJECTS = DevicePath.o UefiDevicePathLib.o DevicePathFromText.o  DevicePathUtili

 include $(MAKEROOT)/Makefiles/app.makefile

 

 # gcc 12 trips over device path handling

-BUILD_CFLAGS += -Wno-error=stringop-overflow

+ifeq($(CC), gcc)

+  BUILD_CFLAGS += -Wno-error=stringop-overflow

+endif

 

Gerd,

I’m not sure if this was caused by my email client but your fix did not work for me.
GNUmakefile:17: *** missing separator.  Stop.

I had to add a space after `ifeq` to get it to work.
diff --git a/BaseTools/Source/C/DevicePath/GNUmakefile b/BaseTools/Source/C/DevicePath/GNUmakefile
index b05d2bddfa68..ebab1d3e2617 100644
--- a/BaseTools/Source/C/DevicePath/GNUmakefile
+++ b/BaseTools/Source/C/DevicePath/GNUmakefile
@@ -14,7 +14,9 @@ OBJECTS = DevicePath.o UefiDevicePathLib.o DevicePathFromText.o  DevicePathUtili
 include $(MAKEROOT)/Makefiles/app.makefile

 

 # gcc 12 trips over device path handling
-BUILD_CFLAGS += -Wno-error=stringop-overflow
+ifeq ($(CC), gcc)
+  BUILD_CFLAGS += -Wno-error=stringop-overflow
+endif

 

 LIBS = -lCommon
 ifeq ($(CYGWIN), CYGWIN)


I had been working around like this previously (I’m not sure about the portability of -Wno-unknown-warning-option):

diff --git a/BaseTools/Source/C/DevicePath/GNUmakefile b/BaseTools/Source/C/DevicePath/GNUmakefile
index b05d2bddfa68..d08588a81f80 100644
--- a/BaseTools/Source/C/DevicePath/GNUmakefile
+++ b/BaseTools/Source/C/DevicePath/GNUmakefile
@@ -14,7 +14,7 @@ OBJECTS = DevicePath.o UefiDevicePathLib.o DevicePathFromText.o  DevicePathUtili
 include $(MAKEROOT)/Makefiles/app.makefile

 

 # gcc 12 trips over device path handling
-BUILD_CFLAGS += -Wno-error=stringop-overflow
+BUILD_CFLAGS += -Wno-error=stringop-overflow -Wno-unknown-warning-option

 

 LIBS = -lCommon
 ifeq ($(CYGWIN), CYGWIN)

Thanks,

Andrew Fish

 LIBS = -lCommon

 ifeq ($(CYGWIN), CYGWIN)


8701 - 8720 of 96835