Date   

Re: [PATCH V2 3/8] SecurityPkg: Add definition of EFI_CC_EVENT_HOB_GUID

Yao, Jiewen
 

Reviewed-by: Jiewen Yao <Jiewen.yao@...>

-----Original Message-----
From: Xu, Min M <min.m.xu@...>
Sent: Friday, April 8, 2022 2:39 PM
To: devel@edk2.groups.io
Cc: Xu, Min M <min.m.xu@...>; Gerd Hoffmann <kraxel@...>;
Yao, Jiewen <jiewen.yao@...>; Sami Mujawar
<sami.mujawar@...>; Wang, Jian J <jian.j.wang@...>
Subject: [PATCH V2 3/8] SecurityPkg: Add definition of
EFI_CC_EVENT_HOB_GUID

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

EFI_CC_EVENT_HOB_GUID is the global ID of a GUIDed HOB used to pass
TDX_DIGEST_VALUE from SEC to a DXE Driver ( This DXE driver will
be introduced in the following commit in this patch-sets ). In that
DXE driver this GUIDed HOB will be parsed and the TDX_DIGEST_VALUE
then will be extracted. After that a EFI_CC_EVENT will be created
based on it.

Cc: Gerd Hoffmann <kraxel@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Sami Mujawar <sami.mujawar@...>
Cc: Jian J Wang <jian.j.wang@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
SecurityPkg/Include/Guid/CcEventHob.h | 22 ++++++++++++++++++++++
SecurityPkg/SecurityPkg.dec | 4 ++++
2 files changed, 26 insertions(+)
create mode 100644 SecurityPkg/Include/Guid/CcEventHob.h

diff --git a/SecurityPkg/Include/Guid/CcEventHob.h
b/SecurityPkg/Include/Guid/CcEventHob.h
new file mode 100644
index 000000000000..072999ce92de
--- /dev/null
+++ b/SecurityPkg/Include/Guid/CcEventHob.h
@@ -0,0 +1,22 @@
+/** @file
+ Defines the HOB GUID used to pass a CC_EVENT from SEC to
+ a CC DXE Driver. A GUIDed HOB is generated for each measurement
+ made in the SEC Phase.
+
+Copyright (c) 2021 - 2022, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef CC_EVENT_HOB_H_
+#define CC_EVENT_HOB_H_
+
+//
+// The Global ID of a GUIDed HOB used to pass a CC_EVENT from SEC to a CC
DXE Driver.
+//
+#define EFI_CC_EVENT_HOB_GUID \
+ { 0x20f8fd36, 0x6d00, 0x40fb, { 0xb7, 0x04, 0xd1, 0x2c, 0x15, 0x3c, 0x62,
0xeb } }
+
+extern EFI_GUID gCcEventEntryHobGuid;
+
+#endif
diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec
index 9f7a032d60d5..0ee75efc1a97 100644
--- a/SecurityPkg/SecurityPkg.dec
+++ b/SecurityPkg/SecurityPkg.dec
@@ -136,6 +136,10 @@
## Include/Guid/TcgEventHob.h
gTcgEvent2EntryHobGuid = { 0xd26c221e, 0x2430, 0x4c8a, { 0x91, 0x70,
0x3f, 0xcb, 0x45, 0x0, 0x41, 0x3f }}

+ ## Hob GUID used to pass a CC_EVENT from SEC to a CC DXE Driver.
+ ## Include/Guid/CcEventHob.h
+ gCcEventEntryHobGuid = { 0x20f8fd36, 0x6d00, 0x40fb, { 0xb7, 0x04,
0xd1, 0x2c, 0x15, 0x3c, 0x62, 0xeb }}
+
## HOB GUID used to record TPM device error.
# Include/Guid/TcgEventHob.h
gTpmErrorHobGuid = { 0xef598499, 0xb25e, 0x473a, { 0xbf, 0xaf,
0xe7, 0xe5, 0x7d, 0xce, 0x82, 0xc4 }}
--
2.29.2.windows.2


Re: [PATCH V2 2/8] CryptoPkg: Add SecCryptLib

Yao, Jiewen
 

Hi
The rule for lib instance is: It must provide all interfaces defined in .h file.

As such, please use NULL version other algorithms in SEC instance.

Thank you
Yao Jiewen

-----Original Message-----
From: Xu, Min M <min.m.xu@...>
Sent: Friday, April 8, 2022 2:39 PM
To: devel@edk2.groups.io
Cc: Xu, Min M <min.m.xu@...>; Yao, Jiewen <jiewen.yao@...>;
Wang, Jian J <jian.j.wang@...>; Lu, Xiaoyu1 <xiaoyu1.lu@...>;
Jiang, Guomin <guomin.jiang@...>; Gerd Hoffmann <kraxel@...>
Subject: [PATCH V2 2/8] CryptoPkg: Add SecCryptLib

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

This is the Cryptographic library instance for SEC. The motivation of
this library is to support SHA384 in SEC phase for Td guest. So only
Hash/CryptSha512.c is included which supports SHA384 and SHA512.

Cc: Jiewen Yao <jiewen.yao@...>
Cc: Jian J Wang <jian.j.wang@...>
Cc: Xiaoyu Lu <xiaoyu1.lu@...>
Cc: Guomin Jiang <guomin.jiang@...>
Cc: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
CryptoPkg/CryptoPkg.dsc | 4 ++
.../Library/BaseCryptLib/SecCryptLib.inf | 67 +++++++++++++++++++
2 files changed, 71 insertions(+)
create mode 100644 CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf

diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc
index 0aa72ed87846..b814e9616454 100644
--- a/CryptoPkg/CryptoPkg.dsc
+++ b/CryptoPkg/CryptoPkg.dsc
@@ -109,6 +109,9 @@
[LibraryClasses.ARM]
ArmSoftFloatLib|ArmPkg/Library/ArmSoftFloatLib/ArmSoftFloatLib.inf

+[LibraryClasses.common.SEC]
+ BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf
+
[LibraryClasses.common.PEIM]
PcdLib|MdePkg/Library/PeiPcdLib/PeiPcdLib.inf

ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiRepo
rtStatusCodeLib.inf
@@ -236,6 +239,7 @@
!if $(CRYPTO_SERVICES) == PACKAGE
[Components]
CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
+ CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf
CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf
CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf
CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf
diff --git a/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf
b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf
new file mode 100644
index 000000000000..6ef2f67e35dd
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf
@@ -0,0 +1,67 @@
+## @file
+# Cryptographic Library Instance for SEC.
+#
+# Caution: This module requires additional review when modified.
+# This library will have external input - signature.
+# This external input must be validated carefully to avoid security issues such
as
+# buffer overflow or integer overflow.
+#
+# Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = SecCryptLib
+ FILE_GUID = 3689D343-0D32-4284-8053-BF10537990E8
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = BaseCryptLib|SEC
+
+#
+# The following information is for reference only and not required by the build
tools.
+#
+# VALID_ARCHITECTURES = IA32 X64
+#
+
+[Sources]
+ InternalCryptLib.h
+ Hash/CryptSha512.c
+
+ SysCall/CrtWrapper.c
+ SysCall/ConstantTimeClock.c
+ SysCall/BaseMemAllocation.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ CryptoPkg/CryptoPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ MemoryAllocationLib
+ DebugLib
+ OpensslLib
+ IntrinsicLib
+
+#
+# Remove these [BuildOptions] after this library is cleaned up
+#
+[BuildOptions]
+ #
+ # suppress the following warnings so we do not break the build with warnings-
as-errors:
+ # C4090: 'function' : different 'const' qualifiers
+ # C4718: 'function call' : recursive call has no side effects, deleting
+ #
+ MSFT:*_*_*_CC_FLAGS = /wd4090 /wd4718
+
+ # -JCryptoPkg/Include : To disable the use of the system includes provided by
RVCT
+ # --diag_remark=1 : Reduce severity of "#1-D: last line of file ends without a
newline"
+ RVCT:*_*_ARM_CC_FLAGS = -JCryptoPkg/Include --diag_remark=1
+
+ GCC:*_CLANG35_*_CC_FLAGS = -std=c99
+ GCC:*_CLANG38_*_CC_FLAGS = -std=c99
+ GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-
pointer-types
+
+ XCODE:*_*_*_CC_FLAGS = -std=c99
--
2.29.2.windows.2


Re: [staging/LoongArch RESEND PATCH v1 21/33] MdePkg/BaseLib: BaseLib for LOONGARCH64 architecture.

Abner Chang
 

Acked-by: Abner Chang <abner.chang@...>

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Chao Li
Sent: Wednesday, February 9, 2022 2:56 PM
To: devel@edk2.groups.io
Cc: Michael D Kinney <michael.d.kinney@...>; Liming Gao
<gaoliming@...>; Zhiguang Liu <zhiguang.liu@...>; Baoqi
Zhang <zhangbaoqi@...>
Subject: [edk2-devel] [staging/LoongArch RESEND PATCH v1 21/33]
MdePkg/BaseLib: BaseLib for LOONGARCH64 architecture.

Add LoongArch LOONGARCH64 BaseLib functions.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>

Signed-off-by: Chao Li <lichao@...>
Co-authored-by: Baoqi Zhang <zhangbaoqi@...>
---
MdePkg/Include/Library/BaseLib.h | 24 ++
MdePkg/Library/BaseLib/BaseLib.inf | 13 +
.../BaseLib/LoongArch64/CpuBreakpoint.S | 24 ++
MdePkg/Library/BaseLib/LoongArch64/CpuPause.S | 31 +++
.../BaseLib/LoongArch64/DisableInterrupts.S | 21 ++
.../BaseLib/LoongArch64/EnableInterrupts.S | 21 ++
.../BaseLib/LoongArch64/GetInterruptState.S | 35 +++
.../BaseLib/LoongArch64/InternalSwitchStack.c | 58 +++++
.../Library/BaseLib/LoongArch64/MemoryFence.S | 19 ++
.../BaseLib/LoongArch64/SetJumpLongJump.S | 49 ++++
.../Library/BaseLib/LoongArch64/SwitchStack.S | 39 +++
.../Library/BaseLib/LoongArch64/Unaligned.c | 244 ++++++++++++++++++
12 files changed, 578 insertions(+)
create mode 100644
MdePkg/Library/BaseLib/LoongArch64/CpuBreakpoint.S
create mode 100644 MdePkg/Library/BaseLib/LoongArch64/CpuPause.S
create mode 100644
MdePkg/Library/BaseLib/LoongArch64/DisableInterrupts.S
create mode 100644
MdePkg/Library/BaseLib/LoongArch64/EnableInterrupts.S
create mode 100644
MdePkg/Library/BaseLib/LoongArch64/GetInterruptState.S
create mode 100644
MdePkg/Library/BaseLib/LoongArch64/InternalSwitchStack.c
create mode 100644
MdePkg/Library/BaseLib/LoongArch64/MemoryFence.S
create mode 100644
MdePkg/Library/BaseLib/LoongArch64/SetJumpLongJump.S
create mode 100644 MdePkg/Library/BaseLib/LoongArch64/SwitchStack.S
create mode 100644 MdePkg/Library/BaseLib/LoongArch64/Unaligned.c

diff --git a/MdePkg/Include/Library/BaseLib.h
b/MdePkg/Include/Library/BaseLib.h
index 6aa0d97218..3c27e2ea93 100644
--- a/MdePkg/Include/Library/BaseLib.h
+++ b/MdePkg/Include/Library/BaseLib.h
@@ -6,6 +6,7 @@ Copyright (c) 2006 - 2021, Intel Corporation. All rights
reserved.<BR>
Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR>
Copyright (c) Microsoft Corporation.<BR>
Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All
rights reserved.<BR>
+Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All
rights reserved.<BR>

SPDX-License-Identifier: BSD-2-Clause-Patent

@@ -152,6 +153,29 @@ typedef struct {

#endif // defined (MDE_CPU_RISCV64)

+#if defined (MDE_CPU_LOONGARCH64)
+///
+/// The LoongArch architecture context buffer used by SetJump() and
LongJump()
+///
+typedef struct {
+ UINT64 S0;
+ UINT64 S1;
+ UINT64 S2;
+ UINT64 S3;
+ UINT64 S4;
+ UINT64 S5;
+ UINT64 S6;
+ UINT64 S7;
+ UINT64 S8;
+ UINT64 SP;
+ UINT64 FP;
+ UINT64 RA;
+} BASE_LIBRARY_JUMP_BUFFER;
+
+#define BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT 8
+
+#endif // defined (MDE_CPU_LOONGARCH64)
+
//
// String Services
//
diff --git a/MdePkg/Library/BaseLib/BaseLib.inf
b/MdePkg/Library/BaseLib/BaseLib.inf
index cebda3b210..4c9b6b50dd 100644
--- a/MdePkg/Library/BaseLib/BaseLib.inf
+++ b/MdePkg/Library/BaseLib/BaseLib.inf
@@ -409,6 +409,19 @@
RiscV64/RiscVInterrupt.S | GCC
RiscV64/FlushCache.S | GCC

+[Sources.LOONGARCH64]
+ Math64.c
+ LoongArch64/Unaligned.c
+ LoongArch64/InternalSwitchStack.c
+ LoongArch64/GetInterruptState.S | GCC
+ LoongArch64/EnableInterrupts.S | GCC
+ LoongArch64/DisableInterrupts.S | GCC
+ LoongArch64/MemoryFence.S | GCC
+ LoongArch64/CpuBreakpoint.S | GCC
+ LoongArch64/CpuPause.S | GCC
+ LoongArch64/SetJumpLongJump.S | GCC
+ LoongArch64/SwitchStack.S | GCC
+
[Packages]
MdePkg/MdePkg.dec

diff --git a/MdePkg/Library/BaseLib/LoongArch64/CpuBreakpoint.S
b/MdePkg/Library/BaseLib/LoongArch64/CpuBreakpoint.S
new file mode 100644
index 0000000000..4e022e9bb5
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/CpuBreakpoint.S
@@ -0,0 +1,24 @@
+#------------------------------------------------------------------------------
+#
+# CpuBreakpoint for LoongArch
+#
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+ASM_GLOBAL ASM_PFX(CpuBreakpoint)
+
+#/**
+# Generates a breakpoint on the CPU.
+#
+# Generates a breakpoint on the CPU. The breakpoint must be
implemented such
+# that code can resume normal execution after the breakpoint.
+#
+#**/
+
+ASM_PFX(CpuBreakpoint):
+ break 3
+ jirl $zero, $ra, 0
+ .end
diff --git a/MdePkg/Library/BaseLib/LoongArch64/CpuPause.S
b/MdePkg/Library/BaseLib/LoongArch64/CpuPause.S
new file mode 100644
index 0000000000..b98dd48f4d
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/CpuPause.S
@@ -0,0 +1,31 @@
+#------------------------------------------------------------------------------
+#
+# CpuPause for LoongArch
+#
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+ASM_GLOBAL ASM_PFX(CpuPause)
+
+#/**
+# Requests CPU to pause for a short period of time.
+#
+# Requests CPU to pause for a short period of time. Typically used in MP
+# systems to prevent memory starvation while waiting for a spin lock.
+#
+#**/
+
+ASM_PFX(CpuPause):
+ andi $zero, $zero, 0x0 //nop
+ andi $zero, $zero, 0x0 //nop
+ andi $zero, $zero, 0x0 //nop
+ andi $zero, $zero, 0x0 //nop
+ andi $zero, $zero, 0x0 //nop
+ andi $zero, $zero, 0x0 //nop
+ andi $zero, $zero, 0x0 //nop
+ andi $zero, $zero, 0x0 //nop
+ jirl $zero, $ra, 0
+ .end
diff --git a/MdePkg/Library/BaseLib/LoongArch64/DisableInterrupts.S
b/MdePkg/Library/BaseLib/LoongArch64/DisableInterrupts.S
new file mode 100644
index 0000000000..0f228339af
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/DisableInterrupts.S
@@ -0,0 +1,21 @@
+#------------------------------------------------------------------------------
+#
+# LoongArch interrupt disable
+#
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+ASM_GLOBAL ASM_PFX(DisableInterrupts)
+
+#/**
+# Disables CPU interrupts.
+#**/
+
+ASM_PFX(DisableInterrupts):
+ li.w $t0, 0x4
+ csrxchg $zero, $t0, 0x0
+ jirl $zero, $ra, 0
+ .end
diff --git a/MdePkg/Library/BaseLib/LoongArch64/EnableInterrupts.S
b/MdePkg/Library/BaseLib/LoongArch64/EnableInterrupts.S
new file mode 100644
index 0000000000..3c34fb2cdd
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/EnableInterrupts.S
@@ -0,0 +1,21 @@
+#------------------------------------------------------------------------------
+#
+# LoongArch interrupt enable
+#
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+ASM_GLOBAL ASM_PFX(EnableInterrupts)
+
+#/**
+# Enables CPU interrupts.
+#**/
+
+ASM_PFX(EnableInterrupts):
+ li.w $t0, 0x4
+ csrxchg $t0, $t0, 0x0
+ jirl $zero, $ra, 0
+ .end
diff --git a/MdePkg/Library/BaseLib/LoongArch64/GetInterruptState.S
b/MdePkg/Library/BaseLib/LoongArch64/GetInterruptState.S
new file mode 100644
index 0000000000..bfd1f2d5f7
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/GetInterruptState.S
@@ -0,0 +1,35 @@
+#------------------------------------------------------------------------------
+#
+# Get LoongArch interrupt status
+#
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+ASM_GLOBAL ASM_PFX(GetInterruptState)
+
+#/**
+# Retrieves the current CPU interrupt state.
+#
+# Returns TRUE means interrupts are currently enabled. Otherwise,
+# returns FALSE.
+#
+# @retval TRUE CPU interrupts are enabled.
+# @retval FALSE CPU interrupts are disabled.
+#
+#**/
+
+ASM_PFX(GetInterruptState):
+ li.w $t1, 0x4
+ csrrd $t0, 0x0
+ and $t0, $t0, $t1
+ beqz $t0, 1f
+ li.w $a0, 0x1
+ b 2f
+1:
+ li.w $a0, 0x0
+2:
+ jirl $zero, $ra, 0
+ .end
diff --git a/MdePkg/Library/BaseLib/LoongArch64/InternalSwitchStack.c
b/MdePkg/Library/BaseLib/LoongArch64/InternalSwitchStack.c
new file mode 100644
index 0000000000..1f1e43106f
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/InternalSwitchStack.c
@@ -0,0 +1,58 @@
+/** @file
+ SwitchStack() function for LoongArch.
+
+ Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include "BaseLibInternals.h"
+
+UINTN
+EFIAPI
+InternalSwitchStackAsm (
+ IN BASE_LIBRARY_JUMP_BUFFER *JumpBuffer
+ );
+
+/**
+ Transfers control to a function starting with a new stack.
+
+ Transfers control to the function specified by EntryPoint using the
+ new stack specified by NewStack and passing in the parameters specified
+ by Context1 and Context2. Context1 and Context2 are optional and may
+ be NULL. The function EntryPoint must never return.
+
+ If EntryPoint is NULL, then ASSERT().
+ If NewStack is NULL, then ASSERT().
+
+ @param EntryPoint A pointer to function to call with the new stack.
+ @param Context1 A pointer to the context to pass into the EntryPoint
+ function.
+ @param Context2 A pointer to the context to pass into the EntryPoint
+ function.
+ @param NewStack A pointer to the new stack to use for the EntryPoint
+ function.
+ @param Marker VA_LIST marker for the variable argument list.
+
+**/
+VOID
+EFIAPI
+InternalSwitchStack (
+ IN SWITCH_STACK_ENTRY_POINT EntryPoint,
+ IN VOID *Context1, OPTIONAL
+ IN VOID *Context2, OPTIONAL
+ IN VOID *NewStack,
+ IN VA_LIST Marker
+ )
+
+{
+ BASE_LIBRARY_JUMP_BUFFER JumpBuffer;
+
+ JumpBuffer.RA = (UINTN)EntryPoint;
+ JumpBuffer.SP = (UINTN)NewStack - sizeof (VOID*);
+ JumpBuffer.SP -= sizeof (Context1) + sizeof (Context2);
+ ((VOID **)(UINTN)JumpBuffer.SP)[0] = Context1;
+ ((VOID **)(UINTN)JumpBuffer.SP)[1] = Context2;
+
+ InternalSwitchStackAsm(&JumpBuffer);
+}
diff --git a/MdePkg/Library/BaseLib/LoongArch64/MemoryFence.S
b/MdePkg/Library/BaseLib/LoongArch64/MemoryFence.S
new file mode 100644
index 0000000000..0d8dc10914
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/MemoryFence.S
@@ -0,0 +1,19 @@
+#------------------------------------------------------------------------------
+#
+# MemoryFence() for LoongArch64
+#
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+ASM_GLOBAL ASM_PFX(MemoryFence)
+
+#
+# Memory fence for LoongArch64
+#
+ASM_PFX(MemoryFence):
+ dbar 0
+ jirl $zero, $ra, 0
+ .end
diff --git a/MdePkg/Library/BaseLib/LoongArch64/SetJumpLongJump.S
b/MdePkg/Library/BaseLib/LoongArch64/SetJumpLongJump.S
new file mode 100644
index 0000000000..35267c925f
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/SetJumpLongJump.S
@@ -0,0 +1,49 @@
+#------------------------------------------------------------------------------
+#
+# Set/Long jump for LoongArch
+#
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+#define STORE st.d /* 64 bit mode regsave instruction */
+#define LOAD ld.d /* 64 bit mode regload instruction */
+#define RSIZE 8 /* 64 bit mode register size */
+
+ASM_GLOBAL ASM_PFX(SetJump)
+ASM_GLOBAL ASM_PFX(InternalLongJump)
+
+ASM_PFX(SetJump):
+ STORE $s0, $a0, RSIZE * 0
+ STORE $s1, $a0, RSIZE * 1
+ STORE $s2, $a0, RSIZE * 2
+ STORE $s3, $a0, RSIZE * 3
+ STORE $s4, $a0, RSIZE * 4
+ STORE $s5, $a0, RSIZE * 5
+ STORE $s6, $a0, RSIZE * 6
+ STORE $s7, $a0, RSIZE * 7
+ STORE $s8, $a0, RSIZE * 8
+ STORE $sp, $a0, RSIZE * 9
+ STORE $fp, $a0, RSIZE * 10
+ STORE $ra, $a0, RSIZE * 11
+ li.w $a0, 0 # Setjmp return
+ jirl $zero, $ra, 0
+
+ASM_PFX(InternalLongJump):
+ LOAD $ra, $a0, RSIZE * 11
+ LOAD $s0, $a0, RSIZE * 0
+ LOAD $s1, $a0, RSIZE * 1
+ LOAD $s2, $a0, RSIZE * 2
+ LOAD $s3, $a0, RSIZE * 3
+ LOAD $s4, $a0, RSIZE * 4
+ LOAD $s5, $a0, RSIZE * 5
+ LOAD $s6, $a0, RSIZE * 6
+ LOAD $s7, $a0, RSIZE * 7
+ LOAD $s8, $a0, RSIZE * 8
+ LOAD $sp, $a0, RSIZE * 9
+ LOAD $fp, $a0, RSIZE * 10
+ move $a0, $a1
+ jirl $zero, $ra, 0
+ .end
diff --git a/MdePkg/Library/BaseLib/LoongArch64/SwitchStack.S
b/MdePkg/Library/BaseLib/LoongArch64/SwitchStack.S
new file mode 100644
index 0000000000..4facc76082
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/SwitchStack.S
@@ -0,0 +1,39 @@
+#------------------------------------------------------------------------------
+#
+# InternalSwitchStackAsm for LoongArch
+#
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#------------------------------------------------------------------------------
+
+#define STORE st.d /* 64 bit mode regsave instruction */
+#define LOAD ld.d /* 64 bit mode regload instruction */
+#define RSIZE 8 /* 64 bit mode register size */
+
+ASM_GLOBAL ASM_PFX(InternalSwitchStackAsm)
+
+/**
+ This allows the caller to switch the stack and goes to the new entry point
+
+ @param JumpBuffer A pointer to CPU context buffer.
+**/
+
+ASM_PFX(InternalSwitchStackAsm):
+ LOAD $ra, $a0, RSIZE * 11
+ LOAD $s0, $a0, RSIZE * 0
+ LOAD $s1, $a0, RSIZE * 1
+ LOAD $s2, $a0, RSIZE * 2
+ LOAD $s3, $a0, RSIZE * 3
+ LOAD $s4, $a0, RSIZE * 4
+ LOAD $s5, $a0, RSIZE * 5
+ LOAD $s6, $a0, RSIZE * 6
+ LOAD $s7, $a0, RSIZE * 7
+ LOAD $s8, $a0, RSIZE * 8
+ LOAD $sp, $a0, RSIZE * 9
+ LOAD $fp, $a0, RSIZE * 10
+ LOAD $a0, $sp, 0
+ LOAD $a1, $sp, 8
+ jirl $zero, $ra, 0
+ .end
diff --git a/MdePkg/Library/BaseLib/LoongArch64/Unaligned.c
b/MdePkg/Library/BaseLib/LoongArch64/Unaligned.c
new file mode 100644
index 0000000000..33fa3d2eed
--- /dev/null
+++ b/MdePkg/Library/BaseLib/LoongArch64/Unaligned.c
@@ -0,0 +1,244 @@
+/** @file
+ Unaligned access functions of BaseLib for LoongArch.
+
+ Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "BaseLibInternals.h"
+
+/**
+ Reads a 16-bit value from memory that may be unaligned.
+
+ This function returns the 16-bit value pointed to by Buffer. The function
+ guarantees that the read operation does not produce an alignment fault.
+
+ If the Buffer is NULL, then ASSERT().
+
+ @param Buffer The pointer to a 16-bit value that may be unaligned.
+
+ @return The 16-bit value read from Buffer.
+
+**/
+UINT16
+EFIAPI
+ReadUnaligned16 (
+ IN CONST UINT16 *Buffer
+ )
+{
+ volatile UINT8 LowerByte;
+ volatile UINT8 HigherByte;
+
+ ASSERT (Buffer != NULL);
+
+ LowerByte = ((UINT8*)Buffer)[0];
+ HigherByte = ((UINT8*)Buffer)[1];
+
+ return (UINT16)(LowerByte | (HigherByte << 8));
+}
+
+/**
+ Writes a 16-bit value to memory that may be unaligned.
+
+ This function writes the 16-bit value specified by Value to Buffer. Value is
+ returned. The function guarantees that the write operation does not
produce
+ an alignment fault.
+
+ If the Buffer is NULL, then ASSERT().
+
+ @param Buffer The pointer to a 16-bit value that may be unaligned.
+ @param Value 16-bit value to write to Buffer.
+
+ @return The 16-bit value to write to Buffer.
+
+**/
+UINT16
+EFIAPI
+WriteUnaligned16 (
+ OUT UINT16 *Buffer,
+ IN UINT16 Value
+ )
+{
+ ASSERT (Buffer != NULL);
+
+ ((volatile UINT8*)Buffer)[0] = (UINT8)Value;
+ ((volatile UINT8*)Buffer)[1] = (UINT8)(Value >> 8);
+
+ return Value;
+}
+
+/**
+ Reads a 24-bit value from memory that may be unaligned.
+
+ This function returns the 24-bit value pointed to by Buffer. The function
+ guarantees that the read operation does not produce an alignment fault.
+
+ If the Buffer is NULL, then ASSERT().
+
+ @param Buffer The pointer to a 24-bit value that may be unaligned.
+
+ @return The 24-bit value read from Buffer.
+
+**/
+UINT32
+EFIAPI
+ReadUnaligned24 (
+ IN CONST UINT32 *Buffer
+ )
+{
+ ASSERT (Buffer != NULL);
+
+ return (UINT32)(
+ ReadUnaligned16 ((UINT16*)Buffer) |
+ (((UINT8*)Buffer)[2] << 16)
+ );
+}
+
+/**
+ Writes a 24-bit value to memory that may be unaligned.
+
+ This function writes the 24-bit value specified by Value to Buffer. Value is
+ returned. The function guarantees that the write operation does not
produce
+ an alignment fault.
+
+ If the Buffer is NULL, then ASSERT().
+
+ @param Buffer The pointer to a 24-bit value that may be unaligned.
+ @param Value 24-bit value to write to Buffer.
+
+ @return The 24-bit value to write to Buffer.
+
+**/
+UINT32
+EFIAPI
+WriteUnaligned24 (
+ OUT UINT32 *Buffer,
+ IN UINT32 Value
+ )
+{
+ ASSERT (Buffer != NULL);
+
+ WriteUnaligned16 ((UINT16*)Buffer, (UINT16)Value);
+ *(UINT8*)((UINT16*)Buffer + 1) = (UINT8)(Value >> 16);
+ return Value;
+}
+
+/**
+ Reads a 32-bit value from memory that may be unaligned.
+
+ This function returns the 32-bit value pointed to by Buffer. The function
+ guarantees that the read operation does not produce an alignment fault.
+
+ If the Buffer is NULL, then ASSERT().
+
+ @param Buffer The pointer to a 32-bit value that may be unaligned.
+
+ @return The 32-bit value read from Buffer.
+
+**/
+UINT32
+EFIAPI
+ReadUnaligned32 (
+ IN CONST UINT32 *Buffer
+ )
+{
+ UINT16 LowerBytes;
+ UINT16 HigherBytes;
+
+ ASSERT (Buffer != NULL);
+
+ LowerBytes = ReadUnaligned16 ((UINT16*) Buffer);
+ HigherBytes = ReadUnaligned16 ((UINT16*) Buffer + 1);
+
+ return (UINT32) (LowerBytes | (HigherBytes << 16));
+}
+
+/**
+ Writes a 32-bit value to memory that may be unaligned.
+
+ This function writes the 32-bit value specified by Value to Buffer. Value is
+ returned. The function guarantees that the write operation does not
produce
+ an alignment fault.
+
+ If the Buffer is NULL, then ASSERT().
+
+ @param Buffer The pointer to a 32-bit value that may be unaligned.
+ @param Value 32-bit value to write to Buffer.
+
+ @return The 32-bit value to write to Buffer.
+
+**/
+UINT32
+EFIAPI
+WriteUnaligned32 (
+ OUT UINT32 *Buffer,
+ IN UINT32 Value
+ )
+{
+ ASSERT (Buffer != NULL);
+
+ WriteUnaligned16 ((UINT16*)Buffer, (UINT16)Value);
+ WriteUnaligned16 ((UINT16*)Buffer + 1, (UINT16)(Value >> 16));
+ return Value;
+}
+
+/**
+ Reads a 64-bit value from memory that may be unaligned.
+
+ This function returns the 64-bit value pointed to by Buffer. The function
+ guarantees that the read operation does not produce an alignment fault.
+
+ If the Buffer is NULL, then ASSERT().
+
+ @param Buffer The pointer to a 64-bit value that may be unaligned.
+
+ @return The 64-bit value read from Buffer.
+
+**/
+UINT64
+EFIAPI
+ReadUnaligned64 (
+ IN CONST UINT64 *Buffer
+ )
+{
+ UINT32 LowerBytes;
+ UINT32 HigherBytes;
+
+ ASSERT (Buffer != NULL);
+
+ LowerBytes = ReadUnaligned32 ((UINT32*) Buffer);
+ HigherBytes = ReadUnaligned32 ((UINT32*) Buffer + 1);
+
+ return (UINT64) (LowerBytes | LShiftU64 (HigherBytes, 32));
+}
+
+/**
+ Writes a 64-bit value to memory that may be unaligned.
+
+ This function writes the 64-bit value specified by Value to Buffer. Value is
+ returned. The function guarantees that the write operation does not
produce
+ an alignment fault.
+
+ If the Buffer is NULL, then ASSERT().
+
+ @param Buffer The pointer to a 64-bit value that may be unaligned.
+ @param Value 64-bit value to write to Buffer.
+
+ @return The 64-bit value to write to Buffer.
+
+**/
+UINT64
+EFIAPI
+WriteUnaligned64 (
+ OUT UINT64 *Buffer,
+ IN UINT64 Value
+ )
+{
+ ASSERT (Buffer != NULL);
+
+ WriteUnaligned32 ((UINT32*)Buffer, (UINT32)Value);
+ WriteUnaligned32 ((UINT32*)Buffer + 1, (UINT32)RShiftU64 (Value, 32));
+ return Value;
+}
--
2.27.0





Re: [staging/LoongArch RESEND PATCH v1 16/33] BaseTools: Enable LoongArch64 architecture for LoongArch64 EDK2 CI.

Abner Chang
 

Acked-by: Abner Chang <abner.chang@...>

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Chao Li
Sent: Wednesday, February 9, 2022 2:55 PM
To: devel@edk2.groups.io
Cc: Bob Feng <bob.c.feng@...>; Liming Gao
<gaoliming@...>; Yuwei Chen <yuwei.chen@...>
Subject: [edk2-devel] [staging/LoongArch RESEND PATCH v1 16/33]
BaseTools: Enable LoongArch64 architecture for LoongArch64 EDK2 CI.

EDK CI for LoongArch64 architecture

Enable LoongArch64 architecture for LoongArch64 EDK2 CI testing.

Cc: Bob Feng <bob.c.feng@...>
Cc: Liming Gao <gaoliming@...>
Cc: Yuwei Chen <yuwei.chen@...>

Signed-off-by: Chao Li <lichao@...>
---
...gcc_loongarch64_unknown_linux_ext_dep.yaml | 22 +++++++++++++
.../LinuxGcc5ToolChain/LinuxGcc5ToolChain.py | 31
+++++++++++++++++++
2 files changed, 53 insertions(+)
create mode 100644
BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml

diff --git a/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml
b/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml
new file mode 100644
index 0000000000..6bdd7388f8
--- /dev/null
+++ b/BaseTools/Bin/gcc_loongarch64_unknown_linux_ext_dep.yaml
@@ -0,0 +1,22 @@
+## @file
+# Download GCC LoongArch64 compiler from LoongArch GitHub release site
+# Set shell variable GCC5_LOONGARCH64_INSTALL to this folder
+#
+# This is only downloaded when a build activates scope
gcc_loongarch64_unknown_linux
+#
+# Copyright (c) Microsoft Corporation.
+# Copyright (c) 2022 Loongson Technology Corporation Limited. All rights
reserved.<BR>
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+##
+{
+ "scope": "gcc_loongarch64_unknown_linux",
+ "type": "web",
+ "name": "gcc_loongarch64_unknown_linux",
+ "source": "https://github.com/loongson/build-
tools/releases/download/2021.12.21/loongarch64-clfs-2021-12-18-cross-
tools-gcc-full.tar.xz",
+ "version": "12.0.0 20210810",
+ "sha256":
"07f4e93423e76c57c775390099c76273b67cde2e441ed78192a2f4da9168c65a",
+ "compression_type": "tar",
+ "internal_path": "/cross-tools/",
+ "flags": ["set_shell_var", ],
+ "var_name": "GCC5_LOONGARCH64_INSTALL"
+}
diff --git a/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py
b/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py
index f0685d8040..5615f8bb35 100644
--- a/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py
+++ b/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py
@@ -5,6 +5,7 @@
#
# Copyright (c) Microsoft Corporation
# Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights
reserved.<BR>
+# Copyright (c) 2022 Loongson Technology Corporation Limited. All rights
reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
import os
@@ -43,6 +44,12 @@ class LinuxGcc5ToolChain(IUefiBuildPlugin):
self.Logger.critical("Failed in check riscv64")
return ret

+ # Check LoongArch64 compiler
+ ret = self._check_loongarch64()
+ if ret != 0:
+ self.Logger.critical("Failed in check loongarch64")
+ return ret
+
return 0

def _check_arm(self):
@@ -121,3 +128,27 @@ class LinuxGcc5ToolChain(IUefiBuildPlugin):

shell_environment.GetEnvironment().set_shell_var("LD_LIBRARY_PATH",
prefix)

