From e21bfae345f9eee1c3f585013ca50ad6ab4f86a1 Mon Sep 17 00:00:00 2001 From: Wenxing Hou Date: Thu, 20 Jun 2024 09:33:10 +0800 Subject: [PATCH 01/67] ReadMe.rst: Add mbedtls submodule license This patch add mbedtls submodule license. Cc: Andrew Fish Cc: Leif Lindholm Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Wenxing Hou --- ReadMe.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/ReadMe.rst b/ReadMe.rst index cfd522fdbd96..3fbabe1a1b92 100644 --- a/ReadMe.rst +++ b/ReadMe.rst @@ -91,6 +91,7 @@ that are covered by additional licenses. - `ArmPkg/Library/ArmSoftFloatLib/berkeley-softfloat-3 `__ - `BaseTools/Source/C/BrotliCompress/brotli `__ - `CryptoPkg/Library/OpensslLib/openssl `__ +- `CryptoPkg/Library/MbedTlsLib/mbedtls `__ - `MdeModulePkg/Library/BrotliCustomDecompressLib/brotli `__ - `MdeModulePkg/Universal/RegularExpressionDxe/oniguruma `__ - `UnitTestFrameworkPkg/Library/CmockaLib/cmocka `__ From ce4c76e46d52e24551f4986bded4c9b764502200 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Tue, 23 Jan 2024 15:33:51 +0100 Subject: [PATCH 02/67] OvmfPkg/Sec: Setup MTRR early in the boot process. Specifically before running lzma uncompress of the main firmware volume. This is needed to make sure caching is enabled, otherwise the uncompress can be extremely slow. Adapt the ASSERTs and MTRR setup in PlatformInitLib to the changes. Background: Depending on virtual machine configuration kvm may uses EPT memory types to apply guest MTRR settings. In case MTRRs are disabled kvm will use the uncachable memory type for all mappings. The vmx_get_mt_mask() function in the linux kernel handles this and can be found here: https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/arch/x86/kvm/vmx/vmx.c?h=v6.7.1#n7580 In most VM configurations kvm uses MTRR_TYPE_WRBACK unconditionally. In case the VM has a mdev device assigned that is not the case though. Before commit e8aa4c6546ad ("UefiCpuPkg/ResetVector: Cache Disable should not be set by default in CR0") kvm also ended up using MTRR_TYPE_WRBACK due to KVM_X86_QUIRK_CD_NW_CLEARED. After that commit kvm evaluates guest mtrr settings, which why setting up MTRRs early is important now. Signed-off-by: Gerd Hoffmann --- OvmfPkg/Bhyve/PlatformPei/MemDetect.c | 10 +++---- OvmfPkg/IntelTdx/Sec/SecMain.c | 32 +++++++++++++++++++++ OvmfPkg/Library/PlatformInitLib/MemDetect.c | 10 +++---- OvmfPkg/Sec/SecMain.c | 32 +++++++++++++++++++++ 4 files changed, 74 insertions(+), 10 deletions(-) diff --git a/OvmfPkg/Bhyve/PlatformPei/MemDetect.c b/OvmfPkg/Bhyve/PlatformPei/MemDetect.c index 29cbb9e3dcc8..351862942d3e 100644 --- a/OvmfPkg/Bhyve/PlatformPei/MemDetect.c +++ b/OvmfPkg/Bhyve/PlatformPei/MemDetect.c @@ -511,18 +511,18 @@ QemuInitializeRam ( MtrrGetAllMtrrs (&MtrrSettings); // - // MTRRs disabled, fixed MTRRs disabled, default type is uncached + // See SecMtrrSetup(), default type should be write back // - ASSERT ((MtrrSettings.MtrrDefType & BIT11) == 0); + ASSERT ((MtrrSettings.MtrrDefType & BIT11) != 0); ASSERT ((MtrrSettings.MtrrDefType & BIT10) == 0); - ASSERT ((MtrrSettings.MtrrDefType & 0xFF) == 0); + ASSERT ((MtrrSettings.MtrrDefType & 0xFF) == MTRR_CACHE_WRITE_BACK); // // flip default type to writeback // - SetMem (&MtrrSettings.Fixed, sizeof MtrrSettings.Fixed, 0x06); + SetMem (&MtrrSettings.Fixed, sizeof MtrrSettings.Fixed, MTRR_CACHE_WRITE_BACK); ZeroMem (&MtrrSettings.Variables, sizeof MtrrSettings.Variables); - MtrrSettings.MtrrDefType |= BIT11 | BIT10 | 6; + MtrrSettings.MtrrDefType |= BIT10; MtrrSetAllMtrrs (&MtrrSettings); // diff --git a/OvmfPkg/IntelTdx/Sec/SecMain.c b/OvmfPkg/IntelTdx/Sec/SecMain.c index 4e750755bf7f..6eeae09e3b57 100644 --- a/OvmfPkg/IntelTdx/Sec/SecMain.c +++ b/OvmfPkg/IntelTdx/Sec/SecMain.c @@ -26,6 +26,8 @@ #include #include #include +#include +#include #define SEC_IDT_ENTRY_COUNT 34 @@ -47,6 +49,31 @@ IA32_IDT_GATE_DESCRIPTOR mIdtEntryTemplate = { } }; +// +// Enable MTRR early, set default type to write back. +// Needed to make sure caching is enabled, +// without this lzma decompress can be very slow. +// +STATIC +VOID +SecMtrrSetup ( + VOID + ) +{ + CPUID_VERSION_INFO_EDX Edx; + MSR_IA32_MTRR_DEF_TYPE_REGISTER DefType; + + AsmCpuid (CPUID_VERSION_INFO, NULL, NULL, NULL, &Edx.Uint32); + if (!Edx.Bits.MTRR) { + return; + } + + DefType.Uint64 = AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE); + DefType.Bits.Type = 6; /* write back */ + DefType.Bits.E = 1; /* enable */ + AsmWriteMsr64 (MSR_IA32_MTRR_DEF_TYPE, DefType.Uint64); +} + VOID EFIAPI SecCoreStartupWithStack ( @@ -203,6 +230,11 @@ SecCoreStartupWithStack ( InitializeApicTimer (0, MAX_UINT32, TRUE, 5); DisableApicTimerInterrupt (); + // + // Initialize MTRR + // + SecMtrrSetup (); + PeilessStartup (&SecCoreData); ASSERT (FALSE); diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c index 2b6404cc5194..bd6c79e4e4e4 100644 --- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c +++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c @@ -1175,18 +1175,18 @@ PlatformQemuInitializeRam ( MtrrGetAllMtrrs (&MtrrSettings); // - // MTRRs disabled, fixed MTRRs disabled, default type is uncached + // See SecMtrrSetup(), default type should be write back // - ASSERT ((MtrrSettings.MtrrDefType & BIT11) == 0); + ASSERT ((MtrrSettings.MtrrDefType & BIT11) != 0); ASSERT ((MtrrSettings.MtrrDefType & BIT10) == 0); - ASSERT ((MtrrSettings.MtrrDefType & 0xFF) == 0); + ASSERT ((MtrrSettings.MtrrDefType & 0xFF) == MTRR_CACHE_WRITE_BACK); // // flip default type to writeback // - SetMem (&MtrrSettings.Fixed, sizeof MtrrSettings.Fixed, 0x06); + SetMem (&MtrrSettings.Fixed, sizeof MtrrSettings.Fixed, MTRR_CACHE_WRITE_BACK); ZeroMem (&MtrrSettings.Variables, sizeof MtrrSettings.Variables); - MtrrSettings.MtrrDefType |= BIT11 | BIT10 | 6; + MtrrSettings.MtrrDefType |= BIT10; MtrrSetAllMtrrs (&MtrrSettings); // diff --git a/OvmfPkg/Sec/SecMain.c b/OvmfPkg/Sec/SecMain.c index 60dfa6184269..b0bb7b295dd0 100644 --- a/OvmfPkg/Sec/SecMain.c +++ b/OvmfPkg/Sec/SecMain.c @@ -29,6 +29,8 @@ #include #include #include +#include +#include #include "AmdSev.h" #define SEC_IDT_ENTRY_COUNT 34 @@ -743,6 +745,31 @@ FindAndReportEntryPoints ( return; } +// +// Enable MTRR early, set default type to write back. +// Needed to make sure caching is enabled, +// without this lzma decompress can be very slow. +// +STATIC +VOID +SecMtrrSetup ( + VOID + ) +{ + CPUID_VERSION_INFO_EDX Edx; + MSR_IA32_MTRR_DEF_TYPE_REGISTER DefType; + + AsmCpuid (CPUID_VERSION_INFO, NULL, NULL, NULL, &Edx.Uint32); + if (!Edx.Bits.MTRR) { + return; + } + + DefType.Uint64 = AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE); + DefType.Bits.Type = 6; /* write back */ + DefType.Bits.E = 1; /* enable */ + AsmWriteMsr64 (MSR_IA32_MTRR_DEF_TYPE, DefType.Uint64); +} + VOID EFIAPI SecCoreStartupWithStack ( @@ -942,6 +969,11 @@ SecCoreStartupWithStack ( InitializeApicTimer (0, MAX_UINT32, TRUE, 5); DisableApicTimerInterrupt (); + // + // Initialize MTRR + // + SecMtrrSetup (); + // // Initialize Debug Agent to support source level debug in SEC/PEI phases before memory ready. // From 5bef25dca4119ae9bd537480d703575ad166723a Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Thu, 25 Jan 2024 08:36:57 +0100 Subject: [PATCH 03/67] MdePkg/ArchitecturalMsr.h: add #defines for MTRR cache types Signed-off-by: Gerd Hoffmann --- MdePkg/Include/Register/Intel/ArchitecturalMsr.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/MdePkg/Include/Register/Intel/ArchitecturalMsr.h b/MdePkg/Include/Register/Intel/ArchitecturalMsr.h index 4715c59dc48d..faabf0c4331b 100644 --- a/MdePkg/Include/Register/Intel/ArchitecturalMsr.h +++ b/MdePkg/Include/Register/Intel/ArchitecturalMsr.h @@ -2103,6 +2103,13 @@ typedef union { #define MSR_IA32_MTRR_PHYSBASE9 0x00000212 /// @} +#define MSR_IA32_MTRR_CACHE_UNCACHEABLE 0 +#define MSR_IA32_MTRR_CACHE_WRITE_COMBINING 1 +#define MSR_IA32_MTRR_CACHE_WRITE_THROUGH 4 +#define MSR_IA32_MTRR_CACHE_WRITE_PROTECTED 5 +#define MSR_IA32_MTRR_CACHE_WRITE_BACK 6 +#define MSR_IA32_MTRR_CACHE_INVALID_TYPE 7 + /** MSR information returned for MSR indexes #MSR_IA32_MTRR_PHYSBASE0 to #MSR_IA32_MTRR_PHYSBASE9 From 71e6cc8dad2de85512de2fdd6439ae2ebada295d Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Thu, 25 Jan 2024 08:38:00 +0100 Subject: [PATCH 04/67] UefiCpuPkg/MtrrLib.h: use cache type #defines from ArchitecturalMsr.h Signed-off-by: Gerd Hoffmann --- UefiCpuPkg/Include/Library/MtrrLib.h | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/UefiCpuPkg/Include/Library/MtrrLib.h b/UefiCpuPkg/Include/Library/MtrrLib.h index 86cc1aab3b8e..9d715d50dfb0 100644 --- a/UefiCpuPkg/Include/Library/MtrrLib.h +++ b/UefiCpuPkg/Include/Library/MtrrLib.h @@ -9,6 +9,8 @@ #ifndef _MTRR_LIB_H_ #define _MTRR_LIB_H_ +#include + // // According to IA32 SDM, MTRRs number and MSR offset are always consistent // for IA32 processor family @@ -82,20 +84,20 @@ typedef struct _MTRR_SETTINGS_ { // Memory cache types // typedef enum { - CacheUncacheable = 0, - CacheWriteCombining = 1, - CacheWriteThrough = 4, - CacheWriteProtected = 5, - CacheWriteBack = 6, - CacheInvalid = 7 + CacheUncacheable = MSR_IA32_MTRR_CACHE_UNCACHEABLE, + CacheWriteCombining = MSR_IA32_MTRR_CACHE_WRITE_COMBINING, + CacheWriteThrough = MSR_IA32_MTRR_CACHE_WRITE_THROUGH, + CacheWriteProtected = MSR_IA32_MTRR_CACHE_WRITE_PROTECTED, + CacheWriteBack = MSR_IA32_MTRR_CACHE_WRITE_BACK, + CacheInvalid = MSR_IA32_MTRR_CACHE_INVALID_TYPE, } MTRR_MEMORY_CACHE_TYPE; -#define MTRR_CACHE_UNCACHEABLE 0 -#define MTRR_CACHE_WRITE_COMBINING 1 -#define MTRR_CACHE_WRITE_THROUGH 4 -#define MTRR_CACHE_WRITE_PROTECTED 5 -#define MTRR_CACHE_WRITE_BACK 6 -#define MTRR_CACHE_INVALID_TYPE 7 +#define MTRR_CACHE_UNCACHEABLE MSR_IA32_MTRR_CACHE_UNCACHEABLE +#define MTRR_CACHE_WRITE_COMBINING MSR_IA32_MTRR_CACHE_WRITE_COMBINING +#define MTRR_CACHE_WRITE_THROUGH MSR_IA32_MTRR_CACHE_WRITE_THROUGH +#define MTRR_CACHE_WRITE_PROTECTED MSR_IA32_MTRR_CACHE_WRITE_PROTECTED +#define MTRR_CACHE_WRITE_BACK MSR_IA32_MTRR_CACHE_WRITE_BACK +#define MTRR_CACHE_INVALID_TYPE MSR_IA32_MTRR_CACHE_INVALID_TYPE typedef struct { UINT64 BaseAddress; From 78bccfec9ce5082499db035270e7998d5330d75c Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Thu, 25 Jan 2024 08:39:18 +0100 Subject: [PATCH 05/67] OvmfPkg/Sec: use cache type #defines from ArchitecturalMsr.h Signed-off-by: Gerd Hoffmann --- OvmfPkg/IntelTdx/Sec/SecMain.c | 2 +- OvmfPkg/Sec/SecMain.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OvmfPkg/IntelTdx/Sec/SecMain.c b/OvmfPkg/IntelTdx/Sec/SecMain.c index 6eeae09e3b57..95a31af02988 100644 --- a/OvmfPkg/IntelTdx/Sec/SecMain.c +++ b/OvmfPkg/IntelTdx/Sec/SecMain.c @@ -69,7 +69,7 @@ SecMtrrSetup ( } DefType.Uint64 = AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE); - DefType.Bits.Type = 6; /* write back */ + DefType.Bits.Type = MSR_IA32_MTRR_CACHE_WRITE_BACK; DefType.Bits.E = 1; /* enable */ AsmWriteMsr64 (MSR_IA32_MTRR_DEF_TYPE, DefType.Uint64); } diff --git a/OvmfPkg/Sec/SecMain.c b/OvmfPkg/Sec/SecMain.c index b0bb7b295dd0..c1c08a947aa4 100644 --- a/OvmfPkg/Sec/SecMain.c +++ b/OvmfPkg/Sec/SecMain.c @@ -765,7 +765,7 @@ SecMtrrSetup ( } DefType.Uint64 = AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE); - DefType.Bits.Type = 6; /* write back */ + DefType.Bits.Type = MSR_IA32_MTRR_CACHE_WRITE_BACK; DefType.Bits.E = 1; /* enable */ AsmWriteMsr64 (MSR_IA32_MTRR_DEF_TYPE, DefType.Uint64); } From dc002d4f2d76bdd826359a3dd608d9bc621fcb47 Mon Sep 17 00:00:00 2001 From: Wenxing Hou Date: Thu, 20 Jun 2024 10:44:10 +0800 Subject: [PATCH 06/67] CryptoPkg: Fix wrong comment for CryptoPkg Fix the wrong comment. Cc: Jiewen Yao Cc: Yi Li Signed-off-by: Wenxing Hou --- CryptoPkg/Include/Library/BaseCryptLib.h | 18 +++++++++--------- CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c | 18 +++++++++--------- .../BaseCryptLibMbedTls/InternalCryptLib.h | 4 ++-- .../Pk/CryptPkcs7VerifyEku.c | 1 - .../Library/BaseCryptLibMbedTls/Pk/CryptX509.c | 18 +++++++++--------- .../BaseCryptLibMbedTls/Pk/CryptX509Null.c | 18 +++++++++--------- .../BaseCryptLibMbedTls/Rand/CryptRand.c | 2 +- .../BaseCryptLibMbedTls/Rand/CryptRandTsc.c | 2 +- 8 files changed, 40 insertions(+), 41 deletions(-) diff --git a/CryptoPkg/Include/Library/BaseCryptLib.h b/CryptoPkg/Include/Library/BaseCryptLib.h index ac5841f1d9d6..95e4142f52a4 100644 --- a/CryptoPkg/Include/Library/BaseCryptLib.h +++ b/CryptoPkg/Include/Library/BaseCryptLib.h @@ -2843,7 +2843,7 @@ X509GetKeyUsage ( @param[in] Cert Pointer to the DER-encoded X509 certificate. @param[in] CertSize Size of the X509 certificate in bytes. @param[out] Usage Key Usage bytes. - @param[in, out] UsageSize Key Usage buffer sizs in bytes. + @param[in, out] UsageSize Key Usage buffer size in bytes. @retval TRUE The Usage bytes retrieve successfully. @retval FALSE If Cert is NULL. @@ -2870,12 +2870,12 @@ X509GetExtendedKeyUsage ( @param[in] RootCertLength Trusted Root Certificate buffer length @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates where the first certificate is signed by the Root - Certificate or is the Root Cerificate itself. and - subsequent cerificate is signed by the preceding - cerificate. + Certificate or is the Root Certificate itself. and + subsequent certificate is signed by the preceding + certificate. @param[in] CertChainLength Total length of the certificate chain, in bytes. - @retval TRUE All cerificates was issued by the first certificate in X509Certchain. + @retval TRUE All certificates was issued by the first certificate in X509Certchain. @retval FALSE Invalid certificate or the certificate was not issued by the given trusted CA. **/ @@ -2893,9 +2893,9 @@ X509VerifyCertChain ( @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates where the first certificate is signed by the Root - Certificate or is the Root Cerificate itself. and - subsequent cerificate is signed by the preceding - cerificate. + Certificate or is the Root Certificate itself. and + subsequent certificate is signed by the preceding + certificate. @param[in] CertChainLength Total length of the certificate chain, in bytes. @param[in] CertIndex Index of certificate. If index is -1 indecate the @@ -2943,7 +2943,7 @@ Asn1GetTag ( @param[in] Cert Pointer to the DER-encoded X509 certificate. @param[in] CertSize size of the X509 certificate in bytes. @param[out] BasicConstraints basic constraints bytes. - @param[in, out] BasicConstraintsSize basic constraints buffer sizs in bytes. + @param[in, out] BasicConstraintsSize basic constraints buffer size in bytes. @retval TRUE The basic constraints retrieve successfully. @retval FALSE If cert is NULL. diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c index 021cc328f889..349d37b045fb 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptX509.c @@ -1391,7 +1391,7 @@ X509GetExtensionData ( @param[in] Cert Pointer to the DER-encoded X509 certificate. @param[in] CertSize Size of the X509 certificate in bytes. @param[out] Usage Key Usage bytes. - @param[in, out] UsageSize Key Usage buffer sizs in bytes. + @param[in, out] UsageSize Key Usage buffer size in bytes. @retval TRUE The Usage bytes retrieve successfully. @retval FALSE If Cert is NULL. @@ -1692,12 +1692,12 @@ X509GetKeyUsage ( @param[in] RootCertLength Trusted Root Certificate buffer length @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates where the first certificate is signed by the Root - Certificate or is the Root Cerificate itself. and - subsequent cerificate is signed by the preceding - cerificate. + Certificate or is the Root Certificate itself. and + subsequent certificate is signed by the preceding + certificate. @param[in] CertChainLength Total length of the certificate chain, in bytes. - @retval TRUE All cerificates was issued by the first certificate in X509Certchain. + @retval TRUE All certificates was issued by the first certificate in X509Certchain. @retval FALSE Invalid certificate or the certificate was not issued by the given trusted CA. **/ @@ -1775,9 +1775,9 @@ X509VerifyCertChain ( @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates where the first certificate is signed by the Root - Certificate or is the Root Cerificate itself. and - subsequent cerificate is signed by the preceding - cerificate. + Certificate or is the Root Certificate itself. and + subsequent certificate is signed by the preceding + certificate. @param[in] CertChainLength Total length of the certificate chain, in bytes. @param[in] CertIndex Index of certificate. @@ -1922,7 +1922,7 @@ Asn1GetTag ( @param[in] Cert Pointer to the DER-encoded X509 certificate. @param[in] CertSize size of the X509 certificate in bytes. @param[out] BasicConstraints basic constraints bytes. - @param[in, out] BasicConstraintsSize basic constraints buffer sizs in bytes. + @param[in, out] BasicConstraintsSize basic constraints buffer size in bytes. @retval TRUE The basic constraints retrieve successfully. @retval FALSE If cert is NULL. diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/InternalCryptLib.h b/CryptoPkg/Library/BaseCryptLibMbedTls/InternalCryptLib.h index c9f19dd0cdf4..d3fa5ffc894a 100644 --- a/CryptoPkg/Library/BaseCryptLibMbedTls/InternalCryptLib.h +++ b/CryptoPkg/Library/BaseCryptLibMbedTls/InternalCryptLib.h @@ -17,7 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include // -// We should alwasy add mbedtls/config.h here +// We should always add mbedtls/config.h here // to ensure the config override takes effect. // #include @@ -25,7 +25,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /** The MbedTLS function f_rng, which MbedtlsRand implements. - @param[in] RngState Not used, just for compatibility with mbedlts. + @param[in] RngState Not used, just for compatibility with mbedtls. @param[out] Output Pointer to buffer to receive random value. @param[in] Len Size of random bytes to generate. diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptPkcs7VerifyEku.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptPkcs7VerifyEku.c index 47a8230cf602..55110062c475 100644 --- a/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptPkcs7VerifyEku.c +++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptPkcs7VerifyEku.c @@ -288,7 +288,6 @@ IsEkuInCertificate ( } Status = EFI_NOT_FOUND; - /*find the spdm hardware identity OID*/ for (Index = 0; Index <= Len - EkuLen; Index++) { if (!CompareMem (Buffer + Index, EKU, EkuLen)) { // check sub EKU diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptX509.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptX509.c index 84b67c8f0a5b..f0727135ada2 100644 --- a/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptX509.c +++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptX509.c @@ -744,12 +744,12 @@ X509VerifyCert ( @param[in] RootCertLength Trusted Root Certificate buffer length @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates where the first certificate is signed by the Root - Certificate or is the Root Cerificate itself. and - subsequent cerificate is signed by the preceding - cerificate. + Certificate or is the Root Certificate itself. and + subsequent certificate is signed by the preceding + certificate. @param[in] CertChainLength Total length of the certificate chain, in bytes. - @retval TRUE All cerificates was issued by the first certificate in X509Certchain. + @retval TRUE All certificates was issued by the first certificate in X509Certchain. @retval FALSE Invalid certificate or the certificate was not issued by the given trusted CA. **/ @@ -816,9 +816,9 @@ X509VerifyCertChain ( @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates where the first certificate is signed by the Root - Certificate or is the Root Cerificate itself. and - subsequent cerificate is signed by the preceding - cerificate. + Certificate or is the Root Certificate itself. and + subsequent certificate is signed by the preceding + certificate. @param[in] CertChainLength Total length of the certificate chain, in bytes. @param[in] CertIndex Index of certificate. @@ -1592,7 +1592,7 @@ X509GetKeyUsage ( @param[in] Cert Pointer to the DER-encoded X509 certificate. @param[in] CertSize Size of the X509 certificate in bytes. @param[out] Usage Key Usage bytes. - @param[in, out] UsageSize Key Usage buffer sizs in bytes. + @param[in, out] UsageSize Key Usage buffer size in bytes. @retval TRUE The Usage bytes retrieve successfully. @retval FALSE If Cert is NULL. @@ -1841,7 +1841,7 @@ X509CompareDateTime ( @param[in] Cert Pointer to the DER-encoded X509 certificate. @param[in] CertSize size of the X509 certificate in bytes. @param[out] BasicConstraints basic constraints bytes. - @param[in, out] BasicConstraintsSize basic constraints buffer sizs in bytes. + @param[in, out] BasicConstraintsSize basic constraints buffer size in bytes. @retval TRUE The basic constraints retrieve successfully. @retval FALSE If cert is NULL. diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptX509Null.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptX509Null.c index 96356f87fd68..b927a6a75520 100644 --- a/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptX509Null.c +++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Pk/CryptX509Null.c @@ -489,7 +489,7 @@ X509GetExtensionData ( @param[in] Cert Pointer to the DER-encoded X509 certificate. @param[in] CertSize Size of the X509 certificate in bytes. @param[out] Usage Key Usage bytes. - @param[in, out] UsageSize Key Usage buffer sizs in bytes. + @param[in, out] UsageSize Key Usage buffer size in bytes. @retval TRUE The Usage bytes retrieve successfully. @retval FALSE If Cert is NULL. @@ -641,12 +641,12 @@ X509GetKeyUsage ( @param[in] RootCertLength Trusted Root Certificate buffer length @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates where the first certificate is signed by the Root - Certificate or is the Root Cerificate itself. and - subsequent cerificate is signed by the preceding - cerificate. + Certificate or is the Root Certificate itself. and + subsequent certificate is signed by the preceding + certificate. @param[in] CertChainLength Total length of the certificate chain, in bytes. - @retval TRUE All cerificates was issued by the first certificate in X509Certchain. + @retval TRUE All certificates was issued by the first certificate in X509Certchain. @retval FALSE Invalid certificate or the certificate was not issued by the given trusted CA. **/ @@ -668,9 +668,9 @@ X509VerifyCertChain ( @param[in] CertChain One or more ASN.1 DER-encoded X.509 certificates where the first certificate is signed by the Root - Certificate or is the Root Cerificate itself. and - subsequent cerificate is signed by the preceding - cerificate. + Certificate or is the Root Certificate itself. and + subsequent certificate is signed by the preceding + certificate. @param[in] CertChainLength Total length of the certificate chain, in bytes. @param[in] CertIndex Index of certificate. @@ -725,7 +725,7 @@ Asn1GetTag ( @param[in] Cert Pointer to the DER-encoded X509 certificate. @param[in] CertSize size of the X509 certificate in bytes. @param[out] BasicConstraints basic constraints bytes. - @param[in, out] BasicConstraintsSize basic constraints buffer sizs in bytes. + @param[in, out] BasicConstraintsSize basic constraints buffer size in bytes. @retval TRUE The basic constraints retrieve successfully. @retval FALSE If cert is NULL. diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Rand/CryptRand.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Rand/CryptRand.c index e01aabc0de08..94367327ca8d 100644 --- a/CryptoPkg/Library/BaseCryptLibMbedTls/Rand/CryptRand.c +++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Rand/CryptRand.c @@ -92,7 +92,7 @@ RandomBytes ( /** The MbedTLS function f_rng, which MbedtlsRand implements. - @param[in] RngState Not used, just for compatibility with mbedlts. + @param[in] RngState Not used, just for compatibility with mbedtls. @param[out] Output Pointer to buffer to receive random value. @param[in] Len Size of random bytes to generate. diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Rand/CryptRandTsc.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Rand/CryptRandTsc.c index e01aabc0de08..94367327ca8d 100644 --- a/CryptoPkg/Library/BaseCryptLibMbedTls/Rand/CryptRandTsc.c +++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Rand/CryptRandTsc.c @@ -92,7 +92,7 @@ RandomBytes ( /** The MbedTLS function f_rng, which MbedtlsRand implements. - @param[in] RngState Not used, just for compatibility with mbedlts. + @param[in] RngState Not used, just for compatibility with mbedtls. @param[out] Output Pointer to buffer to receive random value. @param[in] Len Size of random bytes to generate. From 89377ece8f1c7243d25fd84488dcd03e37b9e661 Mon Sep 17 00:00:00 2001 From: Nhi Pham Date: Mon, 24 Jun 2024 12:22:52 +0700 Subject: [PATCH 07/67] MdeModulePkg/ImagePropertiesRecordLib: Reduce debug level The presense of PdbPointer (PDB file name) is not an error. Hence, the debug message should be categorized as VERBOSE or INFO. However, the DEBUG_VERBOSE is more appropriate since the PDB file name is already output by the PeCoffLoaderRelocateImageExtraAction() function with the inline "add-symbol-file" when a platform uses the library instance DebugPeCoffExtraActionLib. Signed-off-by: Nhi Pham --- .../Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c index 3ac043f98098..08e3311d156f 100644 --- a/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c +++ b/MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.c @@ -1052,7 +1052,7 @@ CreateImagePropertiesRecord ( PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageBase); if (PdbPointer != NULL) { - DEBUG ((DEBUG_ERROR, " Image - %a\n", PdbPointer)); + DEBUG ((DEBUG_VERBOSE, " Image - %a\n", PdbPointer)); } // Check PE/COFF image From ae09721a65ab3294439f6fa233adaf3b897f702f Mon Sep 17 00:00:00 2001 From: Gaurav Pandya Date: Wed, 20 Sep 2023 20:37:49 +0800 Subject: [PATCH 08/67] MdeModulePkg/DisplayEngineDxe: Support "^" and "V" key on pop-up form BZ #4790 Support "^" and "V" key stokes on the pop-up form. Align the implementation with key support on the regular HII form. Signed-off-by: Gaurav Pandya --- .../Universal/DisplayEngineDxe/InputHandler.c | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/MdeModulePkg/Universal/DisplayEngineDxe/InputHandler.c b/MdeModulePkg/Universal/DisplayEngineDxe/InputHandler.c index f70feeb55f0e..b6dc23476a70 100644 --- a/MdeModulePkg/Universal/DisplayEngineDxe/InputHandler.c +++ b/MdeModulePkg/Universal/DisplayEngineDxe/InputHandler.c @@ -2,6 +2,7 @@ Implementation for handling user input from the User Interfaces. Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.
+Copyright (C) 2024 Advanced Micro Devices, Inc. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -1568,6 +1569,47 @@ GetSelectionInputPopUp ( break; + case '^': + if ((TopOptionIndex > 0) && (TopOptionIndex == HighlightOptionIndex)) { + // + // Highlight reaches the top of the popup window, scroll one menu item. + // + TopOptionIndex--; + ShowDownArrow = TRUE; + } + + if (TopOptionIndex == 0) { + ShowUpArrow = FALSE; + } + + if (HighlightOptionIndex > 0) { + HighlightOptionIndex--; + } + + break; + + case 'V': + case 'v': + if (((TopOptionIndex + MenuLinesInView) < PopUpMenuLines) && + (HighlightOptionIndex == (TopOptionIndex + MenuLinesInView - 1))) + { + // + // Highlight reaches the bottom of the popup window, scroll one menu item. + // + TopOptionIndex++; + ShowUpArrow = TRUE; + } + + if ((TopOptionIndex + MenuLinesInView) == PopUpMenuLines) { + ShowDownArrow = FALSE; + } + + if (HighlightOptionIndex < (PopUpMenuLines - 1)) { + HighlightOptionIndex++; + } + + break; + case CHAR_NULL: switch (Key.ScanCode) { case SCAN_UP: From 6862b9d538d96363635677198899e1669e591259 Mon Sep 17 00:00:00 2001 From: Gerd Hoffmann Date: Wed, 19 Jun 2024 09:07:56 +0200 Subject: [PATCH 09/67] NetworkPkg/DxeNetLib: adjust PseudoRandom error logging There is a list of allowed rng algorithms, if /one/ of them is not supported this is not a problem, only /all/ of them failing is an error condition. Downgrade the message for a single unsupported algorithm from ERROR to VERBOSE. Add an error message in case we finish the loop without finding a supported algorithm. Signed-off-by: Gerd Hoffmann --- NetworkPkg/Library/DxeNetLib/DxeNetLib.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/NetworkPkg/Library/DxeNetLib/DxeNetLib.c b/NetworkPkg/Library/DxeNetLib/DxeNetLib.c index 01c13c08d203..4dfbe91a5554 100644 --- a/NetworkPkg/Library/DxeNetLib/DxeNetLib.c +++ b/NetworkPkg/Library/DxeNetLib/DxeNetLib.c @@ -951,7 +951,7 @@ PseudoRandom ( // // Secure Algorithm was not supported on this platform // - DEBUG ((DEBUG_ERROR, "Failed to generate random data using secure algorithm %d: %r\n", AlgorithmIndex, Status)); + DEBUG ((DEBUG_VERBOSE, "Failed to generate random data using secure algorithm %d: %r\n", AlgorithmIndex, Status)); // // Try the next secure algorithm @@ -971,6 +971,7 @@ PseudoRandom ( // If we get here, we failed to generate random data using any secure algorithm // Platform owner should ensure that at least one secure algorithm is supported // + DEBUG ((DEBUG_ERROR, "Failed to generate random data, no supported secure algorithm found\n")); ASSERT_EFI_ERROR (Status); return Status; } From a5f147b2a31c093cc83a3f10cdda529c6b59799b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 27 Jun 2024 13:12:31 +0000 Subject: [PATCH 10/67] pip: bump edk2-pytool-extensions from 0.27.5 to 0.27.6 Bumps [edk2-pytool-extensions](https://github.com/tianocore/edk2-pytool-extensions) from 0.27.5 to 0.27.6. - [Release notes](https://github.com/tianocore/edk2-pytool-extensions/releases) - [Commits](https://github.com/tianocore/edk2-pytool-extensions/compare/v0.27.5...v0.27.6) --- updated-dependencies: - dependency-name: edk2-pytool-extensions dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pip-requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pip-requirements.txt b/pip-requirements.txt index 92d46e865f09..7cee905ba481 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -13,7 +13,7 @@ ## edk2-pytool-library==0.21.5 -edk2-pytool-extensions==0.27.5 +edk2-pytool-extensions==0.27.6 edk2-basetools==0.1.51 antlr4-python3-runtime==4.7.1 lcov-cobertura==2.0.2 From ed46e507e6d220b09e73fed936f50bd875024dab Mon Sep 17 00:00:00 2001 From: Jiaxin Wu Date: Thu, 20 Jun 2024 17:23:19 +0800 Subject: [PATCH 11/67] UefiCpuPkg/Library: Add MM_STANDALONE type for MmSaveStateLib Signed-off-by: Jiaxin Wu Cc: Ray Ni Cc: Rahul Kumar Cc: Gerd Hoffmann Cc: Star Zeng Cc: Dun Tan Cc: Hongbin1 Zhang Cc: Wei6 Xu Cc: Yuanhao Xie --- UefiCpuPkg/Library/MmSaveStateLib/IntelMmSaveStateLib.inf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UefiCpuPkg/Library/MmSaveStateLib/IntelMmSaveStateLib.inf b/UefiCpuPkg/Library/MmSaveStateLib/IntelMmSaveStateLib.inf index b7fd4078f58a..71d8e5e6d177 100644 --- a/UefiCpuPkg/Library/MmSaveStateLib/IntelMmSaveStateLib.inf +++ b/UefiCpuPkg/Library/MmSaveStateLib/IntelMmSaveStateLib.inf @@ -16,7 +16,7 @@ FILE_GUID = 37E8137B-9F74-4250-8951-7A970A3C39C0 MODULE_TYPE = DXE_SMM_DRIVER VERSION_STRING = 1.0 - LIBRARY_CLASS = MmSaveStateLib + LIBRARY_CLASS = MmSaveStateLib|DXE_SMM_DRIVER MM_STANDALONE [Sources] MmSaveState.h From dc3ed379dfb62ed720e46f10b6c6d0ebda6bde5f Mon Sep 17 00:00:00 2001 From: Jiaxin Wu Date: Thu, 20 Jun 2024 17:24:13 +0800 Subject: [PATCH 12/67] UefiCpuPkg/Library: Add MM_STANDALONE type for SmmCpuPlatformHookLib Signed-off-by: Jiaxin Wu Cc: Ray Ni Cc: Rahul Kumar Cc: Gerd Hoffmann Cc: Star Zeng Cc: Dun Tan Cc: Hongbin1 Zhang Cc: Wei6 Xu Cc: Yuanhao Xie --- .../SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.inf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UefiCpuPkg/Library/SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.inf b/UefiCpuPkg/Library/SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.inf index fab6b30b7a3f..50eb74638b58 100644 --- a/UefiCpuPkg/Library/SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.inf +++ b/UefiCpuPkg/Library/SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.inf @@ -18,7 +18,7 @@ FILE_GUID = D6494E1B-E06F-4ab5-B64D-48B25AA9EB33 MODULE_TYPE = DXE_DRIVER VERSION_STRING = 1.0 - LIBRARY_CLASS = SmmCpuPlatformHookLib + LIBRARY_CLASS = SmmCpuPlatformHookLib|DXE_SMM_DRIVER MM_STANDALONE # # The following information is for reference only and not required by the build tools. From 3b2025969e6e8a2f6542996182cd4132868641c6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 28 Jun 2024 13:49:08 +0000 Subject: [PATCH 13/67] pip: bump edk2-pytool-library from 0.21.5 to 0.21.8 Bumps [edk2-pytool-library](https://github.com/tianocore/edk2-pytool-library) from 0.21.5 to 0.21.8. - [Release notes](https://github.com/tianocore/edk2-pytool-library/releases) - [Commits](https://github.com/tianocore/edk2-pytool-library/compare/v0.21.5...v0.21.8) --- updated-dependencies: - dependency-name: edk2-pytool-library dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pip-requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pip-requirements.txt b/pip-requirements.txt index 7cee905ba481..e07b9cac52c5 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -12,7 +12,7 @@ # https://www.python.org/dev/peps/pep-0440/#version-specifiers ## -edk2-pytool-library==0.21.5 +edk2-pytool-library==0.21.8 edk2-pytool-extensions==0.27.6 edk2-basetools==0.1.51 antlr4-python3-runtime==4.7.1 From 8c09d862bfb034e00b6b3bc37fe37243c866dd3a Mon Sep 17 00:00:00 2001 From: Joey Vagedes Date: Wed, 26 Jun 2024 14:04:28 -0700 Subject: [PATCH 14/67] BaseTools: BinToPcd: Remove xdrlib dependency The xdrlib dependency was removed in commit 5cadb8ce2148979b6c464f6da5a8cd97425c5165 but the actual import of the module was not removed. This commit removes the import of xdrlib and sorts the imports. Signed-off-by: Joey Vagedes --- BaseTools/Scripts/BinToPcd.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/BaseTools/Scripts/BinToPcd.py b/BaseTools/Scripts/BinToPcd.py index 460c08b7f7cd..be726cc6d87f 100644 --- a/BaseTools/Scripts/BinToPcd.py +++ b/BaseTools/Scripts/BinToPcd.py @@ -10,13 +10,12 @@ ''' from __future__ import print_function -import sys import argparse -import re -import xdrlib import io -import struct import math +import re +import struct +import sys # # Globals for help information From 469d09d6b25f4ac83dd4ed511db45795aa09d45b Mon Sep 17 00:00:00 2001 From: Jeshua Smith Date: Fri, 3 May 2024 14:25:37 -0700 Subject: [PATCH 15/67] DynamicTablesPkg: AmlLib CONST cleanup Several input strings to AmlLib APIs are treated as CONST but were missing the CONST keyword, requiring their callers to create unnecessary r/w copies of r/o input strings. This change properly marks these input strings as CONST. Signed-off-by: Jeshua Smith Reviewed-by: Jeff Brasen --- DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h | 12 ++++++------ DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApi.c | 2 +- .../Library/Common/AmlLib/CodeGen/AmlCodeGen.c | 10 +++++----- .../Library/Common/AmlLib/NameSpace/AmlNameSpace.c | 4 ++-- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h b/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h index 4427ab68fa16..7c130736b4d9 100644 --- a/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h +++ b/DynamicTablesPkg/Include/Library/AmlLib/AmlLib.h @@ -339,7 +339,7 @@ EFI_STATUS EFIAPI AmlFindNode ( IN AML_NODE_HANDLE ReferenceNode, - IN CHAR8 *AslPath, + IN CONST CHAR8 *AslPath, OUT AML_NODE_HANDLE *OutNode ); @@ -374,7 +374,7 @@ EFI_STATUS EFIAPI AmlDeviceOpUpdateName ( IN AML_OBJECT_NODE_HANDLE DeviceOpNode, - IN CHAR8 *NewNameString + IN CONST CHAR8 *NewNameString ); /** Update an integer value defined by a NameOp object node. @@ -1090,7 +1090,7 @@ EFI_STATUS EFIAPI AmlCodeGenNameString ( IN CONST CHAR8 *NameString, - IN CHAR8 *String, + IN CONST CHAR8 *String, IN AML_NODE_HANDLE ParentNode OPTIONAL, OUT AML_OBJECT_NODE_HANDLE *NewObjectNode OPTIONAL ); @@ -1613,7 +1613,7 @@ AmlAddLpiState ( IN UINT64 Integer OPTIONAL, IN EFI_ACPI_6_3_GENERIC_ADDRESS_STRUCTURE *ResidencyCounterRegister OPTIONAL, IN EFI_ACPI_6_3_GENERIC_ADDRESS_STRUCTURE *UsageCounterRegister OPTIONAL, - IN CHAR8 *StateName OPTIONAL, + IN CONST CHAR8 *StateName OPTIONAL, IN AML_OBJECT_NODE_HANDLE LpiNode ); @@ -1668,7 +1668,7 @@ AmlAddDeviceDataDescriptorPackage ( EFI_STATUS EFIAPI AmlAddNameIntegerPackage ( - IN CHAR8 *Name, + IN CONST CHAR8 *Name, IN UINT64 Value, IN AML_OBJECT_NODE_HANDLE PackageNode ); @@ -1739,7 +1739,7 @@ AmlCreateCpcNode ( EFI_STATUS EFIAPI AmlAddNameStringToNamedPackage ( - IN CHAR8 *NameString, + IN CONST CHAR8 *NameString, IN AML_OBJECT_NODE_HANDLE NamedNode ); diff --git a/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApi.c b/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApi.c index 9f162abe2d09..41643d5eeeae 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApi.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/Api/AmlApi.c @@ -40,7 +40,7 @@ EFI_STATUS EFIAPI AmlDeviceOpUpdateName ( IN AML_OBJECT_NODE_HANDLE DeviceOpNode, - IN CHAR8 *NewNameString + IN CONST CHAR8 *NewNameString ) { EFI_STATUS Status; diff --git a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c index 89fa4e06f8cd..f433a461b24f 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/CodeGen/AmlCodeGen.c @@ -139,7 +139,7 @@ STATIC EFI_STATUS EFIAPI AmlCodeGenString ( - IN CHAR8 *String, + IN CONST CHAR8 *String, OUT AML_OBJECT_NODE **NewObjectNode ) { @@ -664,7 +664,7 @@ EFI_STATUS EFIAPI AmlCodeGenNameString ( IN CONST CHAR8 *NameString, - IN CHAR8 *String, + IN CONST CHAR8 *String, IN AML_NODE_HEADER *ParentNode OPTIONAL, OUT AML_OBJECT_NODE **NewObjectNode OPTIONAL ) @@ -2615,7 +2615,7 @@ AmlAddLpiState ( IN UINT64 Integer OPTIONAL, IN EFI_ACPI_6_3_GENERIC_ADDRESS_STRUCTURE *ResidencyCounterRegister OPTIONAL, IN EFI_ACPI_6_3_GENERIC_ADDRESS_STRUCTURE *UsageCounterRegister OPTIONAL, - IN CHAR8 *StateName OPTIONAL, + IN CONST CHAR8 *StateName OPTIONAL, IN AML_OBJECT_NODE_HANDLE LpiNode ) { @@ -3204,7 +3204,7 @@ AmlAddDeviceDataDescriptorPackage ( EFI_STATUS EFIAPI AmlAddNameIntegerPackage ( - IN CHAR8 *Name, + IN CONST CHAR8 *Name, IN UINT64 Value, IN AML_OBJECT_NODE_HANDLE PackageNode ) @@ -3800,7 +3800,7 @@ AmlCreateCpcNode ( EFI_STATUS EFIAPI AmlAddNameStringToNamedPackage ( - IN CHAR8 *NameString, + IN CONST CHAR8 *NameString, IN AML_OBJECT_NODE_HANDLE NamedNode ) { diff --git a/DynamicTablesPkg/Library/Common/AmlLib/NameSpace/AmlNameSpace.c b/DynamicTablesPkg/Library/Common/AmlLib/NameSpace/AmlNameSpace.c index 9104b781d9b4..e871afef7f12 100644 --- a/DynamicTablesPkg/Library/Common/AmlLib/NameSpace/AmlNameSpace.c +++ b/DynamicTablesPkg/Library/Common/AmlLib/NameSpace/AmlNameSpace.c @@ -1234,7 +1234,7 @@ EFI_STATUS EFIAPI AmlBuildAbsoluteAmlPath ( IN AML_NODE_HEADER *ReferenceNode, - IN CHAR8 *AslPath, + IN CONST CHAR8 *AslPath, IN OUT AML_STREAM *RawAmlAbsSearchPathBStream ) { @@ -1373,7 +1373,7 @@ EFI_STATUS EFIAPI AmlFindNode ( IN AML_NODE_HEADER *ReferenceNode, - IN CHAR8 *AslPath, + IN CONST CHAR8 *AslPath, OUT AML_NODE_HEADER **OutNode ) { From 8bf27965dbb94ecccc453c60de3270acf238ea3d Mon Sep 17 00:00:00 2001 From: Jeshua Smith Date: Wed, 26 Jun 2024 14:22:24 -0700 Subject: [PATCH 16/67] DynamicTablesPkg: AmlLib remove unnecessary cast Now that CONST input strings to the AmlLib APIs are properly marked as CONST we don't need to cast them to non-CONST before passing them. Signed-off-by: Jeshua Smith --- .../Library/Acpi/Arm/AcpiSsdtCmn600LibArm/SsdtCmn600Generator.c | 2 +- .../Common/SsdtSerialPortFixupLib/SsdtSerialPortFixupLib.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCmn600LibArm/SsdtCmn600Generator.c b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCmn600LibArm/SsdtCmn600Generator.c index b990686d40a3..6118df05497e 100644 --- a/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCmn600LibArm/SsdtCmn600Generator.c +++ b/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtCmn600LibArm/SsdtCmn600Generator.c @@ -372,7 +372,7 @@ FixupCmn600Info ( } // Update the CMN600 Device's name. - Status = AmlDeviceOpUpdateName (DeviceNode, (CHAR8 *)Name); + Status = AmlDeviceOpUpdateName (DeviceNode, Name); if (EFI_ERROR (Status)) { goto error_handler; } diff --git a/DynamicTablesPkg/Library/Common/SsdtSerialPortFixupLib/SsdtSerialPortFixupLib.c b/DynamicTablesPkg/Library/Common/SsdtSerialPortFixupLib/SsdtSerialPortFixupLib.c index b1a628e419f0..f2594de2e92c 100644 --- a/DynamicTablesPkg/Library/Common/SsdtSerialPortFixupLib/SsdtSerialPortFixupLib.c +++ b/DynamicTablesPkg/Library/Common/SsdtSerialPortFixupLib/SsdtSerialPortFixupLib.c @@ -381,7 +381,7 @@ FixupName ( } // Update the Device's name. - return AmlDeviceOpUpdateName (DeviceNode, (CHAR8 *)Name); + return AmlDeviceOpUpdateName (DeviceNode, Name); } /** Fixup the Serial Port Information in the AML tree. From 5ab96f5437e03ddc0288771fdfd9e916cd755aac Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Thu, 23 May 2024 17:24:55 +0800 Subject: [PATCH 17/67] SecurityPkg: Add a new gEdkiiTpmInstanceHobGuid This new Guid HOB contains a TPM instance Guid which is the same as PcdTpmInstanceGuid. The HOB is used for StandaloneMm driver which needs to consume the dynamic PcdTpmInstanceGuid. Signed-off-by: Dun Tan --- SecurityPkg/SecurityPkg.dec | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec index a91e3ea0284e..2c2153c19ed3 100644 --- a/SecurityPkg/SecurityPkg.dec +++ b/SecurityPkg/SecurityPkg.dec @@ -230,6 +230,10 @@ ## GUID used to generate Spdm Uid gEfiDeviceSecuritySpdmUidGuid = {0xe37b5665, 0x5ef9, 0x4e7e, {0xb4, 0x91, 0xd6, 0x78, 0xab, 0xff, 0xfb, 0xcb }} + ## GUID used to tag the HOB indicating the TPM instance. + ## The GUIDed HOB contains the same value as PcdGetPtr (PcdTpmInstanceGuid). + gEdkiiTpmInstanceHobGuid = { 0x4551b023, 0xba46, 0x4584, { 0x81, 0xcd, 0x4d, 0xe8, 0x61, 0xa7, 0x28, 0xbe } } + [Ppis] ## The PPI GUID for that TPM physical presence should be locked. # Include/Ppi/LockPhysicalPresence.h From f9950cceecc12d40298b0287f193c6e6ddb9a14b Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Thu, 23 May 2024 17:30:45 +0800 Subject: [PATCH 18/67] SecurityPkg:Add new HOB for PhysicalPresenceInterfaceVersion Add a new gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid. This new Guid HOB contains a a string of the Version of Physical Presence interface which is the same as PcdTcgPhysicalPresenceInterfaceVer. The HOB is used for StandaloneMm driver which needs to consume the dynamic PcdTcgPhysicalPresenceInterfaceVer. Signed-off-by: Dun Tan --- SecurityPkg/SecurityPkg.dec | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec index 2c2153c19ed3..65f3587c4816 100644 --- a/SecurityPkg/SecurityPkg.dec +++ b/SecurityPkg/SecurityPkg.dec @@ -234,6 +234,10 @@ ## The GUIDed HOB contains the same value as PcdGetPtr (PcdTpmInstanceGuid). gEdkiiTpmInstanceHobGuid = { 0x4551b023, 0xba46, 0x4584, { 0x81, 0xcd, 0x4d, 0xe8, 0x61, 0xa7, 0x28, 0xbe } } + ## GUID used to tag the HOB indicating the Version of Physical Presence interface. + ## The GUIDed HOB contains the same value as PcdGetPtr (PcdTcgPhysicalPresenceInterfaceVer). + gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid = { 0x3979411a, 0x4e6d, 0x47e4, { 0x94, 0x4b, 0x0e, 0xcc, 0x6c, 0xf6, 0xc0, 0xcd } } + [Ppis] ## The PPI GUID for that TPM physical presence should be locked. # Include/Ppi/LockPhysicalPresence.h From cb38d27f1dbbd787d3606f6314b5f33a5cb86646 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 24 May 2024 15:00:30 +0800 Subject: [PATCH 19/67] SecurityPkg/Tcg2ConfigPei: Build two new HOBs Build following two new HOBs: gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid gEdkiiTpmInstanceHobGuid The two HOBs will be used by Tcg2StandaloneMm driver to avoid using the related dynamic PCDs. Signed-off-by: Dun Tan --- SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf | 6 ++++- SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c | 24 +++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf b/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf index f2aa3234adf6..b0c9c44e2956 100644 --- a/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf +++ b/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf @@ -4,7 +4,7 @@ # This module initializes TPM device type based on variable and detection. # NOTE: This module is only for reference only, each platform should have its own setup page. # -# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -46,6 +46,7 @@ TimerLib Tpm12CommandLib Tpm12DeviceLib + HobLib [Guids] ## SOMETIMES_CONSUMES ## Variable:L"TCG2_CONFIGURATION" @@ -53,6 +54,8 @@ gTcg2ConfigFormSetGuid gEfiTpmDeviceSelectedGuid ## PRODUCES ## GUID # Used as a PPI GUID gEfiTpmDeviceInstanceNoneGuid ## SOMETIMES_CONSUMES ## GUID # TPM device identifier + gEdkiiTpmInstanceHobGuid + gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid [Ppis] gEfiPeiReadOnlyVariable2PpiGuid ## CONSUMES @@ -62,6 +65,7 @@ gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid ## PRODUCES gEfiSecurityPkgTokenSpaceGuid.PcdTpmInitializationPolicy ## PRODUCES gEfiSecurityPkgTokenSpaceGuid.PcdTpmAutoDetection ## CONSUMES + gEfiSecurityPkgTokenSpaceGuid.PcdTcgPhysicalPresenceInterfaceVer [Depex] gEfiPeiMasterBootModePpiGuid AND diff --git a/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c b/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c index 21a01f07e145..9840deb210db 100644 --- a/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c +++ b/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c @@ -1,7 +1,7 @@ /** @file The module entry point for Tcg2 configuration module. -Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -16,6 +16,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include #include #include @@ -73,6 +74,7 @@ Tcg2ConfigPeimEntryPoint ( TCG2_CONFIGURATION Tcg2Configuration; UINTN Index; UINT8 TpmDevice; + VOID *Hob; Status = PeiServicesLocatePpi (&gEfiPeiReadOnlyVariable2PpiGuid, 0, NULL, (VOID **)&VariablePpi); ASSERT_EFI_ERROR (Status); @@ -133,6 +135,26 @@ Tcg2ConfigPeimEntryPoint ( } } + // + // Build Hob for PcdTpmInstanceGuid + // + Hob = BuildGuidDataHob ( + &gEdkiiTpmInstanceHobGuid, + PcdGetPtr (PcdTpmInstanceGuid), + sizeof (EFI_GUID) + ); + ASSERT (Hob != NULL); + + // + // Build Hob for PcdTcgPhysicalPresenceInterfaceVer + // + Hob = BuildGuidDataHob ( + &gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid, + PcdGetPtr (PcdTcgPhysicalPresenceInterfaceVer), + AsciiStrSize ((CHAR8 *)PcdGetPtr (PcdTcgPhysicalPresenceInterfaceVer)) + ); + ASSERT (Hob != NULL); + // // Selection done // From 97ede07beb5eb09b1e3fe09c9ce0137a7425dc1e Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 24 May 2024 17:03:02 +0800 Subject: [PATCH 20/67] SecurityPkg/Tcg2StandaloneMm:Consume gEdkiiTpmInstanceHobGuid Consume gEdkiiTpmInstanceHobGuid in Tcg2StandaloneMm driver. It's to avoid using dynamic PcdTpmInstanceGuid in StandaloneMm driver. Signed-off-by: Dun Tan --- SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c | 4 +-- SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h | 13 ++++++++- SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.c | 30 +++++++++++++++++++- SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.inf | 7 ++--- SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c | 16 ++++++++++- 5 files changed, 61 insertions(+), 9 deletions(-) diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c index c47c582cc8d2..c2cef764e0c0 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c @@ -9,7 +9,7 @@ PhysicalPresenceCallback() and MemoryClearCallback() will receive untrusted input and do some check. -Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -285,7 +285,7 @@ InitializeTcgCommon ( EFI_HANDLE McSwHandle; EFI_HANDLE NotifyHandle; - if (!CompareGuid (PcdGetPtr (PcdTpmInstanceGuid), &gEfiTpmDeviceInstanceTpm20DtpmGuid)) { + if (!IsTpm20Dtpm ()) { DEBUG ((DEBUG_ERROR, "No TPM2 DTPM instance required!\n")); return EFI_UNSUPPORTED; } diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h index 84b65eb0897c..3672db939b9f 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h @@ -1,7 +1,7 @@ /** @file The header file for Tcg2 SMM driver. -Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -84,4 +84,15 @@ InitializeTcgCommon ( VOID ); +/** + This function checks if the required DTPM instance is TPM 2.0. + + @retval TRUE The required DTPM instance is equal to gEfiTpmDeviceInstanceTpm20DtpmGuid. + @retval FALSE The required DTPM instance is not equal to gEfiTpmDeviceInstanceTpm20DtpmGuid. +**/ +BOOLEAN +IsTpm20Dtpm ( + VOID + ); + #endif // __TCG_SMM_H__ diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.c b/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.c index 77fa3691f493..9320053224aa 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.c +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.c @@ -9,7 +9,7 @@ PhysicalPresenceCallback() and MemoryClearCallback() will receive untrusted input and do some check. -Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -17,6 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Tcg2Smm.h" #include +#include /** Notify the system that the SMM variable driver is ready. @@ -47,6 +48,33 @@ IsBufferOutsideMmValid ( return MmIsBufferOutsideMmValid (Buffer, Length); } +/** + This function checks if the required DTPM instance is TPM 2.0. + + @retval TRUE The required DTPM instance is equal to gEfiTpmDeviceInstanceTpm20DtpmGuid. + @retval FALSE The required DTPM instance is not equal to gEfiTpmDeviceInstanceTpm20DtpmGuid. +**/ +BOOLEAN +IsTpm20Dtpm ( + VOID + ) +{ + VOID *GuidHob; + + GuidHob = GetFirstGuidHob (&gEdkiiTpmInstanceHobGuid); + if (GuidHob != NULL) { + if (CompareGuid ((EFI_GUID *)GET_GUID_HOB_DATA (GuidHob), &gEfiTpmDeviceInstanceTpm20DtpmGuid)) { + return TRUE; + } + + DEBUG ((DEBUG_ERROR, "No TPM2 DTPM instance required! - %g\n", (EFI_GUID *)GET_GUID_HOB_DATA (GuidHob))); + } else { + DEBUG ((DEBUG_ERROR, "No gEdkiiTpmInstanceHobGuid!\n")); + } + + return FALSE; +} + /** The driver's entry point. diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.inf b/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.inf index 746eda3e9fed..bca59a539b19 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.inf +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.inf @@ -20,7 +20,7 @@ # This driver will have external input - variable and ACPINvs data in SMM mode. # This external input must be validated carefully to avoid security issue. # -# Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -55,6 +55,7 @@ Tcg2PhysicalPresenceLib PcdLib MemLib + HobLib [Guids] ## SOMETIMES_PRODUCES ## Variable:L"MemoryOverwriteRequestControl" @@ -63,15 +64,13 @@ gEfiTpmDeviceInstanceTpm20DtpmGuid ## PRODUCES ## GUID # TPM device identifier gTpmNvsMmGuid ## CONSUMES + gEdkiiTpmInstanceHobGuid [Protocols] gEfiSmmSwDispatch2ProtocolGuid ## CONSUMES gEfiSmmVariableProtocolGuid ## CONSUMES gEfiMmReadyToLockProtocolGuid ## CONSUMES -[Pcd] - gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid ## CONSUMES - [Depex] gEfiSmmSwDispatch2ProtocolGuid AND gEfiSmmVariableProtocolGuid diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c b/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c index 514171cfacf6..f7d595e7f3f4 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c @@ -9,7 +9,7 @@ PhysicalPresenceCallback() and MemoryClearCallback() will receive untrusted input and do some check. -Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -58,6 +58,20 @@ IsBufferOutsideMmValid ( return SmmIsBufferOutsideSmmValid (Buffer, Length); } +/** + This function checks if the required DTPM instance is TPM 2.0. + + @retval TRUE The required DTPM instance is equal to gEfiTpmDeviceInstanceTpm20DtpmGuid. + @retval FALSE The required DTPM instance is not equal to gEfiTpmDeviceInstanceTpm20DtpmGuid. +**/ +BOOLEAN +IsTpm20Dtpm ( + VOID + ) +{ + return CompareGuid (PcdGetPtr (PcdTpmInstanceGuid), &gEfiTpmDeviceInstanceTpm20DtpmGuid); +} + /** The driver's entry point. From add3ca4e0060cbf134f3c8559d5569bda24a5c9b Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Fri, 24 May 2024 17:41:40 +0800 Subject: [PATCH 21/67] SecurityPkg:Consume gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid Consume gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid in StandaloneMmTcg2PhysicalPresenceLib. This is to avoid using the dynamic PcdTcgPhysicalPresenceInterfaceVer in StandaloneMm module. Signed-off-by: Dun Tan --- .../MmTcg2PhysicalPresenceLibCommon.c | 20 +++----------- .../MmTcg2PhysicalPresenceLibCommon.h | 25 ++++++++++++++++- .../SmmTcg2PhysicalPresenceLib.c | 16 ++++++++++- .../StandaloneMmTcg2PhysicalPresenceLib.c | 27 ++++++++++++++++++- .../StandaloneMmTcg2PhysicalPresenceLib.inf | 5 ++-- 5 files changed, 71 insertions(+), 22 deletions(-) diff --git a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.c b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.c index f2ab4f125007..e8f3a7a27486 100644 --- a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.c +++ b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.c @@ -10,24 +10,12 @@ Tcg2PhysicalPresenceLibSubmitRequestToPreOSFunction() and Tcg2PhysicalPresenceLibGetUserConfirmationStatusFunction() will receive untrusted input and do validation. -Copyright (c) 2015 - 2020, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#include - -#include - -#include - -#include -#include -#include -#include -#include - -#define PP_INF_VERSION_1_2 "1.2" +#include "MmTcg2PhysicalPresenceLibCommon.h" EFI_SMM_VARIABLE_PROTOCOL *mTcg2PpSmmVariable; BOOLEAN mIsTcg2PPVerLowerThan_1_3 = FALSE; @@ -392,9 +380,7 @@ Tcg2PhysicalPresenceLibCommonConstructor ( { EFI_STATUS Status; - if (AsciiStrnCmp (PP_INF_VERSION_1_2, (CHAR8 *)PcdGetPtr (PcdTcgPhysicalPresenceInterfaceVer), sizeof (PP_INF_VERSION_1_2) - 1) >= 0) { - mIsTcg2PPVerLowerThan_1_3 = TRUE; - } + mIsTcg2PPVerLowerThan_1_3 = IsTcg2PPVerLowerThan_1_3 (); // // Locate SmmVariableProtocol. diff --git a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.h b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.h index a0182739e9c8..4409c4daaab7 100644 --- a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.h +++ b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/MmTcg2PhysicalPresenceLibCommon.h @@ -10,7 +10,7 @@ Tcg2PhysicalPresenceLibSubmitRequestToPreOSFunction() and Tcg2PhysicalPresenceLibGetUserConfirmationStatusFunction() will receive untrusted input and do validation. -Copyright (c) 2015 - 2020, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -18,6 +18,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _MM_TCG2_PHYSICAL_PRESENCE_LIB_COMMON_H_ #define _MM_TCG2_PHYSICAL_PRESENCE_LIB_COMMON_H_ +#include + +#include + +#include +#include +#include +#include +#include + +#define PP_INF_VERSION_1_2 "1.2" + /** The constructor function locates MmVariable protocol. @@ -31,4 +43,15 @@ Tcg2PhysicalPresenceLibCommonConstructor ( VOID ); +/** + Check if Tcg2 PP version is lower than PP_INF_VERSION_1_3. + + @retval TRUE Tcg2 PP version is lower than PP_INF_VERSION_1_3. + @retval Other Tcg2 PP version is not lower than PP_INF_VERSION_1_3. +**/ +BOOLEAN +IsTcg2PPVerLowerThan_1_3 ( + VOID + ); + #endif diff --git a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/SmmTcg2PhysicalPresenceLib.c b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/SmmTcg2PhysicalPresenceLib.c index 36d8b89dcdd9..da89be35bdc9 100644 --- a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/SmmTcg2PhysicalPresenceLib.c +++ b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/SmmTcg2PhysicalPresenceLib.c @@ -10,7 +10,7 @@ Tcg2PhysicalPresenceLibSubmitRequestToPreOSFunction() and Tcg2PhysicalPresenceLibGetUserConfirmationStatusFunction() will receive untrusted input and do validation. -Copyright (c) 2015 - 2020, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -39,3 +39,17 @@ Tcg2PhysicalPresenceLibTraditionalConstructor ( { return Tcg2PhysicalPresenceLibCommonConstructor (); } + +/** + Check if Tcg2 PP version is lower than PP_INF_VERSION_1_3. + + @retval TRUE Tcg2 PP version is lower than PP_INF_VERSION_1_3. + @retval Other Tcg2 PP version is not lower than PP_INF_VERSION_1_3. +**/ +BOOLEAN +IsTcg2PPVerLowerThan_1_3 ( + VOID + ) +{ + return (BOOLEAN)(AsciiStrnCmp (PP_INF_VERSION_1_2, (CHAR8 *)PcdGetPtr (PcdTcgPhysicalPresenceInterfaceVer), sizeof (PP_INF_VERSION_1_2) - 1) >= 0); +} diff --git a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/StandaloneMmTcg2PhysicalPresenceLib.c b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/StandaloneMmTcg2PhysicalPresenceLib.c index 5c298a8d5720..d1646d0b9d4d 100644 --- a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/StandaloneMmTcg2PhysicalPresenceLib.c +++ b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/StandaloneMmTcg2PhysicalPresenceLib.c @@ -10,7 +10,7 @@ Tcg2PhysicalPresenceLibSubmitRequestToPreOSFunction() and Tcg2PhysicalPresenceLibGetUserConfirmationStatusFunction() will receive untrusted input and do validation. -Copyright (c) 2015 - 2020, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -18,6 +18,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include +#include + #include "MmTcg2PhysicalPresenceLibCommon.h" /** @@ -40,3 +42,26 @@ Tcg2PhysicalPresenceLibStandaloneMmConstructor ( { return Tcg2PhysicalPresenceLibCommonConstructor (); } + +/** + Check if Tcg2 PP version is lower than PP_INF_VERSION_1_3. + + @retval TRUE Tcg2 PP version is lower than PP_INF_VERSION_1_3. + @retval Other Tcg2 PP version is not lower than PP_INF_VERSION_1_3. +**/ +BOOLEAN +IsTcg2PPVerLowerThan_1_3 ( + VOID + ) +{ + VOID *GuidHob; + + GuidHob = GetFirstGuidHob (&gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid); + ASSERT (GuidHob != NULL); + + if (AsciiStrnCmp (PP_INF_VERSION_1_2, (CHAR8 *)GET_GUID_HOB_DATA (GuidHob), sizeof (PP_INF_VERSION_1_2) - 1) >= 0) { + return TRUE; + } + + return FALSE; +} diff --git a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/StandaloneMmTcg2PhysicalPresenceLib.inf b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/StandaloneMmTcg2PhysicalPresenceLib.inf index 6d11b6b9f198..0d8d1117922f 100644 --- a/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/StandaloneMmTcg2PhysicalPresenceLib.inf +++ b/SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/StandaloneMmTcg2PhysicalPresenceLib.inf @@ -7,7 +7,7 @@ # This driver will have external input - variable. # This external input must be validated carefully to avoid security issue. # -# Copyright (c) 2015 - 2020, Intel Corporation. All rights reserved.
+# Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -44,18 +44,19 @@ Tcg2PpVendorLib MmServicesTableLib BaseMemoryLib + HobLib [Guids] ## SOMETIMES_PRODUCES ## Variable:L"PhysicalPresence" ## SOMETIMES_CONSUMES ## Variable:L"PhysicalPresence" ## SOMETIMES_CONSUMES ## Variable:L"PhysicalPresenceFlags" gEfiTcg2PhysicalPresenceGuid + gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid [Protocols] gEfiSmmVariableProtocolGuid ## CONSUMES [Pcd] - gEfiSecurityPkgTokenSpaceGuid.PcdTcgPhysicalPresenceInterfaceVer ## CONSUMES gEfiSecurityPkgTokenSpaceGuid.PcdTcg2PhysicalPresenceFlags ## SOMETIMES_CONSUMES [Depex] From cb6ba975ae54f8eb915136264bf040d52d7bc2b4 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Mon, 3 Jun 2024 17:42:10 +0800 Subject: [PATCH 22/67] SecurityPkg: Add new gEdkiiTcg2AcpiCommunicateBufferHobGuid Add a new GUID HOB gEdkiiTcg2AcpiCommunicateBufferHobGuid. This Tcg2 Acpi Communicate Buffer HOB is used to store the address of a buffer reserved for Tcg2Acpi driver. The buffer will be used to retrive information from Standalone mm environment. Signed-off-by: Dun Tan --- .../Include/Guid/Tcg2AcpiCommunicateBuffer.h | 33 +++++++++++++++++++ SecurityPkg/SecurityPkg.dec | 3 ++ 2 files changed, 36 insertions(+) create mode 100644 SecurityPkg/Include/Guid/Tcg2AcpiCommunicateBuffer.h diff --git a/SecurityPkg/Include/Guid/Tcg2AcpiCommunicateBuffer.h b/SecurityPkg/Include/Guid/Tcg2AcpiCommunicateBuffer.h new file mode 100644 index 000000000000..c1d8c2d6f593 --- /dev/null +++ b/SecurityPkg/Include/Guid/Tcg2AcpiCommunicateBuffer.h @@ -0,0 +1,33 @@ +/** @file + This Tcg2 Acpi Communicate Buffer HOB is used to store the address + of a buffer reserved for Tcg2Acpi driver. The buffer will be used to + retrive information from standalone mm environment. + + Copyright (c) 2024, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef TCG2_ACPI_COMMUNICATE_BUFFER_H_ +#define TCG2_ACPI_COMMUNICATE_BUFFER_H_ + +#define TCG2_ACPI_COMMUNICATE_BUFFER_HOB_REVISION 1 + +#define TCG2_ACPI_COMMUNICATE_BUFFER_GUID \ + { \ + 0xcefea14f, 0x9f1a, 0x4774, {0x8d, 0x18, 0x79, 0x93, 0x8d, 0x48, 0xfe, 0x7d} \ + } + +typedef struct { + /// + /// Base address of the buffer reserved for Tcg2Acpi driver. + /// Tcg2Acpi will use it to exchange information with Tcg2StandaloneMm. + /// + EFI_PHYSICAL_ADDRESS Tcg2AcpiCommunicateBuffer; + UINT64 Pages; +} TCG2_ACPI_COMMUNICATE_BUFFER; + +extern EFI_GUID gEdkiiTcg2AcpiCommunicateBufferHobGuid; + +#endif diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec index 65f3587c4816..1fa9a567da31 100644 --- a/SecurityPkg/SecurityPkg.dec +++ b/SecurityPkg/SecurityPkg.dec @@ -238,6 +238,9 @@ ## The GUIDed HOB contains the same value as PcdGetPtr (PcdTcgPhysicalPresenceInterfaceVer). gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid = { 0x3979411a, 0x4e6d, 0x47e4, { 0x94, 0x4b, 0x0e, 0xcc, 0x6c, 0xf6, 0xc0, 0xcd } } + ## Include/Guid/Tcg2AcpiCommunicateBuffer.h + gEdkiiTcg2AcpiCommunicateBufferHobGuid = { 0xcefea14f, 0x9f1a, 0x4774, { 0x8d, 0x18, 0x79, 0x93, 0x8d, 0x48, 0xfe, 0x7d } } + [Ppis] ## The PPI GUID for that TPM physical presence should be locked. # Include/Ppi/LockPhysicalPresence.h From 9a76c7945b762ed8abed3b917aa6217846ae1918 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Tue, 4 Jun 2024 09:52:52 +0800 Subject: [PATCH 23/67] SecurityPkg: Build gEdkiiTcg2AcpiCommunicateBufferHobGuid Install a callback of gEfiPeiMemoryDiscoveredPpiGuid to build the gEdkiiTcg2AcpiCommunicateBufferHobGuid in the Tcg2ConfigPei PEIM. The HOB contains a buffer reserved by MmUnblockMemoryLib. The buffer will be used in Tcg2Acpi driver to retrive information from standalone mm environment. Signed-off-by: Dun Tan --- SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf | 3 ++ SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c | 52 ++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf b/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf index b0c9c44e2956..f7213b278099 100644 --- a/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf +++ b/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPei.inf @@ -47,6 +47,7 @@ Tpm12CommandLib Tpm12DeviceLib HobLib + MmUnblockMemoryLib [Guids] ## SOMETIMES_CONSUMES ## Variable:L"TCG2_CONFIGURATION" @@ -56,10 +57,12 @@ gEfiTpmDeviceInstanceNoneGuid ## SOMETIMES_CONSUMES ## GUID # TPM device identifier gEdkiiTpmInstanceHobGuid gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid + gEdkiiTcg2AcpiCommunicateBufferHobGuid [Ppis] gEfiPeiReadOnlyVariable2PpiGuid ## CONSUMES gPeiTpmInitializationDonePpiGuid ## SOMETIMES_PRODUCES + gEfiPeiMemoryDiscoveredPpiGuid [Pcd] gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid ## PRODUCES diff --git a/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c b/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c index 9840deb210db..ce78e3253721 100644 --- a/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c +++ b/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c @@ -9,6 +9,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include +#include +#include #include #include @@ -17,6 +19,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include #include #include @@ -51,6 +54,53 @@ DetectTpmDevice ( IN UINT8 SetupTpmDevice ); +/** + Build gEdkiiTcg2AcpiCommunicateBufferHobGuid. + + @param[in] PeiServices General purpose services available to every PEIM. + @param[in] NotifyDescriptor The notification structure this PEIM registered on install. + @param[in] Ppi The memory discovered PPI. Not used. + + @retval EFI_SUCCESS The function completed successfully. + @retval others Failed to build Tcg2AcpiCommunicateBuffer Hob. + +**/ +EFI_STATUS +EFIAPI +BuildTcg2AcpiCommunicateBufferHob ( + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, + IN VOID *Ppi + ) +{ + TCG2_ACPI_COMMUNICATE_BUFFER *Tcg2AcpiCommunicateBufferHob; + EFI_STATUS Status; + VOID *Buffer; + UINTN Pages; + + Pages = sizeof (TCG_NVS); + Buffer = AllocateRuntimePages (Pages); + ASSERT (Buffer != NULL); + + Status = MmUnblockMemoryRequest ((UINTN)Buffer, Pages); + if ((Status != EFI_UNSUPPORTED) && EFI_ERROR (Status)) { + return Status; + } + + Tcg2AcpiCommunicateBufferHob = BuildGuidHob (&gEdkiiTcg2AcpiCommunicateBufferHobGuid, sizeof (TCG2_ACPI_COMMUNICATE_BUFFER)); + ASSERT (Tcg2AcpiCommunicateBufferHob != NULL); + Tcg2AcpiCommunicateBufferHob->Tcg2AcpiCommunicateBuffer = (UINTN)Buffer; + Tcg2AcpiCommunicateBufferHob->Pages = Pages; + + return EFI_SUCCESS; +} + +EFI_PEI_NOTIFY_DESCRIPTOR mPostMemNotifyList = { + (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), + &gEfiPeiMemoryDiscoveredPpiGuid, + BuildTcg2AcpiCommunicateBufferHob +}; + /** The entry point for Tcg2 configuration driver. @@ -155,6 +205,8 @@ Tcg2ConfigPeimEntryPoint ( ); ASSERT (Hob != NULL); + PeiServicesNotifyPpi (&mPostMemNotifyList); + // // Selection done // From e939ecf6c19f932535d073e383d016e8bf2e8ee7 Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Tue, 4 Jun 2024 10:26:49 +0800 Subject: [PATCH 24/67] SecurityPkg: Consume gEdkiiTcg2AcpiCommunicateBufferHobGuid Consume gEdkiiTcg2AcpiCommunicateBufferHobGuid in Tcg2Acpi driver. Tcg2Acpi will use the buffer stored in the HOB to exchange information with Tcg2StandaloneMm by the MM_COMMUNICATION_PROTOCOL. Signed-off-by: Dun Tan --- SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c | 28 ++++++++++++++------------- SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.inf | 5 +++-- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c b/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c index 76123fc51a53..5addd2f563ca 100644 --- a/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c +++ b/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c @@ -9,7 +9,7 @@ This driver will have external input - variable and ACPINvs data in SMM mode. This external input must be validated carefully to avoid security issue. -Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -22,6 +22,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include #include #include @@ -38,7 +39,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include -#include +#include // // Physical Presence Interface Version supported by Platform @@ -116,7 +117,7 @@ TCG_NVS *mTcgNvs; @param[in] Name The name string to find in TPM table. @param[in] Size The size of the region to find. - @return The allocated address for the found region. + @return The Acpi Communicate Buffer for the found region. **/ VOID * @@ -126,9 +127,10 @@ AssignOpRegion ( UINT16 Size ) { - EFI_STATUS Status; - AML_OP_REGION_32_8 *OpRegion; - EFI_PHYSICAL_ADDRESS MemoryAddress; + AML_OP_REGION_32_8 *OpRegion; + EFI_PHYSICAL_ADDRESS MemoryAddress; + EFI_HOB_GUID_TYPE *GuidHob; + TCG2_ACPI_COMMUNICATE_BUFFER *Tcg2AcpiCommunicateBufferHob; MemoryAddress = SIZE_4GB - 1; @@ -144,16 +146,16 @@ AssignOpRegion ( (OpRegion->DWordPrefix == AML_DWORD_PREFIX) && (OpRegion->BytePrefix == AML_BYTE_PREFIX)) { - Status = gBS->AllocatePages (AllocateMaxAddress, EfiACPIMemoryNVS, EFI_SIZE_TO_PAGES (Size), &MemoryAddress); - ASSERT_EFI_ERROR (Status); + GuidHob = GetFirstGuidHob (&gEdkiiTcg2AcpiCommunicateBufferHobGuid); + ASSERT (GuidHob != NULL); + Tcg2AcpiCommunicateBufferHob = GET_GUID_HOB_DATA (GuidHob); + MemoryAddress = Tcg2AcpiCommunicateBufferHob->Tcg2AcpiCommunicateBuffer; + ASSERT (MemoryAddress != 0); + ASSERT (EFI_PAGES_TO_SIZE (Tcg2AcpiCommunicateBufferHob->Pages) >= Size); + ZeroMem ((VOID *)(UINTN)MemoryAddress, Size); OpRegion->RegionOffset = (UINT32)(UINTN)MemoryAddress; OpRegion->RegionLen = (UINT8)Size; - // Request to unblock this region from MM core - Status = MmUnblockMemoryRequest (MemoryAddress, EFI_SIZE_TO_PAGES (Size)); - if ((Status != EFI_UNSUPPORTED) && EFI_ERROR (Status)) { - ASSERT_EFI_ERROR (Status); - } break; } diff --git a/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.inf b/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.inf index f1c6ae5b1cb4..d7686251f4e8 100644 --- a/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.inf +++ b/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.inf @@ -22,7 +22,7 @@ # This driver will have external input - variable and ACPINvs data in SMM mode. # This external input must be validated carefully to avoid security issue. # -# Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2015 - 2024, Intel Corporation. All rights reserved.
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -57,12 +57,13 @@ Tpm2CommandLib Tcg2PhysicalPresenceLib PcdLib - MmUnblockMemoryLib + HobLib [Guids] gEfiTpmDeviceInstanceTpm20DtpmGuid ## PRODUCES ## GUID # TPM device identifier gTpmNvsMmGuid ## CONSUMES gEdkiiPiSmmCommunicationRegionTableGuid ## CONSUMES + gEdkiiTcg2AcpiCommunicateBufferHobGuid [Protocols] gEfiAcpiTableProtocolGuid ## CONSUMES From b2216427ca7b0d31a36616e2876d362629de926d Mon Sep 17 00:00:00 2001 From: Leif Lindholm Date: Tue, 2 Jul 2024 09:58:23 +0100 Subject: [PATCH 25/67] EmbeddedPkg/.ci.yaml: add temporary workaround ECC exception A new contributor has a name not describable by the character set developed for 1960s US teleprinters, causing the CI to object and blocking their code from being merged due to the copyright statement. While we do want to keep the code clean from characters other contributors cannot trivially reproduce, this should not extend to requiring intentionally misstating legal claims. Until we figure out the long-term fix, add an exception for the surname triggering the failure. Signed-off-by: Leif Lindholm --- EmbeddedPkg/EmbeddedPkg.ci.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/EmbeddedPkg/EmbeddedPkg.ci.yaml b/EmbeddedPkg/EmbeddedPkg.ci.yaml index 6d042fc721ab..f4956e679d88 100644 --- a/EmbeddedPkg/EmbeddedPkg.ci.yaml +++ b/EmbeddedPkg/EmbeddedPkg.ci.yaml @@ -20,6 +20,7 @@ ## "", "" ## ] "ExceptionList": [ + "1008", "Bălănică" ], ## Both file path and directory path are accepted. "IgnoreFiles": [] From ff1c4fa1680d3f9a5f2be3e0048d2de15a5846fb Mon Sep 17 00:00:00 2001 From: Dionna Glaze Date: Thu, 6 Jun 2024 17:33:45 +0000 Subject: [PATCH 26/67] MdePkg: UefiTcgPlatform.h updates The TCG_Sp800_155_PlatformId_Event2 and 3 structures both list the platform model string twice, which is incorrect according to the TCG PC Client Platform Firmware Profile. Also add constant definitions for the locator types added in the December 2023 revision. Signed-off-by: Dionna Glaze --- .../Include/IndustryStandard/UefiTcgPlatform.h | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/MdePkg/Include/IndustryStandard/UefiTcgPlatform.h b/MdePkg/Include/IndustryStandard/UefiTcgPlatform.h index aaee5d6c8842..1b7b2406e9dd 100644 --- a/MdePkg/Include/IndustryStandard/UefiTcgPlatform.h +++ b/MdePkg/Include/IndustryStandard/UefiTcgPlatform.h @@ -473,8 +473,6 @@ typedef struct tdTCG_Sp800_155_PlatformId_Event2 { // UINT8 PlatformModel[PlatformModelSize]; // UINT8 PlatformVersionSize; // UINT8 PlatformVersion[PlatformVersionSize]; - // UINT8 PlatformModelSize; - // UINT8 PlatformModel[PlatformModelSize]; // UINT8 FirmwareManufacturerStrSize; // UINT8 FirmwareManufacturerStr[FirmwareManufacturerStrSize]; // UINT32 FirmwareManufacturerId; @@ -499,8 +497,6 @@ typedef struct tdTCG_Sp800_155_PlatformId_Event3 { // UINT8 PlatformModel[PlatformModelSize]; // UINT8 PlatformVersionSize; // UINT8 PlatformVersion[PlatformVersionSize]; - // UINT8 PlatformModelSize; - // UINT8 PlatformModel[PlatformModelSize]; // UINT8 FirmwareManufacturerStrSize; // UINT8 FirmwareManufacturerStr[FirmwareManufacturerStrSize]; // UINT32 FirmwareManufacturerId; @@ -517,6 +513,18 @@ typedef struct tdTCG_Sp800_155_PlatformId_Event3 { // UINT8 PlatformCertLocator[PlatformCertLocatorLength]; } TCG_Sp800_155_PlatformId_Event3; +/** + * TCG specifies a locator type with the following values + * 0 - Raw data in the locator itself. + * 1 - URI in rtf2396 format. + * 2 - local device path in EFI_DEVICE_PATH_PROTOCOL format. + * 3 - UEFI variable (16 byte EFI_GUID, then 00-terminated UCS2 string) +**/ +#define TCG_LOCATOR_TYPE_RAW_DATA 0 +#define TCG_LOCATOR_TYPE_URI 1 +#define TCG_LOCATOR_TYPE_DEVICE_PATH 2 +#define TCG_LOCATOR_TYPE_UEFI_VARIABLE 3 + #define TCG_EfiStartupLocalityEvent_SIGNATURE "StartupLocality" // From 6b256cef01825fd597ce31ec9343ea280c6114c9 Mon Sep 17 00:00:00 2001 From: Dionna Glaze Date: Tue, 4 Jun 2024 17:22:53 +0000 Subject: [PATCH 27/67] OvmfPkg: Create SP800155 HOBs from QemuFwCfgFile Signed firmware measurements are allowed to be passed along to in the TCG and CC event logs according to the TCG PC Client Platform Firware Profile. The event logs include events that Tcg2Dxe reads from appropriately GUIDed HOBs, so allow opt/org.tianocode/sp800155evt/%d to pass along events that the VMM sees fit to provide. One event per number, starting from 0, increasing by 1 until there are no more contiguous files. The VMM may provide reference measurements through UEFI variables that it references from the SP800-155 event3 structure given the appropriate RIM locator type, or via URL, etc. Each event read from fw_cfg, is written one-by-one to a EFI_HOB_GUID_TYPE HOB created for the event. The name they target gTcg800155PlatformIdEventHobGuid for the later Dxe driver to use to extend the event log. Signed-off-by: Dionna Glaze --- OvmfPkg/PlatformPei/Platform.c | 2 + OvmfPkg/PlatformPei/PlatformId.c | 124 ++++++++++++++++++++++++++++ OvmfPkg/PlatformPei/PlatformId.h | 26 ++++++ OvmfPkg/PlatformPei/PlatformPei.inf | 4 +- 4 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 OvmfPkg/PlatformPei/PlatformId.c create mode 100644 OvmfPkg/PlatformPei/PlatformId.h diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c index df35726ff650..0114529778e5 100644 --- a/OvmfPkg/PlatformPei/Platform.c +++ b/OvmfPkg/PlatformPei/Platform.c @@ -40,6 +40,7 @@ #include #include "Platform.h" +#include "PlatformId.h" EFI_PEI_PPI_DESCRIPTOR mPpiBootMode[] = { { @@ -363,6 +364,7 @@ InitializePlatform ( MiscInitializationForMicrovm (PlatformInfoHob); } else { MiscInitialization (PlatformInfoHob); + PlatformIdInitialization (PeiServices); } IntelTdxInitialize (); diff --git a/OvmfPkg/PlatformPei/PlatformId.c b/OvmfPkg/PlatformPei/PlatformId.c new file mode 100644 index 000000000000..afa2f811d9c2 --- /dev/null +++ b/OvmfPkg/PlatformPei/PlatformId.c @@ -0,0 +1,124 @@ +/**@file + PlatformId Event HOB creation + + Copyright (c) 2024, Google LLC. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DPREFIX "sp800155evts: " + +/** + * Creates an EFI_HOB_TYPE_GUID_EXTENSION HOB for a given SP800155 event. + * Associates the string data with gTcg800155PlatformIdEventHobGuid. Any + * unused bytes or out-of-bounds event sizes are considered corrupted and + * are discarded. +**/ +STATIC +VOID +PlatformIdRegisterSp800155 ( + IN CONST EFI_PEI_SERVICES **PeiServices, + IN UINT8 *Evt, + IN UINTN EvtSize + ) +{ + EFI_STATUS Status; + VOID *Hob; + EFI_HOB_GUID_TYPE *GuidHob; + UINT8 *EvtDest; + + Status = (*PeiServices)->CreateHob ( + PeiServices, + EFI_HOB_TYPE_GUID_EXTENSION, + sizeof (EFI_HOB_GUID_TYPE) + (UINT16)EvtSize, + &Hob + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, DPREFIX "GUID HOB creation failed, skipping\n")); + return; + } + + GuidHob = (EFI_HOB_GUID_TYPE *)Hob; + CopyGuid (&GuidHob->Name, &gTcg800155PlatformIdEventHobGuid); + EvtDest = (UINT8 *)GET_GUID_HOB_DATA (Hob); + CopyMem (EvtDest, Evt, EvtSize); + // Fill the remaining HOB padding bytes with 0s. + SetMem (EvtDest + EvtSize, GET_GUID_HOB_DATA_SIZE (Hob) - EvtSize, 0); +} + +/** + * Reads the given path from the fw_cfg file and registers it as an + * EFI_HOB_GUID_EXTENSION HOB with gTcg800155PlatformIdEventHobGuid. + * Returns FALSE iff the file does not exist. +**/ +BOOLEAN +PlatformIdRegisterEvent ( + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST CHAR8 *Path + ) +{ + EFI_STATUS Status; + UINTN NumPages; + EFI_PHYSICAL_ADDRESS Pages; + FIRMWARE_CONFIG_ITEM FdtItem; + UINTN FdtSize; + UINT8 *Evt; + + Status = QemuFwCfgFindFile (Path, &FdtItem, &FdtSize); + if (EFI_ERROR (Status)) { + return FALSE; + } + + if (FdtSize > MAX_UINT16 - sizeof (EFI_HOB_GUID_TYPE)) { + DEBUG ((DEBUG_ERROR, DPREFIX "Eventdata too large for HOB, skipping\n")); + return TRUE; + } + + NumPages = EFI_SIZE_TO_PAGES (FdtSize); + Status = (*PeiServices)->AllocatePages ( + PeiServices, + EfiBootServicesData, + NumPages, + &Pages + ); + if (EFI_ERROR (Status)) { + return TRUE; + } + + Evt = (UINT8 *)(UINTN)Pages; + QemuFwCfgSelectItem (FdtItem); + QemuFwCfgReadBytes (FdtSize, Evt); + PlatformIdRegisterSp800155 (PeiServices, Evt, FdtSize); + + Status = (*PeiServices)->FreePages (PeiServices, Pages, NumPages); + ASSERT_EFI_ERROR (Status); + return TRUE; +} + +VOID +PlatformIdInitialization ( + IN CONST EFI_PEI_SERVICES **PeiServices + ) +{ + UINTN Index; + CHAR8 Path[64]; + + for (Index = 0; ; Index++) { + AsciiSPrint (Path, sizeof (Path), "opt/org.tianocode/sp800155evt/%d", Index); + if (!PlatformIdRegisterEvent (PeiServices, Path)) { + break; + } + } +} diff --git a/OvmfPkg/PlatformPei/PlatformId.h b/OvmfPkg/PlatformPei/PlatformId.h new file mode 100644 index 000000000000..c8b55288c454 --- /dev/null +++ b/OvmfPkg/PlatformPei/PlatformId.h @@ -0,0 +1,26 @@ +/** @file + PlatformId internal header for PlatformPei + + Copyright (c) 2024, Google LLC. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __PLATFORM_PEI_PLATFORMID_H__ +#define __PLATFORM_PEI_PLATFORMID_H__ + +/** + * Reads opt/org.tianocode/sp800155evt/%d from 0 to the first positive integer + * where the file does not exist and registers each file's contents in an + * EFI_HOB_GUID_TYPE with name gTcg800155PlatformIdEventHobGuid. These HOBs + * are used by a later driver to write to the event log as unmeasured events. + * These events inform the event log analyzer of firmware provenance and + * reference integrity manifests. +**/ +VOID +PlatformIdInitialization ( + IN CONST EFI_PEI_SERVICES **PeiServices + ); + +#endif // __PLATFORM_PEI_PLATFORMID_H__ diff --git a/OvmfPkg/PlatformPei/PlatformPei.inf b/OvmfPkg/PlatformPei/PlatformPei.inf index e036018eab39..0bb1a4629101 100644 --- a/OvmfPkg/PlatformPei/PlatformPei.inf +++ b/OvmfPkg/PlatformPei/PlatformPei.inf @@ -31,6 +31,8 @@ MemTypeInfo.c Platform.c Platform.h + PlatformId.c + PlatformId.h IntelTdx.c SmmRelocation.c @@ -47,6 +49,7 @@ gFdtHobGuid gUefiOvmfPkgPlatformInfoGuid gGhcbApicIdsGuid + gTcg800155PlatformIdEventHobGuid ## SOMETIMES_PRODUCES [LibraryClasses] BaseLib @@ -148,4 +151,3 @@ [Depex] TRUE - From 4f174696fd8fbd9cc29c9f172e8e83fe6da5b070 Mon Sep 17 00:00:00 2001 From: Joey Vagedes Date: Thu, 27 Jun 2024 08:43:48 -0700 Subject: [PATCH 28/67] .pytool: CompilerPlugin: Pass through build vars Pass build variables (those passed to build.py through -D) to the DSC parser to provide a more accurate parsing of the DSC file. Signed-off-by: Joey Vagedes --- .pytool/Plugin/CompilerPlugin/CompilerPlugin.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.pytool/Plugin/CompilerPlugin/CompilerPlugin.py b/.pytool/Plugin/CompilerPlugin/CompilerPlugin.py index 3cf3888828c0..01101b2f4a8c 100644 --- a/.pytool/Plugin/CompilerPlugin/CompilerPlugin.py +++ b/.pytool/Plugin/CompilerPlugin/CompilerPlugin.py @@ -74,9 +74,10 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, self._env.SetValue("ACTIVE_PLATFORM", AP_Path, "Set in Compiler Plugin") # Parse DSC to check for SUPPORTED_ARCHITECTURES + build_target = self._env.GetValue("TARGET") + input_vars = self._env.GetAllBuildKeyValues(build_target) dp = DscParser() - dp.SetBaseAbsPath(Edk2pathObj.WorkspacePath) - dp.SetPackagePaths(Edk2pathObj.PackagePathList) + dp.SetEdk2Path(Edk2pathObj).SetInputVars(input_vars) dp.ParseFile(AP_Path) if "SUPPORTED_ARCHITECTURES" in dp.LocalVars: SUPPORTED_ARCHITECTURES = dp.LocalVars["SUPPORTED_ARCHITECTURES"].split('|') @@ -85,7 +86,7 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, # Skip if there is no intersection between SUPPORTED_ARCHITECTURES and TARGET_ARCHITECTURES if len(set(SUPPORTED_ARCHITECTURES) & set(TARGET_ARCHITECTURES)) == 0: tc.SetSkipped() - tc.LogStdError("No supported architecutres to build") + tc.LogStdError("No supported architectures to build") return -1 uefiBuilder = UefiBuilder() From ed07a2bb11b358fdece44a760fc193d56f22cfb2 Mon Sep 17 00:00:00 2001 From: Britton Chesley Date: Tue, 16 May 2023 15:40:50 -0500 Subject: [PATCH 29/67] MdeModulePkg/UsbBusDxe: USB issue fix when the port reset BZ #4456 Fixed a bug which led to an ASSERT due to the USB device context being maintained after a port reset, but the underlying XHCI context was uninitialized. Specifically, Xhc->UsbDevContext is freed after a reset and only re-allocates the default [0] enpoint transfer ring. In order to avoid a memory leak, device enumeration is performed after freeing the necessary buffers. This allocates the Xhc->UsbDevContext for all endpoints of the USB device. Signed-off-by: Britton Chesley --- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c | 27 ++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c index c25f3cc2f279..2826ac130ef7 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c @@ -3,6 +3,7 @@ Usb Bus Driver Binding and Bus IO Protocol. Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.
+Copyright (C) 2024 Advanced Micro Devices, Inc. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -821,6 +822,7 @@ UsbIoPortReset ( EFI_TPL OldTpl; EFI_STATUS Status; UINT8 DevAddress; + UINT8 Config; OldTpl = gBS->RaiseTPL (USB_BUS_TPL); @@ -882,8 +884,26 @@ UsbIoPortReset ( // is in CONFIGURED state. // if (Dev->ActiveConfig != NULL) { - Status = UsbSetConfig (Dev, Dev->ActiveConfig->Desc.ConfigurationValue); + UsbFreeDevDesc (Dev->DevDesc); + Status = UsbRemoveConfig (Dev); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "UsbIoPortReset: Failed to remove configuration - %r\n", Status)); + } + + Status = UsbGetMaxPacketSize0 (Dev); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "UsbIoPortReset: Failed to get max packet size - %r\n", Status)); + } + + Status = UsbBuildDescTable (Dev); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "UsbIoPortReset: Failed to build descriptor table - %r\n", Status)); + } + + Config = Dev->DevDesc->Configs[0]->Desc.ConfigurationValue; + + Status = UsbSetConfig (Dev, Config); if (EFI_ERROR (Status)) { DEBUG (( DEBUG_ERROR, @@ -892,6 +912,11 @@ UsbIoPortReset ( Status )); } + + Status = UsbSelectConfig (Dev, Config); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "UsbIoPortReset: Failed to set configuration - %r\n", Status)); + } } ON_EXIT: From 592725d2291b9844cfd9187111e904c6383e2000 Mon Sep 17 00:00:00 2001 From: Joey Vagedes Date: Tue, 25 Jun 2024 10:11:06 -0700 Subject: [PATCH 30/67] DscCompleteCheck: Allow git ignore syntax Allows ignore lines in the CI YAML file to use git ignore syntax. This is especially useful for ignore files recursively in directories like those that may exist in an external dependency folder. Co-authored-by: Michael Kubacki Signed-off-by: Joey Vagedes --- .../DscCompleteCheck/DscCompleteCheck.py | 53 +++++++++++++------ .pytool/Plugin/DscCompleteCheck/Readme.md | 3 +- 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py index 351137c5e4b7..14f99330f6fd 100644 --- a/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py +++ b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py @@ -6,9 +6,12 @@ import logging import os from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin +from edk2toollib.uefi.edk2.path_utilities import Edk2Path from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser from edk2toollib.uefi.edk2.parsers.inf_parser import InfParser from edk2toolext.environment.var_dict import VarDict +from edk2toollib.gitignore_parser import parse_gitignore_lines +from pathlib import Path class DscCompleteCheck(ICiBuildPlugin): @@ -71,38 +74,39 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, # Get INF Files INFFiles = self.WalkDirectoryForExtension([".inf"], abs_pkg_path) - INFFiles = [Edk2pathObj.GetEdk2RelativePathFromAbsolutePath( - x) for x in INFFiles] # make edk2relative path so can compare with DSC # remove ignores - + ignored_paths = [] if "IgnoreInf" in pkgconfig: - for a in pkgconfig["IgnoreInf"]: - a = a.replace(os.sep, "/") + ignore_filter = parse_gitignore_lines( + pkgconfig["IgnoreInf"], + "DSC Complete Check Config", + os.path.dirname(abs_pkg_path)) + + # INFFiles must be a list of absolute paths + ignored_paths = list(filter(ignore_filter, INFFiles)) + for a in ignored_paths: try: tc.LogStdOut("Ignoring INF {0}".format(a)) INFFiles.remove(a) - except: + except Exception: tc.LogStdError( "DscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) logging.info( "DscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + # make edk2relative path so can compare with DSC + INFFiles = [Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(x) for x in INFFiles] + # DSC Parser - dp = DscParser() - dp.SetBaseAbsPath(Edk2pathObj.WorkspacePath) - dp.SetPackagePaths(Edk2pathObj.PackagePathList) + dp = DscParser().SetEdk2Path(Edk2pathObj) dp.SetInputVars(environment.GetAllBuildKeyValues()) dp.ParseFile(wsr_dsc_path) # Check if INF in component section for INF in INFFiles: - if not any(INF.strip() in x for x in dp.ThreeMods) and \ - not any(INF.strip() in x for x in dp.SixMods) and \ - not any(INF.strip() in x for x in dp.OtherMods): - - infp = InfParser().SetBaseAbsPath(Edk2pathObj.WorkspacePath) - infp.SetPackagePaths(Edk2pathObj.PackagePathList) + if not DscCompleteCheck._module_in_dsc(INF, dp, Edk2pathObj): + infp = InfParser().SetEdk2Path(Edk2pathObj) infp.ParseFile(INF) if("MODULE_TYPE" not in infp.Dict): tc.LogStdOut( @@ -131,3 +135,22 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, else: tc.SetSuccess() return overall_status + + @staticmethod + def _module_in_dsc(inf: str, dsc: DscParser, Edk2pathObj: Edk2Path) -> bool: + + """Checks if the given module (inf) is in the given dsc. + Args: + inf (str): The inf file to check for + dsc (DscParser): The parsed dsc file. + Edk2pathObj (Edk2Path): The path object capturing the workspace and package paths. + Returns: + bool: if the module is in the dsc. + """ + for module_type in (dsc.ThreeMods, dsc.SixMods, dsc.OtherMods): + for module in module_type: + if Path(module).is_absolute(): + module = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(module) + if inf in module: + return True + return False diff --git a/.pytool/Plugin/DscCompleteCheck/Readme.md b/.pytool/Plugin/DscCompleteCheck/Readme.md index 8aaa4f76ee0a..9f7291b7474a 100644 --- a/.pytool/Plugin/DscCompleteCheck/Readme.md +++ b/.pytool/Plugin/DscCompleteCheck/Readme.md @@ -29,4 +29,5 @@ Path to DSC to consider platform dsc ### IgnoreInf -Ignore error if Inf file is not listed in DSC file +A list of paths in git ignore syntax to ignore in the check. These can include directory and file paths. The path is +relative to the directory that contains the package. From 6b9307192bf590b3136e690a07196d4255051fdc Mon Sep 17 00:00:00 2001 From: Joey Vagedes Date: Tue, 12 Mar 2024 14:18:14 -0700 Subject: [PATCH 31/67] BaseTools: InfBuildData: Fix Private value retrieval Update retrieval of private guids, protocols, or ppis from a package's declaration file to use the original path of the module's INF file rather than the current path. When building the same module multiple times in the same INF (by override the define's FILE_GUID), a temporary instance of the module is generated outside the package, causing the retrieval of private values to fail as the check to access private values is done by verifying the module to build, is inside the package. Signed-off-by: Joey Vagedes Cc: Rebecca Cran Cc: Liming Gao Cc: Bob Feng Cc: Yuwei Chen --- BaseTools/Source/Python/Workspace/InfBuildData.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/BaseTools/Source/Python/Workspace/InfBuildData.py b/BaseTools/Source/Python/Workspace/InfBuildData.py index e4ff1c668666..6339e494ca87 100644 --- a/BaseTools/Source/Python/Workspace/InfBuildData.py +++ b/BaseTools/Source/Python/Workspace/InfBuildData.py @@ -592,7 +592,7 @@ def Protocols(self): RecordList = self._RawData[MODEL_EFI_PROTOCOL, self._Arch, self._Platform] for Record in RecordList: CName = Record[0] - Value = _ProtocolValue(CName, self.Packages, self.MetaFile.Path) + Value = _ProtocolValue(CName, self.Packages, self.MetaFile.OriginalPath.Path) if Value is None: PackageList = "\n\t".join(str(P) for P in self.Packages) EdkLogger.error('build', RESOURCE_NOT_AVAILABLE, @@ -616,7 +616,7 @@ def Ppis(self): RecordList = self._RawData[MODEL_EFI_PPI, self._Arch, self._Platform] for Record in RecordList: CName = Record[0] - Value = _PpiValue(CName, self.Packages, self.MetaFile.Path) + Value = _PpiValue(CName, self.Packages, self.MetaFile.OriginalPath.Path) if Value is None: PackageList = "\n\t".join(str(P) for P in self.Packages) EdkLogger.error('build', RESOURCE_NOT_AVAILABLE, @@ -640,7 +640,7 @@ def Guids(self): RecordList = self._RawData[MODEL_EFI_GUID, self._Arch, self._Platform] for Record in RecordList: CName = Record[0] - Value = GuidValue(CName, self.Packages, self.MetaFile.Path) + Value = GuidValue(CName, self.Packages, self.MetaFile.OriginalPath.Path) if Value is None: PackageList = "\n\t".join(str(P) for P in self.Packages) EdkLogger.error('build', RESOURCE_NOT_AVAILABLE, @@ -655,7 +655,7 @@ def Guids(self): for TokenSpaceGuid, _, _, _, _, _, LineNo in RecordList: # get the guid value if TokenSpaceGuid not in RetVal: - Value = GuidValue(TokenSpaceGuid, self.Packages, self.MetaFile.Path) + Value = GuidValue(TokenSpaceGuid, self.Packages, self.MetaFile.OriginalPath.Path) if Value is None: PackageList = "\n\t".join(str(P) for P in self.Packages) EdkLogger.error('build', RESOURCE_NOT_AVAILABLE, @@ -818,11 +818,11 @@ def Depex(self): Value = Token else: # get the GUID value now - Value = _ProtocolValue(Token, self.Packages, self.MetaFile.Path) + Value = _ProtocolValue(Token, self.Packages, self.MetaFile.OriginalPath.Path) if Value is None: - Value = _PpiValue(Token, self.Packages, self.MetaFile.Path) + Value = _PpiValue(Token, self.Packages, self.MetaFile.OriginalPath.Path) if Value is None: - Value = GuidValue(Token, self.Packages, self.MetaFile.Path) + Value = GuidValue(Token, self.Packages, self.MetaFile.OriginalPath.Path) if Value is None: PackageList = "\n\t".join(str(P) for P in self.Packages) From 4f73eef8383f423be0fef1d1e66cd897a5367cd3 Mon Sep 17 00:00:00 2001 From: Mike Maslenkin Date: Fri, 16 Feb 2024 15:49:27 +0300 Subject: [PATCH 32/67] MdeModulePkg/NvmExpressDxe: fix format used for Eui64 conversion Eui64 is a 64 bit value, so the "L" or "l" is required for format specifier, otherwise only lower 32 bit will be converted. Signed-off-by: Mike Maslenkin Reviewed-by: Laszlo Ersek --- MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c index dea14f1a446c..dfa3653d6a5e 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c @@ -300,7 +300,7 @@ EnumerateNvmeDevNamespace ( Sn[20] = 0; CopyMem (Mn, Private->ControllerData->Mn, sizeof (Private->ControllerData->Mn)); Mn[40] = 0; - UnicodeSPrintAsciiFormat (Device->ModelName, sizeof (Device->ModelName), "%a-%a-%x", Sn, Mn, NamespaceData->Eui64); + UnicodeSPrintAsciiFormat (Device->ModelName, sizeof (Device->ModelName), "%a-%a-%lx", Sn, Mn, NamespaceData->Eui64); AddUnicodeString2 ( "eng", From 4e36bed8128f67fc73f41acb1beaffd77ef76e90 Mon Sep 17 00:00:00 2001 From: Mike Maslenkin Date: Fri, 16 Feb 2024 17:17:53 +0300 Subject: [PATCH 33/67] MdeModulePkg/NvmExpressDxe: use format "0x%lx" for UINT64 values. Signed-off-by: Mike Maslenkin Reviewed-by: Laszlo Ersek --- MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c index dfa3653d6a5e..069da12a9b1b 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c @@ -288,9 +288,9 @@ EnumerateNvmeDevNamespace ( // Dump NvmExpress Identify Namespace Data // DEBUG ((DEBUG_INFO, " == NVME IDENTIFY NAMESPACE [%d] DATA ==\n", NamespaceId)); - DEBUG ((DEBUG_INFO, " NSZE : 0x%x\n", NamespaceData->Nsze)); - DEBUG ((DEBUG_INFO, " NCAP : 0x%x\n", NamespaceData->Ncap)); - DEBUG ((DEBUG_INFO, " NUSE : 0x%x\n", NamespaceData->Nuse)); + DEBUG ((DEBUG_INFO, " NSZE : 0x%lx\n", NamespaceData->Nsze)); + DEBUG ((DEBUG_INFO, " NCAP : 0x%lx\n", NamespaceData->Ncap)); + DEBUG ((DEBUG_INFO, " NUSE : 0x%lx\n", NamespaceData->Nuse)); DEBUG ((DEBUG_INFO, " LBAF0.LBADS : 0x%x\n", (NamespaceData->LbaFormat[0].Lbads))); // From cdffb638c85da87f6b9d61194513a24cd6a73c6a Mon Sep 17 00:00:00 2001 From: Tobin Feldman-Fitzthum Date: Wed, 26 Jun 2024 18:42:45 +0000 Subject: [PATCH 34/67] AmdSev: enable kernel hashes without initrd If kernel hashes are enabled but no initrd is provided, QEMU will still create an entry in the hash table, but it will be the hash of an empty buffer. Remove the explicit check for the length of the blob. This logic will be handled by the later hash comparison, which will still fail when the blob is not present but is expected, but will pass when the blob is not present and the hash table contains a hash of an empty buffer. Signed-off-by: Tobin Feldman-Fitzthum --- .../BlobVerifierLibSevHashes/BlobVerifierSevHashes.c | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/OvmfPkg/AmdSev/BlobVerifierLibSevHashes/BlobVerifierSevHashes.c b/OvmfPkg/AmdSev/BlobVerifierLibSevHashes/BlobVerifierSevHashes.c index bc2d5daadc23..7bc9f89007c0 100644 --- a/OvmfPkg/AmdSev/BlobVerifierLibSevHashes/BlobVerifierSevHashes.c +++ b/OvmfPkg/AmdSev/BlobVerifierLibSevHashes/BlobVerifierSevHashes.c @@ -156,16 +156,6 @@ VerifyBlob ( DEBUG ((DEBUG_INFO, "%a: Found GUID %g in table\n", __func__, Guid)); - if (BufSize == 0) { - DEBUG (( - DEBUG_ERROR, - "%a: Blob Specified in Hash Table was not Provided", - __func__ - )); - - CpuDeadLoop (); - } - EntrySize = Entry->Len - sizeof Entry->Guid - sizeof Entry->Len; if (EntrySize != SHA256_DIGEST_SIZE) { DEBUG (( From 8430c69dc1d92085c3ef22370bfbb4d41ef2e94c Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 2 Jul 2024 15:05:05 -0400 Subject: [PATCH 35/67] MdePkg/Nvme.h: Add missing NVMe capability descriptions Most of the definitions in this file are currently well documented. This adds documentation for a few missing fields in the NVMe Controller Capabilities structure. Signed-off-by: Michael Kubacki --- MdePkg/Include/IndustryStandard/Nvme.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/MdePkg/Include/IndustryStandard/Nvme.h b/MdePkg/Include/IndustryStandard/Nvme.h index c190d678e1bd..2a94e2120310 100644 --- a/MdePkg/Include/IndustryStandard/Nvme.h +++ b/MdePkg/Include/IndustryStandard/Nvme.h @@ -54,16 +54,16 @@ typedef struct { UINT8 Cqr : 1; // Contiguous Queues Required UINT8 Ams : 2; // Arbitration Mechanism Supported UINT8 Rsvd1 : 5; - UINT8 To; // Timeout - UINT16 Dstrd : 4; + UINT8 To; // Timeout + UINT16 Dstrd : 4; // Doorbell Stride UINT16 Nssrs : 1; // NVM Subsystem Reset Supported NSSRS UINT16 Css : 8; // Command Sets Supported - Bit 37 UINT16 Bps : 1; // Boot Partition Support - Bit 45 in NVMe1.4 UINT16 Rsvd3 : 2; - UINT8 Mpsmin : 4; - UINT8 Mpsmax : 4; - UINT8 Pmrs : 1; - UINT8 Cmbs : 1; + UINT8 Mpsmin : 4; // Memory Page Size Minimum + UINT8 Mpsmax : 4; // Memory Page Size Maximum + UINT8 Pmrs : 1; // Persistent Memory Region Supported + UINT8 Cmbs : 1; // Controller Memory Buffer Supported UINT8 Rsvd4 : 6; } NVME_CAP; From 6852f6984bdab86a1662e89e1ef0f3abc39559b6 Mon Sep 17 00:00:00 2001 From: Chun-Yi Lee Date: Fri, 12 Apr 2024 15:07:33 +0800 Subject: [PATCH 36/67] EmbeddedPkg/VirtualRealTimeClockLib: Support SOURCE_DATE_EPOCH RISC-V ovmf used VirtualRealTimeClockLib but the default epoch is a compilation time. It causes that the RISC-V ovmf binary image is NOT reproducible. This patch added the support of SOURCE_DATE_EPOCH by printenv command. If SOURCE_DATE_EPOCH be found then we use it as BUILD_EPOCH. Otherwise we run date command for setting BUILD_EPOCH. For distributions want a reproducible RISC-V ovmf image, they should export SOURCE_DATE_EPOCH environment variable before building ovmf. References: https://reproducible-builds.org/docs/source-date-epoch/ Cc: Pete Batard Cc: Ard Biesheuvel Signed-off-by: "Lee, Chun-Yi" --- .../Library/VirtualRealTimeClockLib/VirtualRealTimeClockLib.inf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/EmbeddedPkg/Library/VirtualRealTimeClockLib/VirtualRealTimeClockLib.inf b/EmbeddedPkg/Library/VirtualRealTimeClockLib/VirtualRealTimeClockLib.inf index 5d0f867eb6e0..285e880daab8 100644 --- a/EmbeddedPkg/Library/VirtualRealTimeClockLib/VirtualRealTimeClockLib.inf +++ b/EmbeddedPkg/Library/VirtualRealTimeClockLib/VirtualRealTimeClockLib.inf @@ -34,4 +34,4 @@ # Current usage of this library expects GCC in a UNIX-like shell environment with the date command [BuildOptions] - GCC:*_*_*_CC_FLAGS = -DBUILD_EPOCH=`date +%s` + GCC:*_*_*_CC_FLAGS = -DBUILD_EPOCH=`printenv SOURCE_DATE_EPOCH || date +%s` From bc3a1ec2a2838f596678ddd247d10332c6790dab Mon Sep 17 00:00:00 2001 From: Alexey Kardashevskiy Date: Tue, 22 Nov 2022 13:18:41 +1100 Subject: [PATCH 37/67] MdePkg/Register/Amd: Define all bits from MSR_SEV_STATUS_REGISTER For now we need DebugSwap but others are likely to be needed too. Cc: Liming Gao Cc: Michael D Kinney Cc: Zhiguang Liu Reviewed-by: Tom Lendacky Signed-off-by: Alexey Kardashevskiy Changes: v5: * "rb" from Tom v4: * added more from April/2024 APM --- MdePkg/Include/Register/Amd/SevSnpMsr.h | 95 +++++++++++++++++++++++-- 1 file changed, 91 insertions(+), 4 deletions(-) diff --git a/MdePkg/Include/Register/Amd/SevSnpMsr.h b/MdePkg/Include/Register/Amd/SevSnpMsr.h index 1b8fbc1978f2..5187f965a66a 100644 --- a/MdePkg/Include/Register/Amd/SevSnpMsr.h +++ b/MdePkg/Include/Register/Amd/SevSnpMsr.h @@ -126,19 +126,106 @@ typedef union { /// /// [Bit 0] Secure Encrypted Virtualization (Sev) is enabled /// - UINT32 SevBit : 1; + UINT32 SevBit : 1; /// /// [Bit 1] Secure Encrypted Virtualization Encrypted State (SevEs) is enabled /// - UINT32 SevEsBit : 1; + UINT32 SevEsBit : 1; /// /// [Bit 2] Secure Nested Paging (SevSnp) is enabled /// - UINT32 SevSnpBit : 1; + UINT32 SevSnpBit : 1; - UINT32 Reserved2 : 29; + /// + /// [Bit 3] Virtual TOM feature is enabled in SEV_FEATURES[1] + /// + UINT32 vTOM : 1; + + /// + /// [Bit 4] ReflectVC feature is enabled in SEV_FEATURES[2] + /// + UINT32 ReflectVC : 1; + + /// + /// [Bit 5] Restricted Injection feature is enabled in SEV_FEATURES[3] + /// + UINT32 RestrictedInjection : 1; + + /// + /// [Bit 6] Alternate Injection feature is enabled in SEV_FEATURES[4] + /// + UINT32 AlternateInjection : 1; + + /// + /// [Bit 7] Debug Virtualization feature is enabled in SEV_FEATURES[5] + /// + UINT32 DebugVirtualization : 1; + + /// + /// [Bit 8] PreventHostIBS feature is enabled in SEV_FEATURES[6] + /// + UINT32 PreventHostIBS : 1; + + /// + /// [Bit 9] BTB isolation feature is enabled in SEV_FEATURES[7] + /// + UINT32 SNPBTBIsolation : 1; + + /// + /// [Bit 10] VMPL SSS feature is enabled in SEV_FEATURES[8] + /// + UINT32 VmplSSS : 1; + + /// + /// [Bit 11] Secure TSC feature is enabled in SEV_FEATURES[9] + /// + UINT32 SecureTsc : 1; + + /// + /// [Bit 12] VMGEXIT Parameter feature is enabled in SEV_FEATURES[10] + /// + UINT32 VmgexitParameter : 1; + + /// + /// [Bit 13] PMC Virtualization feature is enabled in SEV_FEATURES[11] + /// + UINT32 PmcVirtualization : 1; + + /// + /// [Bit 14] IBS Virtualization feature is enabled in SEV_FEATURES[12] + /// + UINT32 IbsVirtualization : 1; + + /// + /// [Bit 15] + /// + UINT32 Reserved1 : 1; + + /// + /// [Bit 16] VMSA Register Protection feature is enabled in SEV_FEATURES[14] + /// + UINT32 VmsaRegProt : 1; + + /// + /// [Bit 17] SMT Protection feature is enabled in SEV_FEATURES[15] + /// + UINT32 SmtProtection : 1; + /// + /// + /// [Bit 18] Secure AVIC feature is enabled in SEV_FEATURES[16] + /// + UINT32 SecureAVIC : 1; + + UINT32 Reserved2 : 4; + + /// + /// [Bit 23] IBPB on Entry feature is enabled in SEV_FEATURES[21] + /// + UINT32 IbpbOnEntry : 1; + + UINT32 Reserved3 : 8; } Bits; /// /// All bit fields as a 32-bit value From 3f28aa2fb07f57afa58d4030d6dc60f5d01d5888 Mon Sep 17 00:00:00 2001 From: Alexey Kardashevskiy Date: Tue, 22 Nov 2022 16:12:55 +1100 Subject: [PATCH 38/67] MdePkg: Add AMD SEV features to PcdConfidentialComputingGuestAttr PcdConfidentialComputingGuestAttr so far only contained an SEV mode bit but there are more other features which do not translate to levels such as DebugVirtualization or SecureTsc. Add the feature mask and the DebugVirtualization feature bit to the PCD. Cc: Liming Gao Cc: Michael D Kinney Cc: Zhiguang Liu Reviewed-by: Tom Lendacky Signed-off-by: Alexey Kardashevskiy --- Changes: v4: * s/CCAttrFeatureAmdSevDebugSwap/CCAttrFeatureAmdSevEsDebugVirtualization/ v2: * expanded features mask * added type mask --- MdePkg/Include/ConfidentialComputingGuestAttr.h | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/MdePkg/Include/ConfidentialComputingGuestAttr.h b/MdePkg/Include/ConfidentialComputingGuestAttr.h index 44e6df800207..f62158f77e03 100644 --- a/MdePkg/Include/ConfidentialComputingGuestAttr.h +++ b/MdePkg/Include/ConfidentialComputingGuestAttr.h @@ -29,9 +29,20 @@ typedef enum { /* The guest is running with Intel TDX memory encryption enabled. */ CCAttrIntelTdx = 0x200, + + CCAttrTypeMask = 0x000000000000ffff, + + /* Features */ + + /* The AMD SEV-ES DebugVirtualization feature is enabled in SEV_STATUS */ + CCAttrFeatureAmdSevEsDebugVirtualization = 0x0000000000010000, + + CCAttrFeatureMask = 0xffffffffffff0000, } CONFIDENTIAL_COMPUTING_GUEST_ATTR; -#define CC_GUEST_IS_TDX(x) ((x) == CCAttrIntelTdx) -#define CC_GUEST_IS_SEV(x) ((x) == CCAttrAmdSev || (x) == CCAttrAmdSevEs || (x) == CCAttrAmdSevSnp) +#define _CC_GUEST_IS_TDX(x) ((x) == CCAttrIntelTdx) +#define CC_GUEST_IS_TDX(x) _CC_GUEST_IS_TDX((x) & CCAttrTypeMask) +#define _CC_GUEST_IS_SEV(x) ((x) == CCAttrAmdSev || (x) == CCAttrAmdSevEs || (x) == CCAttrAmdSevSnp) +#define CC_GUEST_IS_SEV(x) _CC_GUEST_IS_SEV((x) & CCAttrTypeMask) #endif From 9f06feb5d2fa43e184690034e70e6d427cf6913d Mon Sep 17 00:00:00 2001 From: Alexey Kardashevskiy Date: Wed, 30 Nov 2022 19:41:12 +1100 Subject: [PATCH 39/67] OvmfPkg: Add AMD SEV-ES DebugVirtualization feature support The SEV-ES DebugVirtualization feature enables type B swapping of debug registers on #VMEXIT and makes #DB and DR7 intercepts unnecessary and unwanted. When DebugVirtualization is enabled, this stops booting if interaction from the HV. Add new API to PEI, SEC, DXE. This does not change the existing behaviour yet. Cc: Ard Biesheuvel Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: Jiewen Yao Cc: Michael Roth Cc: Min Xu Reviewed-by: Tom Lendacky Signed-off-by: Alexey Kardashevskiy --- Changes: v5: * "rb" from Tom v4: * s/DebugSwap/DebugVirtualization/ --- OvmfPkg/Include/Library/MemEncryptSevLib.h | 12 +++++++++ .../DxeMemEncryptSevLibInternal.c | 27 ++++++++++++++++--- .../PeiMemEncryptSevLibInternal.c | 15 +++++++++++ .../SecMemEncryptSevLibInternal.c | 15 +++++++++++ OvmfPkg/Library/CcExitLib/CcExitVcHandler.c | 8 ++++++ 5 files changed, 74 insertions(+), 3 deletions(-) diff --git a/OvmfPkg/Include/Library/MemEncryptSevLib.h b/OvmfPkg/Include/Library/MemEncryptSevLib.h index 4fa9c0d70083..c5653539d8d8 100644 --- a/OvmfPkg/Include/Library/MemEncryptSevLib.h +++ b/OvmfPkg/Include/Library/MemEncryptSevLib.h @@ -166,6 +166,18 @@ MemEncryptSevGetEncryptionMask ( VOID ); +/** + Returns a boolean to indicate whether DebugVirtualization is enabled. + + @retval TRUE DebugVirtualization is enabled + @retval FALSE DebugVirtualization is not enabled +**/ +BOOLEAN +EFIAPI +MemEncryptSevEsDebugVirtualizationIsEnabled ( + VOID + ); + /** Returns the encryption state of the specified virtual address range. diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptSevLibInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptSevLibInternal.c index 4aba0075b9e2..9947d663deae 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptSevLibInternal.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/DxeMemEncryptSevLibInternal.c @@ -40,19 +40,25 @@ AmdMemEncryptionAttrCheck ( IN CONFIDENTIAL_COMPUTING_GUEST_ATTR Attr ) { + UINT64 CurrentLevel; + + CurrentLevel = CurrentAttr & CCAttrTypeMask; + switch (Attr) { case CCAttrAmdSev: // // SEV is automatically enabled if SEV-ES or SEV-SNP is active. // - return CurrentAttr >= CCAttrAmdSev; + return CurrentLevel >= CCAttrAmdSev; case CCAttrAmdSevEs: // // SEV-ES is automatically enabled if SEV-SNP is active. // - return CurrentAttr >= CCAttrAmdSevEs; + return CurrentLevel >= CCAttrAmdSevEs; case CCAttrAmdSevSnp: - return CurrentAttr == CCAttrAmdSevSnp; + return CurrentLevel == CCAttrAmdSevSnp; + case CCAttrFeatureAmdSevEsDebugVirtualization: + return !!(CurrentAttr & CCAttrFeatureAmdSevEsDebugVirtualization); default: return FALSE; } @@ -159,3 +165,18 @@ MemEncryptSevGetEncryptionMask ( return mSevEncryptionMask; } + +/** + Returns a boolean to indicate whether DebugVirtualization is enabled. + + @retval TRUE DebugVirtualization is enabled + @retval FALSE DebugVirtualization is not enabled +**/ +BOOLEAN +EFIAPI +MemEncryptSevEsDebugVirtualizationIsEnabled ( + VOID + ) +{ + return ConfidentialComputingGuestHas (CCAttrFeatureAmdSevEsDebugVirtualization); +} diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLibInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLibInternal.c index 41d1246a5b31..7d823ad639f4 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLibInternal.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLibInternal.c @@ -141,3 +141,18 @@ MemEncryptSevGetEncryptionMask ( return SevEsWorkArea->EncryptionMask; } + +/** + Returns a boolean to indicate whether DebugVirtualization is enabled. + + @retval TRUE DebugVirtualization is enabled + @retval FALSE DebugVirtualization is not enabled +**/ +BOOLEAN +EFIAPI +MemEncryptSevEsDebugVirtualizationIsEnabled ( + VOID + ) +{ + return FALSE; +} diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLibInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLibInternal.c index 27148c7e337a..33a326ac1571 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLibInternal.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLibInternal.c @@ -142,6 +142,21 @@ MemEncryptSevGetEncryptionMask ( return SevEsWorkArea->EncryptionMask; } +/** + Returns a boolean to indicate whether DebugVirtualization is enabled. + + @retval TRUE DebugVirtualization is enabled + @retval FALSE DebugVirtualization is not enabled +**/ +BOOLEAN +EFIAPI +MemEncryptSevEsDebugVirtualizationIsEnabled ( + VOID + ) +{ + return FALSE; +} + /** Locate the page range that covers the initial (pre-SMBASE-relocation) SMRAM Save State Map. diff --git a/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c index da8f1e5db9fa..2031fa9e22e6 100644 --- a/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c +++ b/OvmfPkg/Library/CcExitLib/CcExitVcHandler.c @@ -1609,6 +1609,10 @@ Dr7WriteExit ( UINT64 *Register; UINT64 Status; + if (MemEncryptSevEsDebugVirtualizationIsEnabled ()) { + return UnsupportedExit (Ghcb, Regs, InstructionData); + } + Ext = &InstructionData->Ext; SevEsData = (SEV_ES_PER_CPU_DATA *)(Ghcb + 1); @@ -1659,6 +1663,10 @@ Dr7ReadExit ( SEV_ES_PER_CPU_DATA *SevEsData; UINT64 *Register; + if (MemEncryptSevEsDebugVirtualizationIsEnabled ()) { + return UnsupportedExit (Ghcb, Regs, InstructionData); + } + Ext = &InstructionData->Ext; SevEsData = (SEV_ES_PER_CPU_DATA *)(Ghcb + 1); From 63a7152471111306184e4ac20a1ca705e6b75b6b Mon Sep 17 00:00:00 2001 From: Alexey Kardashevskiy Date: Wed, 30 Nov 2022 19:40:48 +1100 Subject: [PATCH 40/67] UefiCpuPkg: Add AMD SEV-ES features support CONFIDENTIAL_COMPUTING_GUEST_ATTR is not a simple SEV level anymore and includes a feature mask since the previous commit. Fix AmdMemEncryptionAttrCheck to check the level and feature correctly and add DebugVirtualization support. Since the actual feature flag is not set yet, this should cause no behavioural change. Cc: Gerd Hoffmann Cc: Jiaxin Wu Cc: Rahul Kumar Cc: Ray Ni Reviewed-by: Tom Lendacky Signed-off-by: Alexey Kardashevskiy --- Changes: v5: * "rb" from Tom --- UefiCpuPkg/Library/MpInitLib/MpLib.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.c b/UefiCpuPkg/Library/MpInitLib/MpLib.c index 8fbcebdc0311..195192291295 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.c @@ -3196,19 +3196,25 @@ AmdMemEncryptionAttrCheck ( IN CONFIDENTIAL_COMPUTING_GUEST_ATTR Attr ) { + UINT64 CurrentLevel; + + CurrentLevel = CurrentAttr & CCAttrTypeMask; + switch (Attr) { case CCAttrAmdSev: // // SEV is automatically enabled if SEV-ES or SEV-SNP is active. // - return CurrentAttr >= CCAttrAmdSev; + return CurrentLevel >= CCAttrAmdSev; case CCAttrAmdSevEs: // // SEV-ES is automatically enabled if SEV-SNP is active. // - return CurrentAttr >= CCAttrAmdSevEs; + return CurrentLevel >= CCAttrAmdSevEs; case CCAttrAmdSevSnp: - return CurrentAttr == CCAttrAmdSevSnp; + return CurrentLevel == CCAttrAmdSevSnp; + case CCAttrFeatureAmdSevEsDebugVirtualization: + return !!(CurrentAttr & CCAttrFeatureAmdSevEsDebugVirtualization); default: return FALSE; } From 28099661893327296e18b8f98a1e7c3e757c7d49 Mon Sep 17 00:00:00 2001 From: Alexey Kardashevskiy Date: Tue, 28 May 2024 14:48:40 +1000 Subject: [PATCH 41/67] OvmfPkg: Enable AMD SEV-ES DebugVirtualization Write the feature bit into PcdConfidentialComputingGuestAttr and enable DebugVirtualization in PEI, SEC, DXE. Cc: Ard Biesheuvel Cc: Erdem Aktas Cc: Gerd Hoffmann Cc: Jiewen Yao Cc: Michael Roth Cc: Min Xu Reviewed-by: Tom Lendacky Signed-off-by: Alexey Kardashevskiy --- Changes: v5: * "rb" from Tom v4: * s/DebugSwap/DebugVirtualization/g --- .../PeiMemEncryptSevLibInternal.c | 6 +++++- .../SecMemEncryptSevLibInternal.c | 6 +++++- OvmfPkg/PlatformPei/AmdSev.c | 13 ++++++++++--- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLibInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLibInternal.c index 7d823ad639f4..f381b9255bb7 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLibInternal.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/PeiMemEncryptSevLibInternal.c @@ -154,5 +154,9 @@ MemEncryptSevEsDebugVirtualizationIsEnabled ( VOID ) { - return FALSE; + MSR_SEV_STATUS_REGISTER Msr; + + Msr.Uint32 = InternalMemEncryptSevStatus (); + + return Msr.Bits.DebugVirtualization ? TRUE : FALSE; } diff --git a/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLibInternal.c b/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLibInternal.c index 33a326ac1571..946bed2ada13 100644 --- a/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLibInternal.c +++ b/OvmfPkg/Library/BaseMemEncryptSevLib/SecMemEncryptSevLibInternal.c @@ -154,7 +154,11 @@ MemEncryptSevEsDebugVirtualizationIsEnabled ( VOID ) { - return FALSE; + MSR_SEV_STATUS_REGISTER Msr; + + Msr.Uint32 = InternalMemEncryptSevStatus (); + + return Msr.Bits.DebugVirtualization ? TRUE : FALSE; } /** diff --git a/OvmfPkg/PlatformPei/AmdSev.c b/OvmfPkg/PlatformPei/AmdSev.c index 88ca14507f5e..8562787035db 100644 --- a/OvmfPkg/PlatformPei/AmdSev.c +++ b/OvmfPkg/PlatformPei/AmdSev.c @@ -434,6 +434,7 @@ AmdSevInitialize ( ) { UINT64 EncryptionMask; + UINT64 CCGuestAttr; RETURN_STATUS PcdStatus; // @@ -517,13 +518,19 @@ AmdSevInitialize ( // technology is active. // if (MemEncryptSevSnpIsEnabled ()) { - PcdStatus = PcdSet64S (PcdConfidentialComputingGuestAttr, CCAttrAmdSevSnp); + CCGuestAttr = CCAttrAmdSevSnp; } else if (MemEncryptSevEsIsEnabled ()) { - PcdStatus = PcdSet64S (PcdConfidentialComputingGuestAttr, CCAttrAmdSevEs); + CCGuestAttr = CCAttrAmdSevEs; } else { - PcdStatus = PcdSet64S (PcdConfidentialComputingGuestAttr, CCAttrAmdSev); + CCGuestAttr = CCAttrAmdSev; } + if (MemEncryptSevEsDebugVirtualizationIsEnabled ()) { + CCGuestAttr |= CCAttrFeatureAmdSevEsDebugVirtualization; + } + + PcdStatus = PcdSet64S (PcdConfidentialComputingGuestAttr, CCGuestAttr); + ASSERT_RETURN_ERROR (PcdStatus); } From ed9a64af1be2724362b50cf96281de7117ad7bff Mon Sep 17 00:00:00 2001 From: Dun Tan Date: Thu, 4 Jul 2024 15:15:15 +0800 Subject: [PATCH 42/67] SecurityPkg/Tcg2Config: avoid potential build error Cast pointer type to VOID* to avoid potential build error. If the two PCD are FixAtBuild, PcdGetPtr will return a const type pointer. Since the second parameter of BuildGuidDataHob is VOID*, build error may happen with following log: C4090: 'function': different 'const' qualifiers Signed-off-by: Dun Tan --- SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c b/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c index ce78e3253721..73121b0a2674 100644 --- a/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c +++ b/SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigPeim.c @@ -190,7 +190,7 @@ Tcg2ConfigPeimEntryPoint ( // Hob = BuildGuidDataHob ( &gEdkiiTpmInstanceHobGuid, - PcdGetPtr (PcdTpmInstanceGuid), + (VOID *)PcdGetPtr (PcdTpmInstanceGuid), sizeof (EFI_GUID) ); ASSERT (Hob != NULL); @@ -200,7 +200,7 @@ Tcg2ConfigPeimEntryPoint ( // Hob = BuildGuidDataHob ( &gEdkiiTcgPhysicalPresenceInterfaceVerHobGuid, - PcdGetPtr (PcdTcgPhysicalPresenceInterfaceVer), + (VOID *)PcdGetPtr (PcdTcgPhysicalPresenceInterfaceVer), AsciiStrSize ((CHAR8 *)PcdGetPtr (PcdTcgPhysicalPresenceInterfaceVer)) ); ASSERT (Hob != NULL); From 9389b9a208cc5c7d9b055ea06d92cc4903f705ee Mon Sep 17 00:00:00 2001 From: Xiaoyao Li Date: Wed, 26 Jun 2024 05:06:05 -0400 Subject: [PATCH 43/67] MdePkg/Tdx.h: Fix the order of NumVcpus and MaxVcpus For TDCALL leaf TDG.VP.INFO, the bit 31:0 in R8 returns NUM_VCPUS and bit 63:32 in R8 returns MAX_VCPUS. Current struct TDCALL_INFO_RETURN_DATA defines them in wrong order. Signed-off-by: Xiaoyao Li Cc: Jiewen Yao Cc: Min Xu Cc: Gerd Hoffmann Cc: Laszlo Ersek --- MdePkg/Include/IndustryStandard/Tdx.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdePkg/Include/IndustryStandard/Tdx.h b/MdePkg/Include/IndustryStandard/Tdx.h index 2662761883e5..17f1e8f4146a 100644 --- a/MdePkg/Include/IndustryStandard/Tdx.h +++ b/MdePkg/Include/IndustryStandard/Tdx.h @@ -113,8 +113,8 @@ typedef struct { typedef struct { UINT64 Gpaw; UINT64 Attributes; - UINT32 MaxVcpus; UINT32 NumVcpus; + UINT32 MaxVcpus; UINT64 Resv[3]; } TDCALL_INFO_RETURN_DATA; From bef0d333dc4fccdfc75e4be31e067b467a9a4093 Mon Sep 17 00:00:00 2001 From: Jiaxin Wu Date: Wed, 3 Jul 2024 16:16:57 +0800 Subject: [PATCH 44/67] UefiCpuPkg/PiSmmCpuDxeSmm: Fix system hang when SmmProfile enable MMIO ranges within the mProtectionMemRange array may exceed 4G and should be configured as 'Present & NX'. However, the initial attribute for these MMIO addresses in the page table is 'non-present'. Other attributes should not be set or updated for a non-present range if the present bit mask is zero, as this could result in an error during the InitPaging for the page table update process. This patch is to resolve the error to make sure MMIO page table can be configured correctly. Signed-off-by: Jiaxin Wu Cc: Ray Ni Cc: Rahul Kumar Cc: Gerd Hoffmann --- UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c | 40 +++++++++++++++++++------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c index 8142d3ceac89..692aad2d157f 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c @@ -1,7 +1,7 @@ /** @file Enable SMM profile. -Copyright (c) 2012 - 2023, Intel Corporation. All rights reserved.
+Copyright (c) 2012 - 2024, Intel Corporation. All rights reserved.
Copyright (c) 2017 - 2020, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -594,6 +594,7 @@ InitPaging ( UINT64 Limit; UINT64 PreviousAddress; UINT64 MemoryAttrMask; + BOOLEAN IsSet; BOOLEAN WriteProtect; BOOLEAN CetEnabled; @@ -616,19 +617,38 @@ InitPaging ( DEBUG ((DEBUG_INFO, "Patch page table start ...\n")); if (FeaturePcdGet (PcdCpuSmmProfileEnable)) { for (Index = 0; Index < mProtectionMemRangeCount; Index++) { - MemoryAttrMask = 0; - if (mProtectionMemRange[Index].Nx == TRUE) { + Base = mProtectionMemRange[Index].Range.Base; + Length = mProtectionMemRange[Index].Range.Top - Base; + + MemoryAttrMask = EFI_MEMORY_RP; + if (!mProtectionMemRange[Index].Present) { + // + // Config the EFI_MEMORY_RP attribute to make it non-present. + // + IsSet = TRUE; + } else { + // + // Clear the EFI_MEMORY_RP attribute to make it present. + // + IsSet = FALSE; + + // + // Config the range as writable and executable when mapping a range as present. + // + MemoryAttrMask |= EFI_MEMORY_RO; MemoryAttrMask |= EFI_MEMORY_XP; } - if (mProtectionMemRange[Index].Present == FALSE) { - MemoryAttrMask = EFI_MEMORY_RP; - } + Status = ConvertMemoryPageAttributes (PageTable, mPagingMode, Base, Length, MemoryAttrMask, IsSet, NULL); + ASSERT_RETURN_ERROR (Status); - Base = mProtectionMemRange[Index].Range.Base; - Length = mProtectionMemRange[Index].Range.Top - Base; - if (MemoryAttrMask != 0) { - Status = ConvertMemoryPageAttributes (PageTable, mPagingMode, Base, Length, MemoryAttrMask, TRUE, NULL); + if (mProtectionMemRange[Index].Present && mProtectionMemRange[Index].Nx) { + // + // Since EFI_MEMORY_XP has already been cleared above, only handle the case to disable execution. + // Config the EFI_MEMORY_XP attribute to disable execution. + // + MemoryAttrMask = EFI_MEMORY_XP; + Status = ConvertMemoryPageAttributes (PageTable, mPagingMode, Base, Length, MemoryAttrMask, TRUE, NULL); ASSERT_RETURN_ERROR (Status); } From 051c7bb434f9f6b908aac2a0b00368192aa616ec Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Tue, 2 Jul 2024 11:43:24 -0400 Subject: [PATCH 45/67] StandaloneMmPkg: Fix section data length returned larger than actual data This change fixes an issue where the returned section data length is always 4 bytes larger than the actual section length. This could cause an issue where the caller accesses the final 4 bytes which would be invalid. Co-authored-by: Kun Qin Signed-off-by: Michael Kubacki --- StandaloneMmPkg/Include/Library/FvLib.h | 2 +- StandaloneMmPkg/Library/FvLib/FvLib.c | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/StandaloneMmPkg/Include/Library/FvLib.h b/StandaloneMmPkg/Include/Library/FvLib.h index 1eb9ea7e04bc..3b603e473d19 100644 --- a/StandaloneMmPkg/Include/Library/FvLib.h +++ b/StandaloneMmPkg/Include/Library/FvLib.h @@ -87,7 +87,7 @@ FindFfsSectionInSections ( @param FfsFileHeader Pointer to the current file to search. @param SectionData Pointer to the Section matching SectionType in FfsFileHeader. NULL if section not found - @param SectionDataSize The size of SectionData + @param SectionDataSize The size of SectionData, excluding the section header. @retval EFI_NOT_FOUND No files matching the search criteria were found @retval EFI_SUCCESS diff --git a/StandaloneMmPkg/Library/FvLib/FvLib.c b/StandaloneMmPkg/Library/FvLib/FvLib.c index 89504b9ee902..e0f344af3873 100644 --- a/StandaloneMmPkg/Library/FvLib/FvLib.c +++ b/StandaloneMmPkg/Library/FvLib/FvLib.c @@ -338,11 +338,11 @@ FfsFindSection ( Given the input file pointer, search for the next matching section in the FFS volume. - @param SearchType Filter to find only sections of this type. - @param FfsFileHeader Pointer to the current file to search. - @param SectionData Pointer to the Section matching SectionType in FfsFileHeader. - NULL if section not found - @param SectionDataSize The size of SectionData + @param[in] SectionType Filter to find only sections of this type. + @param[in] FfsFileHeader Pointer to the current file to search. + @param[in,out] SectionData Pointer to the Section matching SectionType in FfsFileHeader. + NULL if section not found + @param[in,out] SectionDataSize The size of SectionData, excluding the section header. @retval EFI_NOT_FOUND No files matching the search criteria were found @retval EFI_SUCCESS @@ -380,10 +380,10 @@ FfsFindSectionData ( if (Section->Type == SectionType) { if (IS_SECTION2 (Section)) { *SectionData = (VOID *)((EFI_COMMON_SECTION_HEADER2 *)Section + 1); - *SectionDataSize = SECTION2_SIZE (Section); + *SectionDataSize = SECTION2_SIZE (Section) - sizeof (EFI_COMMON_SECTION_HEADER2); } else { *SectionData = (VOID *)(Section + 1); - *SectionDataSize = SECTION_SIZE (Section); + *SectionDataSize = SECTION_SIZE (Section) - sizeof (EFI_COMMON_SECTION_HEADER); } return EFI_SUCCESS; From a1d94d9e6e109aa7e63f29b015e28c76910a0d7d Mon Sep 17 00:00:00 2001 From: Jiaxin Wu Date: Fri, 5 Jul 2024 13:41:06 +0800 Subject: [PATCH 46/67] MdePkg/StandaloneMmServicesTableLib: Support MM_CORE_STANDALONE Support the module type for MM_CORE_STANDALONE Signed-off-by: Jiaxin Wu --- .../StandaloneMmServicesTableLib.inf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdePkg/Library/StandaloneMmServicesTableLib/StandaloneMmServicesTableLib.inf b/MdePkg/Library/StandaloneMmServicesTableLib/StandaloneMmServicesTableLib.inf index 40f14aee62f0..5225d64d97f6 100644 --- a/MdePkg/Library/StandaloneMmServicesTableLib/StandaloneMmServicesTableLib.inf +++ b/MdePkg/Library/StandaloneMmServicesTableLib/StandaloneMmServicesTableLib.inf @@ -16,7 +16,7 @@ FILE_GUID = eaa4684f-fb4e-41f3-9967-307d5b409182 MODULE_TYPE = MM_STANDALONE VERSION_STRING = 1.0 - LIBRARY_CLASS = MmServicesTableLib|MM_STANDALONE + LIBRARY_CLASS = MmServicesTableLib|MM_STANDALONE MM_CORE_STANDALONE PI_SPECIFICATION_VERSION = 0x00010032 CONSTRUCTOR = StandaloneMmServicesTableLibConstructor From 22d0babd3315dc24027321819cf0efc487dc9d18 Mon Sep 17 00:00:00 2001 From: Jiaxin Wu Date: Fri, 5 Jul 2024 13:41:46 +0800 Subject: [PATCH 47/67] MdeModulePkg/StandaloneMmReportStatusCodeLib: Support MM_CORE_STANDALONE Support the module type for MM_CORE_STANDALONE Signed-off-by: Jiaxin Wu --- .../SmmReportStatusCodeLib/StandaloneMmReportStatusCodeLib.inf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Library/SmmReportStatusCodeLib/StandaloneMmReportStatusCodeLib.inf b/MdeModulePkg/Library/SmmReportStatusCodeLib/StandaloneMmReportStatusCodeLib.inf index 866e09249a6a..08437176e747 100644 --- a/MdeModulePkg/Library/SmmReportStatusCodeLib/StandaloneMmReportStatusCodeLib.inf +++ b/MdeModulePkg/Library/SmmReportStatusCodeLib/StandaloneMmReportStatusCodeLib.inf @@ -18,7 +18,7 @@ MODULE_TYPE = MM_STANDALONE VERSION_STRING = 1.0 PI_SPECIFICATION_VERSION = 0x00010032 - LIBRARY_CLASS = ReportStatusCodeLib|MM_STANDALONE + LIBRARY_CLASS = ReportStatusCodeLib|MM_STANDALONE MM_CORE_STANDALONE # # The following information is for reference only and not required by the build tools. From a3359ffb25ce70ee90822f6886136bf0d200406e Mon Sep 17 00:00:00 2001 From: Xianglai Li Date: Thu, 27 Jun 2024 18:57:37 +0800 Subject: [PATCH 48/67] OvmfPkg/LoongArchVirt: Optimize the use of serial port libraries Because the complex dependency between SerialPortLib and PciExpressLib leads to multiple references to the lib library in the loongarch dsc file, optimizing SerialPortLib now simplifies multiple references to lib in the dsc file. Cc: Ard Biesheuvel Cc: Bibo Mao Cc: Chao Li Cc: Gerd Hoffmann Cc: Jiewen Yao Cc: Xianglai Li Signed-off-by: Xianglai Li --- OvmfPkg/LoongArchVirt/LoongArchVirtQemu.dsc | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/OvmfPkg/LoongArchVirt/LoongArchVirtQemu.dsc b/OvmfPkg/LoongArchVirt/LoongArchVirtQemu.dsc index 90be933cdcbc..70f6c75b0f9b 100644 --- a/OvmfPkg/LoongArchVirt/LoongArchVirtQemu.dsc +++ b/OvmfPkg/LoongArchVirt/LoongArchVirtQemu.dsc @@ -130,7 +130,7 @@ IoLib | MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf FdtSerialPortAddressLib | OvmfPkg/Library/FdtSerialPortAddressLib/FdtSerialPortAddressLib.inf PlatformHookLib | OvmfPkg/LoongArchVirt/Library/Fdt16550SerialPortHookLib/Fdt16550SerialPortHookLib.inf - SerialPortLib | MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.inf + SerialPortLib | OvmfPkg/LoongArchVirt/Library/EarlyFdtSerialPortLib16550/EarlyFdtSerialPortLib16550.inf EfiResetSystemLib | OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/BaseResetSystemAcpiGedLib.inf ResetSystemLib | OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/BaseResetSystemAcpiGedLib.inf @@ -196,7 +196,6 @@ MemoryAllocationLib | MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf PeiServicesTablePointerLib | MdePkg/Library/PeiServicesTablePointerLibKs0/PeiServicesTablePointerLibKs0.inf PlatformHookLib | OvmfPkg/LoongArchVirt/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.inf - SerialPortLib | OvmfPkg/LoongArchVirt/Library/EarlyFdtSerialPortLib16550/EarlyFdtSerialPortLib16550.inf CpuExceptionHandlerLib | UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf [LibraryClasses.common.PEI_CORE] @@ -210,7 +209,6 @@ PeCoffGetEntryPointLib | MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf QemuFwCfgLib | OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgMmioPeiLib.inf PlatformHookLib | OvmfPkg/LoongArchVirt/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.inf - SerialPortLib | OvmfPkg/LoongArchVirt/Library/EarlyFdtSerialPortLib16550/EarlyFdtSerialPortLib16550.inf [LibraryClasses.common.PEIM] HobLib | MdePkg/Library/PeiHobLib/PeiHobLib.inf @@ -229,14 +227,12 @@ CpuMmuInitLib | OvmfPkg/LoongArchVirt/Library/CpuMmuInitLib/CpuMmuInitLib.inf MpInitLib | UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf PlatformHookLib | OvmfPkg/LoongArchVirt/Library/Fdt16550SerialPortHookLib/EarlyFdt16550SerialPortHookLib.inf - SerialPortLib | OvmfPkg/LoongArchVirt/Library/EarlyFdtSerialPortLib16550/EarlyFdtSerialPortLib16550.inf [LibraryClasses.common.DXE_CORE] HobLib | MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf DxeCoreEntryPoint | MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf MemoryAllocationLib | MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationLib.inf ReportStatusCodeLib | MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf - PciExpressLib | MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf PciPcdProducerLib | OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf CpuExceptionHandlerLib | UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf @@ -254,7 +250,6 @@ QemuFwCfgLib | OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgMmioDxeLib.inf EfiResetSystemLib | OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/DxeResetSystemAcpiGedLib.inf ResetSystemLib | OvmfPkg/LoongArchVirt/Library/ResetSystemAcpiLib/DxeResetSystemAcpiGedLib.inf - PciExpressLib | MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf !if $(TARGET) != RELEASE DebugLib | MdePkg/Library/DxeRuntimeDebugLibSerialPort/DxeRuntimeDebugLibSerialPort.inf !endif @@ -281,7 +276,6 @@ QemuFwCfgS3Lib | OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf QemuFwCfgLib | OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgMmioDxeLib.inf PciPcdProducerLib | OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf - PciExpressLib | MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf AcpiPlatformLib | OvmfPkg/Library/AcpiPlatformLib/DxeAcpiPlatformLib.inf MpInitLib | UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf @@ -291,7 +285,6 @@ MemoryAllocationLib | MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf ExtractGuidedSectionLib | MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf PciPcdProducerLib | OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf - PciExpressLib | MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf ################################################################################ # @@ -601,18 +594,15 @@ UefiCpuPkg/CpuMmio2Dxe/CpuMmio2Dxe.inf { NULL|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf - NULL|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf } EmbeddedPkg/Drivers/FdtClientDxe/FdtClientDxe.inf MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf { NULL|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf - NULL|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf } MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf { NULL|OvmfPkg/Fdt/FdtPciPcdProducerLib/FdtPciPcdProducerLib.inf - NULL|OvmfPkg/Library/BaseCachingPciExpressLib/BaseCachingPciExpressLib.inf } OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf OvmfPkg/Virtio10Dxe/Virtio10.inf From 4efcd654ecd94b91bd45da79583f114a0fa12a87 Mon Sep 17 00:00:00 2001 From: Yanbo Huang Date: Fri, 5 Jul 2024 17:54:19 +0800 Subject: [PATCH 49/67] Revert "UefiCpuPkg/PiSmmCpuDxeSmm: Consume PcdCpuSmmApSyncTimeout2" This reverts commit cb3134612d11102fe066c94c8fa7edb20d62c1a8. Intel server platform sync this commit will hit conflict since our code base is old. We don't want to cherry-pick the dependent patches to avoid potential issue. We need to revert this commit first and then fix the conflict and reapply the change. Sorry for the incovenience. Signed-off-by: Yanbo Huang --- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 10 +++++----- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h | 11 +++-------- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf | 1 - UefiCpuPkg/PiSmmCpuDxeSmm/SyncTimer.c | 19 +++++-------------- 4 files changed, 13 insertions(+), 28 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index 570e99177f4d..10baf3ceb9cd 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -1,7 +1,7 @@ /** @file SMM MP service implementation -Copyright (c) 2009 - 2024, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2023, Intel Corporation. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -268,7 +268,7 @@ SmmWaitForApArrival ( // Sync with APs 1st timeout // for (Timer = StartSyncTimer (); - !IsSyncTimerTimeout (Timer, mTimeoutTicker) && !(LmceEn && LmceSignal); + !IsSyncTimerTimeout (Timer) && !(LmceEn && LmceSignal); ) { mSmmMpSyncData->AllApArrivedWithException = AllCpusInSmmExceptBlockedDisabled (); @@ -309,7 +309,7 @@ SmmWaitForApArrival ( // Sync with APs 2nd timeout. // for (Timer = StartSyncTimer (); - !IsSyncTimerTimeout (Timer, mTimeoutTicker2); + !IsSyncTimerTimeout (Timer); ) { mSmmMpSyncData->AllApArrivedWithException = AllCpusInSmmExceptBlockedDisabled (); @@ -736,7 +736,7 @@ APHandler ( // Timeout BSP // for (Timer = StartSyncTimer (); - !IsSyncTimerTimeout (Timer, mTimeoutTicker) && + !IsSyncTimerTimeout (Timer) && !(*mSmmMpSyncData->InsideSmm); ) { @@ -764,7 +764,7 @@ APHandler ( // Now clock BSP for the 2nd time // for (Timer = StartSyncTimer (); - !IsSyncTimerTimeout (Timer, mTimeoutTicker2) && + !IsSyncTimerTimeout (Timer) && !(*mSmmMpSyncData->InsideSmm); ) { diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h index 8409891b1d39..315a33d578b2 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h @@ -471,9 +471,6 @@ extern BOOLEAN mSmmDebugAgentSupport; // extern UINT64 mAddressEncMask; -extern UINT64 mTimeoutTicker; -extern UINT64 mTimeoutTicker2; - /** Create 4G PageTable in SMRAM. @@ -536,17 +533,15 @@ StartSyncTimer ( ); /** - Check if the SMM AP Sync Timer is timeout specified by Timeout. + Check if the SMM AP Sync timer is timeout. - @param Timer The start timer from the begin. - @param Timeout The timeout ticker to wait. + @param Timer The start timer from the begin. **/ BOOLEAN EFIAPI IsSyncTimerTimeout ( - IN UINT64 Timer, - IN UINT64 Timeout + IN UINT64 Timer ); /** diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf index 3c4518da7b49..f0598b036443 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf @@ -134,7 +134,6 @@ gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmProfileSize ## SOMETIMES_CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackSize ## CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout ## CONSUMES - gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout2 ## CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugDataAddress ## SOMETIMES_PRODUCES gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmCodeAccessCheckEnable ## CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode ## CONSUMES diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SyncTimer.c b/UefiCpuPkg/PiSmmCpuDxeSmm/SyncTimer.c index 8d29ba7326f6..0c070c5736c6 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/SyncTimer.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SyncTimer.c @@ -1,7 +1,7 @@ /** @file SMM Timer feature support -Copyright (c) 2009 - 2024, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -9,9 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PiSmmCpuDxeSmm.h" UINT64 mTimeoutTicker = 0; - -UINT64 mTimeoutTicker2 = 0; - // // Number of counts in a roll-over cycle of the performance counter. // @@ -39,10 +36,6 @@ InitializeSmmTimer ( MultU64x64 (TimerFrequency, PcdGet64 (PcdCpuSmmApSyncTimeout)), 1000 * 1000 ); - mTimeoutTicker2 = DivU64x32 ( - MultU64x64 (TimerFrequency, PcdGet64 (PcdCpuSmmApSyncTimeout2)), - 1000 * 1000 - ); if (End < Start) { mCountDown = TRUE; mCycle = Start - End; @@ -66,17 +59,15 @@ StartSyncTimer ( } /** - Check if the SMM AP Sync Timer is timeout specified by Timeout. + Check if the SMM AP Sync timer is timeout. - @param Timer The start timer from the begin. - @param Timeout The timeout ticker to wait. + @param Timer The start timer from the begin. **/ BOOLEAN EFIAPI IsSyncTimerTimeout ( - IN UINT64 Timer, - IN UINT64 Timeout + IN UINT64 Timer ) { UINT64 CurrentTimer; @@ -114,5 +105,5 @@ IsSyncTimerTimeout ( } } - return (BOOLEAN)(Delta >= Timeout); + return (BOOLEAN)(Delta >= mTimeoutTicker); } From f8bf46be599a957d9374b513f730243725637127 Mon Sep 17 00:00:00 2001 From: Yanbo Huang Date: Fri, 5 Jul 2024 18:17:57 +0800 Subject: [PATCH 50/67] UefiCpuPkg/PiSmmCpuDxeSmm: Consume PcdCpuSmmApSyncTimeout2 This patch is to consume the PcdCpuSmmApSyncTimeout2 to enhance the flexibility of timeout configuration. In some cases, certain processors may not be able to enter SMI, and prolonged waiting could lead to kernel soft/hard lockup. We have now defined two timeouts. The first timeout can be set to a smaller value to reduce the waiting period. Processors that are unable to enter SMI will be woken up through SMIIPL to enter SMI, followed by a second waiting period. The second timeout can be set to a larger value to prevent delays in processors entering SMI case due to the long instruction execution. This patch adjust the location of PcdCpuSmmApSyncTimeout2 to avoid conflict. Signed-off-by: Yanbo Huang Cc: Ray Ni Cc: Rahul Kumar Cc: Gerd Hoffmann --- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 10 +++++----- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h | 11 ++++++++--- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf | 1 + UefiCpuPkg/PiSmmCpuDxeSmm/SyncTimer.c | 19 ++++++++++++++----- 4 files changed, 28 insertions(+), 13 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index 10baf3ceb9cd..570e99177f4d 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -1,7 +1,7 @@ /** @file SMM MP service implementation -Copyright (c) 2009 - 2023, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2024, Intel Corporation. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -268,7 +268,7 @@ SmmWaitForApArrival ( // Sync with APs 1st timeout // for (Timer = StartSyncTimer (); - !IsSyncTimerTimeout (Timer) && !(LmceEn && LmceSignal); + !IsSyncTimerTimeout (Timer, mTimeoutTicker) && !(LmceEn && LmceSignal); ) { mSmmMpSyncData->AllApArrivedWithException = AllCpusInSmmExceptBlockedDisabled (); @@ -309,7 +309,7 @@ SmmWaitForApArrival ( // Sync with APs 2nd timeout. // for (Timer = StartSyncTimer (); - !IsSyncTimerTimeout (Timer); + !IsSyncTimerTimeout (Timer, mTimeoutTicker2); ) { mSmmMpSyncData->AllApArrivedWithException = AllCpusInSmmExceptBlockedDisabled (); @@ -736,7 +736,7 @@ APHandler ( // Timeout BSP // for (Timer = StartSyncTimer (); - !IsSyncTimerTimeout (Timer) && + !IsSyncTimerTimeout (Timer, mTimeoutTicker) && !(*mSmmMpSyncData->InsideSmm); ) { @@ -764,7 +764,7 @@ APHandler ( // Now clock BSP for the 2nd time // for (Timer = StartSyncTimer (); - !IsSyncTimerTimeout (Timer) && + !IsSyncTimerTimeout (Timer, mTimeoutTicker2) && !(*mSmmMpSyncData->InsideSmm); ) { diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h index 315a33d578b2..8409891b1d39 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h @@ -471,6 +471,9 @@ extern BOOLEAN mSmmDebugAgentSupport; // extern UINT64 mAddressEncMask; +extern UINT64 mTimeoutTicker; +extern UINT64 mTimeoutTicker2; + /** Create 4G PageTable in SMRAM. @@ -533,15 +536,17 @@ StartSyncTimer ( ); /** - Check if the SMM AP Sync timer is timeout. + Check if the SMM AP Sync Timer is timeout specified by Timeout. - @param Timer The start timer from the begin. + @param Timer The start timer from the begin. + @param Timeout The timeout ticker to wait. **/ BOOLEAN EFIAPI IsSyncTimerTimeout ( - IN UINT64 Timer + IN UINT64 Timer, + IN UINT64 Timeout ); /** diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf index f0598b036443..c64d37e49859 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf @@ -130,6 +130,7 @@ gUefiCpuPkgTokenSpaceGuid.PcdSmmApPerfLogEnable ## CONSUMES [Pcd] + gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout2 ## CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber ## SOMETIMES_CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmProfileSize ## SOMETIMES_CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackSize ## CONSUMES diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SyncTimer.c b/UefiCpuPkg/PiSmmCpuDxeSmm/SyncTimer.c index 0c070c5736c6..8d29ba7326f6 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/SyncTimer.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SyncTimer.c @@ -1,7 +1,7 @@ /** @file SMM Timer feature support -Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -9,6 +9,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PiSmmCpuDxeSmm.h" UINT64 mTimeoutTicker = 0; + +UINT64 mTimeoutTicker2 = 0; + // // Number of counts in a roll-over cycle of the performance counter. // @@ -36,6 +39,10 @@ InitializeSmmTimer ( MultU64x64 (TimerFrequency, PcdGet64 (PcdCpuSmmApSyncTimeout)), 1000 * 1000 ); + mTimeoutTicker2 = DivU64x32 ( + MultU64x64 (TimerFrequency, PcdGet64 (PcdCpuSmmApSyncTimeout2)), + 1000 * 1000 + ); if (End < Start) { mCountDown = TRUE; mCycle = Start - End; @@ -59,15 +66,17 @@ StartSyncTimer ( } /** - Check if the SMM AP Sync timer is timeout. + Check if the SMM AP Sync Timer is timeout specified by Timeout. - @param Timer The start timer from the begin. + @param Timer The start timer from the begin. + @param Timeout The timeout ticker to wait. **/ BOOLEAN EFIAPI IsSyncTimerTimeout ( - IN UINT64 Timer + IN UINT64 Timer, + IN UINT64 Timeout ) { UINT64 CurrentTimer; @@ -105,5 +114,5 @@ IsSyncTimerTimeout ( } } - return (BOOLEAN)(Delta >= mTimeoutTicker); + return (BOOLEAN)(Delta >= Timeout); } From 5a4a7172bce4a6aed0090363c10d806c9c6ec41f Mon Sep 17 00:00:00 2001 From: Sergii Dmytruk Date: Sat, 22 Jun 2024 20:26:41 +0300 Subject: [PATCH 51/67] BaseTools/FmpCapsuleHeader.py: Explain error when throwing exceptions This gives a caller a chance to report a meaningful error to the user. Signed-off-by: Sergii Dmytruk --- .../Common/Uefi/Capsule/FmpCapsuleHeader.py | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/BaseTools/Source/Python/Common/Uefi/Capsule/FmpCapsuleHeader.py b/BaseTools/Source/Python/Common/Uefi/Capsule/FmpCapsuleHeader.py index 8abb449c6fd7..6a112d5f89fc 100644 --- a/BaseTools/Source/Python/Common/Uefi/Capsule/FmpCapsuleHeader.py +++ b/BaseTools/Source/Python/Common/Uefi/Capsule/FmpCapsuleHeader.py @@ -92,7 +92,7 @@ def Encode (self): def Decode (self, Buffer): if len (Buffer) < self._StructSize: - raise ValueError + raise ValueError ('Buffer is too small for decoding') (Version, UpdateImageTypeId, UpdateImageIndex, r0, r1, r2, UpdateImageSize, UpdateVendorCodeSize, UpdateHardwareInstance, ImageCapsuleSupport) = \ struct.unpack ( self._StructFormat, @@ -100,11 +100,11 @@ def Decode (self, Buffer): ) if Version < self.EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER_INIT_VERSION: - raise ValueError + raise ValueError ('Incorrect capsule image header version') if UpdateImageIndex < 1: - raise ValueError + raise ValueError ('Update image index is less than 1') if UpdateImageSize + UpdateVendorCodeSize != len (Buffer[self._StructSize:]): - raise ValueError + raise ValueError ('Non-vendor and vendor parts do not add up') self.Version = Version self.UpdateImageTypeId = uuid.UUID (bytes_le = UpdateImageTypeId) @@ -120,7 +120,7 @@ def Decode (self, Buffer): def DumpInfo (self): if not self._Valid: - raise ValueError + raise ValueError ('Can not dump an invalid header') print ('EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER.Version = {Version:08X}'.format (Version = self.Version)) print ('EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER.UpdateImageTypeId = {UpdateImageTypeId}'.format (UpdateImageTypeId = str(self.UpdateImageTypeId).upper())) print ('EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER.UpdateImageIndex = {UpdateImageIndex:08X}'.format (UpdateImageIndex = self.UpdateImageIndex)) @@ -180,7 +180,7 @@ def AddEmbeddedDriver (self, EmbeddedDriver): def GetEmbeddedDriver (self, Index): if Index > len (self._EmbeddedDriverList): - raise ValueError + raise ValueError ('Invalid embedded driver index') return self._EmbeddedDriverList[Index] def AddPayload (self, UpdateImageTypeId, Payload = b'', VendorCodeBytes = b'', HardwareInstance = 0, UpdateImageIndex = 1, CapsuleSupport = 0): @@ -188,7 +188,7 @@ def AddPayload (self, UpdateImageTypeId, Payload = b'', VendorCodeBytes = b'', H def GetFmpCapsuleImageHeader (self, Index): if Index >= len (self._FmpCapsuleImageHeaderList): - raise ValueError + raise ValueError ('Invalid capsule image index') return self._FmpCapsuleImageHeaderList[Index] def Encode (self): @@ -234,14 +234,14 @@ def Encode (self): def Decode (self, Buffer): if len (Buffer) < self._StructSize: - raise ValueError + raise ValueError ('Buffer is too small for decoding') (Version, EmbeddedDriverCount, PayloadItemCount) = \ struct.unpack ( self._StructFormat, Buffer[0:self._StructSize] ) if Version < self.EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER_INIT_VERSION: - raise ValueError + raise ValueError ('Incorrect capsule header version') self.Version = Version self.EmbeddedDriverCount = EmbeddedDriverCount @@ -258,7 +258,7 @@ def Decode (self, Buffer): for Index in range (0, EmbeddedDriverCount + PayloadItemCount): ItemOffset = struct.unpack (self._ItemOffsetFormat, Buffer[Offset:Offset + self._ItemOffsetSize])[0] if ItemOffset >= len (Buffer): - raise ValueError + raise ValueError ('Item offset is outside of buffer') self._ItemOffsetList.append (ItemOffset) Offset = Offset + self._ItemOffsetSize Result = Buffer[Offset:] @@ -297,7 +297,7 @@ def Decode (self, Buffer): def DumpInfo (self): if not self._Valid: - raise ValueError + raise ValueError ('Can not dump an invalid header') print ('EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER.Version = {Version:08X}'.format (Version = self.Version)) print ('EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER.EmbeddedDriverCount = {EmbeddedDriverCount:08X}'.format (EmbeddedDriverCount = self.EmbeddedDriverCount)) for EmbeddedDriver in self._EmbeddedDriverList: From 8e7bd66dc11300cedc520c841e1cc8303f6b4169 Mon Sep 17 00:00:00 2001 From: Sergii Dmytruk Date: Sat, 22 Jun 2024 20:31:39 +0300 Subject: [PATCH 52/67] BaseTools/GenerateCapsule.py: Fix --decode operation Commit b68d566439683d0ebe60d52c85ff0e90331db740 added support for input subject name with signtool and broke --decode operation by using incorrect identifier in one place (could be an incomplete rename during review). It's `args.SignToolSubjectName`, not `args.SignSubjectName`. Signed-off-by: Sergii Dmytruk --- BaseTools/Source/Python/Capsule/GenerateCapsule.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Source/Python/Capsule/GenerateCapsule.py b/BaseTools/Source/Python/Capsule/GenerateCapsule.py index 35435946c664..9a395d0072db 100644 --- a/BaseTools/Source/Python/Capsule/GenerateCapsule.py +++ b/BaseTools/Source/Python/Capsule/GenerateCapsule.py @@ -690,7 +690,7 @@ def Decode (PayloadDescriptorList, PayloadJsonDescriptorList, Buffer): args.HardwareInstance, args.UpdateImageIndex, args.SignToolPfxFile, - args.SignSubjectName, + args.SignToolSubjectName, args.OpenSslSignerPrivateCertFile, args.OpenSslOtherPublicCertFile, args.OpenSslTrustedPublicCertFile, From 3be79ece37085f1037103e665e5df67b3a22b630 Mon Sep 17 00:00:00 2001 From: Sergii Dmytruk Date: Sat, 22 Jun 2024 20:38:03 +0300 Subject: [PATCH 53/67] BaseTools/GenerateCapsule.py: Disallow UpdateImageIndex == 0 on --encode This field seems to be one-based according UEFI specification, default value is 1 and --decode of GenerateCapsule.py errors upon seeing UpdateImageIndex less than 1. So align --encode behaviour to enforce a value within the 1..255 range. Signed-off-by: Sergii Dmytruk --- BaseTools/Source/Python/Capsule/GenerateCapsule.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/BaseTools/Source/Python/Capsule/GenerateCapsule.py b/BaseTools/Source/Python/Capsule/GenerateCapsule.py index 9a395d0072db..de1dbbab5f68 100644 --- a/BaseTools/Source/Python/Capsule/GenerateCapsule.py +++ b/BaseTools/Source/Python/Capsule/GenerateCapsule.py @@ -513,11 +513,11 @@ def Validate(self, args): raise argparse.ArgumentTypeError ('JSON field MonotonicCount must be an integer in range 0x0..0xffffffffffffffff') else: raise argparse.ArgumentTypeError ('--monotonic-count must be an integer in range 0x0..0xffffffffffffffff') - if self.UpdateImageIndex >0xFF: + if self.UpdateImageIndex < 0x1 or self.UpdateImageIndex > 0xFF: if args.JsonFile: - raise argparse.ArgumentTypeError ('JSON field UpdateImageIndex must be an integer in range 0x0..0xff') + raise argparse.ArgumentTypeError ('JSON field UpdateImageIndex must be an integer in range 0x1..0xff') else: - raise argparse.ArgumentTypeError ('--update-image-index must be an integer in range 0x0..0xff') + raise argparse.ArgumentTypeError ('--update-image-index must be an integer in range 0x1..0xff') if self.UseSignTool: if self.SignToolPfxFile is not None: From 822ff966c6dcc8bf5dc9b87d0b4e4ac2f7102e8b Mon Sep 17 00:00:00 2001 From: Sergii Dmytruk Date: Sat, 22 Jun 2024 20:42:16 +0300 Subject: [PATCH 54/67] BaseTools/GenerateCapsule.py: Better error message on --decode failure Print error text from the exception. Signed-off-by: Sergii Dmytruk --- BaseTools/Source/Python/Capsule/GenerateCapsule.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BaseTools/Source/Python/Capsule/GenerateCapsule.py b/BaseTools/Source/Python/Capsule/GenerateCapsule.py index de1dbbab5f68..4d4e526432e6 100644 --- a/BaseTools/Source/Python/Capsule/GenerateCapsule.py +++ b/BaseTools/Source/Python/Capsule/GenerateCapsule.py @@ -873,8 +873,8 @@ def Decode (PayloadDescriptorList, PayloadJsonDescriptorList, Buffer): print ('GenerateCapsule: error: can not write embedded driver file {File}'.format (File = EmbeddedDriverPath)) sys.exit (1) - except: - print ('GenerateCapsule: error: can not decode capsule') + except Exception as Msg: + print ('GenerateCapsule: error: can not decode capsule: ' + str(Msg)) sys.exit (1) GenerateOutputJson(PayloadJsonDescriptorList) PayloadIndex = 0 From 47c107817532609ec5b9a142308408510c0a9e39 Mon Sep 17 00:00:00 2001 From: Sergii Dmytruk Date: Sat, 22 Jun 2024 20:43:13 +0300 Subject: [PATCH 55/67] BaseTools/GenerateCapsule.py: Require --output for --decode --decode unconditionally uses args.OutputFile.name as a prefix for output files that it creates and fails in a non-pretty way without --output option. This doesn't address creation/truncation of the file specified via --output, but at least you're able to decode a capsule. Signed-off-by: Sergii Dmytruk --- BaseTools/Source/Python/Capsule/GenerateCapsule.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/BaseTools/Source/Python/Capsule/GenerateCapsule.py b/BaseTools/Source/Python/Capsule/GenerateCapsule.py index 4d4e526432e6..87fa998274e9 100644 --- a/BaseTools/Source/Python/Capsule/GenerateCapsule.py +++ b/BaseTools/Source/Python/Capsule/GenerateCapsule.py @@ -519,6 +519,10 @@ def Validate(self, args): else: raise argparse.ArgumentTypeError ('--update-image-index must be an integer in range 0x1..0xff') + if args.Decode: + if args.OutputFile is None: + raise argparse.ArgumentTypeError ('--decode requires --output') + if self.UseSignTool: if self.SignToolPfxFile is not None: self.SignToolPfxFile.close() From eeddb86aaaadcf5e716741db54af08531e25ff62 Mon Sep 17 00:00:00 2001 From: Sergii Dmytruk Date: Sat, 22 Jun 2024 20:46:44 +0300 Subject: [PATCH 56/67] BaseTools/GenerateCapsule.py: Fix inconsistent error formatting Just add a space between colon and a more detailed error message in two places. Signed-off-by: Sergii Dmytruk --- BaseTools/Source/Python/Capsule/GenerateCapsule.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BaseTools/Source/Python/Capsule/GenerateCapsule.py b/BaseTools/Source/Python/Capsule/GenerateCapsule.py index 87fa998274e9..d694130bc4f4 100644 --- a/BaseTools/Source/Python/Capsule/GenerateCapsule.py +++ b/BaseTools/Source/Python/Capsule/GenerateCapsule.py @@ -580,7 +580,7 @@ def Encode (PayloadDescriptorList, EmbeddedDriverDescriptorList, Buffer): try: SinglePayloadDescriptor.Validate (args) except Exception as Msg: - print ('GenerateCapsule: error:' + str(Msg)) + print ('GenerateCapsule: error: ' + str(Msg)) sys.exit (1) for SinglePayloadDescriptor in PayloadDescriptorList: ImageCapsuleSupport = 0x0000000000000000 @@ -708,7 +708,7 @@ def Decode (PayloadDescriptorList, PayloadJsonDescriptorList, Buffer): try: SinglePayloadDescriptor.Validate (args) except Exception as Msg: - print ('GenerateCapsule: error:' + str(Msg)) + print ('GenerateCapsule: error: ' + str(Msg)) sys.exit (1) try: Result = UefiCapsuleHeader.Decode (Buffer) From 26bc42f1e34cdf43057a75b8edcc0bd86c091214 Mon Sep 17 00:00:00 2001 From: Sergii Dmytruk Date: Sat, 22 Jun 2024 20:47:56 +0300 Subject: [PATCH 57/67] BaseTools/GenerateCapsule.py: Fix checking for DepExp presence struct.unpack() returns a tuple even for a single-element pack, resulting in signature verification being evaluated to false even when the signature is there. This fixes --decode and --dump-info actions incorrectly reporting issues with parsing capsule dependencies when there are none. Signed-off-by: Sergii Dmytruk --- BaseTools/Source/Python/Capsule/GenerateCapsule.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BaseTools/Source/Python/Capsule/GenerateCapsule.py b/BaseTools/Source/Python/Capsule/GenerateCapsule.py index d694130bc4f4..a773cfb2b304 100644 --- a/BaseTools/Source/Python/Capsule/GenerateCapsule.py +++ b/BaseTools/Source/Python/Capsule/GenerateCapsule.py @@ -831,7 +831,7 @@ def Decode (PayloadDescriptorList, PayloadJsonDescriptorList, Buffer): print ('--------') print ('No EFI_FIRMWARE_IMAGE_AUTHENTICATION') - PayloadSignature = struct.unpack (' Date: Fri, 31 May 2024 13:02:39 +0800 Subject: [PATCH 58/67] MdeModulePkg/FaultTolerantWriteSmm: Update buffer valid check func name In the MdeModulePkg/FaultTolerantWriteSmm, the Primary Buffer (CommBuffer) check function has been updated to match the buffer validation behavior: For SMM, the SMM Handlers is to validate the buffer outside MMRAM. For MM, the MM Handlers do not need to validate the buffer if it is the CommBuffer passed from MmCore through the MmiHandler() parameter. Return TRUE directly in this case. There is no function impact. Signed-off-by: Jiaxin Wu Cc: Liming Gao Cc: Ray Ni Cc: Star Zeng Cc: Hongbin1 Zhang Cc: Wei6 Xu Cc: Dun Tan Cc: Yuanhao Xie --- .../FaultTolerantWriteDxe/FaultTolerantWriteSmm.c | 6 +++--- .../FaultTolerantWriteSmmCommon.h | 13 +++++-------- .../FaultTolerantWriteStandaloneMm.c | 13 +++++-------- .../FaultTolerantWriteTraditionalMm.c | 6 +++--- 4 files changed, 16 insertions(+), 22 deletions(-) diff --git a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.c b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.c index 8c2d209fa07b..676f46ded20e 100644 --- a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.c +++ b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.c @@ -43,7 +43,7 @@ Caution: This module requires additional review when modified. This driver need to make sure the CommBuffer is not in the SMRAM range. -Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2010 - 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -332,8 +332,8 @@ SmmFaultTolerantWriteHandler ( CommBufferPayloadSize = TempCommBufferSize - SMM_FTW_COMMUNICATE_HEADER_SIZE; - if (!FtwSmmIsBufferOutsideSmmValid ((UINTN)CommBuffer, TempCommBufferSize)) { - DEBUG ((DEBUG_ERROR, "SmmFtwHandler: SMM communication buffer in SMRAM or overflow!\n")); + if (!FtwSmmIsPrimaryBufferValid ((UINTN)CommBuffer, TempCommBufferSize)) { + DEBUG ((DEBUG_ERROR, "SmmFtwHandler: SMM Primary(communication buffer) is not valid!\n")); return EFI_SUCCESS; } diff --git a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmmCommon.h b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmmCommon.h index f717432e15ea..73799d325611 100644 --- a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmmCommon.h +++ b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmmCommon.h @@ -2,7 +2,7 @@ The common header file for SMM FTW module and SMM FTW DXE Module. -Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2011 - 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -85,19 +85,16 @@ MmFaultTolerantWriteInitialize ( ); /** - This function checks if the buffer is valid per processor architecture and - does not overlap with SMRAM. + This function checks if the Primary Buffer is valid. @param Buffer The buffer start address to be checked. @param Length The buffer length to be checked. - @retval TRUE This buffer is valid per processor architecture and does not - overlap with SMRAM. - @retval FALSE This buffer is not valid per processor architecture or overlaps - with SMRAM. + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. **/ BOOLEAN -FtwSmmIsBufferOutsideSmmValid ( +FtwSmmIsPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ); diff --git a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandaloneMm.c b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandaloneMm.c index 52922a0c5361..af837f03d51f 100644 --- a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandaloneMm.c +++ b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandaloneMm.c @@ -2,7 +2,7 @@ Parts of the SMM/MM implementation that are specific to standalone MM -Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2010 - 2024, Intel Corporation. All rights reserved.
Copyright (c) 2018, Linaro, Ltd. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -14,19 +14,16 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "FaultTolerantWriteSmmCommon.h" /** - This function checks if the buffer is valid per processor architecture and - does not overlap with SMRAM. + This function checks if the Primary Buffer is valid. @param Buffer The buffer start address to be checked. @param Length The buffer length to be checked. - @retval TRUE This buffer is valid per processor architecture and does not - overlap with SMRAM. - @retval FALSE This buffer is not valid per processor architecture or overlaps - with SMRAM. + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. **/ BOOLEAN -FtwSmmIsBufferOutsideSmmValid ( +FtwSmmIsPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ) diff --git a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteTraditionalMm.c b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteTraditionalMm.c index a7241e651a11..d0a218490b5e 100644 --- a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteTraditionalMm.c +++ b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteTraditionalMm.c @@ -2,7 +2,7 @@ Parts of the SMM/MM implementation that are specific to traditional MM -Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2011 - 2024, Intel Corporation. All rights reserved.
Copyright (c) 2018, Linaro, Ltd. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -14,7 +14,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "FaultTolerantWriteSmmCommon.h" /** - This function checks if the buffer is valid per processor architecture and + This function checks if the Primary Buffer is valid per processor architecture and does not overlap with SMRAM. @param Buffer The buffer start address to be checked. @@ -26,7 +26,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent with SMRAM. **/ BOOLEAN -FtwSmmIsBufferOutsideSmmValid ( +FtwSmmIsPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ) From c0021d31f847f9005cdc1386f8675375d455e8f2 Mon Sep 17 00:00:00 2001 From: Jiaxin Wu Date: Fri, 5 Jul 2024 11:06:25 +0800 Subject: [PATCH 59/67] MdeModulePkg/VarCheckPolicyLib: Update buffer valid check func name In the MdeModulePkg/VarCheckPolicyLib, the Primary Buffer (CommBuffer) check function has been updated to match the buffer validation behavior. For SMM, the SMM Handlers is to validate the buffer outside MMRAM. For MM, the MM Handlers do not need to validate the buffer if it is the CommBuffer passed from MmCore through the MmiHandler() parameter. Return TRUE directly in this case. Existing code is incorrect for the MM check. This will be fixed in the following patch. There is no function impact. Signed-off-by: Jiaxin Wu Cc: Liming Gao Cc: Ray Ni Cc: Star Zeng Cc: Hongbin1 Zhang Cc: Wei6 Xu Cc: Dun Tan Cc: Yuanhao Xie --- .../Library/VarCheckPolicyLib/VarCheckPolicyLib.c | 9 ++++++--- .../Library/VarCheckPolicyLib/VarCheckPolicyLib.h | 9 +++++---- .../VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.c | 9 +++++---- .../VarCheckPolicyLib/VarCheckPolicyLibTraditional.c | 5 +++-- 4 files changed, 19 insertions(+), 13 deletions(-) diff --git a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.c b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.c index 1448af85555a..3539206afca8 100644 --- a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.c +++ b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.c @@ -2,6 +2,7 @@ This is a NULL library instance that leverages the VarCheck interface and the business logic behind the VariablePolicy code to make its decisions. +Copyright (c) 2024, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -105,13 +106,15 @@ VarCheckPolicyLibMmiHandler ( return EFI_INVALID_PARAMETER; } - // Make sure that the buffer does not overlap SMM. + // + // Make sure that the buffer is valid. // This should be covered by the SmiManage infrastructure, but just to be safe... + // InternalCommBufferSize = *CommBufferSize; if ((InternalCommBufferSize > VAR_CHECK_POLICY_MM_COMM_BUFFER_SIZE) || - !VarCheckPolicyIsBufferOutsideValid ((UINTN)CommBuffer, (UINT64)InternalCommBufferSize)) + !VarCheckPolicyIsPrimaryBufferValid ((UINTN)CommBuffer, (UINT64)InternalCommBufferSize)) { - DEBUG ((DEBUG_ERROR, "%a - Invalid CommBuffer supplied! 0x%016lX[0x%016lX]\n", __func__, CommBuffer, InternalCommBufferSize)); + DEBUG ((DEBUG_ERROR, "%a - Invalid Primary Buffer (CommBuffer) supplied! 0x%016lX[0x%016lX]\n", __func__, CommBuffer, InternalCommBufferSize)); return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.h b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.h index 2226c8a19fec..5f89f1e28549 100644 --- a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.h +++ b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.h @@ -2,6 +2,7 @@ This internal header file defines the common interface of constructor for VarCheckPolicyLib. +Copyright (c) 2024, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -24,17 +25,17 @@ VarCheckPolicyLibCommonConstructor ( ); /** - This function is wrapper function to validate the buffer. + This function is wrapper function to validate the Primary Buffer (CommBuffer). @param Buffer The buffer start address to be checked. @param Length The buffer length to be checked. - @retval TRUE This buffer is valid per processor architecture and not overlap with SMRAM/MMRAM. - @retval FALSE This buffer is not valid per processor architecture or overlap with SMRAM/MMRAM. + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. **/ BOOLEAN EFIAPI -VarCheckPolicyIsBufferOutsideValid ( +VarCheckPolicyIsPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ); diff --git a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.c b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.c index 784a2422aa33..f93ad7e7c06e 100644 --- a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.c +++ b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.c @@ -1,6 +1,7 @@ /** @file -- VarCheckPolicyLibStandaloneMm.c This is an instance of a VarCheck lib constructor for Standalone MM. +Copyright (c) 2024, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -31,17 +32,17 @@ VarCheckPolicyLibStandaloneConstructor ( } /** - This function is wrapper function to validate the buffer. + This function is wrapper function to validate the Primary Buffer (CommBuffer). @param Buffer The buffer start address to be checked. @param Length The buffer length to be checked. - @retval TRUE This buffer is valid per processor architectureand not overlap with MMRAM. - @retval FALSE This buffer is not valid per processor architecture or overlap with MMRAM. + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. **/ BOOLEAN EFIAPI -VarCheckPolicyIsBufferOutsideValid ( +VarCheckPolicyIsPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ) diff --git a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibTraditional.c b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibTraditional.c index 07bead27241e..36dccefdd9d1 100644 --- a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibTraditional.c +++ b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibTraditional.c @@ -1,6 +1,7 @@ /** @file -- VarCheckPolicyLibTraditional.c This is an instance of a VarCheck lib constructor for traditional SMM. +Copyright (c) 2024, Intel Corporation. All rights reserved.
Copyright (c) Microsoft Corporation. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent @@ -31,7 +32,7 @@ VarCheckPolicyLibTraditionalConstructor ( } /** - This function is wrapper function to validate the buffer. + This function is wrapper function to validate the Primary Buffer (CommBuffer). @param Buffer The buffer start address to be checked. @param Length The buffer length to be checked. @@ -41,7 +42,7 @@ VarCheckPolicyLibTraditionalConstructor ( **/ BOOLEAN EFIAPI -VarCheckPolicyIsBufferOutsideValid ( +VarCheckPolicyIsPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ) From acfdb6771cdf5db13f8a829b4e1c9f9b45178151 Mon Sep 17 00:00:00 2001 From: Jiaxin Wu Date: Fri, 5 Jul 2024 11:14:16 +0800 Subject: [PATCH 60/67] MdeModulePkg/VarCheckPolicyLib: Fix buffer valid check for MM For MM, the MM Handlers do not need to validate the buffer if it is the CommBuffer passed from MmCore through the MmiHandler() parameter. Return TRUE directly in this case. Fix buffer valid check for MM in this patch. Signed-off-by: Jiaxin Wu Cc: Liming Gao Cc: Ray Ni Cc: Star Zeng Cc: Hongbin1 Zhang Cc: Wei6 Xu Cc: Dun Tan Cc: Yuanhao Xie --- .../Library/VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.c b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.c index f93ad7e7c06e..4bfaf1e261a7 100644 --- a/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.c +++ b/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.c @@ -47,5 +47,5 @@ VarCheckPolicyIsPrimaryBufferValid ( IN UINT64 Length ) { - return MmIsBufferOutsideMmValid (Buffer, Length); + return TRUE; } From 8befdb144193f0fe10c39ab0c21e138c59018b05 Mon Sep 17 00:00:00 2001 From: Jiaxin Wu Date: Fri, 31 May 2024 12:11:53 +0800 Subject: [PATCH 61/67] MdeModulePkg/VariableSmm: Add func for Primary Buffer valid check Add a new function (VariableSmmIsPrimaryBufferValid) to check Primary Buffer valid or not. original function (VariableSmmIsBufferOutsideSmmValid) is used to check the buffer outside MMRAM. Signed-off-by: Jiaxin Wu Cc: Liming Gao Cc: Ray Ni Cc: Star Zeng Cc: Hongbin1 Zhang Cc: Wei6 Xu Cc: Dun Tan Cc: Yuanhao Xie --- .../RuntimeDxe/PrivilegePolymorphic.h | 17 +++++++++++++++- .../Variable/RuntimeDxe/VariableSmm.c | 6 +++--- .../RuntimeDxe/VariableStandaloneMm.c | 20 ++++++++++++++++++- .../RuntimeDxe/VariableTraditionalMm.c | 20 ++++++++++++++++++- 4 files changed, 57 insertions(+), 6 deletions(-) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/PrivilegePolymorphic.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/PrivilegePolymorphic.h index 065c75a64269..23e950aaed5b 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/PrivilegePolymorphic.h +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/PrivilegePolymorphic.h @@ -7,7 +7,7 @@ vs. non-privileged driver code. Copyright (c) 2017, Red Hat, Inc.
- Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.
+ Copyright (c) 2010 - 2024, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -122,6 +122,21 @@ MmVariableServiceInitialize ( VOID ); +/** + This function checks if the communication buffer is valid. + + @param Buffer The buffer start address to be checked. + @param Length The buffer length to be checked. + + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. +**/ +BOOLEAN +VariableSmmIsPrimaryBufferValid ( + IN EFI_PHYSICAL_ADDRESS Buffer, + IN UINT64 Length + ); + /** This function checks if the buffer is valid per processor architecture and does not overlap with SMRAM. diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c index 5253c328dcd9..189880c817c0 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c @@ -14,7 +14,7 @@ VariableServiceSetVariable(), VariableServiceQueryVariableInfo(), ReclaimForOS(), SmmVariableGetStatistics() should also do validation based on its own knowledge. -Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2010 - 2024, Intel Corporation. All rights reserved.
Copyright (c) 2018, Linaro, Ltd. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -497,8 +497,8 @@ SmmVariableHandler ( return EFI_SUCCESS; } - if (!VariableSmmIsBufferOutsideSmmValid ((UINTN)CommBuffer, TempCommBufferSize)) { - DEBUG ((DEBUG_ERROR, "SmmVariableHandler: SMM communication buffer in SMRAM or overflow!\n")); + if (!VariableSmmIsPrimaryBufferValid ((UINTN)CommBuffer, TempCommBufferSize)) { + DEBUG ((DEBUG_ERROR, "SmmVariableHandler: SMM Primary Buffer (CommBuffer) is not valid!\n")); return EFI_SUCCESS; } diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.c index 943993eb6738..1e1e933405e8 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.c @@ -2,7 +2,7 @@ Parts of the SMM/MM implementation that are specific to standalone MM -Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2011 - 2024, Intel Corporation. All rights reserved.
Copyright (c) 2018, Linaro, Ltd. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -10,6 +10,24 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Variable.h" +/** + This function checks if the Primary Buffer (CommBuffer) is valid. + + @param Buffer The buffer start address to be checked. + @param Length The buffer length to be checked. + + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. +**/ +BOOLEAN +VariableSmmIsPrimaryBufferValid ( + IN EFI_PHYSICAL_ADDRESS Buffer, + IN UINT64 Length + ) +{ + return TRUE; +} + /** This function checks if the buffer is valid per processor architecture and does not overlap with SMRAM. diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableTraditionalMm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableTraditionalMm.c index 0369c3cd01b1..35f6f4b04f10 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableTraditionalMm.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableTraditionalMm.c @@ -2,7 +2,7 @@ Parts of the SMM/MM implementation that are specific to traditional MM -Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2011 - 2024, Intel Corporation. All rights reserved.
Copyright (c) 2018, Linaro, Ltd. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -12,6 +12,24 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include "Variable.h" +/** + This function checks if the Primary Buffer (CommBuffer) is valid. + + @param Buffer The buffer start address to be checked. + @param Length The buffer length to be checked. + + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. +**/ +BOOLEAN +VariableSmmIsPrimaryBufferValid ( + IN EFI_PHYSICAL_ADDRESS Buffer, + IN UINT64 Length + ) +{ + return SmmIsBufferOutsideSmmValid (Buffer, Length); +} + /** This function checks if the buffer is valid per processor architecture and does not overlap with SMRAM. From 0986faad973c8d2e98cb8733f9c58d0210f458f4 Mon Sep 17 00:00:00 2001 From: Jiaxin Wu Date: Fri, 31 May 2024 12:27:54 +0800 Subject: [PATCH 62/67] MdeModulePkg/VariableSmm: Fix NonPrimary Buffer check issue VariableSmmIsBufferOutsideSmmValid function is to check the buffer is outside SMM or not. This patch fix the issue that always return true for MM. Meanwhile, this patch renames VariableSmmIsBufferOutsideSmmValid to VariableSmmIsNonPrimaryBufferValid. Signed-off-by: Jiaxin Wu Cc: Liming Gao Cc: Ray Ni Cc: Star Zeng Cc: Hongbin1 Zhang Cc: Wei6 Xu Cc: Dun Tan Cc: Yuanhao Xie --- .../Variable/RuntimeDxe/PrivilegePolymorphic.h | 4 ++-- .../Universal/Variable/RuntimeDxe/VariableSmm.c | 12 ++++++------ .../Variable/RuntimeDxe/VariableStandaloneMm.c | 6 +++--- .../Variable/RuntimeDxe/VariableStandaloneMm.inf | 3 ++- .../Variable/RuntimeDxe/VariableTraditionalMm.c | 2 +- 5 files changed, 14 insertions(+), 13 deletions(-) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/PrivilegePolymorphic.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/PrivilegePolymorphic.h index 23e950aaed5b..e7bd4c9706b1 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/PrivilegePolymorphic.h +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/PrivilegePolymorphic.h @@ -123,7 +123,7 @@ MmVariableServiceInitialize ( ); /** - This function checks if the communication buffer is valid. + This function checks if the Primary Buffer (CommBuffer) is valid. @param Buffer The buffer start address to be checked. @param Length The buffer length to be checked. @@ -150,7 +150,7 @@ VariableSmmIsPrimaryBufferValid ( with SMRAM. **/ BOOLEAN -VariableSmmIsBufferOutsideSmmValid ( +VariableSmmIsNonPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ); diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c index 189880c817c0..12b76a9746a0 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c @@ -864,7 +864,7 @@ SmmVariableHandler ( // Verify runtime buffers do not overlap with SMRAM ranges. // if ((RuntimeVariableCacheContext->RuntimeHobCache != NULL) && - !VariableSmmIsBufferOutsideSmmValid ( + !VariableSmmIsNonPrimaryBufferValid ( (UINTN)RuntimeVariableCacheContext->RuntimeHobCache, (UINTN)RuntimeVariableCacheContext->RuntimeHobCache->Size )) @@ -874,7 +874,7 @@ SmmVariableHandler ( goto EXIT; } - if (!VariableSmmIsBufferOutsideSmmValid ( + if (!VariableSmmIsNonPrimaryBufferValid ( (UINTN)RuntimeVariableCacheContext->RuntimeVolatileCache, (UINTN)RuntimeVariableCacheContext->RuntimeVolatileCache->Size )) @@ -884,7 +884,7 @@ SmmVariableHandler ( goto EXIT; } - if (!VariableSmmIsBufferOutsideSmmValid ( + if (!VariableSmmIsNonPrimaryBufferValid ( (UINTN)RuntimeVariableCacheContext->RuntimeNvCache, (UINTN)RuntimeVariableCacheContext->RuntimeNvCache->Size )) @@ -894,7 +894,7 @@ SmmVariableHandler ( goto EXIT; } - if (!VariableSmmIsBufferOutsideSmmValid ( + if (!VariableSmmIsNonPrimaryBufferValid ( (UINTN)RuntimeVariableCacheContext->PendingUpdate, sizeof (*(RuntimeVariableCacheContext->PendingUpdate)) )) @@ -904,7 +904,7 @@ SmmVariableHandler ( goto EXIT; } - if (!VariableSmmIsBufferOutsideSmmValid ( + if (!VariableSmmIsNonPrimaryBufferValid ( (UINTN)RuntimeVariableCacheContext->ReadLock, sizeof (*(RuntimeVariableCacheContext->ReadLock)) )) @@ -914,7 +914,7 @@ SmmVariableHandler ( goto EXIT; } - if (!VariableSmmIsBufferOutsideSmmValid ( + if (!VariableSmmIsNonPrimaryBufferValid ( (UINTN)RuntimeVariableCacheContext->HobFlushComplete, sizeof (*(RuntimeVariableCacheContext->HobFlushComplete)) )) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.c index 1e1e933405e8..1b9cf6dfd9d0 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.c @@ -7,7 +7,7 @@ Copyright (c) 2018, Linaro, Ltd. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ - +#include #include "Variable.h" /** @@ -41,12 +41,12 @@ VariableSmmIsPrimaryBufferValid ( with SMRAM. **/ BOOLEAN -VariableSmmIsBufferOutsideSmmValid ( +VariableSmmIsNonPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ) { - return TRUE; + return MmIsBufferOutsideMmValid (Buffer, Length); } /** diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf index f09bed40cf51..c4185718aac0 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf @@ -18,7 +18,7 @@ # may not be modified without authorization. If platform fails to protect these resources, # the authentication service provided in this driver will be broken, and the behavior is undefined. # -# Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2010 - 2024, Intel Corporation. All rights reserved.
# Copyright (c) 2018, Linaro, Ltd. All rights reserved.
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -71,6 +71,7 @@ BaseMemoryLib DebugLib HobLib + MemLib MemoryAllocationLib MmServicesTableLib SafeIntLib diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableTraditionalMm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableTraditionalMm.c index 35f6f4b04f10..7247f7574d09 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableTraditionalMm.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableTraditionalMm.c @@ -43,7 +43,7 @@ VariableSmmIsPrimaryBufferValid ( with SMRAM. **/ BOOLEAN -VariableSmmIsBufferOutsideSmmValid ( +VariableSmmIsNonPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ) From d5fad2176cb14283922e07ff1758118d16b17383 Mon Sep 17 00:00:00 2001 From: Jiaxin Wu Date: Mon, 27 May 2024 13:25:15 +0800 Subject: [PATCH 63/67] SecurityPkg/Tcg: Correct buffer valid check func For SMM, the SMM Handlers is to validate the buffer outside MMRAM including the Primary & NonPrimary buffer. For MM, the MM Handlers do not need to validate the Primary buffer if it is passed from MmCore through the MmiHandler() parameter. Return TRUE directly in this case. But need to validate NonPrimary buffer that outside MMRAM. Signed-off-by: Jiaxin Wu Cc: Jiewen Yao Cc: Ray Ni Cc: Star Zeng Cc: Hongbin1 Zhang Cc: Wei6 Xu Cc: Dun Tan Cc: Yuanhao Xie --- SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c | 18 ++++++++++--- SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h | 27 ++++++++++++++++--- SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.c | 30 ++++++++++++++++++--- SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c | 26 ++++++++++++++++-- 4 files changed, 88 insertions(+), 13 deletions(-) diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c index c2cef764e0c0..0c2799b42a71 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c @@ -73,16 +73,28 @@ TpmNvsCommunciate ( return EFI_ACCESS_DENIED; } - if (!IsBufferOutsideMmValid ((UINTN)CommBuffer, TempCommBufferSize)) { + CommParams = (TPM_NVS_MM_COMM_BUFFER *)CommBuffer; + + // + // The Primary Buffer validation + // + if (!Tcg2IsPrimaryBufferValid ((UINTN)CommBuffer, TempCommBufferSize)) { DEBUG ((DEBUG_ERROR, "[%a] - MM Communication buffer in invalid location!\n", __func__)); return EFI_ACCESS_DENIED; } + // + // The NonPrimary Buffer validation + // + if (!Tcg2IsNonPrimaryBufferValid (CommParams->TargetAddress, EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (sizeof (TCG_NVS))))) { + DEBUG ((DEBUG_ERROR, "[%a] - MM NonPrimary buffer pointed from Communication buffer in invalid location!\n", __func__)); + return EFI_ACCESS_DENIED; + } + // // Farm out the job to individual functions based on what was requested. // - CommParams = (TPM_NVS_MM_COMM_BUFFER *)CommBuffer; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; switch (CommParams->Function) { case TpmNvsMmExchangeInfo: DEBUG ((DEBUG_VERBOSE, "[%a] - Function requested: MM_EXCHANGE_NVS_INFO\n", __func__)); diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h index 3672db939b9f..0be4984f87db 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h @@ -55,16 +55,35 @@ Tcg2NotifyMmReady ( ); /** - This function is an abstraction layer for implementation specific Mm buffer validation routine. + This function is for the Primary Buffer validation routine. + The Primary Buffer is the communication buffer requested from + Communicate protocol/PPI. @param Buffer The buffer start address to be checked. @param Length The buffer length to be checked. - @retval TRUE This buffer is valid per processor architecture and not overlap with SMRAM. - @retval FALSE This buffer is not valid per processor architecture or overlap with SMRAM. + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. **/ BOOLEAN -IsBufferOutsideMmValid ( +Tcg2IsPrimaryBufferValid ( + IN EFI_PHYSICAL_ADDRESS Buffer, + IN UINT64 Length + ); + +/** + This function is for the NonPrimary Buffer validation routine. + The NonPrimary Buffer is the buffer which might be pointed from the + communication buffer. + + @param Buffer The buffer start address to be checked. + @param Length The buffer length to be checked. + + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. +**/ +BOOLEAN +Tcg2IsNonPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ); diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.c b/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.c index 9320053224aa..0f23662ff8ce 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.c +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2StandaloneMm.c @@ -31,16 +31,38 @@ Tcg2NotifyMmReady ( } /** - This function is an abstraction layer for implementation specific Mm buffer validation routine. + This function is for the Primary Buffer validation routine. + The Primary Buffer is the communication buffer requested from + Communicate protocol/PPI. @param Buffer The buffer start address to be checked. @param Length The buffer length to be checked. - @retval TRUE This buffer is valid per processor architecture and not overlap with SMRAM. - @retval FALSE This buffer is not valid per processor architecture or overlap with SMRAM. + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. **/ BOOLEAN -IsBufferOutsideMmValid ( +Tcg2IsPrimaryBufferValid ( + IN EFI_PHYSICAL_ADDRESS Buffer, + IN UINT64 Length + ) +{ + return TRUE; +} + +/** + This function is for the Secondary Buffer validation routine. + The Secondary Buffer is the buffer which is pointed from the + communication buffer. + + @param Buffer The buffer start address to be checked. + @param Length The buffer length to be checked. + + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. +**/ +BOOLEAN +Tcg2IsNonPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ) diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c b/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c index f7d595e7f3f4..fd8a51bfd04b 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c @@ -41,7 +41,9 @@ Tcg2NotifyMmReady ( } /** - This function is an abstraction layer for implementation specific Mm buffer validation routine. + This function is for the Primary Buffer validation routine. + The Primary Buffer is the communication buffer requested from + Communicate protocol/PPI. @param Buffer The buffer start address to be checked. @param Length The buffer length to be checked. @@ -50,7 +52,27 @@ Tcg2NotifyMmReady ( @retval FALSE This buffer is not valid per processor architecture or overlap with SMRAM. **/ BOOLEAN -IsBufferOutsideMmValid ( +Tcg2IsPrimaryBufferValid ( + IN EFI_PHYSICAL_ADDRESS Buffer, + IN UINT64 Length + ) +{ + return SmmIsBufferOutsideSmmValid (Buffer, Length); +} + +/** + This function is for the NonPrimary Buffer validation routine. + The NonPrimary Buffer is the buffer which is pointed from the + communication buffer. + + @param Buffer The buffer start address to be checked. + @param Length The buffer length to be checked. + + @retval TRUE This buffer is valid. + @retval FALSE This buffer is not valid. +**/ +BOOLEAN +Tcg2IsNonPrimaryBufferValid ( IN EFI_PHYSICAL_ADDRESS Buffer, IN UINT64 Length ) From 19bcc73213ba1cb280b6e455dea7e153217d579c Mon Sep 17 00:00:00 2001 From: Wei6 Xu Date: Tue, 21 May 2024 10:45:17 +0800 Subject: [PATCH 64/67] MdeModulePkg: Add HobPrintLib header file Interface PrintHobList() is added to dump all HOBs info in the HobList. Caller could specify a custom HOB print handler to replace the default print handler when calling the interface. Cc: Ray Ni Cc: Liming Gao Signed-off-by: Wei6 Xu --- MdeModulePkg/Include/Library/HobPrintLib.h | 46 ++++++++++++++++++++++ MdeModulePkg/MdeModulePkg.dec | 4 ++ 2 files changed, 50 insertions(+) create mode 100644 MdeModulePkg/Include/Library/HobPrintLib.h diff --git a/MdeModulePkg/Include/Library/HobPrintLib.h b/MdeModulePkg/Include/Library/HobPrintLib.h new file mode 100644 index 000000000000..40bb035b9168 --- /dev/null +++ b/MdeModulePkg/Include/Library/HobPrintLib.h @@ -0,0 +1,46 @@ +/** @file + The library to print all the HOBs. + + Copyright (c) 2024, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef HOB_PRINT_LIB_H_ +#define HOB_PRINT_LIB_H_ + +/** + HOB Print Handler to print HOB information. + + @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_GUID_EXTENSION. + @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_GUID_EXTENSION. + + @retval EFI_SUCCESS If it completed successfully. + @retval EFI_UNSUPPORTED If the HOB type is not supported. + +**/ +typedef +EFI_STATUS +(*HOB_PRINT_HANDLER)( + IN VOID *Hob, + IN UINT16 HobLength + ); + +/** + Print all HOBs info from the HOB list. + If the input PrintHandler is not NULL, the PrintHandler will be processed first. + If PrintHandler returns EFI_SUCCESS, default HOB info print logic in PrintHobList + will be skipped. + + @param[in] HobStart A pointer to the HOB list. + @param[in] PrintHandler A custom handler to print HOB info. + +**/ +VOID +EFIAPI +PrintHobList ( + IN CONST VOID *HobStart, + IN HOB_PRINT_HANDLER PrintHandler OPTIONAL + ); + +#endif diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index 6148025085c9..e6e0139fdcb3 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -174,6 +174,10 @@ # SpiHcPlatformLib|Include/Library/SpiHcPlatformLib.h + ## @libraryclass Provides services to prints all HOB information. + # + HobPrintLib|Include/Library/HobPrintLib.h + [Guids] ## MdeModule package token space guid # Include/Guid/MdeModulePkgTokenSpace.h From d5b03d5fba30deb77e3ba0c21f6b0ceb412a9c26 Mon Sep 17 00:00:00 2001 From: Wei6 Xu Date: Mon, 27 May 2024 14:35:47 +0800 Subject: [PATCH 65/67] MdeModulePkg: Add HobPrintLib instance The HobPrintLib prints all HOB info from the HOB list. The code is abstracted from UefiPayloadPkg/UefiPayloadEntry/PrintHob.c. Cc: Guo Dong Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Cc: Ray Ni Signed-off-by: Wei6 Xu --- .../Library/HobPrintLib/HobPrintLib.c | 469 ++++++++++++++++++ .../Library/HobPrintLib/HobPrintLib.inf | 34 ++ MdeModulePkg/MdeModulePkg.dsc | 1 + 3 files changed, 504 insertions(+) create mode 100644 MdeModulePkg/Library/HobPrintLib/HobPrintLib.c create mode 100644 MdeModulePkg/Library/HobPrintLib/HobPrintLib.inf diff --git a/MdeModulePkg/Library/HobPrintLib/HobPrintLib.c b/MdeModulePkg/Library/HobPrintLib/HobPrintLib.c new file mode 100644 index 000000000000..d2fa92ee6a76 --- /dev/null +++ b/MdeModulePkg/Library/HobPrintLib/HobPrintLib.c @@ -0,0 +1,469 @@ +/** @file + Prints all the HOBs. + + Copyright (c) 2024, Intel Corporation. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define ROW_LIMITER 16 + +typedef struct { + UINT16 Type; + CHAR8 *Name; + HOB_PRINT_HANDLER PrintHandler; +} HOB_PRINT_HANDLER_TABLE; + +CHAR8 *mMemoryTypeStr[] = { + "EfiReservedMemoryType", + "EfiLoaderCode", + "EfiLoaderData", + "EfiBootServicesCode", + "EfiBootServicesData", + "EfiRuntimeServicesCode", + "EfiRuntimeServicesData", + "EfiConventionalMemory", + "EfiUnusableMemory", + "EfiACPIReclaimMemory", + "EfiACPIMemoryNVS", + "EfiMemoryMappedIO", + "EfiMemoryMappedIOPortSpace", + "EfiPalCode", + "EfiPersistentMemory", + "EfiMaxMemoryType" +}; + +CHAR8 *mResource_Type_List[] = { + "EFI_RESOURCE_SYSTEM_MEMORY ", // 0x00000000 + "EFI_RESOURCE_MEMORY_MAPPED_IO ", // 0x00000001 + "EFI_RESOURCE_IO ", // 0x00000002 + "EFI_RESOURCE_FIRMWARE_DEVICE ", // 0x00000003 + "EFI_RESOURCE_MEMORY_MAPPED_IO_PORT ", // 0x00000004 + "EFI_RESOURCE_MEMORY_RESERVED ", // 0x00000005 + "EFI_RESOURCE_IO_RESERVED ", // 0x00000006 + "EFI_RESOURCE_MAX_MEMORY_TYPE " // 0x00000007 +}; + +/** + Print the Hex value of a given range. + + @param[in] ErrorLevel Error Level to print the Hex value. + @param[in] DataStart A pointer to the start of data to be printed. + @param[in] DataSize The length of the data to be printed. + + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintHex ( + IN UINT32 ErrorLevel, + IN UINT8 *DataStart, + IN UINT16 DataSize + ) +{ + UINTN Index1; + UINTN Index2; + UINT8 *StartAddr; + + StartAddr = DataStart; + for (Index1 = 0; Index1 * ROW_LIMITER < DataSize; Index1++) { + DEBUG ((ErrorLevel, " 0x%04p:", (DataStart - StartAddr))); + for (Index2 = 0; (Index2 < ROW_LIMITER) && (Index1 * ROW_LIMITER + Index2 < DataSize); Index2++) { + DEBUG ((ErrorLevel, " %02x", *DataStart)); + DataStart++; + } + + DEBUG ((ErrorLevel, "\n")); + } + + return EFI_SUCCESS; +} + +/** + Print the Hex value of the Invalid HOB. + + @param[in] HobStart A pointer to the Invalid HOB. + @param[in] HobLength The length in bytes of the Invalid HOB. + + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintInvalidHob ( + IN VOID *HobStart, + IN UINT16 HobLength + ) +{ + DEBUG ((DEBUG_ERROR, " Invalid HOB. Full hex dump in below:\n")); + PrintHex (DEBUG_ERROR, HobStart, HobLength); + return RETURN_INVALID_PARAMETER; +} + +/** + Print the information in HandOffHob. + + @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_HANDOFF. + @param[in] HobLength The length in bytes of HOB of type EFI_HOB_TYPE_HANDOFF. + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintHandOffHob ( + IN VOID *HobStart, + IN UINT16 HobLength + ) +{ + EFI_PEI_HOB_POINTERS Hob; + + Hob.Raw = (UINT8 *)HobStart; + if (HobLength < sizeof (*Hob.HandoffInformationTable)) { + return PrintInvalidHob (HobStart, HobLength); + } + + DEBUG ((DEBUG_INFO, " BootMode = 0x%x\n", Hob.HandoffInformationTable->BootMode)); + DEBUG ((DEBUG_INFO, " EfiMemoryTop = 0x%lx\n", Hob.HandoffInformationTable->EfiMemoryTop)); + DEBUG ((DEBUG_INFO, " EfiMemoryBottom = 0x%lx\n", Hob.HandoffInformationTable->EfiMemoryBottom)); + DEBUG ((DEBUG_INFO, " EfiFreeMemoryTop = 0x%lx\n", Hob.HandoffInformationTable->EfiFreeMemoryTop)); + DEBUG ((DEBUG_INFO, " EfiFreeMemoryBottom = 0x%lx\n", Hob.HandoffInformationTable->EfiFreeMemoryBottom)); + DEBUG ((DEBUG_INFO, " EfiEndOfHobList = 0x%lx\n", Hob.HandoffInformationTable->EfiEndOfHobList)); + return EFI_SUCCESS; +} + +/** + Print the information in Memory Allocation Hob. + @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_MEMORY_ALLOCATION. + @param[in] HobLength The length in bytes of HOB of type EFI_HOB_TYPE_MEMORY_ALLOCATION. + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintMemoryAllocationHob ( + IN VOID *HobStart, + IN UINT16 HobLength + ) +{ + EFI_PEI_HOB_POINTERS Hob; + + Hob.Raw = (UINT8 *)HobStart; + + if (CompareGuid (&Hob.MemoryAllocation->AllocDescriptor.Name, &gEfiHobMemoryAllocStackGuid)) { + if (HobLength < sizeof (*Hob.MemoryAllocationStack)) { + return PrintInvalidHob (HobStart, HobLength); + } + + DEBUG ((DEBUG_INFO, " Type = EFI_HOB_MEMORY_ALLOCATION_STACK\n")); + } else if (CompareGuid (&Hob.MemoryAllocation->AllocDescriptor.Name, &gEfiHobMemoryAllocBspStoreGuid)) { + if (HobLength < sizeof (*Hob.MemoryAllocationBspStore)) { + return PrintInvalidHob (HobStart, HobLength); + } + + DEBUG ((DEBUG_INFO, " Type = EFI_HOB_MEMORY_ALLOCATION_BSP_STORE\n")); + } else if (CompareGuid (&Hob.MemoryAllocation->AllocDescriptor.Name, &gEfiHobMemoryAllocModuleGuid)) { + if (HobLength < sizeof (*Hob.MemoryAllocationModule)) { + return PrintInvalidHob (HobStart, HobLength); + } + + DEBUG ((DEBUG_INFO, " Type = EFI_HOB_MEMORY_ALLOCATION_MODULE\n")); + DEBUG ((DEBUG_INFO, " ModuleName = %g\n", &Hob.MemoryAllocationModule->ModuleName)); + DEBUG ((DEBUG_INFO, " EntryPoint = 0x%lx\n", Hob.MemoryAllocationModule->EntryPoint)); + } else { + if (HobLength < sizeof (*Hob.MemoryAllocation)) { + return PrintInvalidHob (HobStart, HobLength); + } + + DEBUG ((DEBUG_INFO, " Type = EFI_HOB_TYPE_MEMORY_ALLOCATION\n")); + } + + DEBUG ((DEBUG_INFO, " Name = %g\n", &Hob.MemoryAllocationStack->AllocDescriptor.Name)); + DEBUG ((DEBUG_INFO, " MemoryBaseAddress = 0x%lx\n", Hob.MemoryAllocationStack->AllocDescriptor.MemoryBaseAddress)); + DEBUG ((DEBUG_INFO, " MemoryLength = 0x%lx\n", Hob.MemoryAllocationStack->AllocDescriptor.MemoryLength)); + DEBUG ((DEBUG_INFO, " MemoryType = %a \n", mMemoryTypeStr[Hob.MemoryAllocationStack->AllocDescriptor.MemoryType])); + return EFI_SUCCESS; +} + +/** + Print the information in Resource Discriptor Hob. + @param[in] HobStart A pointer to HOB of type EFI_HOB_TYPE_RESOURCE_DESCRIPTOR. + @param[in] HobLength The Length in bytes of HOB of type EFI_HOB_TYPE_RESOURCE_DESCRIPTOR. + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintResourceDiscriptorHob ( + IN VOID *HobStart, + IN UINT16 HobLength + ) +{ + EFI_PEI_HOB_POINTERS Hob; + + Hob.Raw = (UINT8 *)HobStart; + ASSERT (HobLength >= sizeof (*Hob.ResourceDescriptor)); + + DEBUG ((DEBUG_INFO, " ResourceType = %a\n", mResource_Type_List[Hob.ResourceDescriptor->ResourceType])); + if (!IsZeroGuid (&Hob.ResourceDescriptor->Owner)) { + DEBUG ((DEBUG_INFO, " Owner = %g\n", &Hob.ResourceDescriptor->Owner)); + } + + DEBUG ((DEBUG_INFO, " ResourceAttribute = 0x%x\n", Hob.ResourceDescriptor->ResourceAttribute)); + DEBUG ((DEBUG_INFO, " PhysicalStart = 0x%lx\n", Hob.ResourceDescriptor->PhysicalStart)); + DEBUG ((DEBUG_INFO, " ResourceLength = 0x%lx\n", Hob.ResourceDescriptor->ResourceLength)); + return EFI_SUCCESS; +} + +/** + Print the Guid Hob using related print handle function. + @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_GUID_EXTENSION. + @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_GUID_EXTENSION. + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintGuidHob ( + IN VOID *HobStart, + IN UINT16 HobLength + ) +{ + EFI_PEI_HOB_POINTERS Hob; + UINT16 DataLength; + + Hob.Raw = (UINT8 *)HobStart; + ASSERT (HobLength >= sizeof (*Hob.Guid)); + + DataLength = GET_GUID_HOB_DATA_SIZE (Hob.Raw); + + DEBUG ((DEBUG_INFO, " Name = %g\n", &Hob.Guid->Name)); + DEBUG ((DEBUG_INFO, " DataLength = 0x%x\n", DataLength)); + PrintHex (DEBUG_VERBOSE, GET_GUID_HOB_DATA (Hob.Raw), DataLength); + return EFI_SUCCESS; +} + +/** + Print the information in FV Hob. + @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_FV. + @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_FV. + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintFvHob ( + IN VOID *HobStart, + IN UINT16 HobLength + ) +{ + EFI_PEI_HOB_POINTERS Hob; + + Hob.Raw = (UINT8 *)HobStart; + ASSERT (HobLength >= sizeof (*Hob.FirmwareVolume)); + + DEBUG ((DEBUG_INFO, " BaseAddress = 0x%lx\n", Hob.FirmwareVolume->BaseAddress)); + DEBUG ((DEBUG_INFO, " Length = 0x%lx\n", Hob.FirmwareVolume->Length)); + return EFI_SUCCESS; +} + +/** + Print the information in Cpu Hob. + @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_CPU. + @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_CPU. + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintCpuHob ( + IN VOID *HobStart, + IN UINT16 HobLength + ) +{ + EFI_PEI_HOB_POINTERS Hob; + + Hob.Raw = (UINT8 *)HobStart; + ASSERT (HobLength >= sizeof (*Hob.Cpu)); + + DEBUG ((DEBUG_INFO, " SizeOfMemorySpace = 0x%lx\n", Hob.Cpu->SizeOfMemorySpace)); + DEBUG ((DEBUG_INFO, " SizeOfIoSpace = 0x%lx\n", Hob.Cpu->SizeOfIoSpace)); + return EFI_SUCCESS; +} + +/** + Print the information in MemoryPoolHob. + @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_MEMORY_POOL. + @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_MEMORY_POOL. + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintMemoryPoolHob ( + IN VOID *HobStart, + IN UINT16 HobLength + ) +{ + EFI_PEI_HOB_POINTERS Hob; + UINT16 AllocationSize; + + Hob.Raw = (UINT8 *)HobStart; + ASSERT (HobLength >= sizeof (*Hob.Pool)); + + AllocationSize = HobLength - sizeof (EFI_HOB_GENERIC_HEADER); + DEBUG ((DEBUG_INFO, " AllocationSize = 0x%lx\n", AllocationSize)); + + PrintHex (DEBUG_VERBOSE, Hob.Raw + sizeof (EFI_HOB_GENERIC_HEADER), AllocationSize); + + return EFI_SUCCESS; +} + +/** + Print the information in Fv2Hob. + @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_FV2. + @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_FV2. + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintFv2Hob ( + IN VOID *HobStart, + IN UINT16 HobLength + ) +{ + EFI_PEI_HOB_POINTERS Hob; + + Hob.Raw = (UINT8 *)HobStart; + ASSERT (HobLength >= sizeof (*Hob.FirmwareVolume2)); + + DEBUG ((DEBUG_INFO, " BaseAddress = 0x%lx\n", Hob.FirmwareVolume2->BaseAddress)); + DEBUG ((DEBUG_INFO, " Length = 0x%lx\n", Hob.FirmwareVolume2->Length)); + DEBUG ((DEBUG_INFO, " FvName = %g\n", &Hob.FirmwareVolume2->FvName)); + DEBUG ((DEBUG_INFO, " FileName = %g\n", &Hob.FirmwareVolume2->FileName)); + return EFI_SUCCESS; +} + +/** + Print the information in Capsule Hob. + @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_UEFI_CAPSULE. + @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_UEFI_CAPSULE. + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintCapsuleHob ( + IN VOID *HobStart, + IN UINT16 HobLength + ) +{ + EFI_PEI_HOB_POINTERS Hob; + + Hob.Raw = (UINT8 *)HobStart; + ASSERT (HobLength >= sizeof (*Hob.Capsule)); + + DEBUG ((DEBUG_INFO, " BaseAddress = 0x%lx\n", Hob.Capsule->BaseAddress)); + DEBUG ((DEBUG_INFO, " Length = 0x%lx\n", Hob.Capsule->Length)); + return EFI_SUCCESS; +} + +/** + Print the information in Fv3 Hob. + @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_FV3. + @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_FV3. + @retval EFI_SUCCESS If it completed successfully. +**/ +EFI_STATUS +PrintFv3Hob ( + IN VOID *HobStart, + IN UINT16 HobLength + ) +{ + EFI_PEI_HOB_POINTERS Hob; + + Hob.Raw = (UINT8 *)HobStart; + ASSERT (HobLength >= sizeof (*Hob.FirmwareVolume3)); + + DEBUG ((DEBUG_INFO, " BaseAddress = 0x%lx\n", Hob.FirmwareVolume3->BaseAddress)); + DEBUG ((DEBUG_INFO, " Length = 0x%lx\n", Hob.FirmwareVolume3->Length)); + DEBUG ((DEBUG_INFO, " AuthenticationStatus = 0x%x\n", Hob.FirmwareVolume3->AuthenticationStatus)); + DEBUG ((DEBUG_INFO, " ExtractedFv = %a\n", (Hob.FirmwareVolume3->ExtractedFv ? "True" : "False"))); + DEBUG ((DEBUG_INFO, " FvName = %g\n", &Hob.FirmwareVolume3->FvName)); + DEBUG ((DEBUG_INFO, " FileName = %g\n", &Hob.FirmwareVolume3->FileName)); + return EFI_SUCCESS; +} + +// +// Mapping table from Hob type to Hob print function. +// +HOB_PRINT_HANDLER_TABLE mHobHandles[] = { + { EFI_HOB_TYPE_HANDOFF, "EFI_HOB_TYPE_HANDOFF", PrintHandOffHob }, + { EFI_HOB_TYPE_MEMORY_ALLOCATION, "EFI_HOB_TYPE_MEMORY_ALLOCATION", PrintMemoryAllocationHob }, + { EFI_HOB_TYPE_RESOURCE_DESCRIPTOR, "EFI_HOB_TYPE_RESOURCE_DESCRIPTOR", PrintResourceDiscriptorHob }, + { EFI_HOB_TYPE_GUID_EXTENSION, "EFI_HOB_TYPE_GUID_EXTENSION", PrintGuidHob }, + { EFI_HOB_TYPE_FV, "EFI_HOB_TYPE_FV", PrintFvHob }, + { EFI_HOB_TYPE_CPU, "EFI_HOB_TYPE_CPU", PrintCpuHob }, + { EFI_HOB_TYPE_MEMORY_POOL, "EFI_HOB_TYPE_MEMORY_POOL", PrintMemoryPoolHob }, + { EFI_HOB_TYPE_FV2, "EFI_HOB_TYPE_FV2", PrintFv2Hob }, + { EFI_HOB_TYPE_UEFI_CAPSULE, "EFI_HOB_TYPE_UEFI_CAPSULE", PrintCapsuleHob }, + { EFI_HOB_TYPE_FV3, "EFI_HOB_TYPE_FV3", PrintFv3Hob } +}; + +/** + Print all HOBs info from the HOB list. + + @param[in] HobStart A pointer to the HOB list. + @param[in] PrintHandler A custom handler to print HOB info. + +**/ +VOID +EFIAPI +PrintHobList ( + IN CONST VOID *HobStart, + IN HOB_PRINT_HANDLER PrintHandler + ) +{ + EFI_STATUS Status; + EFI_PEI_HOB_POINTERS Hob; + UINTN Count; + UINTN Index; + + ASSERT (HobStart != NULL); + + Hob.Raw = (UINT8 *)HobStart; + DEBUG ((DEBUG_INFO, "Print all Hob information from Hob 0x%p\n", Hob.Raw)); + + Status = EFI_SUCCESS; + Count = 0; + // + // Parse the HOB list to see which type it is, and print the information. + // + while (!END_OF_HOB_LIST (Hob)) { + // + // Print HOB generic information + // + for (Index = 0; Index < ARRAY_SIZE (mHobHandles); Index++) { + if (Hob.Header->HobType == mHobHandles[Index].Type) { + DEBUG ((DEBUG_INFO, "HOB[%d]: Type = %a, Offset = 0x%p, Length = 0x%x\n", Count, mHobHandles[Index].Name, (Hob.Raw - (UINT8 *)HobStart), Hob.Header->HobLength)); + break; + } + } + + if (Index == ARRAY_SIZE (mHobHandles)) { + DEBUG ((DEBUG_INFO, "HOB[%d]: Type = %d, Offset = 0x%p, Length = 0x%x\n", Count, Hob.Header->HobType, (Hob.Raw - (UINT8 *)HobStart), Hob.Header->HobLength)); + } + + // + // Process custom HOB print handler first + // + if (PrintHandler != NULL) { + Status = PrintHandler (Hob.Raw, Hob.Header->HobLength); + } + + // + // Process internal HOB print handler + // + if ((PrintHandler == NULL) || EFI_ERROR (Status)) { + if (Index < ARRAY_SIZE (mHobHandles)) { + mHobHandles[Index].PrintHandler (Hob.Raw, Hob.Header->HobLength); + } else { + DEBUG ((DEBUG_INFO, " Unkown Hob type, full hex dump in below:\n")); + PrintHex (DEBUG_INFO, Hob.Raw, Hob.Header->HobLength); + } + } + + Count++; + Hob.Raw = GET_NEXT_HOB (Hob); + } + + DEBUG ((DEBUG_INFO, "There are totally %d Hobs, the End Hob address is %p\n", Count, Hob.Raw)); +} diff --git a/MdeModulePkg/Library/HobPrintLib/HobPrintLib.inf b/MdeModulePkg/Library/HobPrintLib/HobPrintLib.inf new file mode 100644 index 000000000000..a88cabf67def --- /dev/null +++ b/MdeModulePkg/Library/HobPrintLib/HobPrintLib.inf @@ -0,0 +1,34 @@ +## @file +# Library class that prints all HOBs. +# +# Copyright (c) 2024, Intel Corporation. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = HobPrintLib + FILE_GUID = 6b6f69c4-4272-4e8f-9c7f-747e7eed3ba8 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = HobPrintLib + +[Sources] + HobPrintLib.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + +[LibraryClasses] + BaseMemoryLib + DebugLib + HobLib + +[Guids] + gEfiHobMemoryAllocBspStoreGuid + gEfiHobMemoryAllocStackGuid + gEfiMemoryTypeInformationGuid diff --git a/MdeModulePkg/MdeModulePkg.dsc b/MdeModulePkg/MdeModulePkg.dsc index a1c8e2f90524..fe7ab972ad17 100644 --- a/MdeModulePkg/MdeModulePkg.dsc +++ b/MdeModulePkg/MdeModulePkg.dsc @@ -353,6 +353,7 @@ MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.inf MdeModulePkg/Library/DisplayUpdateProgressLibText/DisplayUpdateProgressLibText.inf MdeModulePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf + MdeModulePkg/Library/HobPrintLib/HobPrintLib.inf MdeModulePkg/Universal/BdsDxe/BdsDxe.inf MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenuApp.inf From e94cbfc84579304a7f4bfc99cf90ec8fba733ff1 Mon Sep 17 00:00:00 2001 From: Wei6 Xu Date: Mon, 27 May 2024 14:39:19 +0800 Subject: [PATCH 66/67] UefiPayloadPkg/UefiPayloadEntry: Use HobPrintLib to dump HOBs Leverage generic HOB print code in MdeModulePkg/Library/HobPrintLib. Print UefiPayload specified GUID HOB info as custom HOB print handler when calling the PrintHobList() interface. Cc: Guo Dong Cc: Sean Rhodes Cc: James Lu Cc: Gua Guo Cc: Ray Ni Signed-off-by: Wei6 Xu --- .../FitUniversalPayloadEntry.inf | 1 + UefiPayloadPkg/UefiPayloadEntry/PrintHob.c | 343 +----------------- .../UniversalPayloadEntry.inf | 1 + UefiPayloadPkg/UefiPayloadPkg.dsc | 1 + 4 files changed, 20 insertions(+), 326 deletions(-) diff --git a/UefiPayloadPkg/UefiPayloadEntry/FitUniversalPayloadEntry.inf b/UefiPayloadPkg/UefiPayloadEntry/FitUniversalPayloadEntry.inf index b87a0989eee3..04d0a795dc23 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/FitUniversalPayloadEntry.inf +++ b/UefiPayloadPkg/UefiPayloadEntry/FitUniversalPayloadEntry.inf @@ -54,6 +54,7 @@ PeCoffLib CpuLib FdtLib + HobPrintLib [Guids] gEfiMemoryTypeInformationGuid diff --git a/UefiPayloadPkg/UefiPayloadEntry/PrintHob.c b/UefiPayloadPkg/UefiPayloadEntry/PrintHob.c index b63e93c07ec2..8c5d9447593b 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/PrintHob.c +++ b/UefiPayloadPkg/UefiPayloadEntry/PrintHob.c @@ -10,51 +10,7 @@ #include #include #include - -#define ROW_LIMITER 16 - -typedef -EFI_STATUS -(*HOB_PRINT_HANDLER) ( - IN VOID *Hob, - IN UINT16 HobLength - ); - -typedef struct { - UINT16 Type; - CHAR8 *Name; - HOB_PRINT_HANDLER PrintHandler; -} HOB_PRINT_HANDLER_TABLE; - -CHAR8 *mMemoryTypeStr[] = { - "EfiReservedMemoryType", - "EfiLoaderCode", - "EfiLoaderData", - "EfiBootServicesCode", - "EfiBootServicesData", - "EfiRuntimeServicesCode", - "EfiRuntimeServicesData", - "EfiConventionalMemory", - "EfiUnusableMemory", - "EfiACPIReclaimMemory", - "EfiACPIMemoryNVS", - "EfiMemoryMappedIO", - "EfiMemoryMappedIOPortSpace", - "EfiPalCode", - "EfiPersistentMemory", - "EfiMaxMemoryType" -}; - -CHAR8 *mResource_Type_List[] = { - "EFI_RESOURCE_SYSTEM_MEMORY ", // 0x00000000 - "EFI_RESOURCE_MEMORY_MAPPED_IO ", // 0x00000001 - "EFI_RESOURCE_IO ", // 0x00000002 - "EFI_RESOURCE_FIRMWARE_DEVICE ", // 0x00000003 - "EFI_RESOURCE_MEMORY_MAPPED_IO_PORT ", // 0x00000004 - "EFI_RESOURCE_MEMORY_RESERVED ", // 0x00000005 - "EFI_RESOURCE_IO_RESERVED ", // 0x00000006 - "EFI_RESOURCE_MAX_MEMORY_TYPE " // 0x00000007 -}; +#include typedef EFI_STATUS @@ -69,133 +25,6 @@ typedef struct { CHAR8 *GuidName; } GUID_HOB_PRINT_HANDLE; -typedef struct { - EFI_GUID *Guid; - CHAR8 *Type; -} PRINT_MEMORY_ALLOCCATION_HOB; - -/** - Print the Hex value of a given range. - @param[in] DataStart A pointer to the start of data to be printed. - @param[in] DataSize The length of the data to be printed. - @retval EFI_SUCCESS If it completed successfully. -**/ -EFI_STATUS -PrintHex ( - IN UINT8 *DataStart, - IN UINT16 DataSize - ) -{ - UINTN Index1; - UINTN Index2; - UINT8 *StartAddr; - - StartAddr = DataStart; - for (Index1 = 0; Index1 * ROW_LIMITER < DataSize; Index1++) { - DEBUG ((DEBUG_VERBOSE, " 0x%04p:", (DataStart - StartAddr))); - for (Index2 = 0; (Index2 < ROW_LIMITER) && (Index1 * ROW_LIMITER + Index2 < DataSize); Index2++) { - DEBUG ((DEBUG_VERBOSE, " %02x", *DataStart)); - DataStart++; - } - - DEBUG ((DEBUG_VERBOSE, "\n")); - } - - return EFI_SUCCESS; -} - -/** - Print the information in HandOffHob. - - @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_HANDOFF. - @param[in] HobLength The length in bytes of HOB of type EFI_HOB_TYPE_HANDOFF. - @retval EFI_SUCCESS If it completed successfully. -**/ -EFI_STATUS -PrintHandOffHob ( - IN VOID *HobStart, - IN UINT16 HobLength - ) -{ - EFI_PEI_HOB_POINTERS Hob; - - Hob.Raw = (UINT8 *)HobStart; - ASSERT (HobLength >= sizeof (*Hob.HandoffInformationTable)); - DEBUG ((DEBUG_INFO, " BootMode = 0x%x\n", Hob.HandoffInformationTable->BootMode)); - DEBUG ((DEBUG_INFO, " EfiMemoryTop = 0x%lx\n", Hob.HandoffInformationTable->EfiMemoryTop)); - DEBUG ((DEBUG_INFO, " EfiMemoryBottom = 0x%lx\n", Hob.HandoffInformationTable->EfiMemoryBottom)); - DEBUG ((DEBUG_INFO, " EfiFreeMemoryTop = 0x%lx\n", Hob.HandoffInformationTable->EfiFreeMemoryTop)); - DEBUG ((DEBUG_INFO, " EfiFreeMemoryBottom = 0x%lx\n", Hob.HandoffInformationTable->EfiFreeMemoryBottom)); - DEBUG ((DEBUG_INFO, " EfiEndOfHobList = 0x%lx\n", Hob.HandoffInformationTable->EfiEndOfHobList)); - return EFI_SUCCESS; -} - -/** - Print the information in Memory Allocation Hob. - @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_MEMORY_ALLOCATION. - @param[in] HobLength The length in bytes of HOB of type EFI_HOB_TYPE_MEMORY_ALLOCATION. - @retval EFI_SUCCESS If it completed successfully. -**/ -EFI_STATUS -PrintMemoryAllocationHob ( - IN VOID *HobStart, - IN UINT16 HobLength - ) -{ - EFI_PEI_HOB_POINTERS Hob; - - Hob.Raw = (UINT8 *)HobStart; - - if (CompareGuid (&Hob.MemoryAllocation->AllocDescriptor.Name, &gEfiHobMemoryAllocStackGuid)) { - ASSERT (HobLength >= sizeof (*Hob.MemoryAllocationStack)); - DEBUG ((DEBUG_INFO, " Type = EFI_HOB_MEMORY_ALLOCATION_STACK\n")); - } else if (CompareGuid (&Hob.MemoryAllocation->AllocDescriptor.Name, &gEfiHobMemoryAllocBspStoreGuid)) { - ASSERT (HobLength >= sizeof (*Hob.MemoryAllocationBspStore)); - DEBUG ((DEBUG_INFO, " Type = EFI_HOB_MEMORY_ALLOCATION_BSP_STORE\n")); - } else if (CompareGuid (&Hob.MemoryAllocation->AllocDescriptor.Name, &gEfiHobMemoryAllocModuleGuid)) { - ASSERT (HobLength >= sizeof (*Hob.MemoryAllocationModule)); - DEBUG ((DEBUG_INFO, " Type = EFI_HOB_MEMORY_ALLOCATION_MODULE\n")); - DEBUG ((DEBUG_INFO, " Module Name = %g\n", Hob.MemoryAllocationModule->ModuleName)); - DEBUG ((DEBUG_INFO, " Physical Address = 0x%lx\n", Hob.MemoryAllocationModule->EntryPoint)); - } else { - ASSERT (HobLength >= sizeof (*Hob.MemoryAllocation)); - DEBUG ((DEBUG_INFO, " Type = EFI_HOB_TYPE_MEMORY_ALLOCATION\n")); - } - - DEBUG ((DEBUG_INFO, " MemoryBaseAddress = 0x%lx\n", Hob.MemoryAllocationStack->AllocDescriptor.MemoryBaseAddress)); - DEBUG ((DEBUG_INFO, " MemoryLength = 0x%lx\n", Hob.MemoryAllocationStack->AllocDescriptor.MemoryLength)); - DEBUG ((DEBUG_INFO, " MemoryType = %a \n", mMemoryTypeStr[Hob.MemoryAllocationStack->AllocDescriptor.MemoryType])); - return EFI_SUCCESS; -} - -/** - Print the information in Resource Discriptor Hob. - @param[in] HobStart A pointer to HOB of type EFI_HOB_TYPE_RESOURCE_DESCRIPTOR. - @param[in] HobLength The Length in bytes of HOB of type EFI_HOB_TYPE_RESOURCE_DESCRIPTOR. - @retval EFI_SUCCESS If it completed successfully. -**/ -EFI_STATUS -PrintResourceDiscriptorHob ( - IN VOID *HobStart, - IN UINT16 HobLength - ) -{ - EFI_PEI_HOB_POINTERS Hob; - - Hob.Raw = (UINT8 *)HobStart; - ASSERT (HobLength >= sizeof (*Hob.ResourceDescriptor)); - - DEBUG ((DEBUG_INFO, " ResourceType = %a\n", mResource_Type_List[Hob.ResourceDescriptor->ResourceType])); - if (!IsZeroGuid (&Hob.ResourceDescriptor->Owner)) { - DEBUG ((DEBUG_INFO, " Owner = %g\n", Hob.ResourceDescriptor->Owner)); - } - - DEBUG ((DEBUG_INFO, " ResourceAttribute = 0x%x\n", Hob.ResourceDescriptor->ResourceAttribute)); - DEBUG ((DEBUG_INFO, " PhysicalStart = 0x%lx\n", Hob.ResourceDescriptor->PhysicalStart)); - DEBUG ((DEBUG_INFO, " ResourceLength = 0x%lx\n", Hob.ResourceDescriptor->ResourceLength)); - return EFI_SUCCESS; -} - /** Print the information in Acpi Guid Hob. @@ -456,9 +285,10 @@ GUID_HOB_PRINT_HANDLE GuidHobPrintHandleTable[] = { @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_GUID_EXTENSION. @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_GUID_EXTENSION. @retval EFI_SUCCESS If it completed successfully. + @retval EFI_UNSUPPORTED If the HOB GUID is not supported. **/ EFI_STATUS -PrintGuidHob ( +InternalPrintGuidHob ( IN VOID *HobStart, IN UINT16 HobLength ) @@ -478,53 +308,7 @@ PrintGuidHob ( } } - DEBUG ((DEBUG_INFO, " Name = %g\n", &Hob.Guid->Name)); - PrintHex (GET_GUID_HOB_DATA (Hob.Raw), GET_GUID_HOB_DATA_SIZE (Hob.Raw)); - return EFI_SUCCESS; -} - -/** - Print the information in FV Hob. - @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_FV. - @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_FV. - @retval EFI_SUCCESS If it completed successfully. -**/ -EFI_STATUS -PrintFvHob ( - IN VOID *HobStart, - IN UINT16 HobLength - ) -{ - EFI_PEI_HOB_POINTERS Hob; - - Hob.Raw = (UINT8 *)HobStart; - ASSERT (HobLength >= sizeof (*Hob.FirmwareVolume)); - - DEBUG ((DEBUG_INFO, " BaseAddress = 0x%lx\n", Hob.FirmwareVolume->BaseAddress)); - DEBUG ((DEBUG_INFO, " Length = 0x%lx\n", Hob.FirmwareVolume->Length)); - return EFI_SUCCESS; -} - -/** - Print the information in Cpu Hob. - @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_CPU. - @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_CPU. - @retval EFI_SUCCESS If it completed successfully. -**/ -EFI_STATUS -PrintCpuHob ( - IN VOID *HobStart, - IN UINT16 HobLength - ) -{ - EFI_PEI_HOB_POINTERS Hob; - - Hob.Raw = (UINT8 *)HobStart; - ASSERT (HobLength >= sizeof (*Hob.Cpu)); - - DEBUG ((DEBUG_INFO, " SizeOfMemorySpace = 0x%lx\n", Hob.Cpu->SizeOfMemorySpace)); - DEBUG ((DEBUG_INFO, " SizeOfIoSpace = 0x%lx\n", Hob.Cpu->SizeOfIoSpace)); - return EFI_SUCCESS; + return EFI_UNSUPPORTED; } /** @@ -534,7 +318,7 @@ PrintCpuHob ( @retval EFI_SUCCESS If it completed successfully. **/ EFI_STATUS -PrintMemoryPoolHob ( +InternalPrintMemoryPoolHob ( IN VOID *HobStart, IN UINT16 HobLength ) @@ -543,37 +327,16 @@ PrintMemoryPoolHob ( } /** - Print the information in Fv2Hob. - @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_FV2. - @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_FV2. - @retval EFI_SUCCESS If it completed successfully. -**/ -EFI_STATUS -PrintFv2Hob ( - IN VOID *HobStart, - IN UINT16 HobLength - ) -{ - EFI_PEI_HOB_POINTERS Hob; + HOB Print Handler to print Guid Hob. - Hob.Raw = (UINT8 *)HobStart; - ASSERT (HobLength >= sizeof (*Hob.FirmwareVolume2)); - - DEBUG ((DEBUG_INFO, " BaseAddress = 0x%lx\n", Hob.FirmwareVolume2->BaseAddress)); - DEBUG ((DEBUG_INFO, " Length = 0x%lx\n", Hob.FirmwareVolume2->Length)); - DEBUG ((DEBUG_INFO, " FvName = %g\n", &Hob.FirmwareVolume2->FvName)); - DEBUG ((DEBUG_INFO, " FileName = %g\n", &Hob.FirmwareVolume2->FileName)); - return EFI_SUCCESS; -} + @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_GUID_EXTENSION. + @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_GUID_EXTENSION. -/** - Print the information in Capsule Hob. - @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_UEFI_CAPSULE. - @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_UEFI_CAPSULE. @retval EFI_SUCCESS If it completed successfully. + @retval EFI_UNSUPPORTED If the HOB type is not supported. **/ EFI_STATUS -PrintCapsuleHob ( +InternalPrintHobs ( IN VOID *HobStart, IN UINT16 HobLength ) @@ -581,96 +344,24 @@ PrintCapsuleHob ( EFI_PEI_HOB_POINTERS Hob; Hob.Raw = (UINT8 *)HobStart; - ASSERT (HobLength >= sizeof (*Hob.Capsule)); - - DEBUG ((DEBUG_INFO, " BaseAddress = 0x%lx\n", Hob.Capsule->BaseAddress)); - DEBUG ((DEBUG_INFO, " Length = 0x%lx\n", Hob.Capsule->Length)); - return EFI_SUCCESS; -} -/** - Print the information in Fv3 Hob. - @param[in] HobStart A pointer to the HOB of type EFI_HOB_TYPE_FV3. - @param[in] HobLength The length in bytes of the HOB of type EFI_HOB_TYPE_FV3. - @retval EFI_SUCCESS If it completed successfully. -**/ -EFI_STATUS -PrintFv3Hob ( - IN VOID *HobStart, - IN UINT16 HobLength - ) -{ - EFI_PEI_HOB_POINTERS Hob; + if (Hob.Header->HobType == EFI_HOB_TYPE_GUID_EXTENSION) { + return InternalPrintGuidHob (Hob.Raw, HobLength); + } else if (Hob.Header->HobType == EFI_HOB_TYPE_MEMORY_POOL) { + return InternalPrintMemoryPoolHob (Hob.Raw, HobLength); + } - Hob.Raw = (UINT8 *)HobStart; - ASSERT (HobLength >= sizeof (*Hob.FirmwareVolume3)); - - DEBUG ((DEBUG_INFO, " BaseAddress = 0x%lx\n", Hob.FirmwareVolume3->BaseAddress)); - DEBUG ((DEBUG_INFO, " Length = 0x%lx\n", Hob.FirmwareVolume3->Length)); - DEBUG ((DEBUG_INFO, " AuthenticationStatus = 0x%x\n", Hob.FirmwareVolume3->AuthenticationStatus)); - DEBUG ((DEBUG_INFO, " ExtractedFv = %a\n", (Hob.FirmwareVolume3->ExtractedFv ? "True" : "False"))); - DEBUG ((DEBUG_INFO, " FVName = %g\n", &Hob.FirmwareVolume3->FvName)); - DEBUG ((DEBUG_INFO, " FileName = %g\n", &Hob.FirmwareVolume3->FileName)); - return EFI_SUCCESS; + return EFI_UNSUPPORTED; } -// -// Mappint table from Hob type to Hob print function. -// -HOB_PRINT_HANDLER_TABLE mHobHandles[] = { - { EFI_HOB_TYPE_HANDOFF, "EFI_HOB_TYPE_HANDOFF", PrintHandOffHob }, - { EFI_HOB_TYPE_MEMORY_ALLOCATION, "EFI_HOB_TYPE_MEMORY_ALLOCATION", PrintMemoryAllocationHob }, - { EFI_HOB_TYPE_RESOURCE_DESCRIPTOR, "EFI_HOB_TYPE_RESOURCE_DESCRIPTOR", PrintResourceDiscriptorHob }, - { EFI_HOB_TYPE_GUID_EXTENSION, "EFI_HOB_TYPE_GUID_EXTENSION", PrintGuidHob }, - { EFI_HOB_TYPE_FV, "EFI_HOB_TYPE_FV", PrintFvHob }, - { EFI_HOB_TYPE_CPU, "EFI_HOB_TYPE_CPU", PrintCpuHob }, - { EFI_HOB_TYPE_MEMORY_POOL, "EFI_HOB_TYPE_MEMORY_POOL", PrintMemoryPoolHob }, - { EFI_HOB_TYPE_FV2, "EFI_HOB_TYPE_FV2", PrintFv2Hob }, - { EFI_HOB_TYPE_UEFI_CAPSULE, "EFI_HOB_TYPE_UEFI_CAPSULE", PrintCapsuleHob }, - { EFI_HOB_TYPE_FV3, "EFI_HOB_TYPE_FV3", PrintFv3Hob } -}; - /** Print all HOBs info from the HOB list. @param[in] HobStart A pointer to the HOB list - @return The pointer to the HOB list. **/ VOID PrintHob ( IN CONST VOID *HobStart ) { - EFI_PEI_HOB_POINTERS Hob; - UINTN Count; - UINTN Index; - - ASSERT (HobStart != NULL); - - Hob.Raw = (UINT8 *)HobStart; - DEBUG ((DEBUG_INFO, "Print all Hob information from Hob 0x%p\n", Hob.Raw)); - - Count = 0; - // - // Parse the HOB list to see which type it is, and print the information. - // - while (!END_OF_HOB_LIST (Hob)) { - for (Index = 0; Index < ARRAY_SIZE (mHobHandles); Index++) { - if (Hob.Header->HobType == mHobHandles[Index].Type) { - DEBUG ((DEBUG_INFO, "HOB[%d]: Type = %a, Offset = 0x%p, Length = 0x%x\n", Count, mHobHandles[Index].Name, (Hob.Raw - (UINT8 *)HobStart), Hob.Header->HobLength)); - mHobHandles[Index].PrintHandler (Hob.Raw, Hob.Header->HobLength); - break; - } - } - - if (Index == ARRAY_SIZE (mHobHandles)) { - DEBUG ((DEBUG_INFO, "HOB[%d]: Type = %d, Offset = 0x%p, Length = 0x%x\n", Count, Hob.Header->HobType, (Hob.Raw - (UINT8 *)HobStart), Hob.Header->HobLength)); - DEBUG ((DEBUG_INFO, " Unkown Hob type\n")); - PrintHex (Hob.Raw, Hob.Header->HobLength); - } - - Count++; - Hob.Raw = GET_NEXT_HOB (Hob); - } - - DEBUG ((DEBUG_INFO, "There are totally %d Hobs, the End Hob address is %p\n", Count, Hob.Raw)); + PrintHobList (HobStart, InternalPrintHobs); } diff --git a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf index a62da5c7059d..c3571e3c287f 100644 --- a/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf +++ b/UefiPayloadPkg/UefiPayloadEntry/UniversalPayloadEntry.inf @@ -53,6 +53,7 @@ HobLib PeCoffLib CpuLib + HobPrintLib [Guids] gEfiMemoryTypeInformationGuid diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc index 2860a659f6a7..ca419a950bf9 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.dsc +++ b/UefiPayloadPkg/UefiPayloadPkg.dsc @@ -317,6 +317,7 @@ ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf FdtLib|MdePkg/Library/BaseFdtLib/BaseFdtLib.inf SmmRelocationLib|UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf + HobPrintLib|MdeModulePkg/Library/HobPrintLib/HobPrintLib.inf [LibraryClasses.common] !if $(BOOTSPLASH_IMAGE) From 049e12c03d27f0a6bf57f4f1835cab5e205661a7 Mon Sep 17 00:00:00 2001 From: Wei6 Xu Date: Tue, 21 May 2024 11:46:20 +0800 Subject: [PATCH 67/67] StandaloneMmPkg/Core: Dump all HOB info in entrypoint Print HOB information at top of StandaloneMmMain(). Cc: Ard Biesheuvel Cc: Sami Mujawar Cc: Ray Ni Cc: Jiaxin Wu Signed-off-by: Wei6 Xu --- StandaloneMmPkg/Core/StandaloneMmCore.c | 4 ++++ StandaloneMmPkg/Core/StandaloneMmCore.h | 2 +- StandaloneMmPkg/Core/StandaloneMmCore.inf | 1 + StandaloneMmPkg/StandaloneMmPkg.dsc | 1 + 4 files changed, 7 insertions(+), 1 deletion(-) diff --git a/StandaloneMmPkg/Core/StandaloneMmCore.c b/StandaloneMmPkg/Core/StandaloneMmCore.c index 1074f309d718..81db9a953851 100644 --- a/StandaloneMmPkg/Core/StandaloneMmCore.c +++ b/StandaloneMmPkg/Core/StandaloneMmCore.c @@ -512,6 +512,10 @@ StandaloneMmMain ( DEBUG ((DEBUG_INFO, "MmMain - 0x%x\n", HobStart)); + DEBUG_CODE ( + PrintHobList (HobStart, NULL); + ); + // // Determine if the caller has passed a reference to a MM_CORE_PRIVATE_DATA // structure in the Hoblist. This choice will govern how boot information is diff --git a/StandaloneMmPkg/Core/StandaloneMmCore.h b/StandaloneMmPkg/Core/StandaloneMmCore.h index cfb417d7cc75..a8fda6dcc210 100644 --- a/StandaloneMmPkg/Core/StandaloneMmCore.h +++ b/StandaloneMmPkg/Core/StandaloneMmCore.h @@ -40,7 +40,7 @@ #include #include #include - +#include #include #include diff --git a/StandaloneMmPkg/Core/StandaloneMmCore.inf b/StandaloneMmPkg/Core/StandaloneMmCore.inf index 02ecd68f37e2..8cc9638db558 100644 --- a/StandaloneMmPkg/Core/StandaloneMmCore.inf +++ b/StandaloneMmPkg/Core/StandaloneMmCore.inf @@ -52,6 +52,7 @@ PeCoffLib ReportStatusCodeLib StandaloneMmCoreEntryPoint + HobPrintLib [Protocols] gEfiDxeMmReadyToLockProtocolGuid ## UNDEFINED # SmiHandlerRegister diff --git a/StandaloneMmPkg/StandaloneMmPkg.dsc b/StandaloneMmPkg/StandaloneMmPkg.dsc index 8012f93b7dcc..f548bf87d46e 100644 --- a/StandaloneMmPkg/StandaloneMmPkg.dsc +++ b/StandaloneMmPkg/StandaloneMmPkg.dsc @@ -59,6 +59,7 @@ StandaloneMmCoreEntryPoint|StandaloneMmPkg/Library/StandaloneMmCoreEntryPoint/StandaloneMmCoreEntryPoint.inf StandaloneMmDriverEntryPoint|MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEntryPoint.inf VariableMmDependency|StandaloneMmPkg/Library/VariableMmDependency/VariableMmDependency.inf + HobPrintLib|MdeModulePkg/Library/HobPrintLib/HobPrintLib.inf [LibraryClasses.AARCH64, LibraryClasses.ARM] ArmLib|ArmPkg/Library/ArmLib/ArmBaseLib.inf