return 0
+
+ def _check_loongarch64(self):
+ # check to see if full path already configured
+ if
shell_environment.GetEnvironment().get_shell_var("GCC5_LOONGARCH64
_PREFIX") is not None:
+ self.Logger.info("GCC5_LOONGARCH64_PREFIX is already set.")
+
+ else:
+ # now check for install dir. If set then set the Prefix
+ install_path = shell_environment.GetEnvironment(
+ ).get_shell_var("GCC5_LOONGARCH64_INSTALL")
+ if install_path is None:
+ return 0
+
+ # make GCC5_AARCH64_PREFIX to align with tools_def.txt
+ prefix = os.path.join(install_path, "bin", "loongarch64-unknown-linux-
gnu-")
+
shell_environment.GetEnvironment().set_shell_var("GCC5_LOONGARCH64
_PREFIX", prefix)
+
+ # now confirm it exists
+ if not
os.path.exists(shell_environment.GetEnvironment().get_shell_var("GCC5_L
OONGARCH64_PREFIX") + "gcc"):
+ self.Logger.error(
+ "Path for GCC5_LOONGARCH64_PREFIX toolchain is invalid")
+ return -2
+
+ return 0
--
2.27.0





Re: [staging/LoongArch RESEND PATCH v1 15/33] BaseTools: BaseTools changes for LoongArch platform.

Abner Chang
 

Acked-by: Abner Chang <abner.chang@...>

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Chao Li
Sent: Wednesday, February 9, 2022 2:55 PM
To: devel@edk2.groups.io
Cc: Bob Feng <bob.c.feng@...>; Liming Gao
<gaoliming@...>; Yuwei Chen <yuwei.chen@...>; Baoqi
Zhang <zhangbaoqi@...>
Subject: [edk2-devel] [staging/LoongArch RESEND PATCH v1 15/33]
BaseTools: BaseTools changes for LoongArch platform.

Python code changes for building EDK2 LoongArch platform.

Cc: Bob Feng <bob.c.feng@...>
Cc: Liming Gao <gaoliming@...>
Cc: Yuwei Chen <yuwei.chen@...>

Signed-off-by: Chao Li <lichao@...>
Co-authored-by: Baoqi Zhang <zhangbaoqi@...>
---
BaseTools/Source/Python/Common/DataType.py | 21 ++++++++++++++--
.../Source/Python/UPT/Library/DataType.py | 24 ++++++++++++++++++-
BaseTools/Source/Python/build/buildoptions.py | 3 ++-
3 files changed, 44 insertions(+), 4 deletions(-)

diff --git a/BaseTools/Source/Python/Common/DataType.py
b/BaseTools/Source/Python/Common/DataType.py
index dc49623333..48dbf16495 100644
--- a/BaseTools/Source/Python/Common/DataType.py
+++ b/BaseTools/Source/Python/Common/DataType.py
@@ -4,6 +4,7 @@
# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
# Portions copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.<BR>
# Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP.
All rights reserved.<BR>
+# Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All
rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent

##
@@ -52,10 +53,10 @@ TAB_ARCH_X64 = 'X64'
TAB_ARCH_ARM = 'ARM'
TAB_ARCH_EBC = 'EBC'
TAB_ARCH_AARCH64 = 'AARCH64'
-
TAB_ARCH_RISCV64 = 'RISCV64'
+TAB_ARCH_LOONGARCH64 = 'LOONGARCH64'

-ARCH_SET_FULL = {TAB_ARCH_IA32, TAB_ARCH_X64, TAB_ARCH_ARM,
TAB_ARCH_EBC, TAB_ARCH_AARCH64, TAB_ARCH_RISCV64,
TAB_ARCH_COMMON}
+ARCH_SET_FULL = {TAB_ARCH_IA32, TAB_ARCH_X64, TAB_ARCH_ARM,
TAB_ARCH_EBC, TAB_ARCH_AARCH64, TAB_ARCH_RISCV64,
TAB_ARCH_LOONGARCH64, TAB_ARCH_COMMON}

SUP_MODULE_BASE = 'BASE'
SUP_MODULE_SEC = 'SEC'
@@ -138,6 +139,7 @@ TAB_SOURCES_X64 = TAB_SOURCES + TAB_SPLIT +
TAB_ARCH_X64
TAB_SOURCES_ARM = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_ARM
TAB_SOURCES_EBC = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_EBC
TAB_SOURCES_AARCH64 = TAB_SOURCES + TAB_SPLIT +
TAB_ARCH_AARCH64
+TAB_SOURCES_LOONGARCH64 = TAB_SOURCES + TAB_SPLIT +
TAB_ARCH_LOONGARCH64

TAB_BINARIES = 'Binaries'
TAB_BINARIES_COMMON = TAB_BINARIES + TAB_SPLIT +
TAB_ARCH_COMMON
@@ -146,6 +148,7 @@ TAB_BINARIES_X64 = TAB_BINARIES + TAB_SPLIT +
TAB_ARCH_X64
TAB_BINARIES_ARM = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_ARM
TAB_BINARIES_EBC = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_EBC
TAB_BINARIES_AARCH64 = TAB_BINARIES + TAB_SPLIT +
TAB_ARCH_AARCH64
+TAB_BINARIES_LOONGARCH64 = TAB_BINARIES + TAB_SPLIT +
TAB_ARCH_LOONGARCH64

TAB_INCLUDES = 'Includes'
TAB_INCLUDES_COMMON = TAB_INCLUDES + TAB_SPLIT +
TAB_ARCH_COMMON
@@ -154,6 +157,7 @@ TAB_INCLUDES_X64 = TAB_INCLUDES + TAB_SPLIT +
TAB_ARCH_X64
TAB_INCLUDES_ARM = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_ARM
TAB_INCLUDES_EBC = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_EBC
TAB_INCLUDES_AARCH64 = TAB_INCLUDES + TAB_SPLIT +
TAB_ARCH_AARCH64
+TAB_INCLUDES_LOONGARCH64 = TAB_INCLUDES + TAB_SPLIT +
TAB_ARCH_LOONGARCH64

TAB_GUIDS = 'Guids'
TAB_GUIDS_COMMON = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_COMMON
@@ -162,6 +166,7 @@ TAB_GUIDS_X64 = TAB_GUIDS + TAB_SPLIT +
TAB_ARCH_X64
TAB_GUIDS_ARM = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_ARM
TAB_GUIDS_EBC = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_EBC
TAB_GUIDS_AARCH64 = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_AARCH64
+TAB_GUIDS_LOONGARCH64 = TAB_GUIDS + TAB_SPLIT +
TAB_ARCH_LOONGARCH64

TAB_PROTOCOLS = 'Protocols'
TAB_PROTOCOLS_COMMON = TAB_PROTOCOLS + TAB_SPLIT +
TAB_ARCH_COMMON
@@ -170,6 +175,7 @@ TAB_PROTOCOLS_X64 = TAB_PROTOCOLS +
TAB_SPLIT + TAB_ARCH_X64
TAB_PROTOCOLS_ARM = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_ARM
TAB_PROTOCOLS_EBC = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_EBC
TAB_PROTOCOLS_AARCH64 = TAB_PROTOCOLS + TAB_SPLIT +
TAB_ARCH_AARCH64
+TAB_PROTOCOLS_LOONGARCH64 = TAB_PROTOCOLS + TAB_SPLIT +
TAB_ARCH_LOONGARCH64

TAB_PPIS = 'Ppis'
TAB_PPIS_COMMON = TAB_PPIS + TAB_SPLIT + TAB_ARCH_COMMON
@@ -178,6 +184,7 @@ TAB_PPIS_X64 = TAB_PPIS + TAB_SPLIT +
TAB_ARCH_X64
TAB_PPIS_ARM = TAB_PPIS + TAB_SPLIT + TAB_ARCH_ARM
TAB_PPIS_EBC = TAB_PPIS + TAB_SPLIT + TAB_ARCH_EBC
TAB_PPIS_AARCH64 = TAB_PPIS + TAB_SPLIT + TAB_ARCH_AARCH64
+TAB_PPIS_LOONGARCH64 = TAB_PPIS + TAB_SPLIT +
TAB_ARCH_LOONGARCH64

TAB_LIBRARY_CLASSES = 'LibraryClasses'
TAB_LIBRARY_CLASSES_COMMON = TAB_LIBRARY_CLASSES + TAB_SPLIT +
TAB_ARCH_COMMON
@@ -186,6 +193,7 @@ TAB_LIBRARY_CLASSES_X64 = TAB_LIBRARY_CLASSES
+ TAB_SPLIT + TAB_ARCH_X64
TAB_LIBRARY_CLASSES_ARM = TAB_LIBRARY_CLASSES + TAB_SPLIT +
TAB_ARCH_ARM
TAB_LIBRARY_CLASSES_EBC = TAB_LIBRARY_CLASSES + TAB_SPLIT +
TAB_ARCH_EBC
TAB_LIBRARY_CLASSES_AARCH64 = TAB_LIBRARY_CLASSES + TAB_SPLIT +
TAB_ARCH_AARCH64
+TAB_LIBRARY_CLASSES_LOONGARCH64 = TAB_LIBRARY_CLASSES +
TAB_SPLIT + TAB_ARCH_LOONGARCH64

TAB_PACKAGES = 'Packages'
TAB_PACKAGES_COMMON = TAB_PACKAGES + TAB_SPLIT +
TAB_ARCH_COMMON
@@ -194,6 +202,7 @@ TAB_PACKAGES_X64 = TAB_PACKAGES + TAB_SPLIT +
TAB_ARCH_X64
TAB_PACKAGES_ARM = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_ARM
TAB_PACKAGES_EBC = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_EBC
TAB_PACKAGES_AARCH64 = TAB_PACKAGES + TAB_SPLIT +
TAB_ARCH_AARCH64
+TAB_PACKAGES_LOONGARCH64 = TAB_PACKAGES + TAB_SPLIT +
TAB_ARCH_LOONGARCH64

TAB_PCDS = 'Pcds'
TAB_PCDS_FIXED_AT_BUILD = 'FixedAtBuild'
@@ -221,6 +230,7 @@ TAB_PCDS_FIXED_AT_BUILD_X64 = TAB_PCDS +
TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + T
TAB_PCDS_FIXED_AT_BUILD_ARM = TAB_PCDS +
TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_ARM
TAB_PCDS_FIXED_AT_BUILD_EBC = TAB_PCDS +
TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_EBC
TAB_PCDS_FIXED_AT_BUILD_AARCH64 = TAB_PCDS +
TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_AARCH64
+TAB_PCDS_FIXED_AT_BUILD_LOONGARCH64 = TAB_PCDS +
TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_LOONGARCH64

TAB_PCDS_PATCHABLE_IN_MODULE_NULL = TAB_PCDS +
TAB_PCDS_PATCHABLE_IN_MODULE
TAB_PCDS_PATCHABLE_IN_MODULE_COMMON = TAB_PCDS +
TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_COMMON
@@ -229,6 +239,7 @@ TAB_PCDS_PATCHABLE_IN_MODULE_X64 =
TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + TAB
TAB_PCDS_PATCHABLE_IN_MODULE_ARM = TAB_PCDS +
TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_ARM
TAB_PCDS_PATCHABLE_IN_MODULE_EBC = TAB_PCDS +
TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_EBC
TAB_PCDS_PATCHABLE_IN_MODULE_AARCH64 = TAB_PCDS +
TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_AARCH64
+TAB_PCDS_PATCHABLE_IN_MODULE_LOONGARCH64 = TAB_PCDS +
TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT +
TAB_ARCH_LOONGARCH64

TAB_PCDS_FEATURE_FLAG_NULL = TAB_PCDS + TAB_PCDS_FEATURE_FLAG
TAB_PCDS_FEATURE_FLAG_COMMON = TAB_PCDS +
TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_COMMON
@@ -237,6 +248,7 @@ TAB_PCDS_FEATURE_FLAG_X64 = TAB_PCDS +
TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_A
TAB_PCDS_FEATURE_FLAG_ARM = TAB_PCDS + TAB_PCDS_FEATURE_FLAG
+ TAB_SPLIT + TAB_ARCH_ARM
TAB_PCDS_FEATURE_FLAG_EBC = TAB_PCDS + TAB_PCDS_FEATURE_FLAG
+ TAB_SPLIT + TAB_ARCH_EBC
TAB_PCDS_FEATURE_FLAG_AARCH64 = TAB_PCDS +
TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_AARCH64
+TAB_PCDS_FEATURE_FLAG_LOONGARCH64 = TAB_PCDS +
TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_LOONGARCH64

TAB_PCDS_DYNAMIC_EX_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC_EX
TAB_PCDS_DYNAMIC_EX_DEFAULT_NULL = TAB_PCDS +
TAB_PCDS_DYNAMIC_EX_DEFAULT
@@ -248,6 +260,7 @@ TAB_PCDS_DYNAMIC_EX_X64 = TAB_PCDS +
TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + TAB_ARCH_
TAB_PCDS_DYNAMIC_EX_ARM = TAB_PCDS + TAB_PCDS_DYNAMIC_EX +
TAB_SPLIT + TAB_ARCH_ARM
TAB_PCDS_DYNAMIC_EX_EBC = TAB_PCDS + TAB_PCDS_DYNAMIC_EX +
TAB_SPLIT + TAB_ARCH_EBC
TAB_PCDS_DYNAMIC_EX_AARCH64 = TAB_PCDS + TAB_PCDS_DYNAMIC_EX
+ TAB_SPLIT + TAB_ARCH_AARCH64
+TAB_PCDS_DYNAMIC_EX_LOONGARCH64 = TAB_PCDS +
TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + TAB_ARCH_LOONGARCH64

TAB_PCDS_DYNAMIC_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC
TAB_PCDS_DYNAMIC_DEFAULT_NULL = TAB_PCDS +
TAB_PCDS_DYNAMIC_DEFAULT
@@ -259,6 +272,7 @@ TAB_PCDS_DYNAMIC_X64 = TAB_PCDS +
TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_X64
TAB_PCDS_DYNAMIC_ARM = TAB_PCDS + TAB_PCDS_DYNAMIC +
TAB_SPLIT + TAB_ARCH_ARM
TAB_PCDS_DYNAMIC_EBC = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT
+ TAB_ARCH_EBC
TAB_PCDS_DYNAMIC_AARCH64 = TAB_PCDS + TAB_PCDS_DYNAMIC +
TAB_SPLIT + TAB_ARCH_AARCH64
+TAB_PCDS_DYNAMIC_LOONGARCH64 = TAB_PCDS + TAB_PCDS_DYNAMIC
+ TAB_SPLIT + TAB_ARCH_LOONGARCH64

TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE =
'PcdLoadFixAddressPeiCodePageNumber'
TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_PEI_PAGE_SIZE_DATA_TYPE
= 'UINT32'
@@ -285,6 +299,7 @@ TAB_DEPEX_X64 = TAB_DEPEX + TAB_SPLIT +
TAB_ARCH_X64
TAB_DEPEX_ARM = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_ARM
TAB_DEPEX_EBC = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_EBC
TAB_DEPEX_AARCH64 = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_AARCH64
+TAB_DEPEX_LOONGARCH64 = TAB_DEPEX + TAB_SPLIT +
TAB_ARCH_LOONGARCH64

TAB_SKUIDS = 'SkuIds'
TAB_DEFAULT_STORES = 'DefaultStores'
@@ -297,6 +312,7 @@ TAB_LIBRARIES_X64 = TAB_LIBRARIES + TAB_SPLIT +
TAB_ARCH_X64
TAB_LIBRARIES_ARM = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_ARM
TAB_LIBRARIES_EBC = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_EBC
TAB_LIBRARIES_AARCH64 = TAB_LIBRARIES + TAB_SPLIT +
TAB_ARCH_AARCH64
+TAB_LIBRARIES_LOONGARCH64 = TAB_LIBRARIES + TAB_SPLIT +
TAB_ARCH_LOONGARCH64

TAB_COMPONENTS = 'Components'
TAB_COMPONENTS_COMMON = TAB_COMPONENTS + TAB_SPLIT +
TAB_ARCH_COMMON
@@ -305,6 +321,7 @@ TAB_COMPONENTS_X64 = TAB_COMPONENTS +
TAB_SPLIT + TAB_ARCH_X64
TAB_COMPONENTS_ARM = TAB_COMPONENTS + TAB_SPLIT +
TAB_ARCH_ARM
TAB_COMPONENTS_EBC = TAB_COMPONENTS + TAB_SPLIT +
TAB_ARCH_EBC
TAB_COMPONENTS_AARCH64 = TAB_COMPONENTS + TAB_SPLIT +
TAB_ARCH_AARCH64
+TAB_COMPONENTS_LOONGARCH64 = TAB_COMPONENTS + TAB_SPLIT +
TAB_ARCH_LOONGARCH64

TAB_BUILD_OPTIONS = 'BuildOptions'

diff --git a/BaseTools/Source/Python/UPT/Library/DataType.py
b/BaseTools/Source/Python/UPT/Library/DataType.py
index bd216786a5..2bd31f09a2 100644
--- a/BaseTools/Source/Python/UPT/Library/DataType.py
+++ b/BaseTools/Source/Python/UPT/Library/DataType.py
@@ -2,6 +2,7 @@
# This file is used to define class for data type structure
#
# Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR>
+# Portions Copyright (c) 2022 Loongson Technology Corporation Limited. All
rights reserved.
#
# SPDX-License-Identifier: BSD-2-Clause-Patent

@@ -367,10 +368,11 @@ TAB_ARCH_IA32 = 'IA32'
TAB_ARCH_X64 = 'X64'
TAB_ARCH_IPF = 'IPF'
TAB_ARCH_ARM = 'ARM'
+TAB_ARCH_LOONGARCH64 = 'LOONGARCH64'
TAB_ARCH_EBC = 'EBC'

ARCH_LIST = \
-[TAB_ARCH_IA32, TAB_ARCH_X64, TAB_ARCH_IPF, TAB_ARCH_ARM,
TAB_ARCH_EBC]
+[TAB_ARCH_IA32, TAB_ARCH_X64, TAB_ARCH_IPF, TAB_ARCH_ARM,
TAB_ARCH_LOONGARCH64, TAB_ARCH_EBC]

SUP_MODULE_BASE = 'BASE'
SUP_MODULE_SEC = 'SEC'
@@ -454,6 +456,7 @@ TAB_SOURCES_IA32 = TAB_SOURCES + TAB_SPLIT +
TAB_ARCH_IA32
TAB_SOURCES_X64 = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_X64
TAB_SOURCES_IPF = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_IPF
TAB_SOURCES_ARM = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_ARM
+TAB_SOURCES_LOONGARCH64 = TAB_SOURCES + TAB_SPLIT +
TAB_ARCH_LOONGARCH64
TAB_SOURCES_EBC = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_EBC

TAB_BINARIES = 'Binaries'
@@ -462,6 +465,7 @@ TAB_BINARIES_IA32 = TAB_BINARIES + TAB_SPLIT +
TAB_ARCH_IA32
TAB_BINARIES_X64 = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_X64
TAB_BINARIES_IPF = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_IPF
TAB_BINARIES_ARM = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_ARM
+TAB_BINARIES_LOONGARCH64 = TAB_BINARIES + TAB_SPLIT +
TAB_ARCH_LOONGARCH64
TAB_BINARIES_EBC = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_EBC

TAB_INCLUDES = 'Includes'
@@ -470,6 +474,7 @@ TAB_INCLUDES_IA32 = TAB_INCLUDES + TAB_SPLIT +
TAB_ARCH_IA32
TAB_INCLUDES_X64 = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_X64
TAB_INCLUDES_IPF = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_IPF
TAB_INCLUDES_ARM = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_ARM
+TAB_INCLUDES_LOONGARCH64 = TAB_INCLUDES + TAB_SPLIT +
TAB_ARCH_LOONGARCH64
TAB_INCLUDES_EBC = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_EBC

TAB_GUIDS = 'Guids'
@@ -478,6 +483,7 @@ TAB_GUIDS_IA32 = TAB_GUIDS + TAB_SPLIT +
TAB_ARCH_IA32
TAB_GUIDS_X64 = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_X64
TAB_GUIDS_IPF = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_IPF
TAB_GUIDS_ARM = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_ARM
+TAB_GUIDS_LOONGARCH64 = TAB_GUIDS + TAB_SPLIT +
TAB_ARCH_LOONGARCH64
TAB_GUIDS_EBC = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_EBC

TAB_PROTOCOLS = 'Protocols'
@@ -486,6 +492,7 @@ TAB_PROTOCOLS_IA32 = TAB_PROTOCOLS +
TAB_SPLIT + TAB_ARCH_IA32
TAB_PROTOCOLS_X64 = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_X64
TAB_PROTOCOLS_IPF = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_IPF
TAB_PROTOCOLS_ARM = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_ARM
+TAB_PROTOCOLS_LOONGARCH64 = TAB_PROTOCOLS + TAB_SPLIT +
TAB_ARCH_LOONGARCH64
TAB_PROTOCOLS_EBC = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_EBC

TAB_PPIS = 'Ppis'
@@ -494,6 +501,7 @@ TAB_PPIS_IA32 = TAB_PPIS + TAB_SPLIT +
TAB_ARCH_IA32
TAB_PPIS_X64 = TAB_PPIS + TAB_SPLIT + TAB_ARCH_X64
TAB_PPIS_IPF = TAB_PPIS + TAB_SPLIT + TAB_ARCH_IPF
TAB_PPIS_ARM = TAB_PPIS + TAB_SPLIT + TAB_ARCH_ARM
+TAB_PPIS_LOONGARCH64 = TAB_PPIS + TAB_SPLIT +
TAB_ARCH_LOONGARCH64
TAB_PPIS_EBC = TAB_PPIS + TAB_SPLIT + TAB_ARCH_EBC

TAB_LIBRARY_CLASSES = 'LibraryClasses'
@@ -502,6 +510,7 @@ TAB_LIBRARY_CLASSES_IA32 =
TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_IA32
TAB_LIBRARY_CLASSES_X64 = TAB_LIBRARY_CLASSES + TAB_SPLIT +
TAB_ARCH_X64
TAB_LIBRARY_CLASSES_IPF = TAB_LIBRARY_CLASSES + TAB_SPLIT +
TAB_ARCH_IPF
TAB_LIBRARY_CLASSES_ARM = TAB_LIBRARY_CLASSES + TAB_SPLIT +
TAB_ARCH_ARM
+TAB_LIBRARY_CLASSES_LOONGARCH64 = TAB_LIBRARY_CLASSES +
TAB_SPLIT + TAB_ARCH_LOONGARCH64
TAB_LIBRARY_CLASSES_EBC = TAB_LIBRARY_CLASSES + TAB_SPLIT +
TAB_ARCH_EBC

TAB_PACKAGES = 'Packages'
@@ -510,6 +519,7 @@ TAB_PACKAGES_IA32 = TAB_PACKAGES + TAB_SPLIT
+ TAB_ARCH_IA32
TAB_PACKAGES_X64 = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_X64
TAB_PACKAGES_IPF = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_IPF
TAB_PACKAGES_ARM = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_ARM
+TAB_PACKAGES_LOONGARCH64 = TAB_PACKAGES + TAB_SPLIT +
TAB_ARCH_LOONGARCH64
TAB_PACKAGES_EBC = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_EBC

TAB_PCDS = 'Pcds'
@@ -548,6 +558,8 @@ TAB_PCDS_FIXED_AT_BUILD_IPF = TAB_PCDS +
TAB_PCDS_FIXED_AT_BUILD + \
TAB_SPLIT + TAB_ARCH_IPF
TAB_PCDS_FIXED_AT_BUILD_ARM = TAB_PCDS +
TAB_PCDS_FIXED_AT_BUILD + \
TAB_SPLIT + TAB_ARCH_ARM
+TAB_PCDS_FIXED_AT_BUILD_LOONGARCH64 = TAB_PCDS +
TAB_PCDS_FIXED_AT_BUILD + \
+TAB_SPLIT + TAB_ARCH_LOONGARCH64
TAB_PCDS_FIXED_AT_BUILD_EBC = TAB_PCDS +
TAB_PCDS_FIXED_AT_BUILD + \
TAB_SPLIT + TAB_ARCH_EBC

@@ -562,6 +574,8 @@ TAB_PCDS_PATCHABLE_IN_MODULE_IPF =
TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + \
TAB_SPLIT + TAB_ARCH_IPF
TAB_PCDS_PATCHABLE_IN_MODULE_ARM = TAB_PCDS +
TAB_PCDS_PATCHABLE_IN_MODULE + \
TAB_SPLIT + TAB_ARCH_ARM
+TAB_PCDS_PATCHABLE_IN_MODULE_LOONGARCH64 = TAB_PCDS +
TAB_PCDS_PATCHABLE_IN_MODULE + \
+TAB_SPLIT + TAB_ARCH_LOONGARCH64
TAB_PCDS_PATCHABLE_IN_MODULE_EBC = TAB_PCDS +
TAB_PCDS_PATCHABLE_IN_MODULE + \
TAB_SPLIT + TAB_ARCH_EBC

@@ -576,6 +590,8 @@ TAB_PCDS_FEATURE_FLAG_IPF = TAB_PCDS +
TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + \
TAB_ARCH_IPF
TAB_PCDS_FEATURE_FLAG_ARM = TAB_PCDS + TAB_PCDS_FEATURE_FLAG
+ TAB_SPLIT + \
TAB_ARCH_ARM
+TAB_PCDS_FEATURE_FLAG_LOONGARCH64 = TAB_PCDS +
TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + \
+TAB_ARCH_LOONGARCH64
TAB_PCDS_FEATURE_FLAG_EBC = TAB_PCDS + TAB_PCDS_FEATURE_FLAG
+ TAB_SPLIT + \
TAB_ARCH_EBC

@@ -593,6 +609,8 @@ TAB_PCDS_DYNAMIC_EX_IPF = TAB_PCDS +
TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + \
TAB_ARCH_IPF
TAB_PCDS_DYNAMIC_EX_ARM = TAB_PCDS + TAB_PCDS_DYNAMIC_EX +
TAB_SPLIT + \
TAB_ARCH_ARM
+TAB_PCDS_DYNAMIC_EX_LOONGARCH64 = TAB_PCDS +
TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + \
+TAB_ARCH_LOONGARCH64
TAB_PCDS_DYNAMIC_EX_EBC = TAB_PCDS + TAB_PCDS_DYNAMIC_EX +
TAB_SPLIT + \
TAB_ARCH_EBC

@@ -606,6 +624,7 @@ TAB_PCDS_DYNAMIC_IA32 = TAB_PCDS +
TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_IA32
TAB_PCDS_DYNAMIC_X64 = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT
+ TAB_ARCH_X64
TAB_PCDS_DYNAMIC_IPF = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT
+ TAB_ARCH_IPF
TAB_PCDS_DYNAMIC_ARM = TAB_PCDS + TAB_PCDS_DYNAMIC +
TAB_SPLIT + TAB_ARCH_ARM
+TAB_PCDS_DYNAMIC_LOONGARCH64 = TAB_PCDS + TAB_PCDS_DYNAMIC
+ TAB_SPLIT + TAB_ARCH_LOONGARCH64
TAB_PCDS_DYNAMIC_EBC = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT
+ TAB_ARCH_EBC

TAB_PCD_DYNAMIC_TYPE_LIST = [TAB_PCDS_DYNAMIC_DEFAULT_NULL, \
@@ -646,6 +665,7 @@ TAB_DEPEX_IA32 = TAB_DEPEX + TAB_SPLIT +
TAB_ARCH_IA32
TAB_DEPEX_X64 = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_X64
TAB_DEPEX_IPF = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_IPF
TAB_DEPEX_ARM = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_ARM
+TAB_DEPEX_LOONGARCH64 = TAB_DEPEX + TAB_SPLIT +
TAB_ARCH_LOONGARCH64
TAB_DEPEX_EBC = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_EBC

TAB_SKUIDS = 'SkuIds'
@@ -656,6 +676,7 @@ TAB_LIBRARIES_IA32 = TAB_LIBRARIES + TAB_SPLIT +
TAB_ARCH_IA32
TAB_LIBRARIES_X64 = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_X64
TAB_LIBRARIES_IPF = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_IPF
TAB_LIBRARIES_ARM = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_ARM
+TAB_LIBRARIES_LOONGARCH64 = TAB_LIBRARIES + TAB_SPLIT +
TAB_ARCH_LOONGARCH64
TAB_LIBRARIES_EBC = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_EBC

TAB_COMPONENTS = 'Components'
@@ -664,6 +685,7 @@ TAB_COMPONENTS_IA32 = TAB_COMPONENTS +
TAB_SPLIT + TAB_ARCH_IA32
TAB_COMPONENTS_X64 = TAB_COMPONENTS + TAB_SPLIT +
TAB_ARCH_X64
TAB_COMPONENTS_IPF = TAB_COMPONENTS + TAB_SPLIT +
TAB_ARCH_IPF
TAB_COMPONENTS_ARM = TAB_COMPONENTS + TAB_SPLIT +
TAB_ARCH_ARM
+TAB_COMPONENTS_LOONGARCH64 = TAB_COMPONENTS + TAB_SPLIT +
TAB_ARCH_LOONGARCH64
TAB_COMPONENTS_EBC = TAB_COMPONENTS + TAB_SPLIT +
TAB_ARCH_EBC

TAB_BUILD_OPTIONS = 'BuildOptions'
diff --git a/BaseTools/Source/Python/build/buildoptions.py
b/BaseTools/Source/Python/build/buildoptions.py
index 39d92cff20..8334604b46 100644
--- a/BaseTools/Source/Python/build/buildoptions.py
+++ b/BaseTools/Source/Python/build/buildoptions.py
@@ -4,6 +4,7 @@
# Copyright (c) 2014, Hewlett-Packard Development Company, L.P.<BR>
# Copyright (c) 2007 - 2021, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2018 - 2020, Hewlett Packard Enterprise Development,
L.P.<BR>
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
@@ -41,7 +42,7 @@ class MyOptionParser():
def GetOption(self):
Parser = OptionParser(description=__copyright__, version=__version__,
prog="build.exe", usage="%prog [options]
[all|fds|genc|genmake|clean|cleanall|cleanlib|modules|libraries|run]")
Parser.add_option("-a", "--arch", action="append", dest="TargetArch",
- help="ARCHS is one of list: IA32, X64, ARM, AARCH64, RISCV64 or EBC,
which overrides target.txt's TARGET_ARCH definition. To specify more archs,
please repeat this option.")
+ help="ARCHS is one of list: IA32, X64, ARM, AARCH64, RISCV64,
LOONGARCH64 or EBC, which overrides target.txt's TARGET_ARCH definition.
To specify more archs, please repeat this option.")
Parser.add_option("-p", "--platform", action="callback", type="string",
dest="PlatformFile", callback=SingleCheckCallback,
help="Build the platform specified by the DSC file name argument,
overriding target.txt's ACTIVE_PLATFORM definition.")
Parser.add_option("-m", "--module", action="callback", type="string",
dest="ModuleFile", callback=SingleCheckCallback,
--
2.27.0





[PATCH V2 8/8] OvmfPkg/IntelTdx: Enable RTMR based measurement and measure boot

Min Xu
 

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

Enable RTMR based measurement and measure boot for Td guest.

Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Ken Lu <ken.lu@...>
Cc: Sami Mujawar <sami.mujawar@...>
Cc: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
OvmfPkg/IntelTdx/IntelTdxX64.dsc | 12 +++++++++++-
OvmfPkg/IntelTdx/IntelTdxX64.fdf | 5 +++++
2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
index caae49d524f9..774e2aee50a1 100644
--- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc
+++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
@@ -192,7 +192,7 @@
OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf

Tcg2PhysicalPresenceLib|OvmfPkg/Library/Tcg2PhysicalPresenceLibNull/DxeTcg2PhysicalPresenceLib.inf
- TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf
+ TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf

[LibraryClasses.common]
BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
@@ -548,6 +548,7 @@
!if $(SECURE_BOOT_ENABLE) == TRUE
NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf
!endif
+ NULL|SecurityPkg/Library/DxeTpm2MeasureBootLib/DxeTpm2MeasureBootLib.inf
}

MdeModulePkg/Universal/EbcDxe/EbcDxe.inf
@@ -722,3 +723,12 @@
<LibraryClasses>
NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf
}
+
+ #
+ # Cc Measurement Protocol for Td guest
+ #
+OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf {
+ <LibraryClasses>
+ HashLib|SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.inf
+ NULL|SecurityPkg/Library/HashInstanceLibSha384/HashInstanceLibSha384.inf
+}
diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.fdf b/OvmfPkg/IntelTdx/IntelTdxX64.fdf
index 9e290ea78f61..b7eb217847b8 100644
--- a/OvmfPkg/IntelTdx/IntelTdxX64.fdf
+++ b/OvmfPkg/IntelTdx/IntelTdxX64.fdf
@@ -292,6 +292,11 @@ INF OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf
INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf

+#
+# EFI_CC_MEASUREMENT_PROTOCOL
+#
+INF OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf
+
################################################################################

[FV.FVMAIN_COMPACT]
--
2.29.2.windows.2


[PATCH V2 7/8] OvmfPkg/IntelTdx: Add TdTcg2Dxe

Min Xu
 

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

TdTcg2Dxe mimics the Security/Tcg/Tcg2Dxe. It does below tasks:
- Set up and install CC_EVENTLOG ACPI table
- Parse the GUIDed HOB (gCcEventEntryHobGuid) and create CC event log
- Measure handoff tables, Boot##### variables etc
- Measure Exit Boot Service failed
- Install CcMeasurement Protocol

Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Ken Lu <ken.lu@...>
Cc: Sami Mujawar <sami.mujawar@...>
Cc: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
.../IntelTdx/TdTcg2Dxe/MeasureBootPeCoff.c | 407 +++
OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c | 2489 +++++++++++++++++
OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf | 101 +
3 files changed, 2997 insertions(+)
create mode 100644 OvmfPkg/IntelTdx/TdTcg2Dxe/MeasureBootPeCoff.c
create mode 100644 OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c
create mode 100644 OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf

diff --git a/OvmfPkg/IntelTdx/TdTcg2Dxe/MeasureBootPeCoff.c b/OvmfPkg/IntelTdx/TdTcg2Dxe/MeasureBootPeCoff.c
new file mode 100644
index 000000000000..4d542156badd
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdTcg2Dxe/MeasureBootPeCoff.c
@@ -0,0 +1,407 @@
+/** @file
+ This module implements measuring PeCoff image for Tcg2 Protocol.
+
+ Caution: This file requires additional review when modified.
+ This driver will have external input - PE/COFF image.
+ This external input must be validated carefully to avoid security issue like
+ buffer overflow, integer overflow.
+
+Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <PiDxe.h>
+
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/DevicePathLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/PeCoffLib.h>
+#include <Library/HashLib.h>
+
+UINTN mTcg2DxeImageSize = 0;
+
+/**
+ Reads contents of a PE/COFF image in memory buffer.
+
+ Caution: This function may receive untrusted input.
+ PE/COFF image is external input, so this function will make sure the PE/COFF image content
+ read is within the image buffer.
+
+ @param FileHandle Pointer to the file handle to read the PE/COFF image.
+ @param FileOffset Offset into the PE/COFF image to begin the read operation.
+ @param ReadSize On input, the size in bytes of the requested read operation.
+ On output, the number of bytes actually read.
+ @param Buffer Output buffer that contains the data read from the PE/COFF image.
+
+ @retval EFI_SUCCESS The specified portion of the PE/COFF image was read and the size
+**/
+EFI_STATUS
+EFIAPI
+Tcg2DxeImageRead (
+ IN VOID *FileHandle,
+ IN UINTN FileOffset,
+ IN OUT UINTN *ReadSize,
+ OUT VOID *Buffer
+ )
+{
+ UINTN EndPosition;
+
+ if ((FileHandle == NULL) || (ReadSize == NULL) || (Buffer == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (MAX_ADDRESS - FileOffset < *ReadSize) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ EndPosition = FileOffset + *ReadSize;
+ if (EndPosition > mTcg2DxeImageSize) {
+ *ReadSize = (UINT32)(mTcg2DxeImageSize - FileOffset);
+ }
+
+ if (FileOffset >= mTcg2DxeImageSize) {
+ *ReadSize = 0;
+ }
+
+ CopyMem (Buffer, (UINT8 *)((UINTN)FileHandle + FileOffset), *ReadSize);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Measure PE image into TPM log based on the authenticode image hashing in
+ PE/COFF Specification 8.0 Appendix A.
+
+ Caution: This function may receive untrusted input.
+ PE/COFF image is external input, so this function will validate its data structure
+ within this image buffer before use.
+
+ Notes: PE/COFF image is checked by BasePeCoffLib PeCoffLoaderGetImageInfo().
+
+ @param[in] RtmrIndex Rtmr index
+ @param[in] ImageAddress Start address of image buffer.
+ @param[in] ImageSize Image size
+ @param[out] DigestList Digest list of this image.
+
+ @retval EFI_SUCCESS Successfully measure image.
+ @retval EFI_OUT_OF_RESOURCES No enough resource to measure image.
+ @retval other error value
+**/
+EFI_STATUS
+MeasurePeImageAndExtend (
+ IN UINT32 RtmrIndex,
+ IN EFI_PHYSICAL_ADDRESS ImageAddress,
+ IN UINTN ImageSize,
+ OUT TPML_DIGEST_VALUES *DigestList
+ )
+{
+ EFI_STATUS Status;
+ EFI_IMAGE_DOS_HEADER *DosHdr;
+ UINT32 PeCoffHeaderOffset;
+ EFI_IMAGE_SECTION_HEADER *Section;
+ UINT8 *HashBase;
+ UINTN HashSize;
+ UINTN SumOfBytesHashed;
+ EFI_IMAGE_SECTION_HEADER *SectionHeader;
+ UINTN Index;
+ UINTN Pos;
+ EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
+ UINT32 NumberOfRvaAndSizes;
+ UINT32 CertSize;
+ HASH_HANDLE HashHandle;
+ PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
+
+ HashHandle = 0xFFFFFFFF; // Know bad value
+
+ Status = EFI_UNSUPPORTED;
+ SectionHeader = NULL;
+
+ //
+ // Check PE/COFF image
+ //
+ ZeroMem (&ImageContext, sizeof (ImageContext));
+ ImageContext.Handle = (VOID *)(UINTN)ImageAddress;
+ mTcg2DxeImageSize = ImageSize;
+ ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE)Tcg2DxeImageRead;
+
+ //
+ // Get information about the image being loaded
+ //
+ Status = PeCoffLoaderGetImageInfo (&ImageContext);
+ if (EFI_ERROR (Status)) {
+ //
+ // The information can't be got from the invalid PeImage
+ //
+ DEBUG ((DEBUG_INFO, "Tcg2Dxe: PeImage invalid. Cannot retrieve image information.\n"));
+ goto Finish;
+ }
+
+ DosHdr = (EFI_IMAGE_DOS_HEADER *)(UINTN)ImageAddress;
+ PeCoffHeaderOffset = 0;
+ if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
+ PeCoffHeaderOffset = DosHdr->e_lfanew;
+ }
+
+ Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *)(UINTN)ImageAddress + PeCoffHeaderOffset);
+ if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
+ Status = EFI_UNSUPPORTED;
+ goto Finish;
+ }
+
+ //
+ // PE/COFF Image Measurement
+ //
+ // NOTE: The following codes/steps are based upon the authenticode image hashing in
+ // PE/COFF Specification 8.0 Appendix A.
+ //
+ //
+
+ // 1. Load the image header into memory.
+
+ // 2. Initialize a SHA hash context.
+
+ Status = HashStart (&HashHandle);
+ if (EFI_ERROR (Status)) {
+ goto Finish;
+ }
+
+ //
+ // Measuring PE/COFF Image Header;
+ // But CheckSum field and SECURITY data directory (certificate) are excluded
+ //
+
+ //
+ // 3. Calculate the distance from the base of the image header to the image checksum address.
+ // 4. Hash the image header from its base to beginning of the image checksum.
+ //
+ HashBase = (UINT8 *)(UINTN)ImageAddress;
+ if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
+ //
+ // Use PE32 offset
+ //
+ NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
+ HashSize = (UINTN)(&Hdr.Pe32->OptionalHeader.CheckSum) - (UINTN)HashBase;
+ } else {
+ //
+ // Use PE32+ offset
+ //
+ NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
+ HashSize = (UINTN)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - (UINTN)HashBase;
+ }
+
+ Status = HashUpdate (HashHandle, HashBase, HashSize);
+ if (EFI_ERROR (Status)) {
+ goto Finish;
+ }
+
+ //
+ // 5. Skip over the image checksum (it occupies a single ULONG).
+ //
+ if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
+ //
+ // 6. Since there is no Cert Directory in optional header, hash everything
+ // from the end of the checksum to the end of image header.
+ //
+ if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
+ //
+ // Use PE32 offset.
+ //
+ HashBase = (UINT8 *)&Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
+ HashSize = Hdr.Pe32->OptionalHeader.SizeOfHeaders - (UINTN)(HashBase - ImageAddress);
+ } else {
+ //
+ // Use PE32+ offset.
+ //
+ HashBase = (UINT8 *)&Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
+ HashSize = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN)(HashBase - ImageAddress);
+ }
+
+ if (HashSize != 0) {
+ Status = HashUpdate (HashHandle, HashBase, HashSize);
+ if (EFI_ERROR (Status)) {
+ goto Finish;
+ }
+ }
+ } else {
+ //
+ // 7. Hash everything from the end of the checksum to the start of the Cert Directory.
+ //
+ if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
+ //
+ // Use PE32 offset
+ //
+ HashBase = (UINT8 *)&Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
+ HashSize = (UINTN)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN)HashBase;
+ } else {
+ //
+ // Use PE32+ offset
+ //
+ HashBase = (UINT8 *)&Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
+ HashSize = (UINTN)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN)HashBase;
+ }
+
+ if (HashSize != 0) {
+ Status = HashUpdate (HashHandle, HashBase, HashSize);
+ if (EFI_ERROR (Status)) {
+ goto Finish;
+ }
+ }
+
+ //
+ // 8. Skip over the Cert Directory. (It is sizeof(IMAGE_DATA_DIRECTORY) bytes.)
+ // 9. Hash everything from the end of the Cert Directory to the end of image header.
+ //
+ if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
+ //
+ // Use PE32 offset
+ //
+ HashBase = (UINT8 *)&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
+ HashSize = Hdr.Pe32->OptionalHeader.SizeOfHeaders - (UINTN)(HashBase - ImageAddress);
+ } else {
+ //
+ // Use PE32+ offset
+ //
+ HashBase = (UINT8 *)&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
+ HashSize = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN)(HashBase - ImageAddress);
+ }
+
+ if (HashSize != 0) {
+ Status = HashUpdate (HashHandle, HashBase, HashSize);
+ if (EFI_ERROR (Status)) {
+ goto Finish;
+ }
+ }
+ }
+
+ //
+ // 10. Set the SUM_OF_BYTES_HASHED to the size of the header
+ //
+ if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
+ //
+ // Use PE32 offset
+ //
+ SumOfBytesHashed = Hdr.Pe32->OptionalHeader.SizeOfHeaders;
+ } else {
+ //
+ // Use PE32+ offset
+ //
+ SumOfBytesHashed = Hdr.Pe32Plus->OptionalHeader.SizeOfHeaders;
+ }
+
+ //
+ // 11. Build a temporary table of pointers to all the IMAGE_SECTION_HEADER
+ // structures in the image. The 'NumberOfSections' field of the image
+ // header indicates how big the table should be. Do not include any
+ // IMAGE_SECTION_HEADERs in the table whose 'SizeOfRawData' field is zero.
+ //
+ SectionHeader = (EFI_IMAGE_SECTION_HEADER *)AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * Hdr.Pe32->FileHeader.NumberOfSections);
+ if (SectionHeader == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto Finish;
+ }
+
+ //
+ // 12. Using the 'PointerToRawData' in the referenced section headers as
+ // a key, arrange the elements in the table in ascending order. In other
+ // words, sort the section headers according to the disk-file offset of
+ // the section.
+ //
+ Section = (EFI_IMAGE_SECTION_HEADER *)(
+ (UINT8 *)(UINTN)ImageAddress +
+ PeCoffHeaderOffset +
+ sizeof (UINT32) +
+ sizeof (EFI_IMAGE_FILE_HEADER) +
+ Hdr.Pe32->FileHeader.SizeOfOptionalHeader
+ );
+ for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {
+ Pos = Index;
+ while ((Pos > 0) && (Section->PointerToRawData < SectionHeader[Pos - 1].PointerToRawData)) {
+ CopyMem (&SectionHeader[Pos], &SectionHeader[Pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
+ Pos--;
+ }
+
+ CopyMem (&SectionHeader[Pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
+ Section += 1;
+ }
+
+ //
+ // 13. Walk through the sorted table, bring the corresponding section
+ // into memory, and hash the entire section (using the 'SizeOfRawData'
+ // field in the section header to determine the amount of data to hash).
+ // 14. Add the section's 'SizeOfRawData' to SUM_OF_BYTES_HASHED .
+ // 15. Repeat steps 13 and 14 for all the sections in the sorted table.
+ //
+ for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {
+ Section = (EFI_IMAGE_SECTION_HEADER *)&SectionHeader[Index];
+ if (Section->SizeOfRawData == 0) {
+ continue;
+ }
+
+ HashBase = (UINT8 *)(UINTN)ImageAddress + Section->PointerToRawData;
+ HashSize = (UINTN)Section->SizeOfRawData;
+
+ Status = HashUpdate (HashHandle, HashBase, HashSize);
+ if (EFI_ERROR (Status)) {
+ goto Finish;
+ }
+
+ SumOfBytesHashed += HashSize;
+ }
+
+ //
+ // 16. If the file size is greater than SUM_OF_BYTES_HASHED, there is extra
+ // data in the file that needs to be added to the hash. This data begins
+ // at file offset SUM_OF_BYTES_HASHED and its length is:
+ // FileSize - (CertDirectory->Size)
+ //
+ if (ImageSize > SumOfBytesHashed) {
+ HashBase = (UINT8 *)(UINTN)ImageAddress + SumOfBytesHashed;
+
+ if (NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_SECURITY) {
+ CertSize = 0;
+ } else {
+ if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
+ //
+ // Use PE32 offset.
+ //
+ CertSize = Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
+ } else {
+ //
+ // Use PE32+ offset.
+ //
+ CertSize = Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
+ }
+ }
+
+ if (ImageSize > CertSize + SumOfBytesHashed) {
+ HashSize = (UINTN)(ImageSize - CertSize - SumOfBytesHashed);
+
+ Status = HashUpdate (HashHandle, HashBase, HashSize);
+ if (EFI_ERROR (Status)) {
+ goto Finish;
+ }
+ } else if (ImageSize < CertSize + SumOfBytesHashed) {
+ Status = EFI_UNSUPPORTED;
+ goto Finish;
+ }
+ }
+
+ //
+ // 17. Finalize the SHA hash.
+ //
+ Status = HashCompleteAndExtend (HashHandle, RtmrIndex, NULL, 0, DigestList);
+ if (EFI_ERROR (Status)) {
+ goto Finish;
+ }
+
+Finish:
+ if (SectionHeader != NULL) {
+ FreePool (SectionHeader);
+ }
+
+ return Status;
+}
diff --git a/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c b/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c
new file mode 100644
index 000000000000..e9315ecda17b
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c
@@ -0,0 +1,2489 @@
+/** @file
+ This module implements EFI TD Protocol.
+
+ Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <PiDxe.h>
+#include <IndustryStandard/Acpi.h>
+#include <IndustryStandard/PeImage.h>
+#include <IndustryStandard/TcpaAcpi.h>
+
+#include <Guid/GlobalVariable.h>
+#include <Guid/HobList.h>
+#include <Guid/EventGroup.h>
+#include <Guid/EventExitBootServiceFailed.h>
+#include <Guid/ImageAuthentication.h>
+#include <Guid/TpmInstance.h>
+
+#include <Protocol/DevicePath.h>
+#include <Protocol/MpService.h>
+#include <Protocol/VariableWrite.h>
+#include <Protocol/Tcg2Protocol.h>
+#include <Protocol/TrEEProtocol.h>
+#include <Protocol/ResetNotification.h>
+#include <Protocol/AcpiTable.h>
+
+#include <Library/DebugLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/UefiDriverEntryPoint.h>
+#include <Library/HobLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/BaseLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/PrintLib.h>
+#include <Library/PcdLib.h>
+#include <Library/UefiLib.h>
+#include <Library/HashLib.h>
+#include <Library/PerformanceLib.h>
+#include <Library/ReportStatusCodeLib.h>
+#include <Library/TpmMeasurementLib.h>
+
+#include <Protocol/CcMeasurement.h>
+#include <Guid/CcEventHob.h>
+#include <Library/TdxLib.h>
+
+#define PERF_ID_CC_TCG2_DXE 0x3130
+
+#define CC_EVENT_LOG_AREA_COUNT_MAX 1
+#define INVALID_RTMR_INDEX 4
+
+typedef struct {
+ CHAR16 *VariableName;
+ EFI_GUID *VendorGuid;
+} VARIABLE_TYPE;
+
+typedef struct {
+ EFI_GUID *EventGuid;
+ EFI_CC_EVENT_LOG_FORMAT LogFormat;
+} CC_EVENT_INFO_STRUCT;
+
+typedef struct {
+ EFI_CC_EVENT_LOG_FORMAT EventLogFormat;
+ EFI_PHYSICAL_ADDRESS Lasa;
+ UINT64 Laml;
+ UINTN EventLogSize;
+ UINT8 *LastEvent;
+ BOOLEAN EventLogStarted;
+ BOOLEAN EventLogTruncated;
+ UINTN Next800155EventOffset;
+} CC_EVENT_LOG_AREA_STRUCT;
+
+typedef struct _TDX_DXE_DATA {
+ EFI_CC_BOOT_SERVICE_CAPABILITY BsCap;
+ CC_EVENT_LOG_AREA_STRUCT EventLogAreaStruct[CC_EVENT_LOG_AREA_COUNT_MAX];
+ BOOLEAN GetEventLogCalled[CC_EVENT_LOG_AREA_COUNT_MAX];
+ CC_EVENT_LOG_AREA_STRUCT FinalEventLogAreaStruct[CC_EVENT_LOG_AREA_COUNT_MAX];
+ EFI_CC_FINAL_EVENTS_TABLE *FinalEventsTable[CC_EVENT_LOG_AREA_COUNT_MAX];
+} TDX_DXE_DATA;
+
+typedef struct {
+ TPMI_ALG_HASH HashAlgo;
+ UINT16 HashSize;
+ UINT32 HashMask;
+} TDX_HASH_INFO;
+
+//
+//
+CC_EVENT_INFO_STRUCT mCcEventInfo[] = {
+ { &gCcEventEntryHobGuid, EFI_CC_EVENT_LOG_FORMAT_TCG_2 },
+};
+
+TDX_DXE_DATA mTdxDxeData = {
+ {
+ sizeof (EFI_CC_BOOT_SERVICE_CAPABILITY), // Size
+ { 1, 1 }, // StructureVersion
+ { 1, 1 }, // ProtocolVersion
+ EFI_CC_BOOT_HASH_ALG_SHA384, // HashAlgorithmBitmap
+ EFI_CC_EVENT_LOG_FORMAT_TCG_2, // SupportedEventLogs
+ { 2, 0 } // {CC_TYPE, CC_SUBTYPE}
+ },
+};
+
+UINTN mBootAttempts = 0;
+CHAR16 mBootVarName[] = L"BootOrder";
+
+VARIABLE_TYPE mVariableType[] = {
+ { EFI_SECURE_BOOT_MODE_NAME, &gEfiGlobalVariableGuid },
+ { EFI_PLATFORM_KEY_NAME, &gEfiGlobalVariableGuid },
+ { EFI_KEY_EXCHANGE_KEY_NAME, &gEfiGlobalVariableGuid },
+ { EFI_IMAGE_SECURITY_DATABASE, &gEfiImageSecurityDatabaseGuid },
+ { EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid },
+};
+
+EFI_CC_EVENTLOG_ACPI_TABLE mTdxEventlogAcpiTemplate = {
+ {
+ EFI_CC_EVENTLOG_ACPI_TABLE_SIGNATURE,
+ sizeof (mTdxEventlogAcpiTemplate),
+ EFI_CC_EVENTLOG_ACPI_TABLE_REVISION,
+ //
+ // Compiler initializes the remaining bytes to 0
+ // These fields should be filled in production
+ //
+ },
+ { EFI_CC_TYPE_TDX, 0 }, // CcType
+ 0, // rsvd
+ 0, // laml
+ 0, // lasa
+};
+
+//
+// Supported Hash list in Td guest.
+// Currently SHA384 is supported.
+//
+TDX_HASH_INFO mHashInfo[] = {
+ { TPM_ALG_SHA384, SHA384_DIGEST_SIZE, HASH_ALG_SHA384 }
+};
+
+/**
+ Get hash size based on Algo
+
+ @param[in] HashAlgo Hash Algorithm Id.
+
+ @return Size of the hash.
+**/
+UINT16
+GetHashSizeFromAlgo (
+ IN TPMI_ALG_HASH HashAlgo
+ )
+{
+ UINTN Index;
+
+ for (Index = 0; Index < sizeof (mHashInfo)/sizeof (mHashInfo[0]); Index++) {
+ if (mHashInfo[Index].HashAlgo == HashAlgo) {
+ return mHashInfo[Index].HashSize;
+ }
+ }
+
+ return 0;
+}
+
+/**
+ Get hash mask based on Algo
+
+ @param[in] HashAlgo Hash Algorithm Id.
+
+ @return Hash mask.
+**/
+UINT32
+GetHashMaskFromAlgo (
+ IN TPMI_ALG_HASH HashAlgo
+ )
+{
+ UINTN Index;
+
+ for (Index = 0; Index < ARRAY_SIZE (mHashInfo); Index++) {
+ if (mHashInfo[Index].HashAlgo == HashAlgo) {
+ return mHashInfo[Index].HashMask;
+ }
+ }
+
+ ASSERT (FALSE);
+ return 0;
+}
+
+/**
+ Copy TPML_DIGEST_VALUES into a buffer
+
+ @param[in,out] Buffer Buffer to hold copied TPML_DIGEST_VALUES compact binary.
+ @param[in] DigestList TPML_DIGEST_VALUES to be copied.
+ @param[in] HashAlgorithmMask HASH bits corresponding to the desired digests to copy.
+
+ @return The end of buffer to hold TPML_DIGEST_VALUES.
+**/
+VOID *
+CopyDigestListToBuffer (
+ IN OUT VOID *Buffer,
+ IN TPML_DIGEST_VALUES *DigestList,
+ IN UINT32 HashAlgorithmMask
+ )
+{
+ UINTN Index;
+ UINT16 DigestSize;
+ UINT32 DigestListCount;
+ UINT32 *DigestListCountPtr;
+
+ DigestListCountPtr = (UINT32 *)Buffer;
+ DigestListCount = 0;
+ Buffer = (UINT8 *)Buffer + sizeof (DigestList->count);
+ for (Index = 0; Index < DigestList->count; Index++) {
+ if ((DigestList->digests[Index].hashAlg & HashAlgorithmMask) == 0) {
+ DEBUG ((DEBUG_ERROR, "WARNING: TD Event log has HashAlg unsupported (0x%x)\n", DigestList->digests[Index].hashAlg));
+ continue;
+ }
+
+ CopyMem (Buffer, &DigestList->digests[Index].hashAlg, sizeof (DigestList->digests[Index].hashAlg));
+ Buffer = (UINT8 *)Buffer + sizeof (DigestList->digests[Index].hashAlg);
+ DigestSize = GetHashSizeFromAlgo (DigestList->digests[Index].hashAlg);
+ CopyMem (Buffer, &DigestList->digests[Index].digest, DigestSize);
+ Buffer = (UINT8 *)Buffer + DigestSize;
+ DigestListCount++;
+ }
+
+ WriteUnaligned32 (DigestListCountPtr, DigestListCount);
+
+ return Buffer;
+}
+
+EFI_HANDLE mImageHandle;
+
+/**
+ Measure PE image into TPM log based on the authenticode image hashing in
+ PE/COFF Specification 8.0 Appendix A.
+
+ Caution: This function may receive untrusted input.
+ PE/COFF image is external input, so this function will validate its data structure
+ within this image buffer before use.
+
+ Notes: PE/COFF image is checked by BasePeCoffLib PeCoffLoaderGetImageInfo().
+
+ @param[in] MrIndex RTMR index
+ @param[in] ImageAddress Start address of image buffer.
+ @param[in] ImageSize Image size
+ @param[out] DigestList Digest list of this image.
+
+ @retval EFI_SUCCESS Successfully measure image.
+ @retval EFI_OUT_OF_RESOURCES No enough resource to measure image.
+ @retval other error value
+**/
+EFI_STATUS
+MeasurePeImageAndExtend (
+ IN UINT32 MrIndex,
+ IN EFI_PHYSICAL_ADDRESS ImageAddress,
+ IN UINTN ImageSize,
+ OUT TPML_DIGEST_VALUES *DigestList
+ );
+
+#define COLUME_SIZE (16 * 2)
+
+/**
+
+ This function dump raw data.
+
+ @param Data raw data
+ @param Size raw data size
+
+**/
+VOID
+InternalDumpData (
+ IN UINT8 *Data,
+ IN UINTN Size
+ )
+{
+ UINTN Index;
+
+ for (Index = 0; Index < Size; Index++) {
+ DEBUG ((DEBUG_INFO, Index == COLUME_SIZE/2 ? " | %02x" : " %02x", (UINTN)Data[Index]));
+ }
+}
+
+/**
+
+ This function dump raw data with colume format.
+
+ @param Data raw data
+ @param Size raw data size
+
+**/
+VOID
+InternalDumpHex (
+ IN UINT8 *Data,
+ IN UINTN Size
+ )
+{
+ UINTN Index;
+ UINTN Count;
+ UINTN Left;
+
+ Count = Size / COLUME_SIZE;
+ Left = Size % COLUME_SIZE;
+ for (Index = 0; Index < Count; Index++) {
+ DEBUG ((DEBUG_INFO, "%04x: ", Index * COLUME_SIZE));
+ InternalDumpData (Data + Index * COLUME_SIZE, COLUME_SIZE);
+ DEBUG ((DEBUG_INFO, "\n"));
+ }
+
+ if (Left != 0) {
+ DEBUG ((DEBUG_INFO, "%04x: ", Index * COLUME_SIZE));
+ InternalDumpData (Data + Index * COLUME_SIZE, Left);
+ DEBUG ((DEBUG_INFO, "\n"));
+ }
+}
+
+/**
+
+ This function initialize TD_EVENT_HDR for EV_NO_ACTION
+ Event Type other than EFI Specification ID event. The behavior is defined
+ by TCG PC Client PFP Spec. Section 9.3.4 EV_NO_ACTION Event Types
+
+ @param[in, out] NoActionEvent Event Header of EV_NO_ACTION Event
+ @param[in] EventSize Event Size of the EV_NO_ACTION Event
+
+**/
+VOID
+InitNoActionEvent (
+ IN OUT CC_EVENT_HDR *NoActionEvent,
+ IN UINT32 EventSize
+ )
+{
+ UINT32 DigestListCount;
+ TPMI_ALG_HASH HashAlgId;
+ UINT8 *DigestBuffer;
+
+ DigestBuffer = (UINT8 *)NoActionEvent->Digests.digests;
+ DigestListCount = 0;
+
+ NoActionEvent->MrIndex = 0;
+ NoActionEvent->EventType = EV_NO_ACTION;
+
+ //
+ // Set Hash count & hashAlg accordingly, while Digest.digests[n].digest to all 0
+ //
+ ZeroMem (&NoActionEvent->Digests, sizeof (NoActionEvent->Digests));
+
+ if ((mTdxDxeData.BsCap.HashAlgorithmBitmap & EFI_CC_BOOT_HASH_ALG_SHA384) != 0) {
+ HashAlgId = TPM_ALG_SHA384;
+ CopyMem (DigestBuffer, &HashAlgId, sizeof (TPMI_ALG_HASH));
+ DigestBuffer += sizeof (TPMI_ALG_HASH) + GetHashSizeFromAlgo (HashAlgId);
+ DigestListCount++;
+ }
+
+ //
+ // Set Digests Count
+ //
+ WriteUnaligned32 ((UINT32 *)&NoActionEvent->Digests.count, DigestListCount);
+
+ //
+ // Set Event Size
+ //
+ WriteUnaligned32 ((UINT32 *)DigestBuffer, EventSize);
+}
+
+/**
+ Get All processors EFI_CPU_LOCATION in system. LocationBuf is allocated inside the function
+ Caller is responsible to free LocationBuf.
+
+ @param[out] LocationBuf Returns Processor Location Buffer.
+ @param[out] Num Returns processor number.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_UNSUPPORTED MpService protocol not found.
+
+**/
+EFI_STATUS
+GetProcessorsCpuLocation (
+ OUT EFI_CPU_PHYSICAL_LOCATION **LocationBuf,
+ OUT UINTN *Num
+ )
+{
+ EFI_STATUS Status;
+ EFI_MP_SERVICES_PROTOCOL *MpProtocol;
+ UINTN ProcessorNum;
+ UINTN EnabledProcessorNum;
+ EFI_PROCESSOR_INFORMATION ProcessorInfo;
+ EFI_CPU_PHYSICAL_LOCATION *ProcessorLocBuf;
+ UINTN Index;
+
+ Status = gBS->LocateProtocol (&gEfiMpServiceProtocolGuid, NULL, (VOID **)&MpProtocol);
+ if (EFI_ERROR (Status)) {
+ //
+ // MP protocol is not installed
+ //
+ return EFI_UNSUPPORTED;
+ }
+
+ Status = MpProtocol->GetNumberOfProcessors (
+ MpProtocol,
+ &ProcessorNum,
+ &EnabledProcessorNum
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ Status = gBS->AllocatePool (
+ EfiBootServicesData,
+ sizeof (EFI_CPU_PHYSICAL_LOCATION) * ProcessorNum,
+ (VOID **)&ProcessorLocBuf
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ //
+ // Get each processor Location info
+ //
+ for (Index = 0; Index < ProcessorNum; Index++) {
+ Status = MpProtocol->GetProcessorInfo (
+ MpProtocol,
+ Index,
+ &ProcessorInfo
+ );
+ if (EFI_ERROR (Status)) {
+ FreePool (ProcessorLocBuf);
+ return Status;
+ }
+
+ //
+ // Get all Processor Location info & measure
+ //
+ CopyMem (
+ &ProcessorLocBuf[Index],
+ &ProcessorInfo.Location,
+ sizeof (EFI_CPU_PHYSICAL_LOCATION)
+ );
+ }
+
+ *LocationBuf = ProcessorLocBuf;
+ *Num = ProcessorNum;
+
+ return Status;
+}
+
+/**
+ The EFI_CC_MEASUREMENT_PROTOCOL GetCapability function call provides protocol
+ capability information and state information.
+
+ @param[in] This Indicates the calling context
+ @param[in, out] ProtocolCapability The caller allocates memory for a EFI_CC_BOOT_SERVICE_CAPABILITY
+ structure and sets the size field to the size of the structure allocated.
+ The callee fills in the fields with the EFI protocol capability information
+ and the current EFI TCG2 state information up to the number of fields which
+ fit within the size of the structure passed in.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_DEVICE_ERROR The command was unsuccessful.
+ The ProtocolCapability variable will not be populated.
+ @retval EFI_INVALID_PARAMETER One or more of the parameters are incorrect.
+ The ProtocolCapability variable will not be populated.
+ @retval EFI_BUFFER_TOO_SMALL The ProtocolCapability variable is too small to hold the full response.
+ It will be partially populated (required Size field will be set).
+**/
+EFI_STATUS
+EFIAPI
+TdGetCapability (
+ IN EFI_CC_MEASUREMENT_PROTOCOL *This,
+ IN OUT EFI_CC_BOOT_SERVICE_CAPABILITY *ProtocolCapability
+ )
+{
+ DEBUG ((DEBUG_VERBOSE, "TdGetCapability\n"));
+
+ if ((This == NULL) || (ProtocolCapability == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ CopyMem (ProtocolCapability, &mTdxDxeData.BsCap, sizeof (EFI_CC_BOOT_SERVICE_CAPABILITY));
+
+ return EFI_SUCCESS;
+}
+
+/**
+ This function dump PCR event.
+ TD Event log reuse the TCG PCR Event spec.
+ The first event in the event log is the SHA1 log format.
+ There is only ONE TCG_PCR_EVENT in TD Event log.
+
+ @param[in] EventHdr TCG PCR event structure.
+**/
+VOID
+DumpPcrEvent (
+ IN TCG_PCR_EVENT_HDR *EventHdr
+ )
+{
+ UINTN Index;
+
+ DEBUG ((DEBUG_INFO, " Event:\n"));
+ DEBUG ((DEBUG_INFO, " MrIndex - %d\n", EventHdr->PCRIndex));
+ DEBUG ((DEBUG_INFO, " EventType - 0x%08x\n", EventHdr->EventType));
+ DEBUG ((DEBUG_INFO, " Digest - "));
+ for (Index = 0; Index < sizeof (TCG_DIGEST); Index++) {
+ DEBUG ((DEBUG_INFO, "%02x ", EventHdr->Digest.digest[Index]));
+ }
+
+ DEBUG ((DEBUG_INFO, "\n"));
+ DEBUG ((DEBUG_INFO, " EventSize - 0x%08x\n", EventHdr->EventSize));
+ InternalDumpHex ((UINT8 *)(EventHdr + 1), EventHdr->EventSize);
+}
+
+/**
+ This function dump TCG_EfiSpecIDEventStruct.
+
+ @param[in] TcgEfiSpecIdEventStruct A pointer to TCG_EfiSpecIDEventStruct.
+**/
+VOID
+DumpTcgEfiSpecIdEventStruct (
+ IN TCG_EfiSpecIDEventStruct *TcgEfiSpecIdEventStruct
+ )
+{
+ TCG_EfiSpecIdEventAlgorithmSize *DigestSize;
+ UINTN Index;
+ UINT8 *VendorInfoSize;
+ UINT8 *VendorInfo;
+ UINT32 NumberOfAlgorithms;
+
+ DEBUG ((DEBUG_INFO, " TCG_EfiSpecIDEventStruct:\n"));
+ DEBUG ((DEBUG_INFO, " signature - '"));
+ for (Index = 0; Index < sizeof (TcgEfiSpecIdEventStruct->signature); Index++) {
+ DEBUG ((DEBUG_INFO, "%c", TcgEfiSpecIdEventStruct->signature[Index]));
+ }
+
+ DEBUG ((DEBUG_INFO, "'\n"));
+ DEBUG ((DEBUG_INFO, " platformClass - 0x%08x\n", TcgEfiSpecIdEventStruct->platformClass));
+ DEBUG ((DEBUG_INFO, " specVersion - %d.%d%d\n", TcgEfiSpecIdEventStruct->specVersionMajor, TcgEfiSpecIdEventStruct->specVersionMinor, TcgEfiSpecIdEventStruct->specErrata));
+ DEBUG ((DEBUG_INFO, " uintnSize - 0x%02x\n", TcgEfiSpecIdEventStruct->uintnSize));
+
+ CopyMem (&NumberOfAlgorithms, TcgEfiSpecIdEventStruct + 1, sizeof (NumberOfAlgorithms));
+ DEBUG ((DEBUG_INFO, " NumberOfAlgorithms - 0x%08x\n", NumberOfAlgorithms));
+
+ DigestSize = (TCG_EfiSpecIdEventAlgorithmSize *)((UINT8 *)TcgEfiSpecIdEventStruct + sizeof (*TcgEfiSpecIdEventStruct) + sizeof (NumberOfAlgorithms));
+ for (Index = 0; Index < NumberOfAlgorithms; Index++) {
+ DEBUG ((DEBUG_INFO, " digest(%d)\n", Index));
+ DEBUG ((DEBUG_INFO, " algorithmId - 0x%04x\n", DigestSize[Index].algorithmId));
+ DEBUG ((DEBUG_INFO, " digestSize - 0x%04x\n", DigestSize[Index].digestSize));
+ }
+
+ VendorInfoSize = (UINT8 *)&DigestSize[NumberOfAlgorithms];
+ DEBUG ((DEBUG_INFO, " VendorInfoSize - 0x%02x\n", *VendorInfoSize));
+ VendorInfo = VendorInfoSize + 1;
+ DEBUG ((DEBUG_INFO, " VendorInfo - "));
+ for (Index = 0; Index < *VendorInfoSize; Index++) {
+ DEBUG ((DEBUG_INFO, "%02x ", VendorInfo[Index]));
+ }
+
+ DEBUG ((DEBUG_INFO, "\n"));
+}
+
+/**
+ This function get size of TCG_EfiSpecIDEventStruct.
+
+ @param[in] TcgEfiSpecIdEventStruct A pointer to TCG_EfiSpecIDEventStruct.
+**/
+UINTN
+GetTcgEfiSpecIdEventStructSize (
+ IN TCG_EfiSpecIDEventStruct *TcgEfiSpecIdEventStruct
+ )
+{
+ TCG_EfiSpecIdEventAlgorithmSize *DigestSize;
+ UINT8 *VendorInfoSize;
+ UINT32 NumberOfAlgorithms;
+
+ CopyMem (&NumberOfAlgorithms, TcgEfiSpecIdEventStruct + 1, sizeof (NumberOfAlgorithms));
+
+ DigestSize = (TCG_EfiSpecIdEventAlgorithmSize *)((UINT8 *)TcgEfiSpecIdEventStruct + sizeof (*TcgEfiSpecIdEventStruct) + sizeof (NumberOfAlgorithms));
+ VendorInfoSize = (UINT8 *)&DigestSize[NumberOfAlgorithms];
+ return sizeof (TCG_EfiSpecIDEventStruct) + sizeof (UINT32) + (NumberOfAlgorithms * sizeof (TCG_EfiSpecIdEventAlgorithmSize)) + sizeof (UINT8) + (*VendorInfoSize);
+}
+
+/**
+ This function dump TD Event (including the Digests).
+
+ @param[in] CcEvent TD Event structure.
+**/
+VOID
+DumpCcEvent (
+ IN CC_EVENT *CcEvent
+ )
+{
+ UINT32 DigestIndex;
+ UINT32 DigestCount;
+ TPMI_ALG_HASH HashAlgo;
+ UINT32 DigestSize;
+ UINT8 *DigestBuffer;
+ UINT32 EventSize;
+ UINT8 *EventBuffer;
+
+ DEBUG ((DEBUG_INFO, "Cc Event:\n"));
+ DEBUG ((DEBUG_INFO, " MrIndex - %d\n", CcEvent->MrIndex));
+ DEBUG ((DEBUG_INFO, " EventType - 0x%08x\n", CcEvent->EventType));
+ DEBUG ((DEBUG_INFO, " DigestCount: 0x%08x\n", CcEvent->Digests.count));
+
+ DigestCount = CcEvent->Digests.count;
+ HashAlgo = CcEvent->Digests.digests[0].hashAlg;
+ DigestBuffer = (UINT8 *)&CcEvent->Digests.digests[0].digest;
+ for (DigestIndex = 0; DigestIndex < DigestCount; DigestIndex++) {
+ DEBUG ((DEBUG_INFO, " HashAlgo : 0x%04x\n", HashAlgo));
+ DEBUG ((DEBUG_INFO, " Digest(%d): \n", DigestIndex));
+ DigestSize = GetHashSizeFromAlgo (HashAlgo);
+ InternalDumpHex (DigestBuffer, DigestSize);
+ //
+ // Prepare next
+ //
+ CopyMem (&HashAlgo, DigestBuffer + DigestSize, sizeof (TPMI_ALG_HASH));
+ DigestBuffer = DigestBuffer + DigestSize + sizeof (TPMI_ALG_HASH);
+ }
+
+ DigestBuffer = DigestBuffer - sizeof (TPMI_ALG_HASH);
+
+ CopyMem (&EventSize, DigestBuffer, sizeof (CcEvent->EventSize));
+ DEBUG ((DEBUG_INFO, " EventSize - 0x%08x\n", EventSize));
+ EventBuffer = DigestBuffer + sizeof (CcEvent->EventSize);
+ InternalDumpHex (EventBuffer, EventSize);
+ DEBUG ((DEBUG_INFO, "\n"));
+}
+
+/**
+ This function returns size of Td Table event.
+
+ @param[in] CcEvent Td Table event structure.
+
+ @return size of Td event.
+**/
+UINTN
+GetCcEventSize (
+ IN CC_EVENT *CcEvent
+ )
+{
+ UINT32 DigestIndex;
+ UINT32 DigestCount;
+ TPMI_ALG_HASH HashAlgo;
+ UINT32 DigestSize;
+ UINT8 *DigestBuffer;
+ UINT32 EventSize;
+ UINT8 *EventBuffer;
+
+ DigestCount = CcEvent->Digests.count;
+ HashAlgo = CcEvent->Digests.digests[0].hashAlg;
+ DigestBuffer = (UINT8 *)&CcEvent->Digests.digests[0].digest;
+ for (DigestIndex = 0; DigestIndex < DigestCount; DigestIndex++) {
+ DigestSize = GetHashSizeFromAlgo (HashAlgo);
+ //
+ // Prepare next
+ //
+ CopyMem (&HashAlgo, DigestBuffer + DigestSize, sizeof (TPMI_ALG_HASH));
+ DigestBuffer = DigestBuffer + DigestSize + sizeof (TPMI_ALG_HASH);
+ }
+
+ DigestBuffer = DigestBuffer - sizeof (TPMI_ALG_HASH);
+
+ CopyMem (&EventSize, DigestBuffer, sizeof (CcEvent->EventSize));
+ EventBuffer = DigestBuffer + sizeof (CcEvent->EventSize);
+
+ return (UINTN)EventBuffer + EventSize - (UINTN)CcEvent;
+}
+
+/**
+ This function dump CC event log.
+ TDVF only supports EFI_CC_EVENT_LOG_FORMAT_TCG_2
+
+ @param[in] EventLogFormat The type of the event log for which the information is requested.
+ @param[in] EventLogLocation A pointer to the memory address of the event log.
+ @param[in] EventLogLastEntry If the Event Log contains more than one entry, this is a pointer to the
+ address of the start of the last entry in the event log in memory.
+ @param[in] FinalEventsTable A pointer to the memory address of the final event table.
+**/
+VOID
+DumpCcEventLog (
+ IN EFI_CC_EVENT_LOG_FORMAT EventLogFormat,
+ IN EFI_PHYSICAL_ADDRESS EventLogLocation,
+ IN EFI_PHYSICAL_ADDRESS EventLogLastEntry,
+ IN EFI_CC_FINAL_EVENTS_TABLE *FinalEventsTable
+ )
+{
+ TCG_PCR_EVENT_HDR *EventHdr;
+ CC_EVENT *CcEvent;
+ TCG_EfiSpecIDEventStruct *TcgEfiSpecIdEventStruct;
+ UINTN NumberOfEvents;
+
+ DEBUG ((DEBUG_INFO, "EventLogFormat: (0x%x)\n", EventLogFormat));
+ ASSERT (EventLogFormat == EFI_CC_EVENT_LOG_FORMAT_TCG_2);
+
+ //
+ // Dump first event.
+ // The first event is always the TCG_PCR_EVENT_HDR
+ // After this event is a TCG_EfiSpecIDEventStruct
+ //
+ EventHdr = (TCG_PCR_EVENT_HDR *)(UINTN)EventLogLocation;
+ DumpPcrEvent (EventHdr);
+
+ TcgEfiSpecIdEventStruct = (TCG_EfiSpecIDEventStruct *)(EventHdr + 1);
+ DumpTcgEfiSpecIdEventStruct (TcgEfiSpecIdEventStruct);
+
+ //
+ // Then the CcEvent (Its structure is similar to TCG_PCR_EVENT2)
+ //
+ CcEvent = (CC_EVENT *)((UINTN)TcgEfiSpecIdEventStruct + GetTcgEfiSpecIdEventStructSize (TcgEfiSpecIdEventStruct));
+ while ((UINTN)CcEvent <= EventLogLastEntry) {
+ DumpCcEvent (CcEvent);
+ CcEvent = (CC_EVENT *)((UINTN)CcEvent + GetCcEventSize (CcEvent));
+ }
+
+ if (FinalEventsTable == NULL) {
+ DEBUG ((DEBUG_INFO, "FinalEventsTable: NOT FOUND\n"));
+ } else {
+ DEBUG ((DEBUG_INFO, "FinalEventsTable: (0x%x)\n", FinalEventsTable));
+ DEBUG ((DEBUG_INFO, " Version: (0x%x)\n", FinalEventsTable->Version));
+ DEBUG ((DEBUG_INFO, " NumberOfEvents: (0x%x)\n", FinalEventsTable->NumberOfEvents));
+
+ CcEvent = (CC_EVENT *)(UINTN)(FinalEventsTable + 1);
+ for (NumberOfEvents = 0; NumberOfEvents < FinalEventsTable->NumberOfEvents; NumberOfEvents++) {
+ DumpCcEvent (CcEvent);
+ CcEvent = (CC_EVENT *)((UINTN)CcEvent + GetCcEventSize (CcEvent));
+ }
+ }
+
+ return;
+}
+
+/**
+ The EFI_CC_MEASUREMENT_PROTOCOL Get Event Log function call allows a caller to
+ retrieve the address of a given event log and its last entry.
+
+ @param[in] This Indicates the calling context
+ @param[in] EventLogFormat The type of the event log for which the information is requested.
+ @param[out] EventLogLocation A pointer to the memory address of the event log.
+ @param[out] EventLogLastEntry If the Event Log contains more than one entry, this is a pointer to the
+ address of the start of the last entry in the event log in memory.
+ @param[out] EventLogTruncated If the Event Log is missing at least one entry because an event would
+ have exceeded the area allocated for events, this value is set to TRUE.
+ Otherwise, the value will be FALSE and the Event Log will be complete.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_INVALID_PARAMETER One or more of the parameters are incorrect
+ (e.g. asking for an event log whose format is not supported).
+**/
+EFI_STATUS
+EFIAPI
+TdGetEventLog (
+ IN EFI_CC_MEASUREMENT_PROTOCOL *This,
+ IN EFI_CC_EVENT_LOG_FORMAT EventLogFormat,
+ OUT EFI_PHYSICAL_ADDRESS *EventLogLocation,
+ OUT EFI_PHYSICAL_ADDRESS *EventLogLastEntry,
+ OUT BOOLEAN *EventLogTruncated
+ )
+{
+ UINTN Index = 0;
+
+ DEBUG ((DEBUG_INFO, "TdGetEventLog ... (0x%x)\n", EventLogFormat));
+ ASSERT (EventLogFormat == EFI_CC_EVENT_LOG_FORMAT_TCG_2);
+
+ if (EventLogLocation != NULL) {
+ *EventLogLocation = mTdxDxeData.EventLogAreaStruct[Index].Lasa;
+ DEBUG ((DEBUG_INFO, "TdGetEventLog (EventLogLocation - %x)\n", *EventLogLocation));
+ }
+
+ if (EventLogLastEntry != NULL) {
+ if (!mTdxDxeData.EventLogAreaStruct[Index].EventLogStarted) {
+ *EventLogLastEntry = (EFI_PHYSICAL_ADDRESS)(UINTN)0;
+ } else {
+ *EventLogLastEntry = (EFI_PHYSICAL_ADDRESS)(UINTN)mTdxDxeData.EventLogAreaStruct[Index].LastEvent;
+ }
+
+ DEBUG ((DEBUG_INFO, "TdGetEventLog (EventLogLastEntry - %x)\n", *EventLogLastEntry));
+ }
+
+ if (EventLogTruncated != NULL) {
+ *EventLogTruncated = mTdxDxeData.EventLogAreaStruct[Index].EventLogTruncated;
+ DEBUG ((DEBUG_INFO, "TdGetEventLog (EventLogTruncated - %x)\n", *EventLogTruncated));
+ }
+
+ DEBUG ((DEBUG_INFO, "TdGetEventLog - %r\n", EFI_SUCCESS));
+
+ // Dump Event Log for debug purpose
+ if ((EventLogLocation != NULL) && (EventLogLastEntry != NULL)) {
+ DumpCcEventLog (EventLogFormat, *EventLogLocation, *EventLogLastEntry, mTdxDxeData.FinalEventsTable[Index]);
+ }
+
+ //
+ // All events generated after the invocation of EFI_TCG2_GET_EVENT_LOG SHALL be stored
+ // in an instance of an EFI_CONFIGURATION_TABLE named by the VendorGuid of EFI_TCG2_FINAL_EVENTS_TABLE_GUID.
+ //
+ mTdxDxeData.GetEventLogCalled[Index] = TRUE;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Return if this is a Tcg800155PlatformIdEvent.
+
+ @param[in] NewEventHdr Pointer to a TCG_PCR_EVENT_HDR/TCG_PCR_EVENT_EX data structure.
+ @param[in] NewEventHdrSize New event header size.
+ @param[in] NewEventData Pointer to the new event data.
+ @param[in] NewEventSize New event data size.
+
+ @retval TRUE This is a Tcg800155PlatformIdEvent.
+ @retval FALSE This is NOT a Tcg800155PlatformIdEvent.
+
+**/
+BOOLEAN
+Is800155Event (
+ IN VOID *NewEventHdr,
+ IN UINT32 NewEventHdrSize,
+ IN UINT8 *NewEventData,
+ IN UINT32 NewEventSize
+ )
+{
+ if ((((TCG_PCR_EVENT2_HDR *)NewEventHdr)->EventType == EV_NO_ACTION) &&
+ (NewEventSize >= sizeof (TCG_Sp800_155_PlatformId_Event2)) &&
+ (CompareMem (
+ NewEventData,
+ TCG_Sp800_155_PlatformId_Event2_SIGNATURE,
+ sizeof (TCG_Sp800_155_PlatformId_Event2_SIGNATURE) - 1
+ ) == 0))
+ {
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+/**
+ Add a new entry to the Event Log.
+
+ @param[in, out] EventLogAreaStruct The event log area data structure
+ @param[in] NewEventHdr Pointer to a TCG_PCR_EVENT_HDR/TCG_PCR_EVENT_EX data structure.
+ @param[in] NewEventHdrSize New event header size.
+ @param[in] NewEventData Pointer to the new event data.
+ @param[in] NewEventSize New event data size.
+
+ @retval EFI_SUCCESS The new event log entry was added.
+ @retval EFI_OUT_OF_RESOURCES No enough memory to log the new event.
+
+**/
+EFI_STATUS
+TcgCommLogEvent (
+ IN OUT CC_EVENT_LOG_AREA_STRUCT *EventLogAreaStruct,
+ IN VOID *NewEventHdr,
+ IN UINT32 NewEventHdrSize,
+ IN UINT8 *NewEventData,
+ IN UINT32 NewEventSize
+ )
+{
+ UINTN NewLogSize;
+ BOOLEAN Record800155Event;
+ CC_EVENT_HDR *CcEventHdr;
+
+ CcEventHdr = (CC_EVENT_HDR *)NewEventHdr;
+ DEBUG ((DEBUG_VERBOSE, "Td: Try to log event. Index = %d, EventType = 0x%x\n", CcEventHdr->MrIndex, CcEventHdr->EventType));
+
+ if (NewEventSize > MAX_ADDRESS - NewEventHdrSize) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ NewLogSize = NewEventHdrSize + NewEventSize;
+
+ if (NewLogSize > MAX_ADDRESS - EventLogAreaStruct->EventLogSize) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ if (NewLogSize + EventLogAreaStruct->EventLogSize > EventLogAreaStruct->Laml) {
+ DEBUG ((DEBUG_INFO, " Laml - 0x%x\n", EventLogAreaStruct->Laml));
+ DEBUG ((DEBUG_INFO, " NewLogSize - 0x%x\n", NewLogSize));
+ DEBUG ((DEBUG_INFO, " LogSize - 0x%x\n", EventLogAreaStruct->EventLogSize));
+ DEBUG ((DEBUG_INFO, "TcgCommLogEvent - %r\n", EFI_OUT_OF_RESOURCES));
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // Check 800-155 event
+ // Record to 800-155 event offset only.
+ // If the offset is 0, no need to record.
+ //
+ Record800155Event = Is800155Event (NewEventHdr, NewEventHdrSize, NewEventData, NewEventSize);
+ if (Record800155Event) {
+ DEBUG ((DEBUG_INFO, "It is 800155Event.\n"));
+
+ if (EventLogAreaStruct->Next800155EventOffset != 0) {
+ CopyMem (
+ (UINT8 *)(UINTN)EventLogAreaStruct->Lasa + EventLogAreaStruct->Next800155EventOffset + NewLogSize,
+ (UINT8 *)(UINTN)EventLogAreaStruct->Lasa + EventLogAreaStruct->Next800155EventOffset,
+ EventLogAreaStruct->EventLogSize - EventLogAreaStruct->Next800155EventOffset
+ );
+
+ CopyMem (
+ (UINT8 *)(UINTN)EventLogAreaStruct->Lasa + EventLogAreaStruct->Next800155EventOffset,
+ NewEventHdr,
+ NewEventHdrSize
+ );
+ CopyMem (
+ (UINT8 *)(UINTN)EventLogAreaStruct->Lasa + EventLogAreaStruct->Next800155EventOffset + NewEventHdrSize,
+ NewEventData,
+ NewEventSize
+ );
+
+ EventLogAreaStruct->Next800155EventOffset += NewLogSize;
+ EventLogAreaStruct->LastEvent += NewLogSize;
+ EventLogAreaStruct->EventLogSize += NewLogSize;
+ }
+
+ return EFI_SUCCESS;
+ }
+
+ EventLogAreaStruct->LastEvent = (UINT8 *)(UINTN)EventLogAreaStruct->Lasa + EventLogAreaStruct->EventLogSize;
+ EventLogAreaStruct->EventLogSize += NewLogSize;
+
+ CopyMem (EventLogAreaStruct->LastEvent, NewEventHdr, NewEventHdrSize);
+ CopyMem (
+ EventLogAreaStruct->LastEvent + NewEventHdrSize,
+ NewEventData,
+ NewEventSize
+ );
+
+ return EFI_SUCCESS;
+}
+
+/**
+ RTMR[0] => PCR[1,7]
+ RTMR[1] => PCR[2,3,4,5]
+ RTMR[2] => PCR[8~15]
+ RTMR[3] => NA
+**/
+UINT32
+EFIAPI
+MapPcrToMrIndex (
+ IN UINT32 PCRIndex
+ )
+{
+ UINT32 MrIndex;
+
+ if ((PCRIndex > 16) || (PCRIndex == 6) || (PCRIndex == 0)) {
+ ASSERT (FALSE);
+ return INVALID_RTMR_INDEX;
+ }
+
+ MrIndex = 0;
+ if ((PCRIndex == 1) || (PCRIndex == 7)) {
+ MrIndex = 0;
+ } else if ((PCRIndex > 1) && (PCRIndex < 6)) {
+ MrIndex = 1;
+ } else if ((PCRIndex > 7) && (PCRIndex < 16)) {
+ MrIndex = 2;
+ }
+
+ return MrIndex;
+}
+
+EFI_STATUS
+EFIAPI
+TdMapPcrToMrIndex (
+ IN EFI_CC_MEASUREMENT_PROTOCOL *This,
+ IN UINT32 PCRIndex,
+ OUT UINT32 *MrIndex
+ )
+{
+ if (MrIndex == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if ((PCRIndex > 16) || (PCRIndex == 0) || (PCRIndex == 6)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ *MrIndex = MapPcrToMrIndex (PCRIndex);
+
+ return *MrIndex == INVALID_RTMR_INDEX ? EFI_INVALID_PARAMETER : EFI_SUCCESS;
+}
+
+/**
+ Add a new entry to the Event Log.
+
+ @param[in] EventLogFormat The type of the event log for which the information is requested.
+ @param[in] NewEventHdr Pointer to a TCG_PCR_EVENT_HDR/TCG_PCR_EVENT_EX data structure.
+ @param[in] NewEventHdrSize New event header size.
+ @param[in] NewEventData Pointer to the new event data.
+ @param[in] NewEventSize New event data size.
+
+ @retval EFI_SUCCESS The new event log entry was added.
+ @retval EFI_OUT_OF_RESOURCES No enough memory to log the new event.
+
+**/
+EFI_STATUS
+TdxDxeLogEvent (
+ IN EFI_CC_EVENT_LOG_FORMAT EventLogFormat,
+ IN VOID *NewEventHdr,
+ IN UINT32 NewEventHdrSize,
+ IN UINT8 *NewEventData,
+ IN UINT32 NewEventSize
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ CC_EVENT_LOG_AREA_STRUCT *EventLogAreaStruct;
+
+ if (EventLogFormat != EFI_CC_EVENT_LOG_FORMAT_TCG_2) {
+ ASSERT (FALSE);
+ return EFI_INVALID_PARAMETER;
+ }
+
+ Index = 0;
+
+ //
+ // Record to normal event log
+ //
+ EventLogAreaStruct = &mTdxDxeData.EventLogAreaStruct[Index];
+
+ if (EventLogAreaStruct->EventLogTruncated) {
+ return EFI_VOLUME_FULL;
+ }
+
+ Status = TcgCommLogEvent (
+ EventLogAreaStruct,
+ NewEventHdr,
+ NewEventHdrSize,
+ NewEventData,
+ NewEventSize
+ );
+
+ if (Status == EFI_OUT_OF_RESOURCES) {
+ EventLogAreaStruct->EventLogTruncated = TRUE;
+ return EFI_VOLUME_FULL;
+ } else if (Status == EFI_SUCCESS) {
+ EventLogAreaStruct->EventLogStarted = TRUE;
+ }
+
+ //
+ // If GetEventLog is called, record to FinalEventsTable, too.
+ //
+ if (mTdxDxeData.GetEventLogCalled[Index]) {
+ if (mTdxDxeData.FinalEventsTable[Index] == NULL) {
+ //
+ // no need for FinalEventsTable
+ //
+ return EFI_SUCCESS;
+ }
+
+ EventLogAreaStruct = &mTdxDxeData.FinalEventLogAreaStruct[Index];
+
+ if (EventLogAreaStruct->EventLogTruncated) {
+ return EFI_VOLUME_FULL;
+ }
+
+ Status = TcgCommLogEvent (
+ EventLogAreaStruct,
+ NewEventHdr,
+ NewEventHdrSize,
+ NewEventData,
+ NewEventSize
+ );
+ if (Status == EFI_OUT_OF_RESOURCES) {
+ EventLogAreaStruct->EventLogTruncated = TRUE;
+ return EFI_VOLUME_FULL;
+ } else if (Status == EFI_SUCCESS) {
+ EventLogAreaStruct->EventLogStarted = TRUE;
+ //
+ // Increase the NumberOfEvents in FinalEventsTable
+ //
+ (mTdxDxeData.FinalEventsTable[Index])->NumberOfEvents++;
+ DEBUG ((DEBUG_INFO, "FinalEventsTable->NumberOfEvents - 0x%x\n", (mTdxDxeData.FinalEventsTable[Index])->NumberOfEvents));
+ DEBUG ((DEBUG_INFO, " Size - 0x%x\n", (UINTN)EventLogAreaStruct->EventLogSize));
+ }
+ }
+
+ return Status;
+}
+
+/**
+ Get TPML_DIGEST_VALUES compact binary buffer size.
+
+ @param[in] DigestListBin TPML_DIGEST_VALUES compact binary buffer.
+
+ @return TPML_DIGEST_VALUES compact binary buffer size.
+**/
+UINT32
+GetDigestListBinSize (
+ IN VOID *DigestListBin
+ )
+{
+ UINTN Index;
+ UINT16 DigestSize;
+ UINT32 TotalSize;
+ UINT32 Count;
+ TPMI_ALG_HASH HashAlg;
+
+ Count = ReadUnaligned32 (DigestListBin);
+ TotalSize = sizeof (Count);
+ DigestListBin = (UINT8 *)DigestListBin + sizeof (Count);
+ for (Index = 0; Index < Count; Index++) {
+ HashAlg = ReadUnaligned16 (DigestListBin);
+ TotalSize += sizeof (HashAlg);
+ DigestListBin = (UINT8 *)DigestListBin + sizeof (HashAlg);
+
+ DigestSize = GetHashSizeFromAlgo (HashAlg);
+ TotalSize += DigestSize;
+ DigestListBin = (UINT8 *)DigestListBin + DigestSize;
+ }
+
+ return TotalSize;
+}
+
+/**
+ Copy TPML_DIGEST_VALUES compact binary into a buffer
+
+ @param[in,out] Buffer Buffer to hold copied TPML_DIGEST_VALUES compact binary.
+ @param[in] DigestListBin TPML_DIGEST_VALUES compact binary buffer.
+ @param[in] HashAlgorithmMask HASH bits corresponding to the desired digests to copy.
+ @param[out] HashAlgorithmMaskCopied Pointer to HASH bits corresponding to the digests copied.
+
+ @return The end of buffer to hold TPML_DIGEST_VALUES compact binary.
+**/
+VOID *
+CopyDigestListBinToBuffer (
+ IN OUT VOID *Buffer,
+ IN VOID *DigestListBin,
+ IN UINT32 HashAlgorithmMask,
+ OUT UINT32 *HashAlgorithmMaskCopied
+ )
+{
+ UINTN Index;
+ UINT16 DigestSize;
+ UINT32 Count;
+ TPMI_ALG_HASH HashAlg;
+ UINT32 DigestListCount;
+ UINT32 *DigestListCountPtr;
+
+ DigestListCountPtr = (UINT32 *)Buffer;
+ DigestListCount = 0;
+ *HashAlgorithmMaskCopied = 0;
+
+ Count = ReadUnaligned32 (DigestListBin);
+ Buffer = (UINT8 *)Buffer + sizeof (Count);
+ DigestListBin = (UINT8 *)DigestListBin + sizeof (Count);
+ for (Index = 0; Index < Count; Index++) {
+ HashAlg = ReadUnaligned16 (DigestListBin);
+ DigestListBin = (UINT8 *)DigestListBin + sizeof (HashAlg);
+ DigestSize = GetHashSizeFromAlgo (HashAlg);
+
+ if ((HashAlg & HashAlgorithmMask) != 0) {
+ CopyMem (Buffer, &HashAlg, sizeof (HashAlg));
+ Buffer = (UINT8 *)Buffer + sizeof (HashAlg);
+ CopyMem (Buffer, DigestListBin, DigestSize);
+ Buffer = (UINT8 *)Buffer + DigestSize;
+ DigestListCount++;
+ (*HashAlgorithmMaskCopied) |= GetHashMaskFromAlgo (HashAlg);
+ } else {
+ DEBUG ((DEBUG_ERROR, "WARNING: CopyDigestListBinToBuffer Event log has HashAlg unsupported by PCR bank (0x%x)\n", HashAlg));
+ }
+
+ DigestListBin = (UINT8 *)DigestListBin + DigestSize;
+ }
+
+ WriteUnaligned32 (DigestListCountPtr, DigestListCount);
+
+ return Buffer;
+}
+
+/**
+ Add a new entry to the Event Log. The call chain is like below:
+ TdxDxeLogHashEvent -> TdxDxeLogEvent -> TcgCommonLogEvent
+
+ Before this function is called, the event information (including the digest)
+ is ready.
+
+ @param[in] DigestList A list of digest.
+ @param[in,out] NewEventHdr Pointer to a TD_EVENT_HDR data structure.
+ @param[in] NewEventData Pointer to the new event data.
+
+ @retval EFI_SUCCESS The new event log entry was added.
+ @retval EFI_OUT_OF_RESOURCES No enough memory to log the new event.
+**/
+EFI_STATUS
+TdxDxeLogHashEvent (
+ IN TPML_DIGEST_VALUES *DigestList,
+ IN OUT CC_EVENT_HDR *NewEventHdr,
+ IN UINT8 *NewEventData
+ )
+{
+ EFI_STATUS Status;
+ EFI_TPL OldTpl;
+ EFI_STATUS RetStatus;
+ CC_EVENT CcEvent;
+ UINT8 *DigestBuffer;
+ UINT32 *EventSizePtr;
+ EFI_CC_EVENT_LOG_FORMAT LogFormat;
+
+ RetStatus = EFI_SUCCESS;
+ LogFormat = EFI_CC_EVENT_LOG_FORMAT_TCG_2;
+
+ ZeroMem (&CcEvent, sizeof (CcEvent));
+ //
+ // The index of event log is designed as below:
+ // 0 : MRTD
+ // 1-4: RTMR[0-3]
+ //
+ CcEvent.MrIndex = NewEventHdr->MrIndex + 1;
+ CcEvent.EventType = NewEventHdr->EventType;
+ DigestBuffer = (UINT8 *)&CcEvent.Digests;
+ EventSizePtr = CopyDigestListToBuffer (DigestBuffer, DigestList, HASH_ALG_SHA384);
+ CopyMem (EventSizePtr, &NewEventHdr->EventSize, sizeof (NewEventHdr->EventSize));
+
+ //
+ // Enter critical region
+ //
+ OldTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+ Status = TdxDxeLogEvent (
+ LogFormat,
+ &CcEvent,
+ sizeof (CcEvent.MrIndex) + sizeof (CcEvent.EventType) + GetDigestListBinSize (DigestBuffer) + sizeof (CcEvent.EventSize),
+ NewEventData,
+ NewEventHdr->EventSize
+ );
+ if (Status != EFI_SUCCESS) {
+ RetStatus = Status;
+ }
+
+ gBS->RestoreTPL (OldTpl);
+
+ return RetStatus;
+}
+
+/**
+ Do a hash operation on a data buffer, extend a specific RTMR with the hash result,
+ and add an entry to the Event Log.
+
+ @param[in] Flags Bitmap providing additional information.
+ @param[in] HashData Physical address of the start of the data buffer
+ to be hashed, extended, and logged.
+ @param[in] HashDataLen The length, in bytes, of the buffer referenced by HashData
+ @param[in, out] NewEventHdr Pointer to a TD_EVENT_HDR data structure.
+ @param[in] NewEventData Pointer to the new event data.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_OUT_OF_RESOURCES No enough memory to log the new event.
+ @retval EFI_DEVICE_ERROR The command was unsuccessful.
+
+**/
+EFI_STATUS
+TdxDxeHashLogExtendEvent (
+ IN UINT64 Flags,
+ IN UINT8 *HashData,
+ IN UINT64 HashDataLen,
+ IN OUT CC_EVENT_HDR *NewEventHdr,
+ IN UINT8 *NewEventData
+ )
+{
+ EFI_STATUS Status;
+ TPML_DIGEST_VALUES DigestList;
+ CC_EVENT_HDR NoActionEvent;
+
+ if (NewEventHdr->EventType == EV_NO_ACTION) {
+ //
+ // Do not do RTMR extend for EV_NO_ACTION
+ //
+ Status = EFI_SUCCESS;
+ InitNoActionEvent (&NoActionEvent, NewEventHdr->EventSize);
+ if ((Flags & EFI_CC_FLAG_EXTEND_ONLY) == 0) {
+ Status = TdxDxeLogHashEvent (&(NoActionEvent.Digests), NewEventHdr, NewEventData);
+ }
+
+ return Status;
+ }
+
+ Status = HashAndExtend (
+ NewEventHdr->MrIndex,
+ HashData,
+ (UINTN)HashDataLen,
+ &DigestList
+ );
+ if (!EFI_ERROR (Status)) {
+ if ((Flags & EFI_CC_FLAG_EXTEND_ONLY) == 0) {
+ Status = TdxDxeLogHashEvent (&DigestList, NewEventHdr, NewEventData);
+ }
+ }
+
+ return Status;
+}
+
+/**
+ The EFI_CC_MEASUREMENT_PROTOCOL HashLogExtendEvent function call provides callers with
+ an opportunity to extend and optionally log events without requiring
+ knowledge of actual TPM commands.
+ The extend operation will occur even if this function cannot create an event
+ log entry (e.g. due to the event log being full).
+
+ @param[in] This Indicates the calling context
+ @param[in] Flags Bitmap providing additional information.
+ @param[in] DataToHash Physical address of the start of the data buffer to be hashed.
+ @param[in] DataToHashLen The length in bytes of the buffer referenced by DataToHash.
+ @param[in] Event Pointer to data buffer containing information about the event.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_DEVICE_ERROR The command was unsuccessful.
+ @retval EFI_VOLUME_FULL The extend operation occurred, but the event could not be written to one or more event logs.
+ @retval EFI_INVALID_PARAMETER One or more of the parameters are incorrect.
+ @retval EFI_UNSUPPORTED The PE/COFF image type is not supported.
+**/
+EFI_STATUS
+EFIAPI
+TdHashLogExtendEvent (
+ IN EFI_CC_MEASUREMENT_PROTOCOL *This,
+ IN UINT64 Flags,
+ IN EFI_PHYSICAL_ADDRESS DataToHash,
+ IN UINT64 DataToHashLen,
+ IN EFI_CC_EVENT *CcEvent
+ )
+{
+ EFI_STATUS Status;
+ CC_EVENT_HDR NewEventHdr;
+ TPML_DIGEST_VALUES DigestList;
+
+ DEBUG ((DEBUG_VERBOSE, "TdHashLogExtendEvent ...\n"));
+
+ if ((This == NULL) || (CcEvent == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Do not check hash data size for EV_NO_ACTION event.
+ //
+ if ((CcEvent->Header.EventType != EV_NO_ACTION) && (DataToHash == 0)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (CcEvent->Size < CcEvent->Header.HeaderSize + sizeof (UINT32)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (CcEvent->Header.MrIndex > 4) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ NewEventHdr.MrIndex = CcEvent->Header.MrIndex;
+ NewEventHdr.EventType = CcEvent->Header.EventType;
+ NewEventHdr.EventSize = CcEvent->Size - sizeof (UINT32) - CcEvent->Header.HeaderSize;
+ if ((Flags & EFI_CC_FLAG_PE_COFF_IMAGE) != 0) {
+ Status = MeasurePeImageAndExtend (
+ NewEventHdr.MrIndex,
+ DataToHash,
+ (UINTN)DataToHashLen,
+ &DigestList
+ );
+ if (!EFI_ERROR (Status)) {
+ if ((Flags & EFI_CC_FLAG_EXTEND_ONLY) == 0) {
+ Status = TdxDxeLogHashEvent (&DigestList, &NewEventHdr, CcEvent->Event);
+ }
+ }
+ } else {
+ Status = TdxDxeHashLogExtendEvent (
+ Flags,
+ (UINT8 *)(UINTN)DataToHash,
+ DataToHashLen,
+ &NewEventHdr,
+ CcEvent->Event
+ );
+ }
+
+ DEBUG ((DEBUG_VERBOSE, "TdHashLogExtendEvent - %r\n", Status));
+ return Status;
+}
+
+EFI_CC_MEASUREMENT_PROTOCOL mTdProtocol = {
+ TdGetCapability,
+ TdGetEventLog,
+ TdHashLogExtendEvent,
+ TdMapPcrToMrIndex,
+};
+
+#define TD_HASH_COUNT 1
+#define TEMP_BUF_LEN (sizeof(TCG_EfiSpecIDEventStruct) + sizeof(UINT32) \
+ + (TD_HASH_COUNT * sizeof(TCG_EfiSpecIdEventAlgorithmSize)) + sizeof(UINT8))
+
+/**
+ Initialize the TD Event Log and log events passed from the PEI phase.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_OUT_OF_RESOURCES Out of memory.
+
+**/
+EFI_STATUS
+SetupCcEventLog (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ EFI_PHYSICAL_ADDRESS Lasa;
+ UINTN Index;
+ TCG_EfiSpecIDEventStruct *TcgEfiSpecIdEventStruct;
+ UINT8 TempBuf[TEMP_BUF_LEN];
+ TCG_PCR_EVENT_HDR SpecIdEvent;
+ TCG_EfiSpecIdEventAlgorithmSize *DigestSize;
+ TCG_EfiSpecIdEventAlgorithmSize *TempDigestSize;
+ UINT8 *VendorInfoSize;
+ UINT32 NumberOfAlgorithms;
+ EFI_CC_EVENT_LOG_FORMAT LogFormat;
+ EFI_PEI_HOB_POINTERS GuidHob;
+ CC_EVENT_HDR NoActionEvent;
+
+ Status = EFI_SUCCESS;
+ DEBUG ((DEBUG_INFO, "SetupCcEventLog\n"));
+
+ Index = 0;
+ LogFormat = EFI_CC_EVENT_LOG_FORMAT_TCG_2;
+
+ //
+ // 1. Create Log Area
+ //
+ mTdxDxeData.EventLogAreaStruct[Index].EventLogFormat = LogFormat;
+
+ // allocate pages for TD Event log
+ Status = gBS->AllocatePages (
+ AllocateAnyPages,
+ EfiACPIMemoryNVS,
+ EFI_SIZE_TO_PAGES (PcdGet32 (PcdTcgLogAreaMinLen)),
+ &Lasa
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ mTdxDxeData.EventLogAreaStruct[Index].Lasa = Lasa;
+ mTdxDxeData.EventLogAreaStruct[Index].Laml = PcdGet32 (PcdTcgLogAreaMinLen);
+ mTdxDxeData.EventLogAreaStruct[Index].Next800155EventOffset = 0;
+
+ //
+ // Report TD event log address and length, so that they can be reported in
+ // TD ACPI table. Ignore the return status, because those fields are optional.
+ //
+ PcdSet32S (PcdCcEventlogAcpiTableLaml, (UINT32)mTdxDxeData.EventLogAreaStruct[Index].Laml);
+ PcdSet64S (PcdCcEventlogAcpiTableLasa, mTdxDxeData.EventLogAreaStruct[Index].Lasa);
+
+ //
+ // To initialize them as 0xFF is recommended
+ // because the OS can know the last entry for that.
+ //
+ SetMem ((VOID *)(UINTN)Lasa, PcdGet32 (PcdTcgLogAreaMinLen), 0xFF);
+
+ //
+ // Create first entry for Log Header Entry Data
+ //
+
+ //
+ // TcgEfiSpecIdEventStruct
+ //
+ TcgEfiSpecIdEventStruct = (TCG_EfiSpecIDEventStruct *)TempBuf;
+ CopyMem (TcgEfiSpecIdEventStruct->signature, TCG_EfiSpecIDEventStruct_SIGNATURE_03, sizeof (TcgEfiSpecIdEventStruct->signature));
+
+ TcgEfiSpecIdEventStruct->platformClass = PcdGet8 (PcdTpmPlatformClass);
+
+ TcgEfiSpecIdEventStruct->specVersionMajor = TCG_EfiSpecIDEventStruct_SPEC_VERSION_MAJOR_TPM2;
+ TcgEfiSpecIdEventStruct->specVersionMinor = TCG_EfiSpecIDEventStruct_SPEC_VERSION_MINOR_TPM2;
+ TcgEfiSpecIdEventStruct->specErrata = TCG_EfiSpecIDEventStruct_SPEC_ERRATA_TPM2;
+ TcgEfiSpecIdEventStruct->uintnSize = sizeof (UINTN)/sizeof (UINT32);
+ NumberOfAlgorithms = 0;
+ DigestSize = (TCG_EfiSpecIdEventAlgorithmSize *)((UINT8 *)TcgEfiSpecIdEventStruct
+ + sizeof (*TcgEfiSpecIdEventStruct)
+ + sizeof (NumberOfAlgorithms));
+
+ TempDigestSize = DigestSize;
+ TempDigestSize += NumberOfAlgorithms;
+ TempDigestSize->algorithmId = TPM_ALG_SHA384;
+ TempDigestSize->digestSize = SHA384_DIGEST_SIZE;
+ NumberOfAlgorithms++;
+
+ CopyMem (TcgEfiSpecIdEventStruct + 1, &NumberOfAlgorithms, sizeof (NumberOfAlgorithms));
+ TempDigestSize = DigestSize;
+ TempDigestSize += NumberOfAlgorithms;
+ VendorInfoSize = (UINT8 *)TempDigestSize;
+ *VendorInfoSize = 0;
+
+ SpecIdEvent.PCRIndex = 1; // PCRIndex 0 maps to MrIndex 1
+ SpecIdEvent.EventType = EV_NO_ACTION;
+ ZeroMem (&SpecIdEvent.Digest, sizeof (SpecIdEvent.Digest));
+ SpecIdEvent.EventSize = (UINT32)GetTcgEfiSpecIdEventStructSize (TcgEfiSpecIdEventStruct);
+
+ //
+ // TD Event log re-use the spec of TCG2 Event log.
+ // Log TcgEfiSpecIdEventStruct as the first Event. Event format is TCG_PCR_EVENT.
+ // TCG EFI Protocol Spec. Section 5.3 Event Log Header
+ // TCG PC Client PFP spec. Section 9.2 Measurement Event Entries and Log
+ //
+ Status = TdxDxeLogEvent (
+ LogFormat,
+ &SpecIdEvent,
+ sizeof (SpecIdEvent),
+ (UINT8 *)TcgEfiSpecIdEventStruct,
+ SpecIdEvent.EventSize
+ );
+ //
+ // record the offset at the end of 800-155 event.
+ // the future 800-155 event can be inserted here.
+ //
+ mTdxDxeData.EventLogAreaStruct[Index].Next800155EventOffset = mTdxDxeData.EventLogAreaStruct[Index].EventLogSize;
+
+ //
+ // Tcg800155PlatformIdEvent. Event format is TCG_PCR_EVENT2
+ //
+ GuidHob.Guid = GetFirstGuidHob (&gTcg800155PlatformIdEventHobGuid);
+ while (GuidHob.Guid != NULL) {
+ InitNoActionEvent (&NoActionEvent, GET_GUID_HOB_DATA_SIZE (GuidHob.Guid));
+
+ Status = TdxDxeLogEvent (
+ LogFormat,
+ &NoActionEvent,
+ sizeof (NoActionEvent.MrIndex) + sizeof (NoActionEvent.EventType) + GetDigestListBinSize (&NoActionEvent.Digests) + sizeof (NoActionEvent.EventSize),
+ GET_GUID_HOB_DATA (GuidHob.Guid),
+ GET_GUID_HOB_DATA_SIZE (GuidHob.Guid)
+ );
+
+ GuidHob.Guid = GET_NEXT_HOB (GuidHob);
+ GuidHob.Guid = GetNextGuidHob (&gTcg800155PlatformIdEventHobGuid, GuidHob.Guid);
+ }
+
+ //
+ // 2. Create Final Log Area
+ //
+ Status = gBS->AllocatePages (
+ AllocateAnyPages,
+ EfiACPIMemoryNVS,
+ EFI_SIZE_TO_PAGES (PcdGet32 (PcdTcg2FinalLogAreaLen)),
+ &Lasa
+ );
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ SetMem ((VOID *)(UINTN)Lasa, PcdGet32 (PcdTcg2FinalLogAreaLen), 0xFF);
+
+ //
+ // Initialize
+ //
+ mTdxDxeData.FinalEventsTable[Index] = (VOID *)(UINTN)Lasa;
+ (mTdxDxeData.FinalEventsTable[Index])->Version = EFI_TCG2_FINAL_EVENTS_TABLE_VERSION;
+ (mTdxDxeData.FinalEventsTable[Index])->NumberOfEvents = 0;
+
+ mTdxDxeData.FinalEventLogAreaStruct[Index].EventLogFormat = LogFormat;
+ mTdxDxeData.FinalEventLogAreaStruct[Index].Lasa = Lasa + sizeof (EFI_CC_FINAL_EVENTS_TABLE);
+ mTdxDxeData.FinalEventLogAreaStruct[Index].Laml = PcdGet32 (PcdTcg2FinalLogAreaLen) - sizeof (EFI_CC_FINAL_EVENTS_TABLE);
+ mTdxDxeData.FinalEventLogAreaStruct[Index].EventLogSize = 0;
+ mTdxDxeData.FinalEventLogAreaStruct[Index].LastEvent = (VOID *)(UINTN)mTdxDxeData.FinalEventLogAreaStruct[Index].Lasa;
+ mTdxDxeData.FinalEventLogAreaStruct[Index].EventLogStarted = FALSE;
+ mTdxDxeData.FinalEventLogAreaStruct[Index].EventLogTruncated = FALSE;
+ mTdxDxeData.FinalEventLogAreaStruct[Index].Next800155EventOffset = 0;
+
+ //
+ // Install to configuration table for EFI_CC_EVENT_LOG_FORMAT_TCG_2
+ //
+ Status = gBS->InstallConfigurationTable (&gEfiCcFinalEventsTableGuid, (VOID *)mTdxDxeData.FinalEventsTable[Index]);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+
+ return Status;
+}
+
+/**
+ Measure and log an action string, and extend the measurement result into RTMR.
+
+ @param[in] MrIndex MrIndex to extend
+ @param[in] String A specific string that indicates an Action event.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_DEVICE_ERROR The operation was unsuccessful.
+
+**/
+EFI_STATUS
+TdMeasureAction (
+ IN UINT32 MrIndex,
+ IN CHAR8 *String
+ )
+{
+ CC_EVENT_HDR CcEvent;
+
+ CcEvent.MrIndex = MrIndex;
+ CcEvent.EventType = EV_EFI_ACTION;
+ CcEvent.EventSize = (UINT32)AsciiStrLen (String);
+ return TdxDxeHashLogExtendEvent (
+ 0,
+ (UINT8 *)String,
+ CcEvent.EventSize,
+ &CcEvent,
+ (UINT8 *)String
+ );
+}
+
+/**
+ Measure and log EFI handoff tables, and extend the measurement result into PCR[1].
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_DEVICE_ERROR The operation was unsuccessful.
+
+**/
+EFI_STATUS
+MeasureHandoffTables (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ CC_EVENT_HDR CcEvent;
+ EFI_HANDOFF_TABLE_POINTERS HandoffTables;
+ UINTN ProcessorNum;
+ EFI_CPU_PHYSICAL_LOCATION *ProcessorLocBuf;
+
+ ProcessorLocBuf = NULL;
+ Status = EFI_SUCCESS;
+
+ if (PcdGet8 (PcdTpmPlatformClass) == TCG_PLATFORM_TYPE_SERVER) {
+ //
+ // Tcg Server spec.
+ // Measure each processor EFI_CPU_PHYSICAL_LOCATION with EV_TABLE_OF_DEVICES to PCR[1]
+ //
+ Status = GetProcessorsCpuLocation (&ProcessorLocBuf, &ProcessorNum);
+
+ if (!EFI_ERROR (Status)) {
+ CcEvent.MrIndex = MapPcrToMrIndex (1);
+ CcEvent.EventType = EV_TABLE_OF_DEVICES;
+ CcEvent.EventSize = sizeof (HandoffTables);
+
+ HandoffTables.NumberOfTables = 1;
+ HandoffTables.TableEntry[0].VendorGuid = gEfiMpServiceProtocolGuid;
+ HandoffTables.TableEntry[0].VendorTable = ProcessorLocBuf;
+
+ Status = TdxDxeHashLogExtendEvent (
+ 0,
+ (UINT8 *)(UINTN)ProcessorLocBuf,
+ sizeof (EFI_CPU_PHYSICAL_LOCATION) * ProcessorNum,
+ &CcEvent,
+ (UINT8 *)&HandoffTables
+ );
+
+ FreePool (ProcessorLocBuf);
+ }
+ }
+
+ return Status;
+}
+
+/**
+ Measure and log Separator event, and extend the measurement result into a specific PCR.
+
+ @param[in] PCRIndex PCR index.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_DEVICE_ERROR The operation was unsuccessful.
+
+**/
+EFI_STATUS
+MeasureSeparatorEvent (
+ IN UINT32 MrIndex
+ )
+{
+ CC_EVENT_HDR CcEvent;
+ UINT32 EventData;
+
+ DEBUG ((DEBUG_INFO, "MeasureSeparatorEvent to Rtmr - %d\n", MrIndex));
+
+ EventData = 0;
+ CcEvent.MrIndex = MrIndex;
+ CcEvent.EventType = EV_SEPARATOR;
+ CcEvent.EventSize = (UINT32)sizeof (EventData);
+
+ return TdxDxeHashLogExtendEvent (
+ 0,
+ (UINT8 *)&EventData,
+ sizeof (EventData),
+ &CcEvent,
+ (UINT8 *)&EventData
+ );
+}
+
+/**
+ Measure and log an EFI variable, and extend the measurement result into a specific RTMR.
+
+ @param[in] MrIndex RTMR Index.
+ @param[in] EventType Event type.
+ @param[in] VarName A Null-terminated string that is the name of the vendor's variable.
+ @param[in] VendorGuid A unique identifier for the vendor.
+ @param[in] VarData The content of the variable data.
+ @param[in] VarSize The size of the variable data.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_OUT_OF_RESOURCES Out of memory.
+ @retval EFI_DEVICE_ERROR The operation was unsuccessful.
+
+**/
+EFI_STATUS
+MeasureVariable (
+ IN UINT32 MrIndex,
+ IN TCG_EVENTTYPE EventType,
+ IN CHAR16 *VarName,
+ IN EFI_GUID *VendorGuid,
+ IN VOID *VarData,
+ IN UINTN VarSize
+ )
+{
+ EFI_STATUS Status;
+ CC_EVENT_HDR CcEvent;
+ UINTN VarNameLength;
+ UEFI_VARIABLE_DATA *VarLog;
+
+ DEBUG ((DEBUG_INFO, "TdTcg2Dxe: MeasureVariable (Rtmr - %x, EventType - %x, ", (UINTN)MrIndex, (UINTN)EventType));
+ DEBUG ((DEBUG_INFO, "VariableName - %s, VendorGuid - %g)\n", VarName, VendorGuid));
+
+ VarNameLength = StrLen (VarName);
+ CcEvent.MrIndex = MrIndex;
+ CcEvent.EventType = EventType;
+
+ CcEvent.EventSize = (UINT32)(sizeof (*VarLog) + VarNameLength * sizeof (*VarName) + VarSize
+ - sizeof (VarLog->UnicodeName) - sizeof (VarLog->VariableData));
+
+ VarLog = (UEFI_VARIABLE_DATA *)AllocatePool (CcEvent.EventSize);
+ if (VarLog == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ VarLog->VariableName = *VendorGuid;
+ VarLog->UnicodeNameLength = VarNameLength;
+ VarLog->VariableDataLength = VarSize;
+ CopyMem (
+ VarLog->UnicodeName,
+ VarName,
+ VarNameLength * sizeof (*VarName)
+ );
+ if ((VarSize != 0) && (VarData != NULL)) {
+ CopyMem (
+ (CHAR16 *)VarLog->UnicodeName + VarNameLength,
+ VarData,
+ VarSize
+ );
+ }
+
+ if (EventType == EV_EFI_VARIABLE_DRIVER_CONFIG) {
+ //
+ // Digest is the event data (UEFI_VARIABLE_DATA)
+ //
+ Status = TdxDxeHashLogExtendEvent (
+ 0,
+ (UINT8 *)VarLog,
+ CcEvent.EventSize,
+ &CcEvent,
+ (UINT8 *)VarLog
+ );
+ } else {
+ ASSERT (VarData != NULL);
+ Status = TdxDxeHashLogExtendEvent (
+ 0,
+ (UINT8 *)VarData,
+ VarSize,
+ &CcEvent,
+ (UINT8 *)VarLog
+ );
+ }
+
+ FreePool (VarLog);
+ return Status;
+}
+
+/**
+ Read then Measure and log an EFI variable, and extend the measurement result into a specific RTMR.
+
+ @param[in] MrIndex RTMR Index.
+ @param[in] EventType Event type.
+ @param[in] VarName A Null-terminated string that is the name of the vendor's variable.
+ @param[in] VendorGuid A unique identifier for the vendor.
+ @param[out] VarSize The size of the variable data.
+ @param[out] VarData Pointer to the content of the variable.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_OUT_OF_RESOURCES Out of memory.
+ @retval EFI_DEVICE_ERROR The operation was unsuccessful.
+
+**/
+EFI_STATUS
+ReadAndMeasureVariable (
+ IN UINT32 MrIndex,
+ IN TCG_EVENTTYPE EventType,
+ IN CHAR16 *VarName,
+ IN EFI_GUID *VendorGuid,
+ OUT UINTN *VarSize,
+ OUT VOID **VarData
+ )
+{
+ EFI_STATUS Status;
+
+ Status = GetVariable2 (VarName, VendorGuid, VarData, VarSize);
+ if (EventType == EV_EFI_VARIABLE_DRIVER_CONFIG) {
+ if (EFI_ERROR (Status)) {
+ //
+ // It is valid case, so we need handle it.
+ //
+ *VarData = NULL;
+ *VarSize = 0;
+ }
+ } else {
+ //
+ // if status error, VarData is freed and set NULL by GetVariable2
+ //
+ if (EFI_ERROR (Status)) {
+ return EFI_NOT_FOUND;
+ }
+ }
+
+ Status = MeasureVariable (
+ MrIndex,
+ EventType,
+ VarName,
+ VendorGuid,
+ *VarData,
+ *VarSize
+ );
+ return Status;
+}
+
+/**
+ Read then Measure and log an EFI boot variable, and extend the measurement result into PCR[1].
+according to TCG PC Client PFP spec 0021 Section 2.4.4.2
+
+ @param[in] VarName A Null-terminated string that is the name of the vendor's variable.
+ @param[in] VendorGuid A unique identifier for the vendor.
+ @param[out] VarSize The size of the variable data.
+ @param[out] VarData Pointer to the content of the variable.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_OUT_OF_RESOURCES Out of memory.
+ @retval EFI_DEVICE_ERROR The operation was unsuccessful.
+
+**/
+EFI_STATUS
+ReadAndMeasureBootVariable (
+ IN CHAR16 *VarName,
+ IN EFI_GUID *VendorGuid,
+ OUT UINTN *VarSize,
+ OUT VOID **VarData
+ )
+{
+ //
+ // Boot variables are measured into (PCR[5]) RTMR[1],
+ // details in section 8.1 of TDVF design guide.
+ //
+ return ReadAndMeasureVariable (
+ MapPcrToMrIndex (5),
+ EV_EFI_VARIABLE_BOOT,
+ VarName,
+ VendorGuid,
+ VarSize,
+ VarData
+ );
+}
+
+/**
+ Read then Measure and log an EFI Secure variable, and extend the measurement result into PCR[7].
+
+ @param[in] VarName A Null-terminated string that is the name of the vendor's variable.
+ @param[in] VendorGuid A unique identifier for the vendor.
+ @param[out] VarSize The size of the variable data.
+ @param[out] VarData Pointer to the content of the variable.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_OUT_OF_RESOURCES Out of memory.
+ @retval EFI_DEVICE_ERROR The operation was unsuccessful.
+
+**/
+EFI_STATUS
+ReadAndMeasureSecureVariable (
+ IN CHAR16 *VarName,
+ IN EFI_GUID *VendorGuid,
+ OUT UINTN *VarSize,
+ OUT VOID **VarData
+ )
+{
+ return ReadAndMeasureVariable (
+ MapPcrToMrIndex (7),
+ EV_EFI_VARIABLE_DRIVER_CONFIG,
+ VarName,
+ VendorGuid,
+ VarSize,
+ VarData
+ );
+}
+
+/**
+ Measure and log all EFI boot variables, and extend the measurement result into a specific PCR.
+
+ The EFI boot variables are BootOrder and Boot#### variables.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_OUT_OF_RESOURCES Out of memory.
+ @retval EFI_DEVICE_ERROR The operation was unsuccessful.
+
+**/
+EFI_STATUS
+MeasureAllBootVariables (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ UINT16 *BootOrder;
+ UINTN BootCount;
+ UINTN Index;
+ VOID *BootVarData;
+ UINTN Size;
+
+ Status = ReadAndMeasureBootVariable (
+ mBootVarName,
+ &gEfiGlobalVariableGuid,
+ &BootCount,
+ (VOID **)&BootOrder
+ );
+ if ((Status == EFI_NOT_FOUND) || (BootOrder == NULL)) {
+ return EFI_SUCCESS;
+ }
+
+ if (EFI_ERROR (Status)) {
+ //
+ // BootOrder can't be NULL if status is not EFI_NOT_FOUND
+ //
+ FreePool (BootOrder);
+ return Status;
+ }
+
+ BootCount /= sizeof (*BootOrder);
+ for (Index = 0; Index < BootCount; Index++) {
+ UnicodeSPrint (mBootVarName, sizeof (mBootVarName), L"Boot%04x", BootOrder[Index]);
+ Status = ReadAndMeasureBootVariable (
+ mBootVarName,
+ &gEfiGlobalVariableGuid,
+ &Size,
+ &BootVarData
+ );
+ if (!EFI_ERROR (Status)) {
+ FreePool (BootVarData);
+ }
+ }
+
+ FreePool (BootOrder);
+ return EFI_SUCCESS;
+}
+
+/**
+ Measure and log all EFI Secure variables, and extend the measurement result into a specific PCR.
+
+ The EFI boot variables are BootOrder and Boot#### variables.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_OUT_OF_RESOURCES Out of memory.
+ @retval EFI_DEVICE_ERROR The operation was unsuccessful.
+
+**/
+EFI_STATUS
+MeasureAllSecureVariables (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ VOID *Data;
+ UINTN DataSize;
+ UINTN Index;
+
+ Status = EFI_NOT_FOUND;
+ for (Index = 0; Index < sizeof (mVariableType)/sizeof (mVariableType[0]); Index++) {
+ Status = ReadAndMeasureSecureVariable (
+ mVariableType[Index].VariableName,
+ mVariableType[Index].VendorGuid,
+ &DataSize,
+ &Data
+ );
+ if (!EFI_ERROR (Status)) {
+ if (Data != NULL) {
+ FreePool (Data);
+ }
+ }
+ }
+
+ //
+ // Measure DBT if present and not empty
+ //
+ Status = GetVariable2 (EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid, &Data, &DataSize);
+ if (!EFI_ERROR (Status)) {
+ Status = MeasureVariable (
+ MapPcrToMrIndex (7),
+ EV_EFI_VARIABLE_DRIVER_CONFIG,
+ EFI_IMAGE_SECURITY_DATABASE2,
+ &gEfiImageSecurityDatabaseGuid,
+ Data,
+ DataSize
+ );
+ FreePool (Data);
+ } else {
+ DEBUG ((DEBUG_INFO, "Skip measuring variable %s since it's deleted\n", EFI_IMAGE_SECURITY_DATABASE2));
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Measure and log launch of FirmwareDebugger, and extend the measurement result into a specific PCR.
+
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_OUT_OF_RESOURCES Out of memory.
+ @retval EFI_DEVICE_ERROR The operation was unsuccessful.
+
+**/
+EFI_STATUS
+MeasureLaunchOfFirmwareDebugger (
+ VOID
+ )
+{
+ CC_EVENT_HDR CcEvent;
+
+ CcEvent.MrIndex = MapPcrToMrIndex (7);
+ CcEvent.EventType = EV_EFI_ACTION;
+ CcEvent.EventSize = sizeof (FIRMWARE_DEBUGGER_EVENT_STRING) - 1;
+ return TdxDxeHashLogExtendEvent (
+ 0,
+ (UINT8 *)FIRMWARE_DEBUGGER_EVENT_STRING,
+ sizeof (FIRMWARE_DEBUGGER_EVENT_STRING) - 1,
+ &CcEvent,
+ (UINT8 *)FIRMWARE_DEBUGGER_EVENT_STRING
+ );
+}
+
+/**
+ Measure and log all Secure Boot Policy, and extend the measurement result into a specific PCR.
+
+ Platform firmware adhering to the policy must therefore measure the following values into PCR[7]: (in order listed)
+ - The contents of the SecureBoot variable
+ - The contents of the PK variable
+ - The contents of the KEK variable
+ - The contents of the EFI_IMAGE_SECURITY_DATABASE variable
+ - The contents of the EFI_IMAGE_SECURITY_DATABASE1 variable
+ - Separator
+ - Entries in the EFI_IMAGE_SECURITY_DATABASE that are used to validate EFI Drivers or EFI Boot Applications in the boot path
+
+ NOTE: Because of the above, UEFI variables PK, KEK, EFI_IMAGE_SECURITY_DATABASE,
+ EFI_IMAGE_SECURITY_DATABASE1 and SecureBoot SHALL NOT be measured into PCR[3].
+
+ @param[in] Event Event whose notification function is being invoked
+ @param[in] Context Pointer to the notification function's context
+**/
+VOID
+EFIAPI
+MeasureSecureBootPolicy (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ EFI_STATUS Status;
+ VOID *Protocol;
+
+ Status = gBS->LocateProtocol (&gEfiVariableWriteArchProtocolGuid, NULL, (VOID **)&Protocol);
+ if (EFI_ERROR (Status)) {
+ return;
+ }
+
+ if (PcdGetBool (PcdFirmwareDebuggerInitialized)) {
+ Status = MeasureLaunchOfFirmwareDebugger ();
+ DEBUG ((DEBUG_INFO, "MeasureLaunchOfFirmwareDebugger - %r\n", Status));
+ }
+
+ Status = MeasureAllSecureVariables ();
+ DEBUG ((DEBUG_INFO, "MeasureAllSecureVariables - %r\n", Status));
+
+ //
+ // We need measure Separator(7) here, because this event must be between SecureBootPolicy (Configure)
+ // and ImageVerification (Authority)
+ // There might be a case that we need measure UEFI image from DriverOrder, besides BootOrder. So
+ // the Authority measurement happen before ReadToBoot event.
+ //
+ Status = MeasureSeparatorEvent (MapPcrToMrIndex (7));
+ DEBUG ((DEBUG_INFO, "MeasureSeparatorEvent - %r\n", Status));
+ return;
+}
+
+/**
+ Ready to Boot Event notification handler.
+
+ Sequence of OS boot events is measured in this event notification handler.
+
+ @param[in] Event Event whose notification function is being invoked
+ @param[in] Context Pointer to the notification function's context
+
+**/
+VOID
+EFIAPI
+OnReadyToBoot (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ EFI_STATUS Status;
+
+ PERF_START_EX (mImageHandle, "EventRec", "TdTcg2Dxe", 0, PERF_ID_CC_TCG2_DXE);
+ if (mBootAttempts == 0) {
+ //
+ // Measure handoff tables.
+ //
+ Status = MeasureHandoffTables ();
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "HOBs not Measured. Error!\n"));
+ }
+
+ //
+ // Measure BootOrder & Boot#### variables.
+ //
+ Status = MeasureAllBootVariables ();
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "Boot Variables not Measured. Error!\n"));
+ }
+
+ //
+ // 1. This is the first boot attempt.
+ //
+ Status = TdMeasureAction (
+ MapPcrToMrIndex (4),
+ EFI_CALLING_EFI_APPLICATION
+ );
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "%a not Measured. Error!\n", EFI_CALLING_EFI_APPLICATION));
+ }
+
+ //
+ // 2. Draw a line between pre-boot env and entering post-boot env.
+ // PCR[7] (is RTMR[0]) is already done.
+ //
+ Status = MeasureSeparatorEvent (1);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "Separator Event not Measured. Error!\n"));
+ }
+
+ //
+ // 3. Measure GPT. It would be done in SAP driver.
+ //
+
+ //
+ // 4. Measure PE/COFF OS loader. It would be done in SAP driver.
+ //
+
+ //
+ // 5. Read & Measure variable. BootOrder already measured.
+ //
+ } else {
+ //
+ // 6. Not first attempt, meaning a return from last attempt
+ //
+ Status = TdMeasureAction (
+ MapPcrToMrIndex (4),
+ EFI_RETURNING_FROM_EFI_APPLICATION
+ );
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "%a not Measured. Error!\n", EFI_RETURNING_FROM_EFI_APPLICATION));
+ }
+
+ //
+ // 7. Next boot attempt, measure "Calling EFI Application from Boot Option" again
+ // TCG PC Client PFP spec Section 2.4.4.5 Step 4
+ //
+ Status = TdMeasureAction (
+ MapPcrToMrIndex (4),
+ EFI_CALLING_EFI_APPLICATION
+ );
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "%a not Measured. Error!\n", EFI_CALLING_EFI_APPLICATION));
+ }
+ }
+
+ DEBUG ((DEBUG_INFO, "TdTcg2Dxe Measure Data when ReadyToBoot\n"));
+ //
+ // Increase boot attempt counter.
+ //
+ mBootAttempts++;
+ PERF_END_EX (mImageHandle, "EventRec", "Tcg2Dxe", 0, PERF_ID_CC_TCG2_DXE + 1);
+}
+
+/**
+ Exit Boot Services Event notification handler.
+
+ Measure invocation and success of ExitBootServices.
+
+ @param[in] Event Event whose notification function is being invoked
+ @param[in] Context Pointer to the notification function's context
+
+**/
+VOID
+EFIAPI
+OnExitBootServices (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Measure invocation of ExitBootServices,
+ //
+ Status = TdMeasureAction (
+ MapPcrToMrIndex (5),
+ EFI_EXIT_BOOT_SERVICES_INVOCATION
+ );
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "%a not Measured. Error!\n", EFI_EXIT_BOOT_SERVICES_INVOCATION));
+ }
+
+ //
+ // Measure success of ExitBootServices
+ //
+ Status = TdMeasureAction (
+ MapPcrToMrIndex (5),
+ EFI_EXIT_BOOT_SERVICES_SUCCEEDED
+ );
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "%a not Measured. Error!\n", EFI_EXIT_BOOT_SERVICES_SUCCEEDED));
+ }
+}
+
+/**
+ Exit Boot Services Failed Event notification handler.
+
+ Measure Failure of ExitBootServices.
+
+ @param[in] Event Event whose notification function is being invoked
+ @param[in] Context Pointer to the notification function's context
+
+**/
+VOID
+EFIAPI
+OnExitBootServicesFailed (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // Measure Failure of ExitBootServices,
+ //
+ Status = TdMeasureAction (
+ MapPcrToMrIndex (5),
+ EFI_EXIT_BOOT_SERVICES_FAILED
+ );
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "%a not Measured. Error!\n", EFI_EXIT_BOOT_SERVICES_FAILED));
+ }
+}
+
+EFI_STATUS
+SyncCcEvent (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ EFI_PEI_HOB_POINTERS GuidHob;
+ VOID *CcEvent;
+ VOID *DigestListBin;
+ UINT32 DigestListBinSize;
+ UINT8 *Event;
+ UINT32 EventSize;
+ EFI_CC_EVENT_LOG_FORMAT LogFormat;
+
+ DEBUG ((DEBUG_INFO, "Sync Cc event from SEC\n"));
+
+ Status = EFI_SUCCESS;
+ LogFormat = EFI_CC_EVENT_LOG_FORMAT_TCG_2;
+ GuidHob.Guid = GetFirstGuidHob (&gCcEventEntryHobGuid);
+
+ while (!EFI_ERROR (Status) && GuidHob.Guid != NULL) {
+ CcEvent = AllocateCopyPool (GET_GUID_HOB_DATA_SIZE (GuidHob.Guid), GET_GUID_HOB_DATA (GuidHob.Guid));
+ if (CcEvent == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ GuidHob.Guid = GET_NEXT_HOB (GuidHob);
+ GuidHob.Guid = GetNextGuidHob (&gCcEventEntryHobGuid, GuidHob.Guid);
+
+ DigestListBin = (UINT8 *)CcEvent + sizeof (UINT32) + sizeof (TCG_EVENTTYPE);
+ DigestListBinSize = GetDigestListBinSize (DigestListBin);
+
+ //
+ // Event size.
+ //
+ EventSize = *(UINT32 *)((UINT8 *)DigestListBin + DigestListBinSize);
+ Event = (UINT8 *)DigestListBin + DigestListBinSize + sizeof (UINT32);
+
+ //
+ // Log the event
+ //
+ Status = TdxDxeLogEvent (
+ LogFormat,
+ CcEvent,
+ sizeof (UINT32) + sizeof (TCG_EVENTTYPE) + DigestListBinSize + sizeof (UINT32),
+ Event,
+ EventSize
+ );
+
+ DumpCcEvent ((CC_EVENT *)CcEvent);
+ FreePool (CcEvent);
+ }
+
+ return Status;
+}
+
+/**
+ Install TDVF ACPI Table when ACPI Table Protocol is available.
+
+ @param[in] Event Event whose notification function is being invoked
+ @param[in] Context Pointer to the notification function's context
+**/
+VOID
+EFIAPI
+InstallAcpiTable (
+ IN EFI_EVENT Event,
+ IN VOID *Context
+ )
+{
+ UINTN TableKey;
+ EFI_STATUS Status;
+ EFI_ACPI_TABLE_PROTOCOL *AcpiTable;
+ UINT64 OemTableId;
+
+ Status = gBS->LocateProtocol (&gEfiAcpiTableProtocolGuid, NULL, (VOID **)&AcpiTable);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "TD: AcpiTableProtocol is not installed. %r\n", Status));
+ return;
+ }
+
+ mTdxEventlogAcpiTemplate.Laml = (UINT64)PcdGet32 (PcdCcEventlogAcpiTableLaml);
+ mTdxEventlogAcpiTemplate.Lasa = PcdGet64 (PcdCcEventlogAcpiTableLasa);
+ CopyMem (mTdxEventlogAcpiTemplate.Header.OemId, PcdGetPtr (PcdAcpiDefaultOemId), sizeof (mTdxEventlogAcpiTemplate.Header.OemId));
+ OemTableId = PcdGet64 (PcdAcpiDefaultOemTableId);
+ CopyMem (&mTdxEventlogAcpiTemplate.Header.OemTableId, &OemTableId, sizeof (UINT64));
+ mTdxEventlogAcpiTemplate.Header.OemRevision = PcdGet32 (PcdAcpiDefaultOemRevision);
+ mTdxEventlogAcpiTemplate.Header.CreatorId = PcdGet32 (PcdAcpiDefaultCreatorId);
+ mTdxEventlogAcpiTemplate.Header.CreatorRevision = PcdGet32 (PcdAcpiDefaultCreatorRevision);
+
+ //
+ // Construct ACPI Table
+ Status = AcpiTable->InstallAcpiTable (
+ AcpiTable,
+ &mTdxEventlogAcpiTemplate,
+ mTdxEventlogAcpiTemplate.Header.Length,
+ &TableKey
+ );
+ ASSERT_EFI_ERROR (Status);
+
+ DEBUG ((DEBUG_INFO, "TDVF Eventlog ACPI Table is installed.\n"));
+}
+
+/**
+ The function install TdTcg2 protocol.
+
+ @retval EFI_SUCCESS TdTcg2 protocol is installed.
+ @retval other Some error occurs.
+**/
+EFI_STATUS
+InstallCcMeasurementProtocol (
+ VOID
+ )
+{
+ EFI_STATUS Status;
+ EFI_HANDLE Handle;
+
+ Handle = NULL;
+ Status = gBS->InstallMultipleProtocolInterfaces (
+ &Handle,
+ &gEfiCcMeasurementProtocolGuid,
+ &mTdProtocol,
+ NULL
+ );
+ DEBUG ((DEBUG_INFO, "CcProtocol: Install %r\n", Status));
+ return Status;
+}
+
+/**
+ The driver's entry point. It publishes EFI Tcg2 Protocol.
+
+ @param[in] ImageHandle The firmware allocated handle for the EFI image.
+ @param[in] SystemTable A pointer to the EFI System Table.
+
+ @retval EFI_SUCCESS The entry point is executed successfully.
+ @retval other Some error occurs when executing this entry point.
+**/
+EFI_STATUS
+EFIAPI
+DriverEntry (
+ IN EFI_HANDLE ImageHandle,
+ IN EFI_SYSTEM_TABLE *SystemTable
+ )
+{
+ EFI_STATUS Status;
+ EFI_EVENT Event;
+ VOID *Registration;
+
+ if (!TdIsEnabled ()) {
+ return EFI_UNSUPPORTED;
+ }
+
+ mImageHandle = ImageHandle;
+
+ //
+ // Fill information
+ //
+ // ASSERT (TD_EVENT_LOG_AREA_COUNT_MAX == sizeof(mTEventInfo)/sizeof(mTcg2EventInfo[0]));
+
+ mTdxDxeData.BsCap.Size = sizeof (EFI_CC_BOOT_SERVICE_CAPABILITY);
+ mTdxDxeData.BsCap.ProtocolVersion.Major = 1;
+ mTdxDxeData.BsCap.ProtocolVersion.Minor = 1;
+ mTdxDxeData.BsCap.StructureVersion.Major = 1;
+ mTdxDxeData.BsCap.StructureVersion.Minor = 1;
+
+ //
+ // Get supported PCR and current Active PCRs
+ // For TD gueset HA384 is supported.
+ //
+ mTdxDxeData.BsCap.HashAlgorithmBitmap = HASH_ALG_SHA384;
+
+ // TD guest only supports EFI_TCG2_EVENT_LOG_FORMAT_TCG_2
+ mTdxDxeData.BsCap.SupportedEventLogs = EFI_CC_EVENT_LOG_FORMAT_TCG_2;
+
+ //
+ // Setup the log area and copy event log from hob list to it
+ //
+ Status = SetupCcEventLog ();
+ ASSERT_EFI_ERROR (Status);
+
+ if (!EFI_ERROR (Status)) {
+ Status = SyncCcEvent ();
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ //
+ // Measure handoff tables, Boot#### variables etc.
+ //
+ Status = EfiCreateEventReadyToBootEx (
+ TPL_CALLBACK,
+ OnReadyToBoot,
+ NULL,
+ &Event
+ );
+
+ Status = gBS->CreateEventEx (
+ EVT_NOTIFY_SIGNAL,
+ TPL_NOTIFY,
+ OnExitBootServices,
+ NULL,
+ &gEfiEventExitBootServicesGuid,
+ &Event
+ );
+
+ //
+ // Measure Exit Boot Service failed
+ //
+ Status = gBS->CreateEventEx (
+ EVT_NOTIFY_SIGNAL,
+ TPL_NOTIFY,
+ OnExitBootServicesFailed,
+ NULL,
+ &gEventExitBootServicesFailedGuid,
+ &Event
+ );
+
+ //
+ // Create event callback, because we need access variable on SecureBootPolicyVariable
+ // We should use VariableWriteArch instead of VariableArch, because Variable driver
+ // may update SecureBoot value based on last setting.
+ //
+ EfiCreateProtocolNotifyEvent (&gEfiVariableWriteArchProtocolGuid, TPL_CALLBACK, MeasureSecureBootPolicy, NULL, &Registration);
+
+ //
+ // Install CcMeasurementProtocol
+ //
+ Status = InstallCcMeasurementProtocol ();
+ DEBUG ((DEBUG_INFO, "InstallCcMeasurementProtocol - %r\n", Status));
+
+ if (Status == EFI_SUCCESS) {
+ //
+ // Create event callback to install CC EventLog ACPI Table
+ EfiCreateProtocolNotifyEvent (&gEfiAcpiTableProtocolGuid, TPL_CALLBACK, InstallAcpiTable, NULL, &Registration);
+ }
+
+ return Status;
+}
diff --git a/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf b/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf
new file mode 100644
index 000000000000..5efe7ef479f1
--- /dev/null
+++ b/OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf
@@ -0,0 +1,101 @@
+## @file
+#
+# Produces EFI_CC_MEASUREMENT_PROTOCOL and measure boot environment
+#
+#
+# Copyright (c) 2020 - 2022, Intel Corporation. All rights reserved.<BR>
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = TdTcg2Dxe
+ FILE_GUID = F062221E-C607-44C2-B0B4-C3886331D351
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ ENTRY_POINT = DriverEntry
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = X64
+#
+
+[Sources]
+ TdTcg2Dxe.c
+ MeasureBootPeCoff.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ SecurityPkg/SecurityPkg.dec
+ CryptoPkg/CryptoPkg.dec
+ OvmfPkg/OvmfPkg.dec
+
+[LibraryClasses]
+ MemoryAllocationLib
+ BaseLib
+ UefiBootServicesTableLib
+ HobLib
+ UefiDriverEntryPoint
+ UefiRuntimeServicesTableLib
+ BaseMemoryLib
+ DebugLib
+ PrintLib
+ UefiLib
+ HashLib
+ PerformanceLib
+ ReportStatusCodeLib
+ PeCoffLib
+ TpmMeasurementLib
+ TdxLib
+
+[Guids]
+ ## SOMETIMES_CONSUMES ## Variable:L"SecureBoot"
+ ## SOMETIMES_CONSUMES ## Variable:L"PK"
+ ## SOMETIMES_CONSUMES ## Variable:L"KEK"
+ ## SOMETIMES_CONSUMES ## Variable:L"BootXXXX"
+ gEfiGlobalVariableGuid
+
+ ## SOMETIMES_CONSUMES ## Variable:L"db"
+ ## SOMETIMES_CONSUMES ## Variable:L"dbx"
+ gEfiImageSecurityDatabaseGuid
+
+ # gTcgEventEntryHobGuid ## SOMETIMES_CONSUMES ## HOB
+ gEfiEventExitBootServicesGuid ## CONSUMES ## Event
+ gEventExitBootServicesFailedGuid ## SOMETIMES_CONSUMES ## Event
+
+ gCcEventEntryHobGuid ## SOMETIMES_CONSUMES ## HOB
+ gTcg800155PlatformIdEventHobGuid ## SOMETIMES_CONSUMES ## HOB
+ gEfiCcFinalEventsTableGuid ## PRODUCES
+
+[Protocols]
+ gEfiCcMeasurementProtocolGuid ## PRODUCES
+ gEfiMpServiceProtocolGuid ## SOMETIMES_CONSUMES
+ gEfiVariableWriteArchProtocolGuid ## NOTIFY
+ gEfiResetNotificationProtocolGuid ## CONSUMES
+ gEfiAcpiTableProtocolGuid ## NOTIFY
+
+[Pcd]
+ gEfiSecurityPkgTokenSpaceGuid.PcdTpmPlatformClass ## SOMETIMES_CONSUMES
+ gEfiSecurityPkgTokenSpaceGuid.PcdFirmwareDebuggerInitialized ## SOMETIMES_CONSUMES
+ gEfiSecurityPkgTokenSpaceGuid.PcdStatusCodeSubClassTpmDevice ## SOMETIMES_CONSUMES
+ gEfiSecurityPkgTokenSpaceGuid.PcdTcg2HashAlgorithmBitmap ## CONSUMES
+ gEfiSecurityPkgTokenSpaceGuid.PcdTcg2NumberOfPCRBanks ## CONSUMES
+ gEfiSecurityPkgTokenSpaceGuid.PcdTcgLogAreaMinLen ## CONSUMES
+ gEfiSecurityPkgTokenSpaceGuid.PcdTcg2FinalLogAreaLen ## CONSUMES
+ gUefiOvmfPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLaml ## PRODUCES
+ gUefiOvmfPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLasa ## PRODUCES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemId ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemTableId ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemRevision ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultCreatorId ## CONSUMES
+ gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultCreatorRevision ## CONSUMES
+
+[Depex]
+ # According to PcdTpm2AcpiTableRev definition in SecurityPkg.dec
+ # This PCD should be configured at DynamicHii or DynamicHiiEx.
+ # So, this PCD read operation depends on GetVariable service.
+ # Add VariableArch protocol dependency to make sure PCD read works.
+ gEfiVariableArchProtocolGuid AND gEfiAcpiTableProtocolGuid
--
2.29.2.windows.2


[PATCH V2 6/8] MdePkg: Define CC Measure EventLog ACPI Table

Min Xu
 

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

TDVF set up an ACPI table (EFI_CC_EVENTLOG_ACPI_TABLE) to pass the
event-log information. The event log created by the TD owner contains
the hashes to reconstruct the MRTD and RTMR registers.

Please refer to Sec 4.3.3 in blow link:
https://www.intel.com/content/dam/develop/external/us/en/documents/
intel-tdx-guest-hypervisor-communication-interface-1.0-344426-002.pdf

Please be noted, the definition of EFI_CC_EVENTLOG_ACPI_TABLE is a
little different from the above document. This difference is based on
below discussion:
- https://edk2.groups.io/g/devel/message/87396
- https://edk2.groups.io/g/devel/message/87402

This change will be reflected in the next version of the above document.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Jian J Wang <jian.j.wang@...>
Cc: Ken Lu <ken.lu@...>
Cc: Sami Mujawar <sami.mujawar@...>
Cc: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
MdePkg/Include/Protocol/CcMeasurement.h | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)

diff --git a/MdePkg/Include/Protocol/CcMeasurement.h b/MdePkg/Include/Protocol/CcMeasurement.h
index 68029e977fac..58123ca72163 100644
--- a/MdePkg/Include/Protocol/CcMeasurement.h
+++ b/MdePkg/Include/Protocol/CcMeasurement.h
@@ -299,4 +299,25 @@ typedef struct {

extern EFI_GUID gEfiCcFinalEventsTableGuid;

+//
+// Define the CC Measure EventLog ACPI Table
+//
+#pragma pack(1)
+
+typedef struct {
+ EFI_ACPI_DESCRIPTION_HEADER Header;
+ EFI_CC_TYPE CcType;
+ UINT32 Rsvd;
+ UINT64 Laml;
+ UINT64 Lasa;
+} EFI_CC_EVENTLOG_ACPI_TABLE;
+
+#pragma pack()
+
+//
+// Define the signature and revision of CC Measurement EventLog ACPI Table
+//
+#define EFI_CC_EVENTLOG_ACPI_TABLE_SIGNATURE SIGNATURE_32('C', 'C', 'E', 'L')
+#define EFI_CC_EVENTLOG_ACPI_TABLE_REVISION 1
+
#endif
--
2.29.2.windows.2


[PATCH V2 4/8] OvmfPkg/IntelTdx: Measure Td HobList and Configuration FV

Min Xu
 

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

TdHobList and Configuration FV are external data provided by Host VMM.
These are not trusted in Td guest. So they should be validated , measured
and extended to Td RTMR registers. In the meantime 2 EFI_CC_EVENT_HOB are
created. These 2 GUIDed HOBs carry the hash value of TdHobList and
Configuration FV. In DXE phase EFI_CC_EVENT can be created based on these
2 GUIDed HOBs.

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@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
OvmfPkg/IntelTdx/IntelTdxX64.dsc | 3 +
OvmfPkg/Library/PeilessStartupLib/IntelTdx.c | 498 ++++++++++++++++++
.../PeilessStartupLib/PeilessStartup.c | 30 ++
.../PeilessStartupInternal.h | 57 ++
.../PeilessStartupLib/PeilessStartupLib.inf | 7 +-
5 files changed, 593 insertions(+), 2 deletions(-)
create mode 100644 OvmfPkg/Library/PeilessStartupLib/IntelTdx.c

diff --git a/OvmfPkg/IntelTdx/IntelTdxX64.dsc b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
index 245155d41b30..caae49d524f9 100644
--- a/OvmfPkg/IntelTdx/IntelTdxX64.dsc
+++ b/OvmfPkg/IntelTdx/IntelTdxX64.dsc
@@ -520,6 +520,9 @@
OvmfPkg/IntelTdx/Sec/SecMain.inf {
<LibraryClasses>
NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf
+ BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf
+ HashLib|SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.inf
+ NULL|SecurityPkg/Library/HashInstanceLibSha384/HashInstanceLibSha384.inf
}

#
diff --git a/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c b/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c
new file mode 100644
index 000000000000..bb905cf5cd6a
--- /dev/null
+++ b/OvmfPkg/Library/PeilessStartupLib/IntelTdx.c
@@ -0,0 +1,498 @@
+/** @file
+ Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <PiPei.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/HobLib.h>
+#include <IndustryStandard/UefiTcgPlatform.h>
+#include <IndustryStandard/Tpm20.h>
+#include <Library/HashLib.h>
+#include <Protocol/CcMeasurement.h>
+#include <Guid/VariableFormat.h>
+#include <Guid/SystemNvDataGuid.h>
+#include <Guid/CcEventHob.h>
+#include <Library/PrintLib.h>
+#include "PeilessStartupInternal.h"
+
+#pragma pack(1)
+
+typedef struct {
+ UINT32 count;
+ TPMI_ALG_HASH hashAlg;
+ BYTE sha384[SHA384_DIGEST_SIZE];
+} TDX_DIGEST_VALUE;
+
+#define HANDOFF_TABLE_DESC "TdxTable"
+typedef struct {
+ UINT8 TableDescriptionSize;
+ UINT8 TableDescription[sizeof (HANDOFF_TABLE_DESC)];
+ UINT64 NumberOfTables;
+ EFI_CONFIGURATION_TABLE TableEntry[1];
+} TDX_HANDOFF_TABLE_POINTERS2;
+
+#define FV_HANDOFF_TABLE_DESC "Fv(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)"
+typedef struct {
+ UINT8 BlobDescriptionSize;
+ UINT8 BlobDescription[sizeof (FV_HANDOFF_TABLE_DESC)];
+ EFI_PHYSICAL_ADDRESS BlobBase;
+ UINT64 BlobLength;
+} FV_HANDOFF_TABLE_POINTERS2;
+
+#pragma pack()
+
+#define INVALID_PCR2MR_INDEX 0xFF
+
+/**
+ RTMR[0] => PCR[1,7]
+ RTMR[1] => PCR[2,3,4,5]
+ RTMR[2] => PCR[8~15]
+ RTMR[3] => NA
+ Note:
+ PCR[0] is mapped to MRTD and should not appear here.
+ PCR[6] is reserved for OEM. It is not used.
+**/
+UINT8
+GetMappedRtmrIndex (
+ UINT32 PCRIndex
+ )
+{
+ UINT8 RtmrIndex;
+
+ if ((PCRIndex == 6) || (PCRIndex == 0) || (PCRIndex > 15)) {
+ DEBUG ((DEBUG_ERROR, "Invalid PCRIndex(%d) map to MR Index.\n", PCRIndex));
+ ASSERT (FALSE);
+ return INVALID_PCR2MR_INDEX;
+ }
+
+ RtmrIndex = 0;
+ if ((PCRIndex == 1) || (PCRIndex == 7)) {
+ RtmrIndex = 0;
+ } else if ((PCRIndex >= 2) && (PCRIndex < 6)) {
+ RtmrIndex = 1;
+ } else if ((PCRIndex >= 8) && (PCRIndex <= 15)) {
+ RtmrIndex = 2;
+ }
+
+ return RtmrIndex;
+}
+
+/**
+ Tpm measure and log data, and extend the measurement result into a specific PCR.
+ @param[in] PcrIndex PCR Index.
+ @param[in] EventType Event type.
+ @param[in] EventLog Measurement event log.
+ @param[in] LogLen Event log length in bytes.
+ @param[in] HashData The start of the data buffer to be hashed, extended.
+ @param[in] HashDataLen The length, in bytes, of the buffer referenced by HashData
+ @retval EFI_SUCCESS Operation completed successfully.
+ @retval EFI_UNSUPPORTED TPM device not available.
+ @retval EFI_OUT_OF_RESOURCES Out of memory.
+ @retval EFI_DEVICE_ERROR The operation was unsuccessful.
+**/
+EFI_STATUS
+EFIAPI
+TdxMeasureAndLogData (
+ IN UINT32 PcrIndex,
+ IN UINT32 EventType,
+ IN VOID *EventLog,
+ IN UINT32 LogLen,
+ IN VOID *HashData,
+ IN UINT64 HashDataLen
+ )
+{
+ EFI_STATUS Status;
+ UINT32 RtmrIndex;
+ VOID *EventHobData;
+ TCG_PCR_EVENT2 *TcgPcrEvent2;
+ UINT8 *DigestBuffer;
+ TDX_DIGEST_VALUE *TdxDigest;
+ TPML_DIGEST_VALUES DigestList;
+ UINT8 *Ptr;
+
+ RtmrIndex = GetMappedRtmrIndex (PcrIndex);
+ if (RtmrIndex == INVALID_PCR2MR_INDEX) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ DEBUG ((DEBUG_INFO, "Creating TdTcg2PcrEvent PCR[%d]/RTMR[%d] EventType 0x%x\n", PcrIndex, RtmrIndex, EventType));
+
+ Status = HashAndExtend (
+ RtmrIndex,
+ (VOID *)HashData,
+ HashDataLen,
+ &DigestList
+ );
+
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_INFO, "Failed to HashAndExtend. %r\n", Status));
+ return Status;
+ }
+
+ //
+ // Use TDX_DIGEST_VALUE in the GUID HOB DataLength calculation
+ // to reserve enough buffer to hold TPML_DIGEST_VALUES compact binary
+ // which is limited to a SHA384 digest list
+ //
+ EventHobData = BuildGuidHob (
+ &gCcEventEntryHobGuid,
+ sizeof (TcgPcrEvent2->PCRIndex) + sizeof (TcgPcrEvent2->EventType) +
+ sizeof (TDX_DIGEST_VALUE) +
+ sizeof (TcgPcrEvent2->EventSize) + LogLen
+ );
+
+ if (EventHobData == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ Ptr = (UINT8 *)EventHobData;
+ //
+ // Initialize PcrEvent data now
+ //
+ RtmrIndex++;
+ CopyMem (Ptr, &RtmrIndex, sizeof (UINT32));
+ Ptr += sizeof (UINT32);
+ CopyMem (Ptr, &EventType, sizeof (TCG_EVENTTYPE));
+ Ptr += sizeof (TCG_EVENTTYPE);
+
+ DigestBuffer = Ptr;
+
+ TdxDigest = (TDX_DIGEST_VALUE *)DigestBuffer;
+ TdxDigest->count = 1;
+ TdxDigest->hashAlg = TPM_ALG_SHA384;
+ CopyMem (
+ TdxDigest->sha384,
+ DigestList.digests[0].digest.sha384,
+ SHA384_DIGEST_SIZE
+ );
+
+ Ptr += sizeof (TDX_DIGEST_VALUE);
+
+ CopyMem (Ptr, &LogLen, sizeof (UINT32));
+ Ptr += sizeof (UINT32);
+ CopyMem (Ptr, EventLog, LogLen);
+ Ptr += LogLen;
+
+ Status = EFI_SUCCESS;
+ return Status;
+}
+
+/**
+ Measure the Hoblist passed from the VMM.
+
+ This function will create a unique GUID hob entry will be
+ found from the TCG driver building the event log.
+ This module will generate the measurement with the data in
+ this hob, and log the event.
+
+ @param[in] VmmHobList The Hoblist pass the firmware
+
+ @retval EFI_SUCCESS Fv image is measured successfully
+ or it has been already measured.
+ @retval Others Other errors as indicated
+**/
+EFI_STATUS
+EFIAPI
+MeasureHobList (
+ IN CONST VOID *VmmHobList
+ )
+{
+ EFI_PEI_HOB_POINTERS Hob;
+ TDX_HANDOFF_TABLE_POINTERS2 HandoffTables;
+ EFI_STATUS Status;
+
+ if (!TdIsEnabled ()) {
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+ }
+
+ Hob.Raw = (UINT8 *)VmmHobList;
+
+ //
+ // Parse the HOB list until end of list.
+ //
+ while (!END_OF_HOB_LIST (Hob)) {
+ Hob.Raw = GET_NEXT_HOB (Hob);
+ }
+
+ //
+ // Init the log event for HOB measurement
+ //
+
+ HandoffTables.TableDescriptionSize = sizeof (HandoffTables.TableDescription);
+ CopyMem (HandoffTables.TableDescription, HANDOFF_TABLE_DESC, sizeof (HandoffTables.TableDescription));
+ HandoffTables.NumberOfTables = 1;
+ CopyGuid (&(HandoffTables.TableEntry[0].VendorGuid), &gUefiOvmfPkgTokenSpaceGuid);
+ HandoffTables.TableEntry[0].VendorTable = (VOID *)VmmHobList;
+
+ Status = TdxMeasureAndLogData (
+ 1, // PCRIndex
+ EV_EFI_HANDOFF_TABLES2, // EventType
+ (VOID *)&HandoffTables, // EventData
+ sizeof (HandoffTables), // EventSize
+ (UINT8 *)(UINTN)VmmHobList, // HashData
+ (UINTN)((UINT8 *)Hob.Raw - (UINT8 *)VmmHobList) // HashDataLen
+ );
+
+ if (EFI_ERROR (Status)) {
+ ASSERT (FALSE);
+ }
+
+ return Status;
+}
+
+/**
+ Check padding data all bit should be 1.
+
+ @param[in] Buffer - A pointer to buffer header
+ @param[in] BufferSize - Buffer size
+
+ @retval TRUE - The padding data is valid.
+ @retval TRUE - The padding data is invalid.
+
+**/
+BOOLEAN
+CheckPaddingData (
+ IN UINT8 *Buffer,
+ IN UINT32 BufferSize
+ )
+{
+ UINT32 index;
+
+ for (index = 0; index < BufferSize; index++) {
+ if (Buffer[index] != 0xFF) {
+ return FALSE;
+ }
+ }
+
+ return TRUE;
+}
+
+/**
+ Check the integrity of CFV data.
+
+ @param[in] TdxCfvBase - A pointer to CFV header
+ @param[in] TdxCfvSize - CFV data size
+
+ @retval TRUE - The CFV data is valid.
+ @retval FALSE - The CFV data is invalid.
+
+**/
+BOOLEAN
+EFIAPI
+TdxValidateCfv (
+ IN UINT8 *TdxCfvBase,
+ IN UINT32 TdxCfvSize
+ )
+{
+ UINT16 Checksum;
+ UINTN VariableBase;
+ UINT32 VariableOffset;
+ UINT32 VariableOffsetBeforeAlign;
+ EFI_FIRMWARE_VOLUME_HEADER *CfvFvHeader;
+ VARIABLE_STORE_HEADER *CfvVariableStoreHeader;
+ AUTHENTICATED_VARIABLE_HEADER *VariableHeader;
+
+ static EFI_GUID FvHdrGUID = EFI_SYSTEM_NV_DATA_FV_GUID;
+ static EFI_GUID VarStoreHdrGUID = EFI_AUTHENTICATED_VARIABLE_GUID;
+
+ VariableOffset = 0;
+
+ if (TdxCfvBase == NULL) {
+ DEBUG ((DEBUG_ERROR, "TDX CFV: CFV pointer is NULL\n"));
+ return FALSE;
+ }
+
+ //
+ // Verify the header zerovetor, filesystemguid,
+ // revision, signature, attributes, fvlength, checksum
+ // HeaderLength cannot be an odd number
+ //
+ CfvFvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)TdxCfvBase;
+
+ if ((!IsZeroBuffer (CfvFvHeader->ZeroVector, 16)) ||
+ (!CompareGuid (&FvHdrGUID, &CfvFvHeader->FileSystemGuid)) ||
+ (CfvFvHeader->Signature != EFI_FVH_SIGNATURE) ||
+ (CfvFvHeader->Attributes != 0x4feff) ||
+ (CfvFvHeader->Revision != EFI_FVH_REVISION) ||
+ (CfvFvHeader->FvLength != TdxCfvSize)
+ )
+ {
+ DEBUG ((DEBUG_ERROR, "TDX CFV: Basic FV headers were invalid\n"));
+ return FALSE;
+ }
+
+ //
+ // Verify the header checksum
+ //
+ Checksum = CalculateSum16 ((VOID *)CfvFvHeader, CfvFvHeader->HeaderLength);
+
+ if (Checksum != 0) {
+ DEBUG ((DEBUG_ERROR, "TDX CFV: FV checksum was invalid\n"));
+ return FALSE;
+ }
+
+ //
+ // Verify the header signature, size, format, state
+ //
+ CfvVariableStoreHeader = (VARIABLE_STORE_HEADER *)(TdxCfvBase + CfvFvHeader->HeaderLength);
+ if ((!CompareGuid (&VarStoreHdrGUID, &CfvVariableStoreHeader->Signature)) ||
+ (CfvVariableStoreHeader->Format != VARIABLE_STORE_FORMATTED) ||
+ (CfvVariableStoreHeader->State != VARIABLE_STORE_HEALTHY) ||
+ (CfvVariableStoreHeader->Size > (CfvFvHeader->FvLength - CfvFvHeader->HeaderLength)) ||
+ (CfvVariableStoreHeader->Size < sizeof (VARIABLE_STORE_HEADER))
+ )
+ {
+ DEBUG ((DEBUG_ERROR, "TDX CFV: Variable Store header was invalid\n"));
+ return FALSE;
+ }
+
+ //
+ // Verify the header startId, state
+ // Verify data to the end
+ //
+ VariableBase = (UINTN)TdxCfvBase + CfvFvHeader->HeaderLength + sizeof (VARIABLE_STORE_HEADER);
+ while (VariableOffset < (CfvVariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER))) {
+ VariableHeader = (AUTHENTICATED_VARIABLE_HEADER *)(VariableBase + VariableOffset);
+ if (VariableHeader->StartId != VARIABLE_DATA) {
+ if (!CheckPaddingData ((UINT8 *)VariableHeader, CfvVariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER) - VariableOffset)) {
+ DEBUG ((DEBUG_ERROR, "TDX CFV: Variable header was invalid\n"));
+ return FALSE;
+ }
+
+ VariableOffset = CfvVariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER);
+ } else {
+ if (!((VariableHeader->State == VAR_IN_DELETED_TRANSITION) ||
+ (VariableHeader->State == VAR_DELETED) ||
+ (VariableHeader->State == VAR_HEADER_VALID_ONLY) ||
+ (VariableHeader->State == VAR_ADDED)))
+ {
+ DEBUG ((DEBUG_ERROR, "TDX CFV: Variable header was invalid\n"));
+ return FALSE;
+ }
+
+ VariableOffset += sizeof (AUTHENTICATED_VARIABLE_HEADER) + VariableHeader->NameSize + VariableHeader->DataSize;
+ // Verify VariableOffset should be less than or equal CfvVariableStoreHeader->Size - sizeof(VARIABLE_STORE_HEADER)
+ if (VariableOffset > (CfvVariableStoreHeader->Size - sizeof (VARIABLE_STORE_HEADER))) {
+ DEBUG ((DEBUG_ERROR, "TDX CFV: Variable header was invalid\n"));
+ return FALSE;
+ }
+
+ VariableOffsetBeforeAlign = VariableOffset;
+ // 4 byte align
+ VariableOffset = (VariableOffset + 3) & (UINTN)(~3);
+
+ if (!CheckPaddingData ((UINT8 *)(VariableBase + VariableOffsetBeforeAlign), VariableOffset - VariableOffsetBeforeAlign)) {
+ DEBUG ((DEBUG_ERROR, "TDX CFV: Variable header was invalid\n"));
+ return FALSE;
+ }
+ }
+ }
+
+ return TRUE;
+}
+
+/**
+ Get the FvName from the FV header.
+
+ Causion: The FV is untrusted input.
+
+ @param[in] FvBase Base address of FV image.
+ @param[in] FvLength Length of FV image.
+
+ @return FvName pointer
+ @retval NULL FvName is NOT found
+**/
+VOID *
+GetFvName (
+ IN EFI_PHYSICAL_ADDRESS FvBase,
+ IN UINT64 FvLength
+ )
+{
+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;
+ EFI_FIRMWARE_VOLUME_EXT_HEADER *FvExtHeader;
+
+ if (FvBase >= MAX_ADDRESS) {
+ return NULL;
+ }
+
+ if (FvLength >= MAX_ADDRESS - FvBase) {
+ return NULL;
+ }
+
+ if (FvLength < sizeof (EFI_FIRMWARE_VOLUME_HEADER)) {
+ return NULL;
+ }
+
+ FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvBase;
+ if (FvHeader->ExtHeaderOffset < sizeof (EFI_FIRMWARE_VOLUME_HEADER)) {
+ return NULL;
+ }
+
+ if (FvHeader->ExtHeaderOffset + sizeof (EFI_FIRMWARE_VOLUME_EXT_HEADER) > FvLength) {
+ return NULL;
+ }
+
+ FvExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *)(UINTN)(FvBase + FvHeader->ExtHeaderOffset);
+
+ return &FvExtHeader->FvName;
+}
+
+/**
+ Measure FV image.
+ Add it into the measured FV list after the FV is measured successfully.
+
+ @param[in] FvBase Base address of FV image.
+ @param[in] FvLength Length of FV image.
+ @param[in] PcrIndex Index of PCR
+
+ @retval EFI_SUCCESS Fv image is measured successfully
+ or it has been already measured.
+ @retval EFI_OUT_OF_RESOURCES No enough memory to log the new event.
+ @retval EFI_DEVICE_ERROR The command was unsuccessful.
+
+**/
+EFI_STATUS
+EFIAPI
+TdxMeasureCfvImage (
+ IN EFI_PHYSICAL_ADDRESS FvBase,
+ IN UINT64 FvLength,
+ IN UINT8 PcrIndex
+ )
+{
+ EFI_STATUS Status;
+ FV_HANDOFF_TABLE_POINTERS2 FvBlob2;
+ VOID *FvName;
+
+ //
+ // Init the log event for FV measurement
+ //
+ FvBlob2.BlobDescriptionSize = sizeof (FvBlob2.BlobDescription);
+ CopyMem (FvBlob2.BlobDescription, FV_HANDOFF_TABLE_DESC, sizeof (FvBlob2.BlobDescription));
+ FvName = GetFvName (FvBase, FvLength);
+ if (FvName != NULL) {
+ AsciiSPrint ((CHAR8 *)FvBlob2.BlobDescription, sizeof (FvBlob2.BlobDescription), "Fv(%g)", FvName);
+ }
+
+ FvBlob2.BlobBase = FvBase;
+ FvBlob2.BlobLength = FvLength;
+
+ Status = TdxMeasureAndLogData (
+ 1, // PCRIndex
+ EV_EFI_PLATFORM_FIRMWARE_BLOB2, // EventType
+ (VOID *)&FvBlob2, // EventData
+ sizeof (FvBlob2), // EventSize
+ (UINT8 *)(UINTN)FvBase, // HashData
+ (UINTN)(FvLength) // HashDataLen
+ );
+
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "The FV which failed to be measured starts at: 0x%x\n", FvBase));
+ ASSERT (FALSE);
+ }
+
+ return Status;
+}
diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
index 126eb74048f4..aea7f98da92d 100644
--- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
+++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartup.c
@@ -133,11 +133,13 @@ PeilessStartup (
UINT32 DxeCodeSize;
TD_RETURN_DATA TdReturnData;
VOID *VmmHobList;
+ UINT8 *CfvBase;

Status = EFI_SUCCESS;
BootFv = NULL;
VmmHobList = NULL;
SecCoreData = (EFI_SEC_PEI_HAND_OFF *)Context;
+ CfvBase = (UINT8 *)(UINTN)FixedPcdGet32 (PcdCfvBase);

ZeroMem (&PlatformInfoHob, sizeof (PlatformInfoHob));

@@ -167,6 +169,34 @@ PeilessStartup (

DEBUG ((DEBUG_INFO, "HobList: %p\n", GetHobList ()));

+ if (TdIsEnabled ()) {
+ //
+ // Measure HobList
+ //
+ Status = MeasureHobList (VmmHobList);
+ if (EFI_ERROR (Status)) {
+ ASSERT (FALSE);
+ CpuDeadLoop ();
+ }
+
+ //
+ // Validate Tdx CFV
+ //
+ if (!TdxValidateCfv (CfvBase, FixedPcdGet32 (PcdCfvRawDataSize))) {
+ ASSERT (FALSE);
+ CpuDeadLoop ();
+ }
+
+ //
+ // Measure Tdx CFV
+ //
+ Status = TdxMeasureCfvImage ((EFI_PHYSICAL_ADDRESS)(UINTN)CfvBase, FixedPcdGet32 (PcdCfvRawDataSize), 1);
+ if (EFI_ERROR (Status)) {
+ ASSERT (FALSE);
+ CpuDeadLoop ();
+ }
+ }
+
//
// Initialize the Platform
//
diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h
index 23e9e0be53f1..2a100270ff20 100644
--- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h
+++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupInternal.h
@@ -52,4 +52,61 @@ EFIAPI
ConstructSecHobList (
);

+/**
+ Measure the Hoblist passed from the VMM.
+
+ This function will create a unique GUID hob entry will be
+ found from the TCG driver building the event log.
+ This module will generate the measurement with the data in
+ this hob, and log the event.
+
+ @param[in] VmmHobList The Hoblist pass the firmware
+
+ @retval EFI_SUCCESS Fv image is measured successfully
+ or it has been already measured.
+ @retval Others Other errors as indicated
+**/
+EFI_STATUS
+EFIAPI
+MeasureHobList (
+ IN CONST VOID *VmmHobList
+ );
+
+/**
+ Check the integrity of CFV data.
+
+ @param[in] TdxCfvBase - A pointer to CFV header
+ @param[in] TdxCfvSize - CFV data size
+
+ @retval TRUE - The CFV data is valid.
+ @retval FALSE - The CFV data is invalid.
+
+**/
+BOOLEAN
+EFIAPI
+TdxValidateCfv (
+ IN UINT8 *TdxCfvBase,
+ IN UINT32 TdxCfvSize
+ );
+
+/**
+ Measure FV image.
+ Add it into the measured FV list after the FV is measured successfully.
+
+ @param[in] FvBase Base address of FV image.
+ @param[in] FvLength Length of FV image.
+ @param[in] PcrIndex Index of PCR
+
+ @retval EFI_SUCCESS Fv image is measured successfully
+ or it has been already measured.
+ @retval Others Other errors as indicated
+**/
+EFI_STATUS
+EFIAPI
+TdxMeasureCfvImage (
+ IN EFI_PHYSICAL_ADDRESS FvBase,
+ IN UINT64 FvLength,
+ IN UINT8 PcrIndex
+ );
+
#endif
diff --git a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
index 8791984586a4..178b4c35d472 100644
--- a/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
+++ b/OvmfPkg/Library/PeilessStartupLib/PeilessStartupLib.inf
@@ -29,8 +29,7 @@
PeilessStartup.c
Hob.c
DxeLoad.c
-
-[Sources.X64]
+ IntelTdx.c
X64/VirtualMemory.c

[Packages]
@@ -39,6 +38,8 @@
UefiCpuPkg/UefiCpuPkg.dec
OvmfPkg/OvmfPkg.dec
EmbeddedPkg/EmbeddedPkg.dec
+ CryptoPkg/CryptoPkg.dec
+ SecurityPkg/SecurityPkg.dec

[LibraryClasses]
BaseLib
@@ -56,6 +57,7 @@
PrePiLib
QemuFwCfgLib
PlatformInitLib
+ HashLib

[Guids]
gEfiHobMemoryAllocModuleGuid
@@ -63,6 +65,7 @@
gUefiOvmfPkgPlatformInfoGuid
gEfiMemoryTypeInformationGuid
gPcdDataBaseHobGuid
+ gCcEventEntryHobGuid

[Pcd]
gUefiOvmfPkgTokenSpaceGuid.PcdCfvBase
--
2.29.2.windows.2


[PATCH V2 5/8] OvmfPkg: Add PCDs for LAML/LASA field in CC EVENTLOG ACPI table

Min Xu
 

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

Add PCDs to records LAML/LASA field in CC EVENTLOG ACPI table.

Cc: Brijesh Singh <brijesh.singh@...>
Cc: Erdem Aktas <erdemaktas@...>
Cc: James Bottomley <jejb@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Tom Lendacky <thomas.lendacky@...>
Cc: Ken Lu <ken.lu@...>
Cc: Sami Mujawar <sami.mujawar@...>
Cc: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
OvmfPkg/OvmfPkg.dec | 6 ++++++
1 file changed, 6 insertions(+)

diff --git a/OvmfPkg/OvmfPkg.dec b/OvmfPkg/OvmfPkg.dec
index b9ca44120289..f471f3bbeec2 100644
--- a/OvmfPkg/OvmfPkg.dec
+++ b/OvmfPkg/OvmfPkg.dec
@@ -436,6 +436,12 @@
# 2 - set by GOP Driver.
gUefiOvmfPkgTokenSpaceGuid.PcdVideoResolutionSource|0|UINT8|0x64

+ ## This PCD records LAML field in CC EVENTLOG ACPI table.
+ gUefiOvmfPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLaml|0|UINT32|0x66
+
+ ## This PCD records LASA field in CC EVENTLOG ACPI table.
+ gUefiOvmfPkgTokenSpaceGuid.PcdCcEventlogAcpiTableLasa|0|UINT64|0x67
+
[PcdsFeatureFlag]
gUefiOvmfPkgTokenSpaceGuid.PcdQemuBootOrderPciTranslation|TRUE|BOOLEAN|0x1c
gUefiOvmfPkgTokenSpaceGuid.PcdQemuBootOrderMmioTranslation|FALSE|BOOLEAN|0x1d
--
2.29.2.windows.2


[PATCH V2 2/8] CryptoPkg: Add SecCryptLib

Min Xu
 

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

This is the Cryptographic library instance for SEC. The motivation of
this library is to support SHA384 in SEC phase for Td guest. So only
Hash/CryptSha512.c is included which supports SHA384 and SHA512.

Cc: Jiewen Yao <jiewen.yao@...>
Cc: Jian J Wang <jian.j.wang@...>
Cc: Xiaoyu Lu <xiaoyu1.lu@...>
Cc: Guomin Jiang <guomin.jiang@...>
Cc: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
CryptoPkg/CryptoPkg.dsc | 4 ++
.../Library/BaseCryptLib/SecCryptLib.inf | 67 +++++++++++++++++++
2 files changed, 71 insertions(+)
create mode 100644 CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf

diff --git a/CryptoPkg/CryptoPkg.dsc b/CryptoPkg/CryptoPkg.dsc
index 0aa72ed87846..b814e9616454 100644
--- a/CryptoPkg/CryptoPkg.dsc
+++ b/CryptoPkg/CryptoPkg.dsc
@@ -109,6 +109,9 @@
[LibraryClasses.ARM]
ArmSoftFloatLib|ArmPkg/Library/ArmSoftFloatLib/ArmSoftFloatLib.inf

+[LibraryClasses.common.SEC]
+ BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf
+
[LibraryClasses.common.PEIM]
PcdLib|MdePkg/Library/PeiPcdLib/PeiPcdLib.inf
ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf
@@ -236,6 +239,7 @@
!if $(CRYPTO_SERVICES) == PACKAGE
[Components]
CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf
+ CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf
CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf
CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf
CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf
diff --git a/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf
new file mode 100644
index 000000000000..6ef2f67e35dd
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf
@@ -0,0 +1,67 @@
+## @file
+# Cryptographic Library Instance for SEC.
+#
+# Caution: This module requires additional review when modified.
+# This library will have external input - signature.
+# This external input must be validated carefully to avoid security issues such as
+# buffer overflow or integer overflow.
+#
+# Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = SecCryptLib
+ FILE_GUID = 3689D343-0D32-4284-8053-BF10537990E8
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = BaseCryptLib|SEC
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = IA32 X64
+#
+
+[Sources]
+ InternalCryptLib.h
+ Hash/CryptSha512.c
+
+ SysCall/CrtWrapper.c
+ SysCall/ConstantTimeClock.c
+ SysCall/BaseMemAllocation.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ CryptoPkg/CryptoPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ MemoryAllocationLib
+ DebugLib
+ OpensslLib
+ IntrinsicLib
+
+#
+# Remove these [BuildOptions] after this library is cleaned up
+#
+[BuildOptions]
+ #
+ # suppress the following warnings so we do not break the build with warnings-as-errors:
+ # C4090: 'function' : different 'const' qualifiers
+ # C4718: 'function call' : recursive call has no side effects, deleting
+ #
+ MSFT:*_*_*_CC_FLAGS = /wd4090 /wd4718
+
+ # -JCryptoPkg/Include : To disable the use of the system includes provided by RVCT
+ # --diag_remark=1 : Reduce severity of "#1-D: last line of file ends without a newline"
+ RVCT:*_*_ARM_CC_FLAGS = -JCryptoPkg/Include --diag_remark=1
+
+ GCC:*_CLANG35_*_CC_FLAGS = -std=c99
+ GCC:*_CLANG38_*_CC_FLAGS = -std=c99
+ GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types
+
+ XCODE:*_*_*_CC_FLAGS = -std=c99
--
2.29.2.windows.2


[PATCH V2 3/8] SecurityPkg: Add definition of EFI_CC_EVENT_HOB_GUID

Min Xu
 

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

EFI_CC_EVENT_HOB_GUID is the global ID of a GUIDed HOB used to pass
TDX_DIGEST_VALUE from SEC to a DXE Driver ( This DXE driver will
be introduced in the following commit in this patch-sets ). In that
DXE driver this GUIDed HOB will be parsed and the TDX_DIGEST_VALUE
then will be extracted. After that a EFI_CC_EVENT will be created
based on it.

Cc: Gerd Hoffmann <kraxel@...>
Cc: Jiewen Yao <jiewen.yao@...>
Cc: Sami Mujawar <sami.mujawar@...>
Cc: Jian J Wang <jian.j.wang@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
SecurityPkg/Include/Guid/CcEventHob.h | 22 ++++++++++++++++++++++
SecurityPkg/SecurityPkg.dec | 4 ++++
2 files changed, 26 insertions(+)
create mode 100644 SecurityPkg/Include/Guid/CcEventHob.h

diff --git a/SecurityPkg/Include/Guid/CcEventHob.h b/SecurityPkg/Include/Guid/CcEventHob.h
new file mode 100644
index 000000000000..072999ce92de
--- /dev/null
+++ b/SecurityPkg/Include/Guid/CcEventHob.h
@@ -0,0 +1,22 @@
+/** @file
+ Defines the HOB GUID used to pass a CC_EVENT from SEC to
+ a CC DXE Driver. A GUIDed HOB is generated for each measurement
+ made in the SEC Phase.
+
+Copyright (c) 2021 - 2022, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef CC_EVENT_HOB_H_
+#define CC_EVENT_HOB_H_
+
+//
+// The Global ID of a GUIDed HOB used to pass a CC_EVENT from SEC to a CC DXE Driver.
+//
+#define EFI_CC_EVENT_HOB_GUID \
+ { 0x20f8fd36, 0x6d00, 0x40fb, { 0xb7, 0x04, 0xd1, 0x2c, 0x15, 0x3c, 0x62, 0xeb } }
+
+extern EFI_GUID gCcEventEntryHobGuid;
+
+#endif
diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec
index 9f7a032d60d5..0ee75efc1a97 100644
--- a/SecurityPkg/SecurityPkg.dec
+++ b/SecurityPkg/SecurityPkg.dec
@@ -136,6 +136,10 @@
## Include/Guid/TcgEventHob.h
gTcgEvent2EntryHobGuid = { 0xd26c221e, 0x2430, 0x4c8a, { 0x91, 0x70, 0x3f, 0xcb, 0x45, 0x0, 0x41, 0x3f }}

+ ## Hob GUID used to pass a CC_EVENT from SEC to a CC DXE Driver.
+ ## Include/Guid/CcEventHob.h
+ gCcEventEntryHobGuid = { 0x20f8fd36, 0x6d00, 0x40fb, { 0xb7, 0x04, 0xd1, 0x2c, 0x15, 0x3c, 0x62, 0xeb }}
+
## HOB GUID used to record TPM device error.
# Include/Guid/TcgEventHob.h
gTpmErrorHobGuid = { 0xef598499, 0xb25e, 0x473a, { 0xbf, 0xaf, 0xe7, 0xe5, 0x7d, 0xce, 0x82, 0xc4 }}
--
2.29.2.windows.2


[PATCH V2 1/8] Security: Add HashLibBaseCryptoRouterTdx

Min Xu
 

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

This library provides hash service by registered hash handler in Td
guest. It redirects hash request to each individual hash handler
(currently only SHA384 is supported). After that the hash value is
extended to Td RTMR registers which is similar to TPM PCRs.

Cc: Jiewen Yao <jiewen.yao@...>
Cc: Jian J Wang <jian.j.wang@...>
Cc: Gerd Hoffmann <kraxel@...>
Signed-off-by: Min Xu <min.m.xu@...>
---
.../HashLibBaseCryptoRouterTdx.c | 214 ++++++++++++++++++
.../HashLibBaseCryptoRouterTdx.inf | 41 ++++
SecurityPkg/SecurityPkg.dsc | 10 +
3 files changed, 265 insertions(+)
create mode 100644 SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.c
create mode 100644 SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.inf

diff --git a/SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.c b/SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.c
new file mode 100644
index 000000000000..77e2a14c19be
--- /dev/null
+++ b/SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.c
@@ -0,0 +1,214 @@
+/** @file
+ This library is BaseCrypto router for Tdx.
+
+Copyright (c) 2021 - 2022, Intel Corporation. All rights reserved. <BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <PiPei.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PcdLib.h>
+#include <Library/HashLib.h>
+#include <Library/TdxLib.h>
+#include <Protocol/CcMeasurement.h>
+#include "HashLibBaseCryptoRouterCommon.h"
+
+//
+// Currently TDX supports SHA384.
+//
+#define TDX_HASH_COUNT 1
+HASH_INTERFACE mHashInterface[TDX_HASH_COUNT] = {
+ {
+ { 0 }, NULL, NULL, NULL
+ }
+};
+
+UINTN mHashInterfaceCount = 0;
+HASH_HANDLE mHashCtx[TDX_HASH_COUNT] = { 0 };
+
+/**
+ Start hash sequence.
+
+ @param HashHandle Hash handle.
+
+ @retval EFI_SUCCESS Hash sequence start and HandleHandle returned.
+ @retval EFI_OUT_OF_RESOURCES No enough resource to start hash.
+**/
+EFI_STATUS
+EFIAPI
+HashStart (
+ OUT HASH_HANDLE *HashHandle
+ )
+{
+ HASH_HANDLE *HashCtx;
+
+ if (mHashInterfaceCount == 0) {
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+ }
+
+ HashCtx = mHashCtx;
+ mHashInterface[0].HashInit (&HashCtx[0]);
+
+ *HashHandle = (HASH_HANDLE)HashCtx;
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Update hash sequence data.
+
+ @param HashHandle Hash handle.
+ @param DataToHash Data to be hashed.
+ @param DataToHashLen Data size.
+
+ @retval EFI_SUCCESS Hash sequence updated.
+**/
+EFI_STATUS
+EFIAPI
+HashUpdate (
+ IN HASH_HANDLE HashHandle,
+ IN VOID *DataToHash,
+ IN UINTN DataToHashLen
+ )
+{
+ HASH_HANDLE *HashCtx;
+
+ if (mHashInterfaceCount == 0) {
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+ }
+
+ HashCtx = (HASH_HANDLE *)HashHandle;
+ mHashInterface[0].HashUpdate (HashCtx[0], DataToHash, DataToHashLen);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Hash sequence complete and extend to PCR.
+
+ @param HashHandle Hash handle.
+ @param PcrIndex PCR to be extended.
+ @param DataToHash Data to be hashed.
+ @param DataToHashLen Data size.
+ @param DigestList Digest list.
+
+ @retval EFI_SUCCESS Hash sequence complete and DigestList is returned.
+**/
+EFI_STATUS
+EFIAPI
+HashCompleteAndExtend (
+ IN HASH_HANDLE HashHandle,
+ IN TPMI_DH_PCR PcrIndex,
+ IN VOID *DataToHash,
+ IN UINTN DataToHashLen,
+ OUT TPML_DIGEST_VALUES *DigestList
+ )
+{
+ TPML_DIGEST_VALUES Digest;
+ HASH_HANDLE *HashCtx;
+ EFI_STATUS Status;
+
+ if (mHashInterfaceCount == 0) {
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+ }
+
+ HashCtx = (HASH_HANDLE *)HashHandle;
+ ZeroMem (DigestList, sizeof (*DigestList));
+
+ mHashInterface[0].HashUpdate (HashCtx[0], DataToHash, DataToHashLen);
+ mHashInterface[0].HashFinal (HashCtx[0], &Digest);
+ Tpm2SetHashToDigestList (DigestList, &Digest);
+
+ ASSERT (DigestList->count == 1 && DigestList->digests[0].hashAlg == TPM_ALG_SHA384);
+
+ Status = TdExtendRtmr (
+ (UINT32 *)DigestList->digests[0].digest.sha384,
+ SHA384_DIGEST_SIZE,
+ (UINT8)PcrIndex
+ );
+
+ ASSERT (!EFI_ERROR (Status));
+ return Status;
+}
+
+/**
+ Hash data and extend to RTMR.
+
+ @param PcrIndex PCR to be extended.
+ @param DataToHash Data to be hashed.
+ @param DataToHashLen Data size.
+ @param DigestList Digest list.
+
+ @retval EFI_SUCCESS Hash data and DigestList is returned.
+**/
+EFI_STATUS
+EFIAPI
+HashAndExtend (
+ IN TPMI_DH_PCR PcrIndex,
+ IN VOID *DataToHash,
+ IN UINTN DataToHashLen,
+ OUT TPML_DIGEST_VALUES *DigestList
+ )
+{
+ HASH_HANDLE HashHandle;
+ EFI_STATUS Status;
+
+ if (mHashInterfaceCount == 0) {
+ ASSERT (FALSE);
+ return EFI_UNSUPPORTED;
+ }
+
+ ASSERT (TdIsEnabled ());
+
+ HashStart (&HashHandle);
+ HashUpdate (HashHandle, DataToHash, DataToHashLen);
+ Status = HashCompleteAndExtend (HashHandle, PcrIndex, NULL, 0, DigestList);
+
+ return Status;
+}
+
+/**
+ This service register Hash.
+
+ @param HashInterface Hash interface
+
+ @retval EFI_SUCCESS This hash interface is registered successfully.
+ @retval EFI_UNSUPPORTED System does not support register this interface.
+ @retval EFI_ALREADY_STARTED System already register this interface.
+**/
+EFI_STATUS
+EFIAPI
+RegisterHashInterfaceLib (
+ IN HASH_INTERFACE *HashInterface
+ )
+{
+ UINT32 HashMask;
+
+ ASSERT (TdIsEnabled ());
+
+ //
+ // Check allow
+ //
+ HashMask = Tpm2GetHashMaskFromAlgo (&HashInterface->HashGuid);
+ ASSERT (HashMask == HASH_ALG_SHA384);
+
+ if (HashMask != HASH_ALG_SHA384) {
+ return EFI_UNSUPPORTED;
+ }
+
+ if (mHashInterfaceCount >= ARRAY_SIZE (mHashInterface)) {
+ ASSERT (FALSE);
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ CopyMem (&mHashInterface[mHashInterfaceCount], HashInterface, sizeof (*HashInterface));
+ mHashInterfaceCount++;
+
+ return EFI_SUCCESS;
+}
diff --git a/SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.inf b/SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.inf
new file mode 100644
index 000000000000..f6b1353d0041
--- /dev/null
+++ b/SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.inf
@@ -0,0 +1,41 @@
+## @file
+# Provides hash service by registered hash handler in Tdx.
+#
+# This library is BaseCrypto router. It will redirect hash request to each individual
+# hash handler registered. Currently only SHA384 is supported in this router.
+#
+# Copyright (c) 2020 - 2021, Intel Corporation. All rights reserved.<BR>
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = HashLibBaseCryptoRouterTdx
+ MODULE_UNI_FILE = HashLibBaseCryptoRouter.uni
+ FILE_GUID = 77F6EA3E-1ABA-4467-A447-926E8CEB2D13
+ MODULE_TYPE = BASE
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = HashLib|SEC DXE_DRIVER
+
+#
+# The following information is for reference only and not required by the build tools.
+#
+# VALID_ARCHITECTURES = X64
+#
+
+[Sources]
+ HashLibBaseCryptoRouterCommon.h
+ HashLibBaseCryptoRouterCommon.c
+ HashLibBaseCryptoRouterTdx.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ SecurityPkg/SecurityPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ DebugLib
+ PcdLib
+ TdxLib
diff --git a/SecurityPkg/SecurityPkg.dsc b/SecurityPkg/SecurityPkg.dsc
index 73a93c2285b1..b23701ad124e 100644
--- a/SecurityPkg/SecurityPkg.dsc
+++ b/SecurityPkg/SecurityPkg.dsc
@@ -72,6 +72,7 @@
MmUnblockMemoryLib|MdePkg/Library/MmUnblockMemoryLib/MmUnblockMemoryLibNull.inf
SecureBootVariableLib|SecurityPkg/Library/SecureBootVariableLib/SecureBootVariableLib.inf
SecureBootVariableProvisionLib|SecurityPkg/Library/SecureBootVariableProvisionLib/SecureBootVariableProvisionLib.inf
+ TdxLib|MdePkg/Library/TdxLib/TdxLib.inf

[LibraryClasses.ARM, LibraryClasses.AARCH64]
#
@@ -92,6 +93,12 @@
[LibraryClasses.RISCV64]
RngLib|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf

+[LibraryClasses.X64.SEC]
+ HashLib|SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.inf
+
+[LibraryClasses.X64.DXE_DRIVER]
+ HashLib|SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.inf
+
[LibraryClasses.common.PEIM]
PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf
PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf
@@ -283,6 +290,9 @@
#
SecurityPkg/RandomNumberGenerator/RngDxe/RngDxe.inf

+[Components.X64]
+ SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.inf
+
[Components.IA32, Components.X64]
SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf

--
2.29.2.windows.2


[PATCH V2 0/8] Enable RTMR based measurement and measure boot for Td guest

Min Xu
 

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

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 below features of Config-B in OvmfPkg.
- Enable RTMR based measurement and measured boot
- Install CC_MEASUREMENT_PROTOCOL instance in Td guest

The measurement for the other components, such as kernel image, initrd,
will be in the following patch-sets.

Patch 1:
HashLibBaseCryptoRouterTdx provides SHA384 service and extend to
RTMR registers.

Patch 2:
SecCryptLib is the cryptographic library instance for SEC.

Patch 3 - 7:
These 5 patches are related to RTMR based measurement and
CC Eventlog ACPI table.

Patch 8:
Update IntelTdxX64.dsc/IntelTdxX64.fdf to support RTMR based
measurement and measured boot.

Code at: https://github.com/mxu9/edk2/tree/tdvf_wave4.v2

v2 changes:
- Move the definition of EFI_CC_EVENT_HOB_GUID from MdePkg to
SecurityPkg.
- Update the definition of EFI_CC_EVENTLOG_ACPI_TABLE based
on below discussion:
https://edk2.groups.io/g/devel/message/87396
https://edk2.groups.io/g/devel/message/87402
- Update the code base to 94f905b3bf.

Cc: Jiewen Yao <jiewen.yao@...>
Cc: Jian J Wang <jian.j.wang@...>
Cc: Gerd Hoffmann <kraxel@...>
Cc: Xiaoyu Lu <xiaoyu1.lu@...>
Cc: Guomin Jiang <guomin.jiang@...>
Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Sami Mujawar <sami.mujawar@...>
Cc: Ken Lu <ken.lu@...>
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: Tom Lendacky <thomas.lendacky@...>
Signed-off-by: Min Xu <min.m.xu@...>

Min Xu (8):
Security: Add HashLibBaseCryptoRouterTdx
CryptoPkg: Add SecCryptLib
SecurityPkg: Add definition of EFI_CC_EVENT_HOB_GUID
OvmfPkg/IntelTdx: Measure Td HobList and Configuration FV
OvmfPkg: Add PCDs for LAML/LASA field in CC EVENTLOG ACPI table
MdePkg: Define CC Measure EventLog ACPI Table
OvmfPkg/IntelTdx: Add TdTcg2Dxe
OvmfPkg/IntelTdx: Enable RTMR based measurement and measure boot

CryptoPkg/CryptoPkg.dsc | 4 +
.../Library/BaseCryptLib/SecCryptLib.inf | 67 +
MdePkg/Include/Protocol/CcMeasurement.h | 21 +
OvmfPkg/IntelTdx/IntelTdxX64.dsc | 15 +-
OvmfPkg/IntelTdx/IntelTdxX64.fdf | 5 +
.../IntelTdx/TdTcg2Dxe/MeasureBootPeCoff.c | 407 +++
OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c | 2489 +++++++++++++++++
OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf | 101 +
OvmfPkg/Library/PeilessStartupLib/IntelTdx.c | 498 ++++
.../PeilessStartupLib/PeilessStartup.c | 30 +
.../PeilessStartupInternal.h | 57 +
.../PeilessStartupLib/PeilessStartupLib.inf | 7 +-
OvmfPkg/OvmfPkg.dec | 6 +
SecurityPkg/Include/Guid/CcEventHob.h | 22 +
.../HashLibBaseCryptoRouterTdx.c | 214 ++
.../HashLibBaseCryptoRouterTdx.inf | 41 +
SecurityPkg/SecurityPkg.dec | 4 +
SecurityPkg/SecurityPkg.dsc | 10 +
18 files changed, 3995 insertions(+), 3 deletions(-)
create mode 100644 CryptoPkg/Library/BaseCryptLib/SecCryptLib.inf
create mode 100644 OvmfPkg/IntelTdx/TdTcg2Dxe/MeasureBootPeCoff.c
create mode 100644 OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.c
create mode 100644 OvmfPkg/IntelTdx/TdTcg2Dxe/TdTcg2Dxe.inf
create mode 100644 OvmfPkg/Library/PeilessStartupLib/IntelTdx.c
create mode 100644 SecurityPkg/Include/Guid/CcEventHob.h
create mode 100644 SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.c
create mode 100644 SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterTdx.inf

--
2.29.2.windows.2


回复: [edk2-devel] [PATCH 1/1] UEFI-SCT: SctPkg: Updated the check for monotonic count after restart

Gao Jie
 

Hi Eday,

The patch looks good to me.

Reviewed-by: Barton Gao <gaojie@...>

Thanks
Barton

-----邮件原件-----
发件人: devel@edk2.groups.io <devel@edk2.groups.io> 代表 G Edhaya Chandran
发送时间: 2022年3月3日 16:59
收件人: devel@edk2.groups.io
主题: [edk2-devel] [PATCH 1/1] UEFI-SCT: SctPkg: Updated the check for monotonic count after restart

Updated the check for montonic count in the case of after restart

From the UEFI Spec:
"The platform’s monotonic counter is comprised of two parts: the high 32 bits and the low 32 bits.
The low 32-bit value is volatile and is reset to zero on every system reset.
It is increased by 1 on every call to GetNextMonotonicCount().
The high 32-bit value is nonvolatile and is increased by one on
whenever the system resets or the low 32-bit counter overflows."

It was found in one case where the higher 32-bit increased by 2
presumably due to the overflow of lower 32-bit counter.
Update the logic to handle this case and to print a warning.

Please find more details in the ticket: https://bugzilla.tianocore.org/show_bug.cgi?id=2774

Cc: Barton Gao <gaojie@...>
Cc: Carolyn Gjertsen <Carolyn.Gjertsen@...>
Cc: Heinrich Schuchardt <heinrich.schuchardt@...>
Cc: Samer El-Haj-Mahmoud <samer.el-haj-mahmoud@...>

Signed-off-by: G Edhaya Chandran<edhaya.chandran@...>
---
.../MiscBootServicesBBTestFunction.c | 20 +++++++++++++------
1 file changed, 14 insertions(+), 6 deletions(-)

diff --git a/uefi-sct/SctPkg/TestCase/UEFI/EFI/BootServices/MiscBootServices/BlackBoxTest/MiscBootServicesBBTestFunction.c b/uefi-sct/SctPkg/TestCase/UEFI/EFI/BootServices/MiscBootServices/BlackBoxTest/MiscBootServicesBBTestFunction.c
index 5d631c16d58b..12703d46f98c 100644
--- a/uefi-sct/SctPkg/TestCase/UEFI/EFI/BootServices/MiscBootServices/BlackBoxTest/MiscBootServicesBBTestFunction.c
+++ b/uefi-sct/SctPkg/TestCase/UEFI/EFI/BootServices/MiscBootServices/BlackBoxTest/MiscBootServicesBBTestFunction.c
@@ -1707,12 +1707,20 @@ GetNextMonotonicCountStep2:
TplArray[Index]
);

- if (SctRShiftU64 (Count2, 32) == SctRShiftU64 (Count, 32) + 1) {
- AssertionType = EFI_TEST_ASSERTION_PASSED;
- } else {
- AssertionType = EFI_TEST_ASSERTION_FAILED;
- }
- StandardLib->RecordAssertion (
+ //The new count of upper 32 bits must be atleast 1 more than the old count.
+ //Pass case: new count is equal to old count + 1
+ if (SctRShiftU64 (Count2, 32) <= SctRShiftU64 (Count, 32)) {
+ AssertionType = EFI_TEST_ASSERTION_FAILED;
+ } else {
+ //If new count is more that old count + 1, then print warning.
+ if (SctRShiftU64 (Count2, 32) > SctRShiftU64 (Count, 32) + 1) {
+ AssertionType = EFI_TEST_ASSERTION_WARNING;
+ } else {
+ //new count == old count + 1
+ AssertionType = EFI_TEST_ASSERTION_PASSED;
+ }
+ }
+ StandardLib->RecordAssertion (
StandardLib,
AssertionType,
Index==0? \
--
2.17.1


Re: [staging/LoongArch RESEND PATCH v1 14/33] BaseTools: BaseTools changes for LoongArch platform.

Abner Chang
 

Acked-by: Abner Chang <abner.chang@...>

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Chao Li
Sent: Wednesday, February 9, 2022 2:55 PM
To: devel@edk2.groups.io
Cc: Bob Feng <bob.c.feng@...>; Liming Gao
<gaoliming@...>; Yuwei Chen <yuwei.chen@...>; Baoqi
Zhang <zhangbaoqi@...>
Subject: [edk2-devel] [staging/LoongArch RESEND PATCH v1 14/33]
BaseTools: BaseTools changes for LoongArch platform.

BaseTools define template files changes for building EDK2 LoongArch
platform.

Cc: Bob Feng <bob.c.feng@...>
Cc: Liming Gao <gaoliming@...>
Cc: Yuwei Chen <yuwei.chen@...>

Signed-off-by: Chao Li <lichao@...>
Co-authored-by: Baoqi Zhang <zhangbaoqi@...>
---
BaseTools/Conf/tools_def.template | 43
++++++++++++++++++++++++++++++-
1 file changed, 42 insertions(+), 1 deletion(-)

diff --git a/BaseTools/Conf/tools_def.template
b/BaseTools/Conf/tools_def.template
index 85b8afbb2d..67b6c69dcf 100755
--- a/BaseTools/Conf/tools_def.template
+++ b/BaseTools/Conf/tools_def.template
@@ -4,6 +4,7 @@
# Portions copyright (c) 2011 - 2019, ARM Ltd. All rights reserved.<BR>
# Copyright (c) 2015, Hewlett-Packard Development Company, L.P.<BR>
# (C) Copyright 2020, Hewlett Packard Enterprise Development LP<BR>
+# Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
# Copyright (c) Microsoft Corporation
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
@@ -267,7 +268,7 @@ DEFINE DTC_BIN = ENV(DTC_PREFIX)dtc
# Intel(r) ACPI Compiler from
# https://acpica.org/downloads
# GCC5 -Linux,Windows- Requires:
-# GCC 5 with LTO support, targeting x86_64-linux-gnu,
aarch64-linux-gnu, arm-linux-gnueabi or riscv64-linux-gnu
+# GCC 5 with LTO support, targeting x86_64-linux-gnu,
aarch64-linux-gnu, arm-linux-gnueabi, riscv64-linux-gnu ro loongarch64-linux-
gnu
# Optional:
# Required to build platforms or ACPI tables:
# Intel(r) ACPI Compiler from
@@ -1871,6 +1872,7 @@ DEFINE GCC_ALL_CC_FLAGS = -g -Os -fshort-
wchar -fno-builtin -fno-stri
DEFINE GCC_IA32_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -m32 -
malign-double -freorder-blocks -freorder-blocks-and-partition -O2 -mno-
stack-arg-probe
DEFINE GCC_X64_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mno-red-
zone -Wno-address -mno-stack-arg-probe
DEFINE GCC_ARM_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mlittle-
endian -mabi=aapcs -fno-short-enums -funsigned-char -ffunction-sections -
fdata-sections -fomit-frame-pointer -Wno-address -mthumb -mfloat-
abi=soft -fno-pic -fno-pie
+DEFINE GCC_LOONGARCH64_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -
march=loongarch64 -mabi=lp64d -Wa,-mla-global-with-abs -fno-plt -Wno-
address -fno-short-enums -fsigned-char -ffunction-sections -fdata-sections
DEFINE GCC_ARM_CC_XIPFLAGS = -mno-unaligned-access
DEFINE GCC_AARCH64_CC_FLAGS = DEF(GCC_ALL_CC_FLAGS) -mlittle-
endian -fno-short-enums -fverbose-asm -funsigned-char -ffunction-sections
-fdata-sections -Wno-address -fno-asynchronous-unwind-tables -fno-
unwind-tables -fno-pic -fno-pie -ffixed-x18
DEFINE GCC_AARCH64_CC_XIPFLAGS = -mstrict-align -mgeneral-regs-only
@@ -1878,12 +1880,15 @@ DEFINE GCC_DLINK_FLAGS_COMMON = -
nostdlib --pie
DEFINE GCC_DLINK2_FLAGS_COMMON = -Wl,--
script=$(EDK_TOOLS_PATH)/Scripts/GccBase.lds
DEFINE GCC_IA32_X64_DLINK_COMMON =
DEF(GCC_DLINK_FLAGS_COMMON) --gc-sections
DEFINE GCC_ARM_AARCH64_DLINK_COMMON= -Wl,--emit-relocs -nostdlib
-Wl,--gc-sections -u $(IMAGE_ENTRY_POINT) -Wl,-
e,$(IMAGE_ENTRY_POINT),-Map,$(DEST_DIR_DEBUG)/$(BASE_NAME).map
+DEFINE GCC_LOONGARCH64_DLINK_COMMON= -Wl,--emit-relocs -
nostdlib -Wl,--gc-sections -u $(IMAGE_ENTRY_POINT) -Wl,-
e,$(IMAGE_ENTRY_POINT),-Map,$(DEST_DIR_DEBUG)/$(BASE_NAME).map
DEFINE GCC_ARM_DLINK_FLAGS =
DEF(GCC_ARM_AARCH64_DLINK_COMMON) -z common-page-size=0x20 -
Wl,--pic-veneer
DEFINE GCC_AARCH64_DLINK_FLAGS =
DEF(GCC_ARM_AARCH64_DLINK_COMMON) -z common-page-size=0x20
+DEFINE GCC_LOONGARCH64_DLINK_FLAGS =
DEF(GCC_LOONGARCH64_DLINK_COMMON) -z common-page-size=0x20
DEFINE GCC_ARM_AARCH64_ASLDLINK_FLAGS = -Wl,--
defsym=PECOFF_HEADER_SIZE=0 DEF(GCC_DLINK2_FLAGS_COMMON) -z
common-page-size=0x20
DEFINE GCC_IA32_X64_ASLDLINK_FLAGS =
DEF(GCC_IA32_X64_DLINK_COMMON) --entry _ReferenceAcpiTable -u
$(IMAGE_ENTRY_POINT)
DEFINE GCC_ARM_ASLDLINK_FLAGS = DEF(GCC_ARM_DLINK_FLAGS) -
Wl,--entry,ReferenceAcpiTable -u $(IMAGE_ENTRY_POINT)
DEF(GCC_ARM_AARCH64_ASLDLINK_FLAGS)
DEFINE GCC_AARCH64_ASLDLINK_FLAGS =
DEF(GCC_AARCH64_DLINK_FLAGS) -Wl,--entry,ReferenceAcpiTable -u
$(IMAGE_ENTRY_POINT) DEF(GCC_ARM_AARCH64_ASLDLINK_FLAGS)
+DEFINE GCC_LOONGARCH64_ASLDLINK_FLAGS =
DEF(GCC_LOONGARCH64_DLINK_FLAGS) --entry ReferenceAcpiTable -u
$(IMAGE_ENTRY_POINT)
DEFINE GCC_IA32_X64_DLINK_FLAGS =
DEF(GCC_IA32_X64_DLINK_COMMON) --entry _$(IMAGE_ENTRY_POINT) --
file-alignment 0x20 --section-alignment 0x20 -Map
$(DEST_DIR_DEBUG)/$(BASE_NAME).map
DEFINE GCC_ASM_FLAGS = -c -x assembler -imacros AutoGen.h
DEFINE GCC_PP_FLAGS = -E -x assembler-with-cpp -include
AutoGen.h
@@ -1897,6 +1902,7 @@ DEFINE GCC_X64_RC_FLAGS = -I binary -O
elf64-x86-64 -B i386
DEFINE GCC_ARM_RC_FLAGS = -I binary -O elf32-littlearm -B arm --
rename-section .data=.hii
DEFINE GCC_AARCH64_RC_FLAGS = -I binary -O elf64-littleaarch64 -B
aarch64 --rename-section .data=.hii
DEFINE GCC_RISCV64_RC_FLAGS = -I binary -O elf64-littleriscv -B riscv -
-rename-section .data=.hii
+DEFINE GCC_LOONGARCH64_RC_FLAGS = -I binary -O elf64-loongarch -B
loongarch64 --alt-elf-eflags=0x3 --rename-section .data=.hii

# GCC Build Flag for included header file list generation
DEFINE GCC_DEPS_FLAGS = -MMD -MF $@.deps
@@ -1986,6 +1992,12 @@ DEFINE GCC5_RISCV64_CC_FLAGS =
DEF(GCC5_RISCV_ALL_CC_FLAGS) DEF(GC
DEFINE GCC5_RISCV64_DLINK_FLAGS =
DEF(GCC5_RISCV_ALL_DLINK_FLAGS) -Wl,-melf64lriscv,--oformat=elf64-
littleriscv,--no-relax
DEFINE GCC5_RISCV64_DLINK2_FLAGS =
DEF(GCC5_RISCV_ALL_DLINK2_FLAGS)
DEFINE GCC5_RISCV64_ASM_FLAGS =
DEF(GCC5_RISCV_ALL_ASM_FLAGS) -march=DEF(GCC5_RISCV64_ARCH) -
mcmodel=medany -mabi=lp64
+DEFINE GCC5_LOONGARCH64_CC_FLAGS =
DEF(GCC_LOONGARCH64_CC_FLAGS) -mno-memcpy -Werror -Wno-maybe-
uninitialized -Wno-stringop-overflow -Wno-pointer-to-int-cast
+DEFINE GCC5_LOONGARCH64_DLINK_FLAGS =
DEF(GCC_LOONGARCH64_DLINK_FLAGS)
+DEFINE GCC5_LOONGARCH64_DLINK2_FLAGS =
DEF(GCC_DLINK2_FLAGS_COMMON) -Wl,--
defsym=PECOFF_HEADER_SIZE=0x228
+DEFINE GCC5_LOONGARCH64_ASLDLINK_FLAGS =
DEF(GCC_LOONGARCH64_ASLDLINK_FLAGS)
+DEFINE GCC5_LOONGARCH64_ASM_FLAGS = -x assembler-with-cpp -
mabi=lp64d -march=loongarch64 -Wa,-mla-global-with-abs -fno-builtin -c -
Wall
+DEFINE GCC5_LOONGARCH64_PP_FLAGS = -mabi=lp64d -
march=loongarch64 DEF(GCC_PP_FLAGS)
DEFINE GCC_PP_FLAGS = -E -x assembler-with-cpp -include
AutoGen.h DEF(GCC5_RISCV_OPENSBI_TYPES)


##########################################################
##########################
@@ -2464,6 +2476,35 @@ RELEASE_GCC5_AARCH64_DLINK_XIPFLAGS = -z
common-page-size=0x20
*_GCC5_RISCV64_OBJCOPY_FLAGS =
*_GCC5_RISCV64_DTCPP_FLAGS = DEF(GCC_DTCPP_FLAGS)

+##################
+# GCC5 LOONGARCH64 definitions
+##################
+*_GCC5_LOONGARCH64_OBJCOPY_PATH =
ENV(GCC5_LOONGARCH64_PREFIX)objcopy
+*_GCC5_LOONGARCH64_CC_PATH =
ENV(GCC5_LOONGARCH64_PREFIX)gcc
+*_GCC5_LOONGARCH64_SLINK_PATH =
ENV(GCC5_LOONGARCH64_PREFIX)gcc-ar
+*_GCC5_LOONGARCH64_DLINK_PATH =
ENV(GCC5_LOONGARCH64_PREFIX)gcc
+*_GCC5_LOONGARCH64_ASLDLINK_PATH =
ENV(GCC5_LOONGARCH64_PREFIX)gcc
+*_GCC5_LOONGARCH64_ASM_PATH =
ENV(GCC5_LOONGARCH64_PREFIX)gcc
+*_GCC5_LOONGARCH64_PP_PATH =
ENV(GCC5_LOONGARCH64_PREFIX)gcc
+*_GCC5_LOONGARCH64_VFRPP_PATH =
ENV(GCC5_LOONGARCH64_PREFIX)gcc
+*_GCC5_LOONGARCH64_ASLCC_PATH =
ENV(GCC5_LOONGARCH64_PREFIX)gcc
+*_GCC5_LOONGARCH64_ASLPP_PATH =
ENV(GCC5_LOONGARCH64_PREFIX)gcc
+*_GCC5_LOONGARCH64_RC_PATH =
ENV(GCC5_LOONGARCH64_PREFIX)objcopy
+
+*_GCC5_LOONGARCH64_ASLCC_FLAGS = DEF(GCC_ASLCC_FLAGS)
+*_GCC5_LOONGARCH64_ASLDLINK_FLAGS =
DEF(GCC5_LOONGARCH64_ASLDLINK_FLAGS)
+*_GCC5_LOONGARCH64_ASM_FLAGS =
DEF(GCC5_LOONGARCH64_ASM_FLAGS)
+*_GCC5_LOONGARCH64_CC_FLAGS =
DEF(GCC5_LOONGARCH64_CC_FLAGS)
+*_GCC5_LOONGARCH64_DLINK_FLAGS =
DEF(GCC5_LOONGARCH64_DLINK_FLAGS)
+*_GCC5_LOONGARCH64_DLINK2_FLAGS =
DEF(GCC5_LOONGARCH64_DLINK2_FLAGS)
+*_GCC5_LOONGARCH64_RC_FLAGS =
DEF(GCC_LOONGARCH64_RC_FLAGS)
+*_GCC5_LOONGARCH64_OBJCOPY_FLAGS =
+*_GCC5_LOONGARCH64_NASM_FLAGS = -f elf32
+*_GCC5_LOONGARCH64_PP_FLAGS =
DEF(GCC5_LOONGARCH64_PP_FLAGS)
+
+DEBUG_GCC5_LOONGARCH64_CC_FLAGS =
DEF(GCC5_LOONGARCH64_CC_FLAGS)
+RELEASE_GCC5_LOONGARCH64_CC_FLAGS =
DEF(GCC5_LOONGARCH64_CC_FLAGS) -Wno-unused-but-set-variable -
Wno-unused-variable
+

##########################################################
##########################
#
# CLANG35 - This configuration is used to compile under Linux to produce
--
2.27.0





Re: [staging/LoongArch RESEND PATCH v1 13/33] BaseTools: BaseTools changes for LoongArch platform.

Abner Chang
 

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Chao Li
Sent: Wednesday, February 9, 2022 2:55 PM
To: devel@edk2.groups.io
Cc: Bob Feng <bob.c.feng@...>; Liming Gao
<gaoliming@...>; Yuwei Chen <yuwei.chen@...>; Baoqi
Zhang <zhangbaoqi@...>
Subject: [edk2-devel] [staging/LoongArch RESEND PATCH v1 13/33]
BaseTools: BaseTools changes for LoongArch platform.

C code changes for building EDK2 LoongArch platform.

Cc: Bob Feng <bob.c.feng@...>
Cc: Liming Gao <gaoliming@...>
Cc: Yuwei Chen <yuwei.chen@...>

Signed-off-by: Chao Li <lichao@...>
Co-authored-by: Baoqi Zhang <zhangbaoqi@...>
---
BaseTools/Source/C/Common/BasePeCoff.c | 15 +-
BaseTools/Source/C/Common/PeCoffLoaderEx.c | 76 +++++++++
BaseTools/Source/C/GenFv/GenFvInternalLib.c | 128 ++++++++++++++-
BaseTools/Source/C/GenFw/Elf64Convert.c | 153 +++++++++++++++++-
BaseTools/Source/C/GenFw/elf_common.h | 58 +++++++
.../C/Include/IndustryStandard/PeImage.h | 57 ++++---
6 files changed, 454 insertions(+), 33 deletions(-)

diff --git a/BaseTools/Source/C/Common/BasePeCoff.c
b/BaseTools/Source/C/Common/BasePeCoff.c
index 62fbb2985c..30400d1341 100644
--- a/BaseTools/Source/C/Common/BasePeCoff.c
+++ b/BaseTools/Source/C/Common/BasePeCoff.c
@@ -5,6 +5,7 @@
Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.<BR>
Portions Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.<BR>
Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All
rights reserved.<BR>
+Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All
rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent

**/
@@ -68,6 +69,14 @@ PeCoffLoaderRelocateRiscVImage (
IN UINT64 Adjust
);

+RETURN_STATUS
+PeCoffLoaderRelocateLoongArch64Image (
+ IN UINT16 *Reloc,
+ IN OUT CHAR8 *Fixup,
+ IN OUT CHAR8 **FixupData,
+ IN UINT64 Adjust
+ );
+
STATIC
RETURN_STATUS
PeCoffLoaderGetPeHeader (
@@ -184,7 +193,8 @@ Returns:
ImageContext->Machine != EFI_IMAGE_MACHINE_ARMT && \
ImageContext->Machine != EFI_IMAGE_MACHINE_EBC && \
ImageContext->Machine != EFI_IMAGE_MACHINE_AARCH64 && \
- ImageContext->Machine != EFI_IMAGE_MACHINE_RISCV64) {
+ ImageContext->Machine != EFI_IMAGE_MACHINE_RISCV64 && \
+ ImageContext->Machine != EFI_IMAGE_MACHINE_LOONGARCH64) {
if (ImageContext->Machine == IMAGE_FILE_MACHINE_ARM) {
//
// There are two types of ARM images. Pure ARM and ARM/Thumb.
@@ -815,6 +825,9 @@ Returns:
case EFI_IMAGE_MACHINE_RISCV64:
Status = PeCoffLoaderRelocateRiscVImage (Reloc, Fixup, &FixupData,
Adjust);
break;
+ case EFI_IMAGE_MACHINE_LOONGARCH64:
+ Status = PeCoffLoaderRelocateLoongArch64Image (Reloc, Fixup,
&FixupData, Adjust);
+ break;
default:
Status = RETURN_UNSUPPORTED;
break;
diff --git a/BaseTools/Source/C/Common/PeCoffLoaderEx.c
b/BaseTools/Source/C/Common/PeCoffLoaderEx.c
index 799f282970..b50ce8bdef 100644
--- a/BaseTools/Source/C/Common/PeCoffLoaderEx.c
+++ b/BaseTools/Source/C/Common/PeCoffLoaderEx.c
@@ -4,6 +4,7 @@ IA32 and X64 Specific relocation fixups
Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.<BR>
Portions Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.<BR>
Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights
reserved.<BR>
+Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent

--*/
@@ -332,3 +333,78 @@ PeCoffLoaderRelocateArmImage (

return RETURN_SUCCESS;
}
+
+/**
+ Performs a LoongArch specific relocation fixup.
+
+ @param Reloc Pointer to the relocation record.
+ @param Fixup Pointer to the address to fix up.
+ @param FixupData Pointer to a buffer to log the fixups.
+ @param Adjust The offset to adjust the fixup.
+
+ @return Status code.
+**/
+RETURN_STATUS
+PeCoffLoaderRelocateLoongArch64Image (
+ IN UINT16 *Reloc,
+ IN OUT CHAR8 *Fixup,
+ IN OUT CHAR8 **FixupData,
+ IN UINT64 Adjust
+ )
+{
+ UINT8 RelocType;
+ UINT64 Value = 0;
+ UINT64 Tmp1 = 0;
+ UINT64 Tmp2 = 0;
+
+ RelocType = ((*Reloc) >> 12);
+
+ switch (RelocType) {
+ case EFI_IMAGE_REL_BASED_LOONGARCH64_MARK_LA:
+ /* The next four instructions are used to load a 64 bit address, we
change it together*/
+ Value = (*(UINT32*)Fixup & 0x1ffffe0) << 7 | /* lu12i.w 20bits from
bit5 */
Please use double back slash for the comment in the function. So the comment in the entire file look consistent. This applied to the changes in this patch.

+ (*((UINT32*)Fixup + 1) & 0x3ffc00) >> 10; /* ori 12bits from bit10 */
+ Tmp1 = *((UINT32*)Fixup + 2) & 0x1ffffe0; /* lu32i.d 20bits from bit5
*/
+ Tmp2 = *((UINT32*)Fixup + 3) & 0x3ffc00; /* lu52i.d 12bits from
bit10 */
+ Value = Value | (Tmp1 << 27) | (Tmp2 << 42);
+
+ Value += Adjust;
+
+ *(UINT32*)Fixup = (*(UINT32*)Fixup & ~0x1ffffe0) | (((Value >> 12) &
0xfffff) << 5);
+ if (*FixupData != NULL) {
+ *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32));
+ *(UINT32 *) (*FixupData) = *(UINT32*)Fixup;
+ *FixupData = *FixupData + sizeof (UINT32);
+ }
+
+ Fixup += sizeof(UINT32);
+ *(UINT32*)Fixup = (*(UINT32*)Fixup & ~0x3ffc00) | ((Value & 0xfff) <<
10);
+ if (*FixupData != NULL) {
+ *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32));
+ *(UINT32 *) (*FixupData) = *(UINT32*)Fixup;
+ *FixupData = *FixupData + sizeof (UINT32);
+ }
+
+ Fixup += sizeof(UINT32);
+ *(UINT32*)Fixup = (*(UINT32*)Fixup & ~0x1ffffe0) | (((Value >> 32) &
0xfffff) << 5);
+ if (*FixupData != NULL) {
+ *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32));
+ *(UINT32 *) (*FixupData) = *(UINT32*)Fixup;
+ *FixupData = *FixupData + sizeof (UINT32);
+ }
+
+ Fixup += sizeof(UINT32);
+ *(UINT32*)Fixup = (*(UINT32*)Fixup & ~0x3ffc00) | (((Value >> 52) &
0xfff) << 10);
+ if (*FixupData != NULL) {
+ *FixupData = ALIGN_POINTER (*FixupData, sizeof (UINT32));
+ *(UINT32 *) (*FixupData) = *(UINT32*)Fixup;
+ *FixupData = *FixupData + sizeof (UINT32);
+ }
+ break;
+ default:
+ Error (NULL, 0, 3000, "", "PeCoffLoaderRelocateLoongArch64Image:
Fixup[0x%x] Adjust[0x%llx] *Reloc[0x%x], type[0x%x].", *(UINT32*)Fixup,
Adjust, *Reloc, RelocType);
+ return RETURN_UNSUPPORTED;
+ }
+
+ return RETURN_SUCCESS;
+}
diff --git a/BaseTools/Source/C/GenFv/GenFvInternalLib.c
b/BaseTools/Source/C/GenFv/GenFvInternalLib.c
index d650a527a5..9c518b3609 100644
--- a/BaseTools/Source/C/GenFv/GenFvInternalLib.c
+++ b/BaseTools/Source/C/GenFv/GenFvInternalLib.c
@@ -5,6 +5,7 @@ Copyright (c) 2004 - 2018, Intel Corporation. All rights
reserved.<BR>
Portions Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.<BR>
Portions Copyright (c) 2016 HP Development Company, L.P.<BR>
Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All
rights reserved.<BR>
+Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All
rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent

**/
@@ -57,6 +58,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent

BOOLEAN mArm = FALSE;
BOOLEAN mRiscV = FALSE;
+BOOLEAN mLoongArch = FALSE;
STATIC UINT32 MaxFfsAlignment = 0;
BOOLEAN VtfFileFlag = FALSE;

@@ -2416,6 +2418,102 @@ Returns:
return EFI_SUCCESS;
}

+EFI_STATUS
+UpdateLoongArchResetVectorIfNeeded (
+ IN MEMORY_FILE *FvImage,
+ IN FV_INFO *FvInfo
+ )
+/*++
+
+Routine Description:
+ This parses the FV looking for SEC and patches that address into the
+ beginning of the FV header.
+
+ For LoongArch ISA, the reset vector is at 0x1c000000.
+
+ We relocate it to SecCoreEntry and copy the ResetVector code to the
+ beginning of the FV.
+
+Arguments:
+ FvImage Memory file for the FV memory image
+ FvInfo Information read from INF file.
+
+Returns:
+
+ EFI_SUCCESS Function Completed successfully.
+ EFI_ABORTED Error encountered.
+ EFI_INVALID_PARAMETER A required parameter was NULL.
+ EFI_NOT_FOUND PEI Core file not found.
+
+--*/
+{
+ EFI_STATUS Status;
+ EFI_FILE_SECTION_POINTER SecPe32;
+ BOOLEAN UpdateVectorSec = FALSE;
+ UINT16 MachineType = 0;
+ EFI_PHYSICAL_ADDRESS SecCoreEntryAddress = 0;
+
+ //
+ // Verify input parameters
+ //
+ if (FvImage == NULL || FvInfo == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Locate an SEC Core instance and if found extract the machine type and
entry point address
+ //
+ Status = FindCorePeSection(FvImage->FileImage, FvInfo->Size,
EFI_FV_FILETYPE_SECURITY_CORE, &SecPe32);
+ if (!EFI_ERROR(Status)) {
+
+ Status = GetCoreMachineType(SecPe32, &MachineType);
+ if (EFI_ERROR(Status)) {
+ Error(NULL, 0, 3000, "Invalid", "Could not get the PE32 machine type for
SEC Core.");
+ return EFI_ABORTED;
+ }
+
+ Status = GetCoreEntryPointAddress(FvImage->FileImage, FvInfo,
SecPe32, &SecCoreEntryAddress);
+ if (EFI_ERROR(Status)) {
+ Error(NULL, 0, 3000, "Invalid", "Could not get the PE32 entry point
address for SEC Core.");
+ return EFI_ABORTED;
+ }
+
+ UpdateVectorSec = TRUE;
+ }
+
+ if (!UpdateVectorSec)
+ return EFI_SUCCESS;
+
+ if (MachineType == EFI_IMAGE_MACHINE_LOONGARCH64) {
+ UINT32 ResetVector[3];
+ UINT32 InstrStack;
+
+ memset(ResetVector, 0, sizeof (ResetVector));
+
+ /* if we found an SEC core entry point then generate a branch instruction
*/
+ if (UpdateVectorSec) {
+ VerboseMsg("UpdateLoongArchResetVectorIfNeeded updating
LOONGARCH64 SEC vector");
+
+ InstrStack = (SecCoreEntryAddress >> 12) & 0xfffff;
+ ResetVector[0] = 0x14000001 | (InstrStack << 5); /* lu12i.w ra si20 */
+
+ InstrStack = (SecCoreEntryAddress & 0x0fff);
+ ResetVector[1] = 0x03800021 | (InstrStack << 10); /* ori ra, ra, ui12 */
+ ResetVector[2] = 0x4c000021; /* jirl ra, ra, 0 */
+ }
+
+ //
+ // Copy to the beginning of the FV
+ //
+ memcpy(FvImage->FileImage, ResetVector, sizeof (ResetVector));
+ } else {
+ Error(NULL, 0, 3000, "Invalid", "Unknown machine type");
+ return EFI_ABORTED;
+ }
+
+ return EFI_SUCCESS;
+}
+
EFI_STATUS
GetPe32Info (
IN UINT8 *Pe32,
@@ -2509,7 +2607,7 @@ Returns:
//
if ((*MachineType != EFI_IMAGE_MACHINE_IA32) && (*MachineType !=
EFI_IMAGE_MACHINE_X64) && (*MachineType !=
EFI_IMAGE_MACHINE_EBC) &&
(*MachineType != EFI_IMAGE_MACHINE_ARMT) && (*MachineType !=
EFI_IMAGE_MACHINE_AARCH64) &&
- (*MachineType != EFI_IMAGE_MACHINE_RISCV64)) {
+ (*MachineType != EFI_IMAGE_MACHINE_RISCV64) &&
(*MachineType != EFI_IMAGE_MACHINE_LOONGARCH64)) {
Error (NULL, 0, 3000, "Invalid", "Unrecognized machine type in the PE32
file.");
return EFI_UNSUPPORTED;
}
@@ -2953,7 +3051,7 @@ Returns:
goto Finish;
}

- if (!mArm && !mRiscV) {
+ if (!mArm && !mRiscV && !mLoongArch) {
//
// Update reset vector (SALE_ENTRY for IPF)
// Now for IA32 and IA64 platform, the fv which has bsf file must have the
@@ -3004,6 +3102,19 @@ Returns:
FvHeader->Checksum = CalculateChecksum16 ((UINT16 *) FvHeader,
FvHeader->HeaderLength / sizeof (UINT16));
}

+ if (mLoongArch) {
+ Status = UpdateLoongArchResetVectorIfNeeded (&FvImageMemoryFile,
&mFvDataInfo);
+ if (EFI_ERROR (Status)) {
+ Error (NULL, 0, 3000, "Invalid", "Could not update the reset vector.");
+ goto Finish;
+ }
+ //
+ // Update Checksum for FvHeader
+ //
+ FvHeader->Checksum = 0;
+ FvHeader->Checksum = CalculateChecksum16 ((UINT16 *) FvHeader,
FvHeader->HeaderLength / sizeof (UINT16));
+ }
+
//
// Update FV Alignment attribute to the largest alignment of all the FFS files
in the FV
//
@@ -3450,6 +3561,11 @@ Returns:
VerboseMsg("Located ARM/AArch64 SEC/PEI core in child FV");
mArm = TRUE;
}
+ // machine type is LOONGARCH64, set a flag so LOONGARCH64 reset
vector procesing occurs
+ if ((MachineType == EFI_IMAGE_MACHINE_LOONGARCH64)) {
+ VerboseMsg("Located LOONGARCH64 SEC core in child FV");
+ mLoongArch = TRUE;
+ }
}

//
@@ -3608,6 +3724,10 @@ Returns:
mRiscV = TRUE;
}

+ if ( (ImageContext.Machine == EFI_IMAGE_MACHINE_LOONGARCH64) ) {
+ mLoongArch = TRUE;
+ }
+
//
// Keep Image Context for PE image in FV
//
@@ -3885,6 +4005,10 @@ Returns:
mArm = TRUE;
}

+ if ( (ImageContext.Machine == EFI_IMAGE_MACHINE_LOONGARCH64) ) {
+ mLoongArch = TRUE;
+ }
+
//
// Keep Image Context for TE image in FV
//
diff --git a/BaseTools/Source/C/GenFw/Elf64Convert.c
b/BaseTools/Source/C/GenFw/Elf64Convert.c
index 0bb3ead228..b66aadfd6c 100644
--- a/BaseTools/Source/C/GenFw/Elf64Convert.c
+++ b/BaseTools/Source/C/GenFw/Elf64Convert.c
@@ -4,6 +4,7 @@ Elf64 convert solution
Copyright (c) 2010 - 2021, Intel Corporation. All rights reserved.<BR>
Portions copyright (c) 2013-2014, ARM Ltd. All rights reserved.<BR>
Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All
rights reserved.<BR>
+Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All
rights reserved.<BR>

SPDX-License-Identifier: BSD-2-Clause-Patent

@@ -163,7 +164,7 @@ InitializeElf64 (
Error (NULL, 0, 3000, "Unsupported", "ELF e_type not ET_EXEC or
ET_DYN");
return FALSE;
}
- if (!((mEhdr->e_machine == EM_X86_64) || (mEhdr->e_machine ==
EM_AARCH64) || (mEhdr->e_machine == EM_RISCV64))) {
+ if (!((mEhdr->e_machine == EM_X86_64) || (mEhdr->e_machine ==
EM_AARCH64) || (mEhdr->e_machine == EM_RISCV64) || (mEhdr-
e_machine == EM_LOONGARCH64))) {
Warning (NULL, 0, 3000, "Unsupported", "ELF e_machine is not Elf64
machine.");
}
if (mEhdr->e_version != EV_CURRENT) {
@@ -730,6 +731,7 @@ ScanSections64 (
case EM_X86_64:
case EM_AARCH64:
case EM_RISCV64:
+ case EM_LOONGARCH64:
mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS64);
break;
default:
@@ -943,6 +945,10 @@ ScanSections64 (
NtHdr->Pe32Plus.FileHeader.Machine = EFI_IMAGE_MACHINE_RISCV64;
NtHdr->Pe32Plus.OptionalHeader.Magic =
EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
break;
+ case EM_LOONGARCH64:
+ NtHdr->Pe32Plus.FileHeader.Machine =
EFI_IMAGE_MACHINE_LOONGARCH64;
+ NtHdr->Pe32Plus.OptionalHeader.Magic =
EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC;
+ break;

default:
VerboseMsg ("%s unknown e_machine type. Assume X64",
(UINTN)mEhdr->e_machine);
@@ -1149,10 +1155,10 @@ WriteSections64 (
}

//
- // Skip error on EM_RISCV64 becasue no symble name is built
- // from RISC-V toolchain.
+ // Skip error on EM_RISCV64 and EM_LOONGARCH64 becasue no
symble name is built
+ // from RISC-V and LoongArch toolchain.
//
- if (mEhdr->e_machine != EM_RISCV64) {
+ if ((mEhdr->e_machine != EM_RISCV64) && (mEhdr->e_machine !=
EM_LOONGARCH64)) {
Error (NULL, 0, 3000, "Invalid",
"%s: Bad definition for symbol '%s'@%#llx or unsupported symbol
type. "
"For example, absolute and undefined symbols are not
supported.",
@@ -1417,6 +1423,74 @@ WriteSections64 (
// Write section for RISC-V 64 architecture.
//
WriteSectionRiscV64 (Rel, Targ, SymShdr, Sym);
+ } else if (mEhdr->e_machine == EM_LOONGARCH64) {
+ switch (ELF_R_TYPE(Rel->r_info)) {
+
+ case R_LARCH_SOP_PUSH_ABSOLUTE:
+ //
+ // Absolute relocation.
+ //
+ *(UINT64 *)Targ = *(UINT64 *)Targ - SymShdr->sh_addr +
mCoffSectionsOffset[Sym->st_shndx];
+ break;
+
+ case R_LARCH_MARK_LA:
+ case R_LARCH_64:
+ case R_LARCH_NONE:
+ case R_LARCH_32:
+ case R_LARCH_RELATIVE:
+ case R_LARCH_COPY:
+ case R_LARCH_JUMP_SLOT:
+ case R_LARCH_TLS_DTPMOD32:
+ case R_LARCH_TLS_DTPMOD64:
+ case R_LARCH_TLS_DTPREL32:
+ case R_LARCH_TLS_DTPREL64:
+ case R_LARCH_TLS_TPREL32:
+ case R_LARCH_TLS_TPREL64:
+ case R_LARCH_IRELATIVE:
+ case R_LARCH_MARK_PCREL:
+ case R_LARCH_SOP_PUSH_PCREL:
+ case R_LARCH_SOP_PUSH_DUP:
+ case R_LARCH_SOP_PUSH_GPREL:
+ case R_LARCH_SOP_PUSH_TLS_TPREL:
+ case R_LARCH_SOP_PUSH_TLS_GOT:
+ case R_LARCH_SOP_PUSH_TLS_GD:
+ case R_LARCH_SOP_PUSH_PLT_PCREL:
+ case R_LARCH_SOP_ASSERT:
+ case R_LARCH_SOP_NOT:
+ case R_LARCH_SOP_SUB:
+ case R_LARCH_SOP_SL:
+ case R_LARCH_SOP_SR:
+ case R_LARCH_SOP_ADD:
+ case R_LARCH_SOP_AND:
+ case R_LARCH_SOP_IF_ELSE:
+ case R_LARCH_SOP_POP_32_S_10_5:
+ case R_LARCH_SOP_POP_32_U_10_12:
+ case R_LARCH_SOP_POP_32_S_10_12:
+ case R_LARCH_SOP_POP_32_S_10_16:
+ case R_LARCH_SOP_POP_32_S_10_16_S2:
+ case R_LARCH_SOP_POP_32_S_5_20:
+ case R_LARCH_SOP_POP_32_S_0_5_10_16_S2:
+ case R_LARCH_SOP_POP_32_S_0_10_10_16_S2:
+ case R_LARCH_SOP_POP_32_U:
+ case R_LARCH_ADD8:
+ case R_LARCH_ADD16:
+ case R_LARCH_ADD24:
+ case R_LARCH_ADD32:
+ case R_LARCH_ADD64:
+ case R_LARCH_SUB8:
+ case R_LARCH_SUB16:
+ case R_LARCH_SUB24:
+ case R_LARCH_SUB32:
+ case R_LARCH_SUB64:
+ case R_LARCH_GNU_VTINHERIT:
+ case R_LARCH_GNU_VTENTRY:
+ //
+ // These types are not used or do not need to fix the offsets.
+ //
+ break;
+ default:
+ Error (NULL, 0, 3000, "Invalid", "WriteSections64(): %s unsupported
ELF EM_LOONGARCH64 relocation 0x%x.", mInImageName, (unsigned)
ELF64_R_TYPE(Rel->r_info));
+ }
} else {
Error (NULL, 0, 3000, "Invalid", "Not a supported machine type");
}
@@ -1647,6 +1721,77 @@ WriteRelocations64 (
default:
Error (NULL, 0, 3000, "Invalid", "WriteRelocations64(): %s
unsupported ELF EM_RISCV64 relocation 0x%x.", mInImageName, (unsigned)
ELF_R_TYPE(Rel->r_info));
}
+ } else if (mEhdr->e_machine == EM_LOONGARCH64) {
+ switch (ELF_R_TYPE(Rel->r_info)) {
+ case R_LARCH_MARK_LA:
+ CoffAddFixup(
+ (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
+ + (Rel->r_offset - SecShdr->sh_addr)),
+ EFI_IMAGE_REL_BASED_LOONGARCH64_MARK_LA);
+ break;
+ case R_LARCH_64:
+ CoffAddFixup(
+ (UINT32) ((UINT64) mCoffSectionsOffset[RelShdr->sh_info]
+ + (Rel->r_offset - SecShdr->sh_addr)),
+ EFI_IMAGE_REL_BASED_DIR64);
+ break;
+ case R_LARCH_NONE:
+ case R_LARCH_32:
+ case R_LARCH_RELATIVE:
+ case R_LARCH_COPY:
+ case R_LARCH_JUMP_SLOT:
+ case R_LARCH_TLS_DTPMOD32:
+ case R_LARCH_TLS_DTPMOD64:
+ case R_LARCH_TLS_DTPREL32:
+ case R_LARCH_TLS_DTPREL64:
+ case R_LARCH_TLS_TPREL32:
+ case R_LARCH_TLS_TPREL64:
+ case R_LARCH_IRELATIVE:
+ case R_LARCH_MARK_PCREL:
+ case R_LARCH_SOP_PUSH_PCREL:
+ case R_LARCH_SOP_PUSH_ABSOLUTE:
+ case R_LARCH_SOP_PUSH_DUP:
+ case R_LARCH_SOP_PUSH_GPREL:
+ case R_LARCH_SOP_PUSH_TLS_TPREL:
+ case R_LARCH_SOP_PUSH_TLS_GOT:
+ case R_LARCH_SOP_PUSH_TLS_GD:
+ case R_LARCH_SOP_PUSH_PLT_PCREL:
+ case R_LARCH_SOP_ASSERT:
+ case R_LARCH_SOP_NOT:
+ case R_LARCH_SOP_SUB:
+ case R_LARCH_SOP_SL:
+ case R_LARCH_SOP_SR:
+ case R_LARCH_SOP_ADD:
+ case R_LARCH_SOP_AND:
+ case R_LARCH_SOP_IF_ELSE:
+ case R_LARCH_SOP_POP_32_S_10_5:
+ case R_LARCH_SOP_POP_32_U_10_12:
+ case R_LARCH_SOP_POP_32_S_10_12:
+ case R_LARCH_SOP_POP_32_S_10_16:
+ case R_LARCH_SOP_POP_32_S_10_16_S2:
+ case R_LARCH_SOP_POP_32_S_5_20:
+ case R_LARCH_SOP_POP_32_S_0_5_10_16_S2:
+ case R_LARCH_SOP_POP_32_S_0_10_10_16_S2:
+ case R_LARCH_SOP_POP_32_U:
+ case R_LARCH_ADD8:
+ case R_LARCH_ADD16:
+ case R_LARCH_ADD24:
+ case R_LARCH_ADD32:
+ case R_LARCH_ADD64:
+ case R_LARCH_SUB8:
+ case R_LARCH_SUB16:
+ case R_LARCH_SUB24:
+ case R_LARCH_SUB32:
+ case R_LARCH_SUB64:
+ case R_LARCH_GNU_VTINHERIT:
+ case R_LARCH_GNU_VTENTRY:
+ //
+ // These types are not used or do not require fixup in PE format
files.
+ //
+ break;
+ default:
+ Error (NULL, 0, 3000, "Invalid", "WriteRelocations64(): %s
unsupported ELF EM_LOONGARCH64 relocation 0x%x.", mInImageName,
(unsigned) ELF64_R_TYPE(Rel->r_info));
+ }
} else {
Error (NULL, 0, 3000, "Not Supported", "This tool does not support
relocations for ELF with e_machine %u (processor type).", (unsigned) mEhdr-
e_machine);
}
diff --git a/BaseTools/Source/C/GenFw/elf_common.h
b/BaseTools/Source/C/GenFw/elf_common.h
index b67f59e7a0..34c8748f39 100644
--- a/BaseTools/Source/C/GenFw/elf_common.h
+++ b/BaseTools/Source/C/GenFw/elf_common.h
@@ -4,6 +4,7 @@ Ported ELF include files from FreeBSD
Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
Portions Copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.<BR>
Portion Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All
rights reserved.<BR>
+Portions Copyright (c) 2022, Loongson Technology Corporation Limited. All
rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent


@@ -181,6 +182,7 @@ typedef struct {
#define EM_AARCH64 183 /* ARM 64bit Architecture */
#define EM_RISCV64 243 /* 64bit RISC-V Architecture */
#define EM_RISCV 244 /* 32bit RISC-V Architecture */
+#define EM_LOONGARCH64 258 /* LoongArch 64-bit Architecture */
Do you have 32-bit LOONGARCH that also requires a value in spec?

Abner

/* Non-standard or deprecated. */
#define EM_486 6 /* Intel i486. */
@@ -1042,4 +1044,60 @@ typedef struct {
#define R_RISCV_SET8 54
#define R_RISCV_SET16 55
#define R_RISCV_SET32 56
+
+/*
+ * LoongArch relocation types
+ */
+#define R_LARCH_NONE 0
+#define R_LARCH_32 1
+#define R_LARCH_64 2
+#define R_LARCH_RELATIVE 3
+#define R_LARCH_COPY 4
+#define R_LARCH_JUMP_SLOT 5
+#define R_LARCH_TLS_DTPMOD32 6
+#define R_LARCH_TLS_DTPMOD64 7
+#define R_LARCH_TLS_DTPREL32 8
+#define R_LARCH_TLS_DTPREL64 9
+#define R_LARCH_TLS_TPREL32 10
+#define R_LARCH_TLS_TPREL64 11
+#define R_LARCH_IRELATIVE 12
+#define R_LARCH_MARK_LA 20
+#define R_LARCH_MARK_PCREL 21
+#define R_LARCH_SOP_PUSH_PCREL 22
+#define R_LARCH_SOP_PUSH_ABSOLUTE 23
+#define R_LARCH_SOP_PUSH_DUP 24
+#define R_LARCH_SOP_PUSH_GPREL 25
+#define R_LARCH_SOP_PUSH_TLS_TPREL 26
+#define R_LARCH_SOP_PUSH_TLS_GOT 27
+#define R_LARCH_SOP_PUSH_TLS_GD 28
+#define R_LARCH_SOP_PUSH_PLT_PCREL 29
+#define R_LARCH_SOP_ASSERT 30
+#define R_LARCH_SOP_NOT 31
+#define R_LARCH_SOP_SUB 32
+#define R_LARCH_SOP_SL 33
+#define R_LARCH_SOP_SR 34
+#define R_LARCH_SOP_ADD 35
+#define R_LARCH_SOP_AND 36
+#define R_LARCH_SOP_IF_ELSE 37
+#define R_LARCH_SOP_POP_32_S_10_5 38
+#define R_LARCH_SOP_POP_32_U_10_12 39
+#define R_LARCH_SOP_POP_32_S_10_12 40
+#define R_LARCH_SOP_POP_32_S_10_16 41
+#define R_LARCH_SOP_POP_32_S_10_16_S2 42
+#define R_LARCH_SOP_POP_32_S_5_20 43
+#define R_LARCH_SOP_POP_32_S_0_5_10_16_S2 44
+#define R_LARCH_SOP_POP_32_S_0_10_10_16_S2 45
+#define R_LARCH_SOP_POP_32_U 46
+#define R_LARCH_ADD8 47
+#define R_LARCH_ADD16 48
+#define R_LARCH_ADD24 49
+#define R_LARCH_ADD32 50
+#define R_LARCH_ADD64 51
+#define R_LARCH_SUB8 52
+#define R_LARCH_SUB16 53
+#define R_LARCH_SUB24 54
+#define R_LARCH_SUB32 55
+#define R_LARCH_SUB64 56
+#define R_LARCH_GNU_VTINHERIT 57
+#define R_LARCH_GNU_VTENTRY 58
#endif /* !_SYS_ELF_COMMON_H_ */
diff --git a/BaseTools/Source/C/Include/IndustryStandard/PeImage.h
b/BaseTools/Source/C/Include/IndustryStandard/PeImage.h
index f17b8ee19b..80961e5576 100644
--- a/BaseTools/Source/C/Include/IndustryStandard/PeImage.h
+++ b/BaseTools/Source/C/Include/IndustryStandard/PeImage.h
@@ -7,6 +7,7 @@
Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
Portions copyright (c) 2011 - 2013, ARM Ltd. All rights reserved.<BR>
Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights
reserved.<BR>
+ Copyright (c) 2022, Loongson Technology Corporation Limited. All rights
reserved.<BR>

SPDX-License-Identifier: BSD-2-Clause-Patent

@@ -36,23 +37,25 @@
//
// PE32+ Machine type for EFI images
//
-#define IMAGE_FILE_MACHINE_I386 0x014c
-#define IMAGE_FILE_MACHINE_EBC 0x0EBC
-#define IMAGE_FILE_MACHINE_X64 0x8664
-#define IMAGE_FILE_MACHINE_ARM 0x01c0 // Thumb only
-#define IMAGE_FILE_MACHINE_ARMT 0x01c2 // 32bit Mixed ARM and
Thumb/Thumb 2 Little Endian
-#define IMAGE_FILE_MACHINE_ARM64 0xAA64 // 64bit ARM
Architecture, Little Endian
-#define IMAGE_FILE_MACHINE_RISCV64 0x5064 // 64bit RISC-V ISA
+#define IMAGE_FILE_MACHINE_I386 0x014c
+#define IMAGE_FILE_MACHINE_EBC 0x0EBC
+#define IMAGE_FILE_MACHINE_X64 0x8664
+#define IMAGE_FILE_MACHINE_ARM 0x01c0 // Thumb only
+#define IMAGE_FILE_MACHINE_ARMT 0x01c2 // 32bit Mixed ARM and
Thumb/Thumb 2 Little Endian
+#define IMAGE_FILE_MACHINE_ARM64 0xAA64 // 64bit ARM
Architecture, Little Endian
+#define IMAGE_FILE_MACHINE_RISCV64 0x5064 // 64bit RISC-V ISA
+#define IMAGE_FILE_MACHINE_LOONGARCH64 0x6264 // 64bit LoongArch
Architecture

//
// Support old names for backward compatible
//
-#define EFI_IMAGE_MACHINE_IA32 IMAGE_FILE_MACHINE_I386
-#define EFI_IMAGE_MACHINE_EBC IMAGE_FILE_MACHINE_EBC
-#define EFI_IMAGE_MACHINE_X64 IMAGE_FILE_MACHINE_X64
-#define EFI_IMAGE_MACHINE_ARMT IMAGE_FILE_MACHINE_ARMT
-#define EFI_IMAGE_MACHINE_AARCH64 IMAGE_FILE_MACHINE_ARM64
-#define EFI_IMAGE_MACHINE_RISCV64 IMAGE_FILE_MACHINE_RISCV64
+#define EFI_IMAGE_MACHINE_IA32 IMAGE_FILE_MACHINE_I386
+#define EFI_IMAGE_MACHINE_EBC IMAGE_FILE_MACHINE_EBC
+#define EFI_IMAGE_MACHINE_X64 IMAGE_FILE_MACHINE_X64
+#define EFI_IMAGE_MACHINE_ARMT IMAGE_FILE_MACHINE_ARMT
+#define EFI_IMAGE_MACHINE_AARCH64
IMAGE_FILE_MACHINE_ARM64
+#define EFI_IMAGE_MACHINE_RISCV64 IMAGE_FILE_MACHINE_RISCV64
+#define EFI_IMAGE_MACHINE_LOONGARCH64
IMAGE_FILE_MACHINE_LOONGARCH64

#define EFI_IMAGE_DOS_SIGNATURE 0x5A4D // MZ
#define EFI_IMAGE_OS2_SIGNATURE 0x454E // NE
@@ -500,19 +503,21 @@ typedef struct {
//
// Based relocation types.
//
-#define EFI_IMAGE_REL_BASED_ABSOLUTE 0
-#define EFI_IMAGE_REL_BASED_HIGH 1
-#define EFI_IMAGE_REL_BASED_LOW 2
-#define EFI_IMAGE_REL_BASED_HIGHLOW 3
-#define EFI_IMAGE_REL_BASED_HIGHADJ 4
-#define EFI_IMAGE_REL_BASED_MIPS_JMPADDR 5
-#define EFI_IMAGE_REL_BASED_ARM_MOV32A 5
-#define EFI_IMAGE_REL_BASED_RISCV_HI20 5
-#define EFI_IMAGE_REL_BASED_ARM_MOV32T 7
-#define EFI_IMAGE_REL_BASED_RISCV_LOW12I 7
-#define EFI_IMAGE_REL_BASED_RISCV_LOW12S 8
-#define EFI_IMAGE_REL_BASED_IA64_IMM64 9
-#define EFI_IMAGE_REL_BASED_DIR64 10
+#define EFI_IMAGE_REL_BASED_ABSOLUTE 0
+#define EFI_IMAGE_REL_BASED_HIGH 1
+#define EFI_IMAGE_REL_BASED_LOW 2
+#define EFI_IMAGE_REL_BASED_HIGHLOW 3
+#define EFI_IMAGE_REL_BASED_HIGHADJ 4
+#define EFI_IMAGE_REL_BASED_MIPS_JMPADDR 5
+#define EFI_IMAGE_REL_BASED_ARM_MOV32A 5
+#define EFI_IMAGE_REL_BASED_RISCV_HI20 5
+#define EFI_IMAGE_REL_BASED_ARM_MOV32T 7
+#define EFI_IMAGE_REL_BASED_RISCV_LOW12I 7
+#define EFI_IMAGE_REL_BASED_RISCV_LOW12S 8
+#define EFI_IMAGE_REL_BASED_LOONGARCH32_MARK_LA 8
+#define EFI_IMAGE_REL_BASED_LOONGARCH64_MARK_LA 8
+#define EFI_IMAGE_REL_BASED_IA64_IMM64 9
+#define EFI_IMAGE_REL_BASED_DIR64 10


///
--
2.27.0





Re: [PATCH v3] OvmfPkg/BhyveBhfPkg: add support for QemuFwCfg

Yao, Jiewen
 

Acked-by: Jiewen Yao <Jiewen.yao@...>

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Corvin
Köhne
Sent: Friday, April 8, 2022 1:53 PM
Cc: Corvin Köhne <CorvinK@...>; Köhne, Corvin
<c.koehne@...>; Ard Biesheuvel <ardb+tianocore@...>; Yao,
Jiewen <jiewen.yao@...>; Justen, Jordan L <jordan.l.justen@...>;
devel@edk2.groups.io; FreeBSD Virtualization <freebsd-
virtualization@...>; Gerd Hoffmann <kraxel@...>; Rebecca
Cran <rebecca@...>; Peter Grehan <grehan@...>
Subject: [edk2-devel] [PATCH v3] OvmfPkg/BhyveBhfPkg: add support for
QemuFwCfg

From: Corvin Köhne <CorvinK@...>

QemuFwCfg is much more powerful than BhyveFwCtl. Sadly, BhyveFwCtl
decided to use the same IO ports as QemuFwCfg. It's not possible to use
both interfaces simultaneously. So, prefer QemuFwCfg over BhyveFwCtl.

Signed-off-by: Corvin Köhne <c.koehne@...>
Acked-by: Gerd Hoffmann <kraxel@...>
Acked-by: Rebecca Cran <rebecca@...>
Acked-by: Peter Grehan <grehan@...>
CC: Ard Biesheuvel <ardb+tianocore@...>
CC: Jiewen Yao <jiewen.yao@...>
CC: Jordan Justen <jordan.l.justen@...>
CC: devel@edk2.groups.io
CC: FreeBSD Virtualization <freebsd-virtualization@...>
---
OvmfPkg/Bhyve/AcpiPlatformDxe/AcpiPlatformDxe.inf | 1 +
OvmfPkg/Bhyve/AcpiPlatformDxe/Bhyve.c | 41 ++++++++++++++++++++-
--
OvmfPkg/Bhyve/BhyveX64.dsc | 4 +--
3 files changed, 40 insertions(+), 6 deletions(-)

diff --git a/OvmfPkg/Bhyve/AcpiPlatformDxe/AcpiPlatformDxe.inf
b/OvmfPkg/Bhyve/AcpiPlatformDxe/AcpiPlatformDxe.inf
index 595fd055f9..94c65f32dc 100644
--- a/OvmfPkg/Bhyve/AcpiPlatformDxe/AcpiPlatformDxe.inf
+++ b/OvmfPkg/Bhyve/AcpiPlatformDxe/AcpiPlatformDxe.inf
@@ -43,6 +43,7 @@
MemoryAllocationLib
OrderedCollectionLib
PcdLib
+ QemuFwCfgLib
UefiBootServicesTableLib
UefiDriverEntryPoint
UefiLib
diff --git a/OvmfPkg/Bhyve/AcpiPlatformDxe/Bhyve.c
b/OvmfPkg/Bhyve/AcpiPlatformDxe/Bhyve.c
index 8e80aa33e1..e216a21bfa 100644
--- a/OvmfPkg/Bhyve/AcpiPlatformDxe/Bhyve.c
+++ b/OvmfPkg/Bhyve/AcpiPlatformDxe/Bhyve.c
@@ -11,6 +11,41 @@
#include <Library/BaseMemoryLib.h>
#include <Library/BhyveFwCtlLib.h>
#include <Library/MemoryAllocationLib.h>
+#include <Library/QemuFwCfgLib.h> // QemuFwCfgFindFile()
+
+STATIC
+EFI_STATUS
+EFIAPI
+BhyveGetCpuCount (
+ OUT UINT32 *CpuCount
+ )
+{
+ FIRMWARE_CONFIG_ITEM Item;
+ UINTN Size;
+
+ if (QemuFwCfgIsAvailable ()) {
+ if (EFI_ERROR (QemuFwCfgFindFile ("opt/bhyve/hw.ncpu", &Item, &Size))) {
+ return EFI_NOT_FOUND;
+ } else if (Size != sizeof (*CpuCount)) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ QemuFwCfgSelectItem (Item);
+ QemuFwCfgReadBytes (Size, CpuCount);
+
+ return EFI_SUCCESS;
+ }
+
+ //
+ // QemuFwCfg not available, try BhyveFwCtl.
+ //
+ Size = sizeof (*CpuCount);
+ if (BhyveFwCtlGet ("hw.ncpu", CpuCount, &Size) == RETURN_SUCCESS) {
+ return EFI_SUCCESS;
+ }
+
+ return EFI_UNSUPPORTED;
+}

STATIC
EFI_STATUS
@@ -23,7 +58,6 @@ BhyveInstallAcpiMadtTable (
)
{
UINT32 CpuCount;
- UINTN cSize;
UINTN NewBufferSize;
EFI_ACPI_1_0_MULTIPLE_APIC_DESCRIPTION_TABLE_HEADER *Madt;
EFI_ACPI_1_0_PROCESSOR_LOCAL_APIC_STRUCTURE *LocalApic;
@@ -36,9 +70,8 @@ BhyveInstallAcpiMadtTable (
ASSERT (AcpiTableBufferSize >= sizeof (EFI_ACPI_DESCRIPTION_HEADER));

// Query the host for the number of vCPUs
- CpuCount = 0;
- cSize = sizeof (CpuCount);
- if (BhyveFwCtlGet ("hw.ncpu", &CpuCount, &cSize) == RETURN_SUCCESS) {
+ Status = BhyveGetCpuCount (&CpuCount);
+ if (!EFI_ERROR (Status)) {
DEBUG ((DEBUG_INFO, "Retrieved CpuCount %d\n", CpuCount));
ASSERT (CpuCount >= 1);
} else {
diff --git a/OvmfPkg/Bhyve/BhyveX64.dsc b/OvmfPkg/Bhyve/BhyveX64.dsc
index 5fa08bebd7..14070fd6dd 100644
--- a/OvmfPkg/Bhyve/BhyveX64.dsc
+++ b/OvmfPkg/Bhyve/BhyveX64.dsc
@@ -163,8 +163,7 @@

SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/D
xeSecurityManagementLib.inf
UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf

SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLi
b.inf
- QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgLibNull.inf
-
QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/BaseQemuFwCfgS3LibNu
ll.inf
+ QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
BhyveFwCtlLib|OvmfPkg/Library/BhyveFwCtlLib/BhyveFwCtlLib.inf
VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf

MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptS
evLib.inf
@@ -355,6 +354,7 @@
!endif
PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf
MpInitLib|UefiCpuPkg/Library/MpInitLibUp/MpInitLibUp.inf
+
QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwC
fg.inf

[LibraryClasses.common.UEFI_APPLICATION]
PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
--
2.11.0

Beckhoff Automation GmbH & Co. KG | Managing Director: Dipl. Phys. Hans
Beckhoff
Registered office: Verl, Germany | Register court: Guetersloh HRA 7075







[PATCH] ShellPkg: Update smbiosview type 9 with SMBIOS 3.5 fields

Bo Chang Ke
 

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

update smbiosview type 9 related fileds.

Signed-off-by: Bo Chang Ke <bo-changx.ke@...>
Cc: Dandan Bi <dandan.bi@...>
Cc: Star Zeng <star.zeng@...>
---
MdePkg/Include/IndustryStandard/SmBios.h | 50 +++-
.../SmbiosView/PrintInfo.c | 11 +-
.../SmbiosView/QueryTable.c | 238 ++++++++++++++++++
.../SmbiosView/QueryTable.h | 36 +++
.../SmbiosView/SmbiosViewStrings.uni | 5 +-
5 files changed, 334 insertions(+), 6 deletions(-)

diff --git a/MdePkg/Include/IndustryStandard/SmBios.h b/MdePkg/Include/IndustryStandard/SmBios.h
index 2b1567b052..cb39470c92 100644
--- a/MdePkg/Include/IndustryStandard/SmBios.h
+++ b/MdePkg/Include/IndustryStandard/SmBios.h
@@ -1306,6 +1306,11 @@ typedef enum {
SlotTypePciExpressMini52pinWithBSKO = 0x21, ///< PCI Express Mini 52-pin (CEM spec. 2.0) with bottom-side keep-outs.
SlotTypePciExpressMini52pinWithoutBSKO = 0x22, ///< PCI Express Mini 52-pin (CEM spec. 2.0) without bottom-side keep-outs.
SlotTypePciExpressMini76pin = 0x23, ///< PCI Express Mini 76-pin (CEM spec. 2.0) Corresponds to Display-Mini card.
+ SlotTypePCIExpressGen4SFF_8639 = 0x24, ///< U.2
+ SlotTypePCIExpressGen5SFF_8639 = 0x25, ///< U.2
+ SlotTypeOCPNIC30SmallFormFactor = 0x26, ///< SFF
+ SlotTypeOCPNIC30LargeFormFactor = 0x27, ///< LFF
+ SlotTypeOCPNICPriorto30 = 0x28,
SlotTypeCXLFlexbus10 = 0x30,
SlotTypePC98C20 = 0xA0,
SlotTypePC98C24 = 0xA1,
@@ -1335,7 +1340,17 @@ typedef enum {
SlotTypePciExpressGen4X2 = 0xBA,
SlotTypePciExpressGen4X4 = 0xBB,
SlotTypePciExpressGen4X8 = 0xBC,
- SlotTypePciExpressGen4X16 = 0xBD
+ SlotTypePciExpressGen4X16 = 0xBD,
+ SlotTypePCIExpressGen5 = 0xBE,
+ SlotTypePCIExpressGen5X1 = 0xBF,
+ SlotTypePCIExpressGen5X2 = 0xC0,
+ SlotTypePCIExpressGen5X4 = 0xC1,
+ SlotTypePCIExpressGen5X8 = 0xC2,
+ SlotTypePCIExpressGen5X16 = 0xC3,
+ SlotTypePCIExpressGen6andBeyond = 0xC4,
+ SlotTypeEnterpriseandDatacenter1UE1FormFactorSlot = 0xC5,
+ SlotTypeEnterpriseandDatacenter3E3FormFactorSlot = 0xC6
+
} MISC_SLOT_TYPE;

///
@@ -1358,6 +1373,39 @@ typedef enum {
SlotDataBusWidth32X = 0x0E ///< Or X32
} MISC_SLOT_DATA_BUS_WIDTH;

+///
+/// System Slots - Slot Physical Width.
+///
+typedef enum {
+ SlotPhysicalWidthOther = 0x01,
+ SlotPhysicalWidthUnknown = 0x02,
+ SlotPhysicalWidth8Bit = 0x03,
+ SlotPhysicalWidth16Bit = 0x04,
+ SlotPhysicalWidth32Bit = 0x05,
+ SlotPhysicalWidth64Bit = 0x06,
+ SlotPhysicalWidth128Bit = 0x07,
+ SlotPhysicalWidth1X = 0x08, ///< Or X1
+ SlotPhysicalWidth2X = 0x09, ///< Or X2
+ SlotPhysicalWidth4X = 0x0A, ///< Or X4
+ SlotPhysicalWidth8X = 0x0B, ///< Or X8
+ SlotPhysicalWidth12X = 0x0C, ///< Or X12
+ SlotPhysicalWidth16X = 0x0D, ///< Or X16
+ SlotPhysicalWidth32X = 0x0E ///< Or X32
+} MISC_SLOT_PHYSICAL_WIDTH;
+
+///
+/// System Slots - Slot Information.
+///
+typedef enum{
+ others = 0x00,
+ Gen1 = 0x01,
+ Gen2 = 0x01,
+ Gen3 = 0x03,
+ Gen4 = 0x04,
+ Gen5 = 0x05,
+ Gen6 = 0x06
+}MISC_SLOT_INFORMATION;
+
///
/// System Slots - Current Usage.
///
diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
index b144600a25..0fa40dbe0c 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
@@ -637,6 +637,13 @@ SmbiosPrintStructure (
}
}
}
+ if (AE_SMBIOS_VERSION (0x3, 0x2)) {
+ if (Struct->Hdr->Length > 0x12) {
+ DisplaySystemSlotHeight(Struct->Type9->SlotHeight, Option);
+ DisplaySystemSlotPhysicalWidth(Struct->Type9->SlotPhysicalWidth, Option);
+ DisplaySystemSlotInformation(Struct->Type9->SlotInformation, Option);
+ }
+ }

break;
}
@@ -2898,10 +2905,6 @@ DisplaySystemSlotId (
IN UINT8 Option
)
{
- //
- // Display slot type first
- //
- DisplaySystemSlotType (SlotType, Option);

ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_SLOT_ID), gShellDebug1HiiHandle);
//
diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c
index c4a6acb167..96e0e4036a 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c
@@ -1447,6 +1447,27 @@ TABLE_ITEM SystemSlotTypeTable[] = {
0x23,
L"PCI Express Mini 76-pin (CEM spec. 2.0) Corresponds to Display-Mini card"
},
+ {
+ 0x24,
+ L"PCI Express Gen 4 SFF-8639 (U.2)"
+ },
+ {
+ 0x25,
+ L"PCI Express Gen 5 SFF-8639 (U.2)"
+ },
+ {
+ 0x26,
+ L"OCP NIC 3.0 Small Form Factor (SFF)"
+ },
+ {
+ 0x27,
+ L"OCP NIC 3.0 Large Form Factor (LFF)"
+ },
+ {
+ 0x28,
+ L"OCP NIC Prior to 3.0"
+ },
+
{
SlotTypeCXLFlexbus10,
L"CXL Flexbus 1.0"
@@ -1566,6 +1587,42 @@ TABLE_ITEM SystemSlotTypeTable[] = {
{
SlotTypePciExpressGen4X16,
L"PCI Express Gen 4 X16"
+ },
+ {
+ SlotTypePCIExpressGen5,
+ L"PCI Express Gen 5"
+ },
+ {
+ SlotTypePCIExpressGen5X1,
+ L"PCI Express Gen 5 x1"
+ },
+ {
+ SlotTypePCIExpressGen5X2,
+ L"PCI Express Gen 5 x2"
+ },
+ {
+ SlotTypePCIExpressGen5X4,
+ L"PCI Express Gen 5 x4"
+ },
+ {
+ SlotTypePCIExpressGen5X8,
+ L"PCI Express Gen 5 x8"
+ },
+ {
+ SlotTypePCIExpressGen5X16,
+ L"PCI Express Gen 5 x16"
+ },
+ {
+ SlotTypePCIExpressGen6andBeyond,
+ L"PCI Express Gen 6 and Beyond"
+ },
+ {
+ SlotTypeEnterpriseandDatacenter1UE1FormFactorSlot,
+ L"Enterprise and Datacenter 1U E1 Form Factor Slot"
+ },
+ {
+ SlotTypeEnterpriseandDatacenter3E3FormFactorSlot,
+ L"Enterprise and Datacenter 3'E3 Form Factor Slot"
}
};

@@ -1628,6 +1685,96 @@ TABLE_ITEM SystemSlotDataBusWidthTable[] = {
}
};

+TABLE_ITEM SystemSlotPhysicalWidthTable[] = {
+ {
+ 0x01,
+ L" Other"
+ },
+ {
+ 0x02,
+ L" Unknown"
+ },
+ {
+ 0x03,
+ L" 8 bit"
+ },
+ {
+ 0x04,
+ L" 16 bit"
+ },
+ {
+ 0x05,
+ L" 32 bit"
+ },
+ {
+ 0x06,
+ L" 64 bit"
+ },
+ {
+ 0x07,
+ L" 128 bit"
+ },
+ {
+ 0x08,
+ L" 1x or x1"
+ },
+ {
+ 0x09,
+ L" 2x or x2"
+ },
+ {
+ 0x0A,
+ L" 4x or x4"
+ },
+ {
+ 0x0B,
+ L" 8x or x8"
+ },
+ {
+ 0x0C,
+ L" 12x or x12"
+ },
+ {
+ 0x0D,
+ L" 16x or x16"
+ },
+ {
+ 0x0E,
+ L" 32x or x32"
+ }
+};
+
+TABLE_ITEM SystemSlotInformationTable[] = {
+ {
+ 0x00,
+ L" Others"
+ },
+ {
+ 0x01,
+ L" Gen 1"
+ },
+ {
+ 0x02,
+ L" Gen 2"
+ },
+ {
+ 0x03,
+ L" Gen 3"
+ },
+ {
+ 0x04,
+ L" Gen 4"
+ },
+ {
+ 0x05,
+ L" Gen 5"
+ },
+ {
+ 0x06,
+ L" Gen 6"
+ }
+};
+
TABLE_ITEM SystemSlotCurrentUsageTable[] = {
{
0x01,
@@ -1670,6 +1817,30 @@ TABLE_ITEM SystemSlotLengthTable[] = {
},
};

+TABLE_ITEM SystemSlotHeightTable[] = {
+ {
+ 0x00,
+ L" Not applicable"
+ },
+ {
+ 0x01,
+ L" Other"
+ },
+ {
+ 0x02,
+ L" Unkown"
+ },
+ {
+ 0x03,
+ L" Full height"
+ },
+ {
+ 0x04,
+ L" Low-Profile"
+ },
+
+};
+
TABLE_ITEM SlotCharacteristics1Table[] = {
{
0,
@@ -1722,6 +1893,22 @@ TABLE_ITEM SlotCharacteristics2Table[] = {
{
3,
L" PCIe slot supports bifurcation"
+ },
+ {
+ 4,
+ L" Slot supports async/surprise removal"
+ },
+ {
+ 5,
+ L" Flexbus slot, CXL 1.0 capable"
+ },
+ {
+ 6,
+ L" Flexbus slot, CXL 2.0 capable"
+ },
+ {
+ 7,
+ L" Reserved"
}
};

@@ -4208,6 +4395,57 @@ DisplaySlotCharacteristics2 (
PRINT_BITS_INFO (SlotCharacteristics2Table, Chara2);
}

+/**
+ Display System Slots (Type 9) Information.
+
+ @param[in] Width The key of the structure.
+ @param[in] Option The optional information.
+**/
+VOID
+DisplaySystemSlotInformation (
+ IN UINT8 Width,
+ IN UINT8 Option
+ )
+{
+ ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_INFORMATION), gShellDebug1HiiHandle);
+ PRINT_INFO_OPTION (Width, Option);
+ PRINT_TABLE_ITEM (SystemSlotInformationTable, Width);
+}
+
+/**
+ Display System Slots (Type 9) Physical Width.
+
+ @param[in] Width The key of the structure.
+ @param[in] Option The optional information.
+**/
+VOID
+DisplaySystemSlotPhysicalWidth (
+ IN UINT8 Width,
+ IN UINT8 Option
+ )
+{
+ ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_PHYSICAL_WIDTH), gShellDebug1HiiHandle);
+ PRINT_INFO_OPTION (Width, Option);
+ PRINT_TABLE_ITEM (SystemSlotPhysicalWidthTable, Width);
+}
+
+/**
+ Display System Slots (Type 9) slot height.
+
+ @param[in] Length The key of the structure.
+ @param[in] Option The optional information.
+**/
+VOID
+DisplaySystemSlotHeight (
+ IN UINT8 Length,
+ IN UINT8 Option
+ )
+{
+ ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_HEIGHT), gShellDebug1HiiHandle);
+ PRINT_INFO_OPTION (Length, Option);
+ PRINT_TABLE_ITEM (SystemSlotHeightTable, Length);
+}
+
/**
Display On Board Devices Information (Type 10) types.

diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.h b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.h
index 5111d35f63..5f062762b3 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.h
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.h
@@ -415,6 +415,42 @@ DisplaySlotCharacteristics2 (
IN UINT8 Option
);

+/**
+ Display System Slots (Type 9) Information.
+
+ @param[in] Width The key of the structure.
+ @param[in] Option The optional information.
+**/
+VOID
+DisplaySystemSlotInformation (
+ IN UINT8 Width,
+ IN UINT8 Option
+ );
+
+/**
+ Display System Slots (Type 9) Physical Width.
+
+ @param[in] Width The key of the structure.
+ @param[in] Option The optional information.
+**/
+VOID
+DisplaySystemSlotPhysicalWidth (
+ IN UINT8 Width,
+ IN UINT8 Option
+ );
+
+/**
+ Display System Slots (Type 9) slot height.
+
+ @param[in] Length The key of the structure.
+ @param[in] Option The optional information.
+**/
+VOID
+DisplaySystemSlotHeight (
+ IN UINT8 Length,
+ IN UINT8 Option
+ );
+
/**
Display On Board Devices Information (Type 10) types.

diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
index 9433e8a25f..a8728d6abc 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
@@ -294,7 +294,7 @@
#string STR_SMBIOSVIEW_PRINTINFO_MEM_SIZE #language en-US " Memory Size: %d MB\r\n"
#string STR_SMBIOSVIEW_PRINTINFO_MEM_MODULE_DOUBLE_BANK #language en-US "The memory module has a Double-bank connection\r\n"
#string STR_SMBIOSVIEW_PRINTINFO_MEM_MODULE_SINGLE_BANK #language en-US "The memory module has a Single-bank connection\r\n"
-#string STR_SMBIOSVIEW_PRINTINFO_SLOT_ID #language en-US " Slot Id:"
+#string STR_SMBIOSVIEW_PRINTINFO_SLOT_ID #language en-US "Slot Id:"
#string STR_SMBIOSVIEW_PRINTINFO_LOGICAL_MICRO_CHAN #language en-US " the logical Micro Channel slot number is:"
#string STR_SMBIOSVIEW_PRINTINFO_ONE_VAR_D #language en-US " %d\r\n"
#string STR_SMBIOSVIEW_PRINTINFO_ERROR_NOT_1_15 #language en-US " error, not 1-15.\r\n"
@@ -412,6 +412,9 @@
#string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_LENGTH #language en-US "System Slot Length: "
#string STR_SMBIOSVIEW_QUERYTABLE_SLOT_CHARACTERISTICS #language en-US "Slot characteristics 1: "
#string STR_SMBIOSVIEW_QUERYTABLE_SLOT_CHARACTERISTICS_2 #language en-US "Slot characteristics 2: "
+#string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_INFORMATION #language en-US "System Slot Information: "
+#string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_HEIGHT #language en-US "System Slot Height: "
+#string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_SLOT_PHYSICAL_WIDTH #language en-US "System Slot Physical Width: "
#string STR_SMBIOSVIEW_QUERYTABLE_ONBOARD_DEVICE_TYPE #language en-US "Onboard Device Type: "
#string STR_SMBIOSVIEW_QUERYTABLE_SYSTEM_EVENT_LOG_TYPE #language en-US "System Event Log Type: "
#string STR_SMBIOSVIEW_QUERYTABLE_EVENT_LOG_VAR_DATA_FORMAT #language en-US "Event Log Variable Data Format Types: "
--
2.32.0.windows.1


Re: [PATCH v2] OvmfPkg/BhyveBhfPkg: add support for QemuFwCfg

Corvin Köhne <c.koehne@...>
 

Hi Rebecca and Peter,

thank you very much for your feedback.


Best regards
Corvin

Beckhoff Automation GmbH & Co. KG | Managing Director: Dipl. Phys. Hans Beckhoff
Registered office: Verl, Germany | Register court: Guetersloh HRA 7075

8041 - 8060 of 96543