From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from NAM11-BN8-obe.outbound.protection.outlook.com (NAM11-BN8-obe.outbound.protection.outlook.com [40.92.20.97]) by mx.groups.io with SMTP id smtpd.web12.1532.1614033198084367976 for ; Mon, 22 Feb 2021 14:33:18 -0800 Authentication-Results: mx.groups.io; dkim=pass header.i=@outlook.com header.s=selector1 header.b=UKM1Qz6o; spf=pass (domain: outlook.com, ip: 40.92.20.97, mailfrom: kun.q@outlook.com) ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none; b=a/UW59MPOo/PDFqWhw4V4CfR/AR2AaqsRm313cvq5CHUglM+yBp+GzWteZJfvm25q2toQhsnvw8aWV+DW5WcKvXNJILQVoVn6MopUrRfDYJkckzDq66q6MLXyUkcAVSetU0H7O5shRCkmzIc3nKodvzX2636sf41lS+RoZwkIWogboRfL444v8nv35EAPU6e6Dli7WD3HrN8HlIUMMhvUMsuIStaLPp+rE34aPbDb0WE1yaS8Pi9ez2dyokJ1iLQuoYV7PYcIar2tMrEKMNrJxPlf/L0m6g2UBUWI3kWiCVWFlkzAJr1VEsIXOInxb+UgNlAJ6ZQgH6qAimHp2NZWQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector9901; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=yHbExFY8erCbqO1zqRwdWrZnwQTlcj0ZGKs7QzAkHFU=; b=L4BCZD16SkiB/nI/pA0Vk359Qwof4eB26lubA+PsRddorbm4ySaYGSBbRFNvI45DpKH+ryWx0B4ULfN2tQb92iDwj+v5LK4+286bmlGtE6053W1MD+XzA489EQH8g3NqHR0op+3As68CiIZATi0O/FINPestlY2GXCcaDK1b+U02eXkL30bk43dwb7A5koX6z8XbO8ZFhRM62j8wpY6L9LB8bu19ZyDBAGv326xavzHeDd3hB/CwlTy6AzZCaV187vVj9htpYkyJpeP4qmLpi9cAv6gHlEbf66kPA7crYLCc9kbmXBl45304EF8UtttVYOQTUIXi7u/xks0P5/UIHQ== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=none; dmarc=none; dkim=none; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=outlook.com; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=yHbExFY8erCbqO1zqRwdWrZnwQTlcj0ZGKs7QzAkHFU=; b=UKM1Qz6ovFDDP85u5hfGuarCfw85LAt3T0IvmUt8DtgomdsOxCUlBoW/jy9fkaw3UALaBah6/wgcpoDwle+fktjibqd+cRA+6gmM37qvFcpg7324X/YRBG6EFesKYUrB3DTAUMrpdEpjvUK7zP7do8a2anLGiNJMMBENJCAijXh1pudf0Q6NVtLJLaJeUsct0/mD6dZJqVCia5WuKBXEpn7V28jCexuGDQrYF9/lspn924ZdLs3Br6WsOOPOHJkaa8GaYKQw10KbpcOkdZCaNoW9boe2rNV03nq7gOuyOp7ldzq13NSWoDwuB9CLpsp2hqLeeH0y2xvC1UuYnuKaxw== Received: from BN8NAM11FT021.eop-nam11.prod.protection.outlook.com (2a01:111:e400:fc4b::4c) by BN8NAM11HT151.eop-nam11.prod.protection.outlook.com (2a01:111:e400:fc4b::205) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.3868.27; Mon, 22 Feb 2021 22:33:14 +0000 Received: from MWHPR06MB3102.namprd06.prod.outlook.com (2a01:111:e400:fc4b::42) by BN8NAM11FT021.mail.protection.outlook.com (2a01:111:e400:fc4b::370) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.3868.27 via Frontend Transport; Mon, 22 Feb 2021 22:33:14 +0000 Received: from MWHPR06MB3102.namprd06.prod.outlook.com ([fe80::d4ee:1260:6f53:3f7b]) by MWHPR06MB3102.namprd06.prod.outlook.com ([fe80::d4ee:1260:6f53:3f7b%7]) with mapi id 15.20.3868.032; Mon, 22 Feb 2021 22:33:14 +0000 From: "Kun Qin" To: "devel@edk2.groups.io" CC: Jiewen Yao , Jian J Wang , Qi Zhang , Rahul Kumar Subject: Re: [PATCH v2 4/6] SecurityPkg: Tcg2Smm: Separate Tcg2Smm into 2 modules Thread-Topic: [PATCH v2 4/6] SecurityPkg: Tcg2Smm: Separate Tcg2Smm into 2 modules Thread-Index: AQHW/0uVqGLybN529kmKrKNf1U2xkKpk0c87 Date: Mon, 22 Feb 2021 22:33:14 +0000 Message-ID: References: <20210210012457.315-1-kun.q@outlook.com>, In-Reply-To: Accept-Language: en-US X-MS-Has-Attach: X-MS-TNEF-Correlator: x-incomingtopheadermarker: OriginalChecksum:945D0DFC79F1DAFA929F3EAF6B2D51F3BEDDF237191A241CF72F392D21CDE75A;UpperCasedChecksum:20BA4BD199224410005B24F3D47D7AF1F28D8C9E77EBFF648B5926D2D48D07EB;SizeAsReceived:7060;Count:44 x-tmn: [WhgyRvYmxvFwHkMDcrWVifaAVwMRnUio] x-ms-publictraffictype: Email x-incomingheadercount: 44 x-eopattributedmessage: 0 x-ms-office365-filtering-correlation-id: 49e56c25-e06e-42be-cb33-08d8d781d7ce x-ms-traffictypediagnostic: BN8NAM11HT151: x-microsoft-antispam: BCL:0; x-microsoft-antispam-message-info: UalndtCCxeIfCNomUI7Ppb9160bqz72g8AQkF5x7Tk/TVxahzQdviUPAj4FSwzKWaF0tiuvBfEJPIgjVyHp3wjiFQHVK+sKtT3V+aNZsmwBoGJ/bD3IaLtzvqzmAndkn8yysO1HRxrmK310diAFKXDcpHeFWUmabwshV6ub3rSGhva8iFvBfBg6LfrJZCrL99WnqmbssH34BVZl1v1R1Y3oN7J2uK5ESbw5MdFVDJE9VUDtxQSsTWe3L/EJrXa9D2y3lsGU1KfuNPLPXnbXA1DD8obaIFB1jYArC9ZUWKuJ7qO+dsJgzCvqdgwp7kYevzEX3kfPBtJ+BxX26IsBaYJ7BYoLdCJseNf9+uZJtQsbWUrz3wD9a95VuX4J2NZPnBeMW8CUPTYImcQxirTOJaMfhqIodLw3nD7I+QkEwRN0= x-ms-exchange-antispam-messagedata: uUBeO2EY74SmHze+UzFOZ+PwBTuntW2hysa7mT3uKkxSLSr34s64UQQez9dGbBQpuGq6YKK5PAe86z96Qs/GT3hQCtbiKdD6gpoLnvt2uq/iJ9OzBulfetWgpW0oajeDpUDNU5RceM9172+PPSL5+g== x-ms-exchange-transport-forked: True MIME-Version: 1.0 X-OriginatorOrg: outlook.com X-MS-Exchange-CrossTenant-AuthAs: Anonymous X-MS-Exchange-CrossTenant-AuthSource: BN8NAM11FT021.eop-nam11.prod.protection.outlook.com X-MS-Exchange-CrossTenant-RMS-PersistedConsumerOrg: 00000000-0000-0000-0000-000000000000 X-MS-Exchange-CrossTenant-Network-Message-Id: 49e56c25-e06e-42be-cb33-08d8d781d7ce X-MS-Exchange-CrossTenant-originalarrivaltime: 22 Feb 2021 22:33:14.3024 (UTC) X-MS-Exchange-CrossTenant-fromentityheader: Internet X-MS-Exchange-CrossTenant-id: 84df9e7f-e9f6-40af-b435-aaaaaaaaaaaa X-MS-Exchange-CrossTenant-rms-persistedconsumerorg: 00000000-0000-0000-0000-000000000000 X-MS-Exchange-Transport-CrossTenantHeadersStamped: BN8NAM11HT151 Content-Language: en-US Content-Type: multipart/alternative; boundary="_000_MWHPR06MB310237B5CBEC479B1C78CBC1F3819MWHPR06MB3102namp_" --_000_MWHPR06MB310237B5CBEC479B1C78CBC1F3819MWHPR06MB3102namp_ Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Hi Jiewen/Jian/Qi/Rahul, This patch is intended to separate the Tcg2Smm driver into DXE and SMM driv= ers based on their functionalities. Could you please provide feedback? It i= s a relatively heavy modification, please let me know if you have suggestio= ns on how to break them down into smaller pieces. Thanks in advance. Regards, Kun From: Kun Qin Sent: Tuesday, February 9, 2021 17:25 To: devel@edk2.groups.io Cc: Jiewen Yao; Jian J Wang; Qi Zhang; Rahul Kumar Subject: [PATCH v2 4/6] SecurityPkg: Tcg2Smm: Separate Tcg2Smm into 2 modul= es REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3D3169 This change separated the original Tcg2Smm module into 2 drivers: the SMM driver that registers callback for physical presence and memory clear; the Tcg2Acpi driver that patches and publishes ACPI table for runtime use. Tcg2Smm introduced an SMI root handler to allow Tcg2Acpi to communicate the NVS region used by Tpm.asl and exchange the registered SwSmiValue. Lastly, Tcg2Smm driver will publish gTcg2MmSwSmiRegisteredGuid at the end of entrypoint to ensure Tcg2Acpi to load after Tcg2Smm is ready to communicate. Cc: Jiewen Yao Cc: Jian J Wang Cc: Qi Zhang Cc: Rahul Kumar Signed-off-by: Kun Qin --- Notes: v2: - Newly added in v2. v2: - Newly added. SecurityPkg/Tcg/{Tcg2Smm/Tcg2Smm.c =3D> Tcg2Acpi/Tcg2Acpi.c} | 350 +++= +---- SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c | 850 ++++-= --------------- SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c | 82 ++ SecurityPkg/Include/Guid/TpmNvsMm.h | 68 ++ SecurityPkg/SecurityPkg.dec | 7 + SecurityPkg/SecurityPkg.dsc | 1 + SecurityPkg/Tcg/{Tcg2Smm/Tcg2Smm.inf =3D> Tcg2Acpi/Tcg2Acpi.inf} | 32 +- SecurityPkg/Tcg/{Tcg2Smm =3D> Tcg2Acpi}/Tpm.asl | 0 SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h | 119 +-- SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf | 25 +- 10 files changed, 542 insertions(+), 992 deletions(-) diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c b/SecurityPkg/Tcg/Tcg2Acpi/T= cg2Acpi.c similarity index 72% copy from SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c copy to SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c index 08105c3692ba..7080df81efe7 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c +++ b/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c @@ -1,20 +1,74 @@ /** @file - It updates TPM2 items in ACPI table and registers SMI2 callback - functions for Tcg2 physical presence, ClearMemory, and sample - for dTPM StartMethod. + This driver implements TPM 2.0 definition block in ACPI table and + populates registered SMI callback functions for Tcg2 physical presence + and MemoryClear to handle the requests for ACPI method. Caution: This module requires additional review when modified. This driver will have external input - variable and ACPINvs data in SMM = mode. This external input must be validated carefully to avoid security issue. - PhysicalPresenceCallback() and MemoryClearCallback() will receive untrus= ted input and do some check. - Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#include "Tcg2Smm.h" +#include + +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// +// Physical Presence Interface Version supported by Platform +// +#define PHYSICAL_PRESENCE_VERSION_TAG "$PV" +#define PHYSICAL_PRESENCE_VERSION_SIZE 4 + +// +// PNP _HID for TPM2 device +// +#define TPM_HID_TAG "NNNN00= 00" +#define TPM_HID_PNP_SIZE 8 +#define TPM_HID_ACPI_SIZE 9 + +#define TPM_PRS_RESL "RESL" +#define TPM_PRS_RESS "RESS" +#define TPM_PRS_RES_NAME_SIZE 4 +// +// Minimum PRS resource template size +// 1 byte for BufferOp +// 1 byte for PkgLength +// 2 bytes for BufferSize +// 12 bytes for Memory32Fixed descriptor +// 5 bytes for Interrupt descriptor +// 2 bytes for END Tag +// +#define TPM_POS_RES_TEMPLATE_MIN_SIZE (1 + 1 = + 2 + 12 + 5 + 2) + +// +// Max Interrupt buffer size for PRS interrupt resource +// Now support 15 interrupts in maxmum +// +#define MAX_PRS_INT_BUF_SIZE (15*4) #pragma pack(1) @@ -49,142 +103,8 @@ EFI_TPM2_ACPI_TABLE_V4 mTpm2AcpiTemplate =3D { EFI_TPM2_ACPI_TABLE_START_METHOD_TIS, // StartMethod }; -EFI_SMM_VARIABLE_PROTOCOL *mSmmVariable; TCG_NVS *mTcgNvs; -/** - Software SMI callback for TPM physical presence which is called from ACP= I method. - - Caution: This function may receive untrusted input. - Variable and ACPINvs are external input, so this function will validate - its data structure to be valid value. - - @param[in] DispatchHandle The unique handle assigned to this handl= er by SmiHandlerRegister(). - @param[in] Context Points to an optional handler context wh= ich was specified when the - handler was registered. - @param[in, out] CommBuffer A pointer to a collection of data in mem= ory that will - be conveyed from a non-SMM environment i= nto an SMM environment. - @param[in, out] CommBufferSize The size of the CommBuffer. - - @retval EFI_SUCCESS The interrupt was handled successfully. - -**/ -EFI_STATUS -EFIAPI -PhysicalPresenceCallback ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *Context, - IN OUT VOID *CommBuffer, - IN OUT UINTN *CommBufferSize - ) -{ - UINT32 MostRecentRequest; - UINT32 Response; - UINT32 OperationRequest; - UINT32 RequestParameter; - - - if (mTcgNvs->PhysicalPresence.Parameter =3D=3D TCG_ACPI_FUNCTION_RETURN_= REQUEST_RESPONSE_TO_OS) { - mTcgNvs->PhysicalPresence.ReturnCode =3D Tcg2PhysicalPresenceLibReturn= OperationResponseToOsFunction ( - &MostRecentRequest, - &Response - ); - mTcgNvs->PhysicalPresence.LastRequest =3D MostRecentRequest; - mTcgNvs->PhysicalPresence.Response =3D Response; - return EFI_SUCCESS; - } else if ((mTcgNvs->PhysicalPresence.Parameter =3D=3D TCG_ACPI_FUNCTION= _SUBMIT_REQUEST_TO_BIOS) - || (mTcgNvs->PhysicalPresence.Parameter =3D=3D TCG_ACPI_FUNCTION= _SUBMIT_REQUEST_TO_BIOS_2)) { - - OperationRequest =3D mTcgNvs->PhysicalPresence.Request; - RequestParameter =3D mTcgNvs->PhysicalPresence.RequestParameter; - mTcgNvs->PhysicalPresence.ReturnCode =3D Tcg2PhysicalPresenceLibSubmit= RequestToPreOSFunctionEx ( - &OperationRequest, - &RequestParameter - ); - mTcgNvs->PhysicalPresence.Request =3D OperationRequest; - mTcgNvs->PhysicalPresence.RequestParameter =3D RequestParameter; - } else if (mTcgNvs->PhysicalPresence.Parameter =3D=3D TCG_ACPI_FUNCTION_= GET_USER_CONFIRMATION_STATUS_FOR_REQUEST) { - mTcgNvs->PhysicalPresence.ReturnCode =3D Tcg2PhysicalPresenceLibGetUse= rConfirmationStatusFunction (mTcgNvs->PPRequestUserConfirm); - } - - return EFI_SUCCESS; -} - - -/** - Software SMI callback for MemoryClear which is called from ACPI method. - - Caution: This function may receive untrusted input. - Variable and ACPINvs are external input, so this function will validate - its data structure to be valid value. - - @param[in] DispatchHandle The unique handle assigned to this handl= er by SmiHandlerRegister(). - @param[in] Context Points to an optional handler context wh= ich was specified when the - handler was registered. - @param[in, out] CommBuffer A pointer to a collection of data in mem= ory that will - be conveyed from a non-SMM environment i= nto an SMM environment. - @param[in, out] CommBufferSize The size of the CommBuffer. - - @retval EFI_SUCCESS The interrupt was handled successfully. - -**/ -EFI_STATUS -EFIAPI -MemoryClearCallback ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *Context, - IN OUT VOID *CommBuffer, - IN OUT UINTN *CommBufferSize - ) -{ - EFI_STATUS Status; - UINTN DataSize; - UINT8 MorControl; - - mTcgNvs->MemoryClear.ReturnCode =3D MOR_REQUEST_SUCCESS; - if (mTcgNvs->MemoryClear.Parameter =3D=3D ACPI_FUNCTION_DSM_MEMORY_CLEAR= _INTERFACE) { - MorControl =3D (UINT8) mTcgNvs->MemoryClear.Request; - } else if (mTcgNvs->MemoryClear.Parameter =3D=3D ACPI_FUNCTION_PTS_CLEAR= _MOR_BIT) { - DataSize =3D sizeof (UINT8); - Status =3D mSmmVariable->SmmGetVariable ( - MEMORY_OVERWRITE_REQUEST_VARIABLE_NAME, - &gEfiMemoryOverwriteControlDataGuid, - NULL, - &DataSize, - &MorControl - ); - if (EFI_ERROR (Status)) { - mTcgNvs->MemoryClear.ReturnCode =3D MOR_REQUEST_GENERAL_FAILURE; - DEBUG ((EFI_D_ERROR, "[TPM] Get MOR variable failure! Status =3D %r\= n", Status)); - return EFI_SUCCESS; - } - - if (MOR_CLEAR_MEMORY_VALUE (MorControl) =3D=3D 0x0) { - return EFI_SUCCESS; - } - MorControl &=3D ~MOR_CLEAR_MEMORY_BIT_MASK; - } else { - mTcgNvs->MemoryClear.ReturnCode =3D MOR_REQUEST_GENERAL_FAILURE; - DEBUG ((EFI_D_ERROR, "[TPM] MOR Parameter error! Parameter =3D %x\n", = mTcgNvs->MemoryClear.Parameter)); - return EFI_SUCCESS; - } - - DataSize =3D sizeof (UINT8); - Status =3D mSmmVariable->SmmSetVariable ( - MEMORY_OVERWRITE_REQUEST_VARIABLE_NAME, - &gEfiMemoryOverwriteControlDataGuid, - EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSE= RVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, - DataSize, - &MorControl - ); - if (EFI_ERROR (Status)) { - mTcgNvs->MemoryClear.ReturnCode =3D MOR_REQUEST_GENERAL_FAILURE; - DEBUG ((EFI_D_ERROR, "[TPM] Set MOR variable failure! Status =3D %r\n"= , Status)); - } - - return EFI_SUCCESS; -} - /** Find the operation region in TCG ACPI table by given Name and Size, and initialize it if the region is found. @@ -232,6 +152,103 @@ AssignOpRegion ( return (VOID *) (UINTN) MemoryAddress; } +/** + Locate the MM communication buffer and protocol, then use it to exchange= information with + Tcg2StandaloneMmm on NVS address and SMI value. + + @param[in, out] TcgNvs The NVS subject to send to MM environment= . + + @return The status for locating MM common buffer,= communicate to MM, etc. + +**/ +EFI_STATUS +EFIAPI +ExchangeCommonBuffer ( + IN OUT TCG_NVS *TcgNvs +) +{ + EFI_STATUS Status; + EFI_MM_COMMUNICATION_PROTOCOL *MmCommunication; + EDKII_PI_SMM_COMMUNICATION_REGION_TABLE *PiSmmCommunicationRegionTable= ; + EFI_MEMORY_DESCRIPTOR *MmCommMemRegion; + EFI_MM_COMMUNICATE_HEADER *CommHeader; + TPM_NVS_MM_COMM_BUFFER *CommBuffer; + UINTN CommBufferSize; + UINTN Index; + + // Step 0: Sanity check for input argument + if (TcgNvs =3D=3D NULL) { + DEBUG ((DEBUG_ERROR, "%a - Input argument is NULL!\n", __FUNCTION__)); + return EFI_INVALID_PARAMETER; + } + + // Step 1: Grab the common buffer header + Status =3D EfiGetSystemConfigurationTable (&gEdkiiPiSmmCommunicationRegi= onTableGuid, (VOID**) &PiSmmCommunicationRegionTable); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a - Failed to locate SMM communciation common b= uffer - %r!\n", __FUNCTION__, Status)); + return Status; + } + + // Step 2: Grab one that is large enough to hold TPM_NVS_MM_COMM_BUFFER,= the IPL one should be sufficient + CommBufferSize =3D 0; + MmCommMemRegion =3D (EFI_MEMORY_DESCRIPTOR*) (PiSmmCommunicationRegionTa= ble + 1); + for (Index =3D 0; Index < PiSmmCommunicationRegionTable->NumberOfEntries= ; Index++) { + if (MmCommMemRegion->Type =3D=3D EfiConventionalMemory) { + CommBufferSize =3D EFI_PAGES_TO_SIZE ((UINTN)MmCommMemRegion->Number= OfPages); + if (CommBufferSize >=3D (sizeof (TPM_NVS_MM_COMM_BUFFER) + OFFSET_OF= (EFI_MM_COMMUNICATE_HEADER, Data))) { + break; + } + } + MmCommMemRegion =3D (EFI_MEMORY_DESCRIPTOR*)((UINT8*)MmCommMemRegion += PiSmmCommunicationRegionTable->DescriptorSize); + } + + if (Index >=3D PiSmmCommunicationRegionTable->NumberOfEntries) { + // Could not find one that meets our goal... + DEBUG ((DEBUG_ERROR, "%a - Could not find a common buffer that is big = enough for NVS!\n", __FUNCTION__)); + return EFI_OUT_OF_RESOURCES; + } + + // Step 3: Start to populate contents + // Step 3.1: MM Communication common header + CommHeader =3D (EFI_MM_COMMUNICATE_HEADER *) (UINTN) MmCommMemRegion->Ph= ysicalStart; + CommBufferSize =3D sizeof (TPM_NVS_MM_COMM_BUFFER) + OFFSET_OF (EFI_MM_C= OMMUNICATE_HEADER, Data); + ZeroMem (CommHeader, CommBufferSize); + CopyGuid (&CommHeader->HeaderGuid, &gTpmNvsMmGuid); + CommHeader->MessageLength =3D sizeof (TPM_NVS_MM_COMM_BUFFER); + + // Step 3.2: TPM_NVS_MM_COMM_BUFFER content per our needs + CommBuffer =3D (TPM_NVS_MM_COMM_BUFFER *) (CommHeader->Data); + CommBuffer->Function =3D TpmNvsMmExchangeInfo; + CommBuffer->TargetAddress =3D (EFI_PHYSICAL_ADDRESS) (UINTN) TcgNvs; + + // Step 4: Locate the protocol and signal Mmi. + Status =3D gBS->LocateProtocol (&gEfiMmCommunicationProtocolGuid, NULL, = (VOID**) &MmCommunication); + if (!EFI_ERROR (Status)) { + Status =3D MmCommunication->Communicate (MmCommunication, CommHeader, = &CommBufferSize); + DEBUG ((DEBUG_INFO, "%a - Communicate() =3D %r\n", __FUNCTION__, Statu= s)); + } + else { + DEBUG ((DEBUG_ERROR, "%a - Failed to locate MmCommunication protocol -= %r\n", __FUNCTION__, Status)); + return Status; + } + + // Step 5: If everything goes well, populate the channel number + if (!EFI_ERROR (CommBuffer->ReturnStatus)) { + // Need to demote to UINT8 according to SMI value definition + TcgNvs->PhysicalPresence.SoftwareSmi =3D (UINT8) CommBuffer->Registere= dPpSwiValue; + TcgNvs->MemoryClear.SoftwareSmi =3D (UINT8) CommBuffer->RegisteredMcSw= iValue; + DEBUG (( + DEBUG_INFO, + "%a Communication returned software SMI value. PP: 0x%x; MC: 0x%x.\n= ", + __FUNCTION__, + TcgNvs->PhysicalPresence.SoftwareSmi, + TcgNvs->MemoryClear.SoftwareSmi + )); + } + + return (EFI_STATUS) CommBuffer->ReturnStatus; +} + /** Patch version string of Physical Presence interface supported by platfor= m. The initial string tag in TPM ACPI table is "$PV". @@ -259,7 +276,7 @@ UpdatePPVersion ( DataPtr +=3D 1) { if (AsciiStrCmp((CHAR8 *)DataPtr, PHYSICAL_PRESENCE_VERSION_TAG) =3D= =3D 0) { Status =3D AsciiStrCpyS((CHAR8 *)DataPtr, PHYSICAL_PRESENCE_VERSION_= SIZE, PPVer); - DEBUG((EFI_D_INFO, "TPM2 Physical Presence Interface Version update = status 0x%x\n", Status)); + DEBUG((DEBUG_INFO, "TPM2 Physical Presence Interface Version update = status 0x%x\n", Status)); return Status; } } @@ -548,7 +565,7 @@ UpdateHID ( // Status =3D Tpm2GetCapabilityManufactureID(&ManufacturerID); if (!EFI_ERROR(Status)) { - DEBUG((EFI_D_INFO, "TPM_PT_MANUFACTURER 0x%08x\n", ManufacturerID)); + DEBUG((DEBUG_INFO, "TPM_PT_MANUFACTURER 0x%08x\n", ManufacturerID)); // // ManufacturerID defined in TCG Vendor ID Registry // may tailed with 0x00 or 0x20 @@ -568,15 +585,15 @@ UpdateHID ( PnpHID =3D FALSE; } } else { - DEBUG ((EFI_D_ERROR, "Get TPM_PT_MANUFACTURER failed %x!\n", Status)); + DEBUG ((DEBUG_ERROR, "Get TPM_PT_MANUFACTURER failed %x!\n", Status)); ASSERT(FALSE); return Status; } Status =3D Tpm2GetCapabilityFirmwareVersion(&FirmwareVersion1, &Firmware= Version2); if (!EFI_ERROR(Status)) { - DEBUG((EFI_D_INFO, "TPM_PT_FIRMWARE_VERSION_1 0x%x\n", FirmwareVersion= 1)); - DEBUG((EFI_D_INFO, "TPM_PT_FIRMWARE_VERSION_2 0x%x\n", FirmwareVersion= 2)); + DEBUG((DEBUG_INFO, "TPM_PT_FIRMWARE_VERSION_1 0x%x\n", FirmwareVersion= 1)); + DEBUG((DEBUG_INFO, "TPM_PT_FIRMWARE_VERSION_2 0x%x\n", FirmwareVersion= 2)); // // #### is Firmware Version 1 // @@ -587,7 +604,7 @@ UpdateHID ( } } else { - DEBUG ((EFI_D_ERROR, "Get TPM_PT_FIRMWARE_VERSION_X failed %x!\n", Sta= tus)); + DEBUG ((DEBUG_ERROR, "Get TPM_PT_FIRMWARE_VERSION_X failed %x!\n", Sta= tus)); ASSERT(FALSE); return Status; } @@ -615,7 +632,7 @@ UpdateHID ( } } - DEBUG((EFI_D_ERROR, "TPM2 ACPI HID TAG for patch not found!\n")); + DEBUG((DEBUG_ERROR, "TPM2 ACPI HID TAG for patch not found!\n")); return EFI_NOT_FOUND; } @@ -716,6 +733,8 @@ PublishAcpiTable ( mTcgNvs->TpmIrqNum =3D PcdGet32(PcdTpm2CurrentIrqNum); mTcgNvs->IsShortFormPkgLength =3D IsShortFormPkgLength; + Status =3D ExchangeCommonBuffer (mTcgNvs); + // // Publish the TPM ACPI table. Table is re-checksummed. // @@ -806,7 +825,7 @@ PublishTpm2 ( case Tpm2PtpInterfaceTis: break; default: - DEBUG((EFI_D_ERROR, "TPM2 InterfaceType get error! %d\n", InterfaceTyp= e)); + DEBUG((DEBUG_ERROR, "TPM2 InterfaceType get error! %d\n", InterfaceTyp= e)); break; } @@ -849,58 +868,27 @@ PublishTpm2 ( **/ EFI_STATUS EFIAPI -InitializeTcgSmm ( +InitializeTcgAcpi ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; - EFI_SMM_SW_DISPATCH2_PROTOCOL *SwDispatch; - EFI_SMM_SW_REGISTER_CONTEXT SwContext; - EFI_HANDLE SwHandle; if (!CompareGuid (PcdGetPtr(PcdTpmInstanceGuid), &gEfiTpmDeviceInstanceT= pm20DtpmGuid)){ - DEBUG ((EFI_D_ERROR, "No TPM2 DTPM instance required!\n")); + DEBUG ((DEBUG_ERROR, "No TPM2 DTPM instance required!\n")); return EFI_UNSUPPORTED; } Status =3D PublishAcpiTable (); ASSERT_EFI_ERROR (Status); - // - // Get the Sw dispatch protocol and register SMI callback functions. - // - Status =3D gMmst->MmLocateProtocol (&gEfiSmmSwDispatch2ProtocolGuid, NUL= L, (VOID**)&SwDispatch); - ASSERT_EFI_ERROR (Status); - SwContext.SwSmiInputValue =3D (UINTN) -1; - Status =3D SwDispatch->Register (SwDispatch, PhysicalPresenceCallback, &= SwContext, &SwHandle); - ASSERT_EFI_ERROR (Status); - if (EFI_ERROR (Status)) { - return Status; - } - mTcgNvs->PhysicalPresence.SoftwareSmi =3D (UINT8) SwContext.SwSmiInputVa= lue; - - SwContext.SwSmiInputValue =3D (UINTN) -1; - Status =3D SwDispatch->Register (SwDispatch, MemoryClearCallback, &SwCon= text, &SwHandle); - ASSERT_EFI_ERROR (Status); - if (EFI_ERROR (Status)) { - return Status; - } - mTcgNvs->MemoryClear.SoftwareSmi =3D (UINT8) SwContext.SwSmiInputValue; - - // - // Locate SmmVariableProtocol. - // - Status =3D gMmst->MmLocateProtocol (&gEfiSmmVariableProtocolGuid, NULL, = (VOID**)&mSmmVariable); - ASSERT_EFI_ERROR (Status); - // // Set TPM2 ACPI table // Status =3D PublishTpm2 (); ASSERT_EFI_ERROR (Status); - return EFI_SUCCESS; } diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c b/SecurityPkg/Tcg/Tcg2Smm/Tc= g2Smm.c index 08105c3692ba..977ea3b1dfd2 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c @@ -10,47 +10,95 @@ PhysicalPresenceCallback() and MemoryClearCallback() will receive untrus= ted input and do some check. Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "Tcg2Smm.h" -#pragma pack(1) - -typedef struct { - EFI_ACPI_DESCRIPTION_HEADER Header; - // Flags field is replaced in version 4 and above - // BIT0~15: PlatformClass This field is only valid for version = 4 and above - // BIT16~31: Reserved - UINT32 Flags; - UINT64 AddressOfControlArea; - UINT32 StartMethod; - UINT8 PlatformSpecificParameters[12]; // size up = to 12 - UINT32 Laml; // Optional - UINT64 Lasa; // Optional -} EFI_TPM2_ACPI_TABLE_V4; - -#pragma pack() - -EFI_TPM2_ACPI_TABLE_V4 mTpm2AcpiTemplate =3D { - { - EFI_ACPI_5_0_TRUSTED_COMPUTING_PLATFORM_2_TABLE_SIGNATURE, - sizeof (mTpm2AcpiTemplate), - EFI_TPM2_ACPI_TABLE_REVISION, - // - // Compiler initializes the remaining bytes to 0 - // These fields should be filled in in production - // - }, - 0, // BIT0~15: PlatformClass - // BIT16~31: Reserved - 0, // Control Area - EFI_TPM2_ACPI_TABLE_START_METHOD_TIS, // StartMethod -}; - -EFI_SMM_VARIABLE_PROTOCOL *mSmmVariable; -TCG_NVS *mTcgNvs; +EFI_SMM_VARIABLE_PROTOCOL *mSmmVariable =3D NULL; +TCG_NVS *mTcgNvs =3D NULL; +UINTN mPpSoftwareSmi; +UINTN mMcSoftwareSmi; +EFI_HANDLE mReadyToLockHandle; + +/** + Communication service SMI Handler entry. + + This handler takes requests to exchange Mmi channel and Nvs address betw= een MM and DXE. + + Caution: This function may receive untrusted input. + Communicate buffer and buffer size are external input, so this function = will do basic validation. + + @param[in] DispatchHandle The unique handle assigned to this han= dler by SmiHandlerRegister(). + @param[in] RegisterContext Points to an optional handler context = which was specified when the + handler was registered. + @param[in, out] CommBuffer A pointer to a collection of data in m= emory that will + be conveyed from a non-SMM environment= into an SMM environment. + @param[in, out] CommBufferSize The size of the CommBuffer. + + @retval EFI_SUCCESS The interrupt was handled and quiesced= . No other handlers + should still be called. + @retval EFI_UNSUPPORTED An unknown test function was requested= . + @retval EFI_ACCESS_DENIED Part of the communication buffer lies = in an invalid region. + +**/ +EFI_STATUS +EFIAPI +TpmNvsCommunciate ( + IN EFI_HANDLE DispatchHandle, + IN CONST VOID *RegisterContext, + IN OUT VOID *CommBuffer, + IN OUT UINTN *CommBufferSize + ) +{ + EFI_STATUS Status; + UINTN TempCommBufferSize; + TPM_NVS_MM_COMM_BUFFER *CommParams; + + DEBUG ((DEBUG_VERBOSE, "%a()\n", __FUNCTION__)); + + // + // If input is invalid, stop processing this SMI + // + if (CommBuffer =3D=3D NULL || CommBufferSize =3D=3D NULL) { + return EFI_SUCCESS; + } + + TempCommBufferSize =3D *CommBufferSize; + + if(TempCommBufferSize !=3D sizeof (TPM_NVS_MM_COMM_BUFFER)) { + DEBUG ((DEBUG_ERROR, "[%a] MM Communication buffer size is invalid for= this handler!\n", __FUNCTION__)); + return EFI_ACCESS_DENIED; + } + if (!IsBufferOutsideMmValid ((UINTN) CommBuffer, TempCommBufferSize)) { + DEBUG ((DEBUG_ERROR, "[%a] - MM Communication buffer in invalid locati= on!\n", __FUNCTION__)); + return EFI_ACCESS_DENIED; + } + + // + // Farm out the job to individual functions based on what was requested. + // + CommParams =3D (TPM_NVS_MM_COMM_BUFFER*) CommBuffer; + Status =3D EFI_SUCCESS; + switch (CommParams->Function) { + case TpmNvsMmExchangeInfo: + DEBUG ((DEBUG_VERBOSE, "[%a] - Function requested: MM_EXCHANGE_NVS_I= NFO\n", __FUNCTION__)); + CommParams->RegisteredPpSwiValue =3D mPpSoftwareSmi; + CommParams->RegisteredMcSwiValue =3D mMcSoftwareSmi; + mTcgNvs =3D (TCG_NVS*) (UINTN) CommParams->TargetAddress; + break; + + default: + DEBUG ((DEBUG_INFO, "[%a] - Unknown function %d!\n", __FUNCTION__, C= ommParams->Function)); + Status =3D EFI_UNSUPPORTED; + break; + } + + CommParams->ReturnStatus =3D (UINT64) Status; + return EFI_SUCCESS; +} /** Software SMI callback for TPM physical presence which is called from ACP= I method. @@ -186,721 +234,137 @@ MemoryClearCallback ( } /** - Find the operation region in TCG ACPI table by given Name and Size, - and initialize it if the region is found. + Notification for SMM ReadyToLock protocol. - @param[in, out] Table The TPM item in ACPI table. - @param[in] Name The name string to find in TPM table. - @param[in] Size The size of the region to find. + @param[in] Protocol Points to the protocol's unique identifier. + @param[in] Interface Points to the interface instance. + @param[in] Handle The handle on which the interface was installed. - @return The allocated address for the found regio= n. - -**/ -VOID * -AssignOpRegion ( - EFI_ACPI_DESCRIPTION_HEADER *Table, - UINT32 Name, - UINT16 Size - ) -{ - EFI_STATUS Status; - AML_OP_REGION_32_8 *OpRegion; - EFI_PHYSICAL_ADDRESS MemoryAddress; - - MemoryAddress =3D SIZE_4GB - 1; - - // - // Patch some pointers for the ASL code before loading the SSDT. - // - for (OpRegion =3D (AML_OP_REGION_32_8 *) (Table + 1); - OpRegion <=3D (AML_OP_REGION_32_8 *) ((UINT8 *) Table + Table->Leng= th); - OpRegion =3D (AML_OP_REGION_32_8 *) ((UINT8 *) OpRegion + 1)) { - if ((OpRegion->OpRegionOp =3D=3D AML_EXT_REGION_OP) && - (OpRegion->NameString =3D=3D Name) && - (OpRegion->DWordPrefix =3D=3D AML_DWORD_PREFIX) && - (OpRegion->BytePrefix =3D=3D AML_BYTE_PREFIX)) { - - Status =3D gBS->AllocatePages(AllocateMaxAddress, EfiACPIMemoryNVS, = EFI_SIZE_TO_PAGES (Size), &MemoryAddress); - ASSERT_EFI_ERROR (Status); - ZeroMem ((VOID *)(UINTN)MemoryAddress, Size); - OpRegion->RegionOffset =3D (UINT32) (UINTN) MemoryAddress; - OpRegion->RegionLen =3D (UINT8) Size; - break; - } - } - - return (VOID *) (UINTN) MemoryAddress; -} - -/** - Patch version string of Physical Presence interface supported by platfor= m. The initial string tag in TPM -ACPI table is "$PV". - - @param[in, out] Table The TPM item in ACPI table. - @param[in] PPVer Version string of Physical Presence inter= face supported by platform. - - @return The allocated address for the found regio= n. - -**/ -EFI_STATUS -UpdatePPVersion ( - EFI_ACPI_DESCRIPTION_HEADER *Table, - CHAR8 *PPVer - ) -{ - EFI_STATUS Status; - UINT8 *DataPtr; - - // - // Patch some pointers for the ASL code before loading the SSDT. - // - for (DataPtr =3D (UINT8 *)(Table + 1); - DataPtr <=3D (UINT8 *) ((UINT8 *) Table + Table->Length - PHYSICAL_= PRESENCE_VERSION_SIZE); - DataPtr +=3D 1) { - if (AsciiStrCmp((CHAR8 *)DataPtr, PHYSICAL_PRESENCE_VERSION_TAG) =3D= =3D 0) { - Status =3D AsciiStrCpyS((CHAR8 *)DataPtr, PHYSICAL_PRESENCE_VERSION_= SIZE, PPVer); - DEBUG((EFI_D_INFO, "TPM2 Physical Presence Interface Version update = status 0x%x\n", Status)); - return Status; - } - } - - return EFI_NOT_FOUND; -} - -/** - Patch interrupt resources returned by TPM _PRS. ResourceTemplate to patc= h is determined by input - interrupt buffer size. BufferSize, PkgLength and interrupt descriptor in= ByteList need to be patched - - @param[in, out] Table The TPM item in ACPI table. - @param[in] IrqBuffer Input new IRQ buffer. - @param[in] IrqBuffserSize Input new IRQ buffer size. - @param[out] IsShortFormPkgLength If _PRS returns Short length Pack= age(ACPI spec 20.2.4). - - @return patch status. - -**/ -EFI_STATUS -UpdatePossibleResource ( - IN OUT EFI_ACPI_DESCRIPTION_HEADER *Table, - IN UINT32 *IrqBuffer, - IN UINT32 IrqBuffserSize, - OUT BOOLEAN *IsShortFormPkgLength - ) -{ - UINT8 *DataPtr; - UINT8 *DataEndPtr; - UINT32 NewPkgLength; - UINT32 OrignalPkgLength; - - NewPkgLength =3D 0; - OrignalPkgLength =3D 0; - DataEndPtr =3D NULL; - - // - // Follow ACPI spec - // 6.4.3 Extend Interrupt Descriptor. - // 19.3.3 ASL Resource Template - // 20 AML specification - // to patch TPM ACPI object _PRS returned ResourceTemplate() containing = 2 resource descriptors and an auto appended End Tag - // - // AML data is organized by following rule. - // Code need to patch BufferSize and PkgLength and interrupt descriptor= in ByteList - // - // =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Buffer =3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D - // DefBuffer :=3D BufferOp PkgLength BufferSize ByteList - // BufferOp :=3D 0x11 - // - // =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3DPkgLength=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D - // PkgLength :=3D PkgLeadByte | - // | - // | - // - // - // PkgLeadByte :=3D - // - // - // - //=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3DBufferSize=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D - // BufferSize :=3D Integer - // Integer :=3D ByteConst|WordConst|DwordConst.... - // - // ByteConst :=3D BytePrefix ByteData - // - //=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3DByteList=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D - // ByteList :=3D ByteData ByteList - // - //=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D - - // - // 1. Check TPM_PRS_RESS with PkgLength <=3D63 can hold the input interr= upt number buffer for patching - // - for (DataPtr =3D (UINT8 *)(Table + 1); - DataPtr < (UINT8 *) ((UINT8 *) Table + Table->Length - (TPM_PRS_RES= _NAME_SIZE + TPM_POS_RES_TEMPLATE_MIN_SIZE)); - DataPtr +=3D 1) { - if (CompareMem(DataPtr, TPM_PRS_RESS, TPM_PRS_RES_NAME_SIZE) =3D=3D 0)= { - // - // Jump over object name & BufferOp - // - DataPtr +=3D TPM_PRS_RES_NAME_SIZE + 1; - - if ((*DataPtr & (BIT7|BIT6)) =3D=3D 0) { - OrignalPkgLength =3D (UINT32)*DataPtr; - DataEndPtr =3D DataPtr + OrignalPkgLength; - - // - // Jump over PkgLength =3D PkgLeadByte only - // - NewPkgLength++; - - // - // Jump over BufferSize - // - if (*(DataPtr + 1) =3D=3D AML_BYTE_PREFIX) { - NewPkgLength +=3D 2; - } else if (*(DataPtr + 1) =3D=3D AML_WORD_PREFIX) { - NewPkgLength +=3D 3; - } else if (*(DataPtr + 1) =3D=3D AML_DWORD_PREFIX) { - NewPkgLength +=3D 5; - } else { - ASSERT(FALSE); - return EFI_UNSUPPORTED; - } - } else { - ASSERT(FALSE); - return EFI_UNSUPPORTED; - } - - // - // Include Memory32Fixed Descriptor (12 Bytes) + Interrupt Descripto= r header(5 Bytes) + End Tag(2 Bytes) - // - NewPkgLength +=3D 19 + IrqBuffserSize; - if (NewPkgLength > 63) { - break; - } - - if (NewPkgLength > OrignalPkgLength) { - ASSERT(FALSE); - return EFI_INVALID_PARAMETER; - } - - // - // 1.1 Patch PkgLength - // - *DataPtr =3D (UINT8)NewPkgLength; - - // - // 1.2 Patch BufferSize =3D sizeof(Memory32Fixed Descriptor + Interr= upt Descriptor + End Tag). - // It is Little endian. So only patch lowest byte of BufferSize= due to current interrupt number limit. - // - *(DataPtr + 2) =3D (UINT8)(IrqBuffserSize + 19); - - // - // Notify _PRS to report short formed ResourceTemplate - // - *IsShortFormPkgLength =3D TRUE; - - break; - } - } - - // - // 2. Use TPM_PRS_RESL with PkgLength > 63 to hold longer input interrup= t number buffer for patching - // - if (NewPkgLength > 63) { - NewPkgLength =3D 0; - OrignalPkgLength =3D 0; - for (DataPtr =3D (UINT8 *)(Table + 1); - DataPtr < (UINT8 *) ((UINT8 *) Table + Table->Length - (TPM_PRS_R= ES_NAME_SIZE + TPM_POS_RES_TEMPLATE_MIN_SIZE)); - DataPtr +=3D 1) { - if (CompareMem(DataPtr, TPM_PRS_RESL, TPM_PRS_RES_NAME_SIZE) =3D=3D = 0) { - // - // Jump over object name & BufferOp - // - DataPtr +=3D TPM_PRS_RES_NAME_SIZE + 1; - - if ((*DataPtr & (BIT7|BIT6)) !=3D 0) { - OrignalPkgLength =3D (UINT32)(*(DataPtr + 1) << 4) + (*DataPtr &= 0x0F); - DataEndPtr =3D DataPtr + OrignalPkgLength; - // - // Jump over PkgLength =3D PkgLeadByte + ByteData length - // - NewPkgLength +=3D 1 + ((*DataPtr & (BIT7|BIT6)) >> 6); - - // - // Jump over BufferSize - // - if (*(DataPtr + NewPkgLength) =3D=3D AML_BYTE_PREFIX) { - NewPkgLength +=3D 2; - } else if (*(DataPtr + NewPkgLength) =3D=3D AML_WORD_PREFIX) { - NewPkgLength +=3D 3; - } else if (*(DataPtr + NewPkgLength) =3D=3D AML_DWORD_PREFIX) { - NewPkgLength +=3D 5; - } else { - ASSERT(FALSE); - return EFI_UNSUPPORTED; - } - } else { - ASSERT(FALSE); - return EFI_UNSUPPORTED; - } - - // - // Include Memory32Fixed Descriptor (12 Bytes) + Interrupt Descrip= tor header(5 Bytes) + End Tag(2 Bytes) - // - NewPkgLength +=3D 19 + IrqBuffserSize; - - if (NewPkgLength > OrignalPkgLength) { - ASSERT(FALSE); - return EFI_INVALID_PARAMETER; - } - - // - // 2.1 Patch PkgLength. Only patch PkgLeadByte and first ByteData - // - *DataPtr =3D (UINT8)((*DataPtr) & 0xF0) | (NewPkgLength & 0x0F); - *(DataPtr + 1) =3D (UINT8)((NewPkgLength & 0xFF0) >> 4); - - // - // 2.2 Patch BufferSize =3D sizeof(Memory32Fixed Descriptor + Inte= rrupt Descriptor + End Tag). - // It is Little endian. Only patch lowest byte of BufferSize d= ue to current interrupt number limit. - // - *(DataPtr + 2 + ((*DataPtr & (BIT7|BIT6)) >> 6)) =3D (UINT8)(IrqBu= ffserSize + 19); - - // - // Notify _PRS to report long formed ResourceTemplate - // - *IsShortFormPkgLength =3D FALSE; - break; - } - } - } - - if (DataPtr >=3D (UINT8 *) ((UINT8 *) Table + Table->Length - (TPM_PRS_R= ES_NAME_SIZE + TPM_POS_RES_TEMPLATE_MIN_SIZE))) { - return EFI_NOT_FOUND; - } - - // - // 3. Move DataPtr to Interrupt descriptor header and patch interrupt de= scriptor. - // 5 bytes for interrupt descriptor header, 2 bytes for End Tag - // - DataPtr +=3D NewPkgLength - (5 + IrqBuffserSize + 2); - // - // 3.1 Patch Length bit[7:0] of Interrupt descriptor patch interrupt d= escriptor - // - *(DataPtr + 1) =3D (UINT8)(2 + IrqBuffserSize); - // - // 3.2 Patch Interrupt Table Length - // - *(DataPtr + 4) =3D (UINT8)(IrqBuffserSize / sizeof(UINT32)); - // - // 3.3 Copy patched InterruptNumBuffer - // - CopyMem(DataPtr + 5, IrqBuffer, IrqBuffserSize); - - // - // 4. Jump over Interrupt descriptor and Patch END Tag, set Checksum fie= ld to 0 - // - DataPtr +=3D 5 + IrqBuffserSize; - *DataPtr =3D ACPI_END_TAG_DESCRIPTOR; - *(DataPtr + 1) =3D 0; - - // - // 5. Jump over new ResourceTemplate. Stuff rest bytes to NOOP - // - DataPtr +=3D 2; - if (DataPtr < DataEndPtr) { - SetMem(DataPtr, (UINTN)DataEndPtr - (UINTN)DataPtr, AML_NOOP_OP); - } - - return EFI_SUCCESS; -} - -/** - Patch TPM2 device HID string. The initial string tag in TPM2 ACPI table= is "NNN0000". - - @param[in, out] Table The TPM2 SSDT ACPI table. - - @return HID Update status. - -**/ -EFI_STATUS -UpdateHID ( - EFI_ACPI_DESCRIPTION_HEADER *Table - ) -{ - EFI_STATUS Status; - UINT8 *DataPtr; - CHAR8 Hid[TPM_HID_ACPI_SIZE]; - UINT32 ManufacturerID; - UINT32 FirmwareVersion1; - UINT32 FirmwareVersion2; - BOOLEAN PnpHID; - - PnpHID =3D TRUE; - - // - // Initialize HID with Default PNP string - // - ZeroMem(Hid, TPM_HID_ACPI_SIZE); - - // - // Get Manufacturer ID - // - Status =3D Tpm2GetCapabilityManufactureID(&ManufacturerID); - if (!EFI_ERROR(Status)) { - DEBUG((EFI_D_INFO, "TPM_PT_MANUFACTURER 0x%08x\n", ManufacturerID)); - // - // ManufacturerID defined in TCG Vendor ID Registry - // may tailed with 0x00 or 0x20 - // - if ((ManufacturerID >> 24) =3D=3D 0x00 || ((ManufacturerID >> 24) =3D= =3D 0x20)) { - // - // HID containing PNP ID "NNN####" - // NNN is uppercase letter for Vendor ID specified by manufacturer - // - CopyMem(Hid, &ManufacturerID, 3); - } else { - // - // HID containing ACP ID "NNNN####" - // NNNN is uppercase letter for Vendor ID specified by manufacture= r - // - CopyMem(Hid, &ManufacturerID, 4); - PnpHID =3D FALSE; - } - } else { - DEBUG ((EFI_D_ERROR, "Get TPM_PT_MANUFACTURER failed %x!\n", Status)); - ASSERT(FALSE); - return Status; - } - - Status =3D Tpm2GetCapabilityFirmwareVersion(&FirmwareVersion1, &Firmware= Version2); - if (!EFI_ERROR(Status)) { - DEBUG((EFI_D_INFO, "TPM_PT_FIRMWARE_VERSION_1 0x%x\n", FirmwareVersion= 1)); - DEBUG((EFI_D_INFO, "TPM_PT_FIRMWARE_VERSION_2 0x%x\n", FirmwareVersion= 2)); - // - // #### is Firmware Version 1 - // - if (PnpHID) { - AsciiSPrint(Hid + 3, TPM_HID_PNP_SIZE - 3, "%02d%02d", ((FirmwareVer= sion1 & 0xFFFF0000) >> 16), (FirmwareVersion1 & 0x0000FFFF)); - } else { - AsciiSPrint(Hid + 4, TPM_HID_ACPI_SIZE - 4, "%02d%02d", ((FirmwareVe= rsion1 & 0xFFFF0000) >> 16), (FirmwareVersion1 & 0x0000FFFF)); - } - - } else { - DEBUG ((EFI_D_ERROR, "Get TPM_PT_FIRMWARE_VERSION_X failed %x!\n", Sta= tus)); - ASSERT(FALSE); - return Status; - } - - // - // Patch HID in ASL code before loading the SSDT. - // - for (DataPtr =3D (UINT8 *)(Table + 1); - DataPtr <=3D (UINT8 *) ((UINT8 *) Table + Table->Length - TPM_HID_P= NP_SIZE); - DataPtr +=3D 1) { - if (AsciiStrCmp((CHAR8 *)DataPtr, TPM_HID_TAG) =3D=3D 0) { - if (PnpHID) { - CopyMem(DataPtr, Hid, TPM_HID_PNP_SIZE); - // - // if HID is PNP ID, patch the last byte in HID TAG to Noop - // - *(DataPtr + TPM_HID_PNP_SIZE) =3D AML_NOOP_OP; - } else { - - CopyMem(DataPtr, Hid, TPM_HID_ACPI_SIZE); - } - DEBUG((DEBUG_INFO, "TPM2 ACPI _HID is patched to %a\n", DataPtr)); - - return Status; - } - } - - DEBUG((EFI_D_ERROR, "TPM2 ACPI HID TAG for patch not found!\n")); - return EFI_NOT_FOUND; -} - -/** - Initialize and publish TPM items in ACPI table. - - @retval EFI_SUCCESS The TCG ACPI table is published successfully. - @retval Others The TCG ACPI table is not published. - -**/ -EFI_STATUS -PublishAcpiTable ( - VOID - ) -{ - EFI_STATUS Status; - EFI_ACPI_TABLE_PROTOCOL *AcpiTable; - UINTN TableKey; - EFI_ACPI_DESCRIPTION_HEADER *Table; - UINTN TableSize; - UINT32 *PossibleIrqNumBuf; - UINT32 PossibleIrqNumBufSize; - BOOLEAN IsShortFormPkgLength; - - IsShortFormPkgLength =3D FALSE; - - Status =3D GetSectionFromFv ( - &gEfiCallerIdGuid, - EFI_SECTION_RAW, - 0, - (VOID **) &Table, - &TableSize - ); - ASSERT_EFI_ERROR (Status); - - // - // Measure to PCR[0] with event EV_POST_CODE ACPI DATA. - // The measurement has to be done before any update. - // Otherwise, the PCR record would be different after TPM FW update - // or the PCD configuration change. - // - TpmMeasureAndLogData( - 0, - EV_POST_CODE, - EV_POSTCODE_INFO_ACPI_DATA, - ACPI_DATA_LEN, - Table, - TableSize - ); - - // - // Update Table version before measuring it to PCR - // - Status =3D UpdatePPVersion(Table, (CHAR8 *)PcdGetPtr(PcdTcgPhysicalPrese= nceInterfaceVer)); - ASSERT_EFI_ERROR (Status); - - DEBUG (( - DEBUG_INFO, - "Current physical presence interface version - %a\n", - (CHAR8 *) PcdGetPtr(PcdTcgPhysicalPresenceInterfaceVer) - )); - - // - // Update TPM2 HID after measuring it to PCR - // - Status =3D UpdateHID(Table); - if (EFI_ERROR(Status)) { - return Status; - } - - if (PcdGet32(PcdTpm2CurrentIrqNum) !=3D 0) { - // - // Patch _PRS interrupt resource only when TPM interrupt is supported - // - PossibleIrqNumBuf =3D (UINT32 *)PcdGetPtr(PcdTpm2PossibleIrqNumBuf= ); - PossibleIrqNumBufSize =3D (UINT32)PcdGetSize(PcdTpm2PossibleIrqNumBuf)= ; - - if (PossibleIrqNumBufSize <=3D MAX_PRS_INT_BUF_SIZE && (PossibleIrqNum= BufSize % sizeof(UINT32)) =3D=3D 0) { - Status =3D UpdatePossibleResource(Table, PossibleIrqNumBuf, Possible= IrqNumBufSize, &IsShortFormPkgLength); - DEBUG (( - DEBUG_INFO, - "UpdatePossibleResource status - %x. TPM2 service may not ready in= OS.\n", - Status - )); - } else { - DEBUG (( - DEBUG_INFO, - "PcdTpm2PossibleIrqNumBuf size %x is not correct. TPM2 service may= not ready in OS.\n", - PossibleIrqNumBufSize - )); - } - } - - ASSERT (Table->OemTableId =3D=3D SIGNATURE_64 ('T', 'p', 'm', '2', 'T', = 'a', 'b', 'l')); - CopyMem (Table->OemId, PcdGetPtr (PcdAcpiDefaultOemId), sizeof (Table->O= emId) ); - mTcgNvs =3D AssignOpRegion (Table, SIGNATURE_32 ('T', 'N', 'V', 'S'), (U= INT16) sizeof (TCG_NVS)); - ASSERT (mTcgNvs !=3D NULL); - mTcgNvs->TpmIrqNum =3D PcdGet32(PcdTpm2CurrentIrqNum); - mTcgNvs->IsShortFormPkgLength =3D IsShortFormPkgLength; - - // - // Publish the TPM ACPI table. Table is re-checksummed. - // - Status =3D gBS->LocateProtocol (&gEfiAcpiTableProtocolGuid, NULL, (VOID = **) &AcpiTable); - ASSERT_EFI_ERROR (Status); - - TableKey =3D 0; - Status =3D AcpiTable->InstallAcpiTable ( - AcpiTable, - Table, - TableSize, - &TableKey - ); - ASSERT_EFI_ERROR (Status); - - return Status; -} - -/** - Publish TPM2 ACPI table - - @retval EFI_SUCCESS The TPM2 ACPI table is published successfully. - @retval Others The TPM2 ACPI table is not published. + @retval EFI_SUCCESS Notification runs successfully. **/ EFI_STATUS -PublishTpm2 ( - VOID - ) +EFIAPI +TcgMmReadyToLock ( + IN CONST EFI_GUID *Protocol, + IN VOID *Interface, + IN EFI_HANDLE Handle +) { - EFI_STATUS Status; - EFI_ACPI_TABLE_PROTOCOL *AcpiTable; - UINTN TableKey; - UINT64 OemTableId; - EFI_TPM2_ACPI_CONTROL_AREA *ControlArea; - TPM2_PTP_INTERFACE_TYPE InterfaceType; - - // - // Measure to PCR[0] with event EV_POST_CODE ACPI DATA. - // The measurement has to be done before any update. - // Otherwise, the PCR record would be different after event log update - // or the PCD configuration change. - // - TpmMeasureAndLogData( - 0, - EV_POST_CODE, - EV_POSTCODE_INFO_ACPI_DATA, - ACPI_DATA_LEN, - &mTpm2AcpiTemplate, - mTpm2AcpiTemplate.Header.Length - ); - - mTpm2AcpiTemplate.Header.Revision =3D PcdGet8(PcdTpm2AcpiTableRev); - DEBUG((DEBUG_INFO, "Tpm2 ACPI table revision is %d\n", mTpm2AcpiTemplate= .Header.Revision)); - - // - // PlatformClass is only valid for version 4 and above - // BIT0~15: PlatformClass - // BIT16~31: Reserved - // - if (mTpm2AcpiTemplate.Header.Revision >=3D EFI_TPM2_ACPI_TABLE_REVISION_= 4) { - mTpm2AcpiTemplate.Flags =3D (mTpm2AcpiTemplate.Flags & 0xFFFF0000) | P= cdGet8(PcdTpmPlatformClass); - DEBUG((DEBUG_INFO, "Tpm2 ACPI table PlatformClass is %d\n", (mTpm2Acpi= Template.Flags & 0x0000FFFF))); - } - - mTpm2AcpiTemplate.Laml =3D PcdGet32(PcdTpm2AcpiTableLaml); - mTpm2AcpiTemplate.Lasa =3D PcdGet64(PcdTpm2AcpiTableLasa); - if ((mTpm2AcpiTemplate.Header.Revision < EFI_TPM2_ACPI_TABLE_REVISION_4)= || - (mTpm2AcpiTemplate.Laml =3D=3D 0) || (mTpm2AcpiTemplate.Lasa =3D=3D = 0)) { - // - // If version is smaller than 4 or Laml/Lasa is not valid, rollback to= original Length. - // - mTpm2AcpiTemplate.Header.Length =3D sizeof(EFI_TPM2_ACPI_TABLE); - } + EFI_STATUS Status; - InterfaceType =3D PcdGet8(PcdActiveTpmInterfaceType); - switch (InterfaceType) { - case Tpm2PtpInterfaceCrb: - mTpm2AcpiTemplate.StartMethod =3D EFI_TPM2_ACPI_TABLE_START_METHOD_COM= MAND_RESPONSE_BUFFER_INTERFACE; - mTpm2AcpiTemplate.AddressOfControlArea =3D PcdGet64 (PcdTpmBaseAddress= ) + 0x40; - ControlArea =3D (EFI_TPM2_ACPI_CONTROL_AREA *)(UINTN)mTpm2AcpiTemplate= .AddressOfControlArea; - ControlArea->CommandSize =3D 0xF80; - ControlArea->ResponseSize =3D 0xF80; - ControlArea->Command =3D PcdGet64 (PcdTpmBaseAddress) + 0x80; - ControlArea->Response =3D PcdGet64 (PcdTpmBaseAddress) + 0x80; - break; - case Tpm2PtpInterfaceFifo: - case Tpm2PtpInterfaceTis: - break; - default: - DEBUG((EFI_D_ERROR, "TPM2 InterfaceType get error! %d\n", InterfaceTyp= e)); - break; + if (mReadyToLockHandle !=3D NULL) { + Status =3D gMmst->MmiHandlerUnRegister (mReadyToLockHandle); + mReadyToLockHandle =3D NULL; } - - CopyMem (mTpm2AcpiTemplate.Header.OemId, PcdGetPtr (PcdAcpiDefaultOemId)= , sizeof (mTpm2AcpiTemplate.Header.OemId)); - OemTableId =3D PcdGet64 (PcdAcpiDefaultOemTableId); - CopyMem (&mTpm2AcpiTemplate.Header.OemTableId, &OemTableId, sizeof (UINT= 64)); - mTpm2AcpiTemplate.Header.OemRevision =3D PcdGet32 (PcdAcpiDefaultOe= mRevision); - mTpm2AcpiTemplate.Header.CreatorId =3D PcdGet32 (PcdAcpiDefaultCr= eatorId); - mTpm2AcpiTemplate.Header.CreatorRevision =3D PcdGet32 (PcdAcpiDefaultCr= eatorRevision); - - // - // Construct ACPI table - // - Status =3D gBS->LocateProtocol (&gEfiAcpiTableProtocolGuid, NULL, (VOID = **) &AcpiTable); - ASSERT_EFI_ERROR (Status); - - Status =3D AcpiTable->InstallAcpiTable ( - AcpiTable, - &mTpm2AcpiTemplate, - mTpm2AcpiTemplate.Header.Length, - &TableKey - ); - ASSERT_EFI_ERROR (Status); - return Status; } /** - The driver's entry point. + The driver's common initialization routine. It install callbacks for TPM physical presence and MemoryClear, and loca= te SMM variable to be used in the callback function. - @param[in] ImageHandle The firmware allocated handle for the EFI image. - @param[in] SystemTable A pointer to the EFI System Table. - @retval EFI_SUCCESS The entry point is executed successfully. @retval Others Some error occurs when executing this entry poin= t. **/ EFI_STATUS -EFIAPI -InitializeTcgSmm ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +InitializeTcgCommon ( + VOID ) { EFI_STATUS Status; EFI_SMM_SW_DISPATCH2_PROTOCOL *SwDispatch; EFI_SMM_SW_REGISTER_CONTEXT SwContext; - EFI_HANDLE SwHandle; + EFI_HANDLE PpSwHandle; + EFI_HANDLE McSwHandle; + EFI_HANDLE NotifyHandle; if (!CompareGuid (PcdGetPtr(PcdTpmInstanceGuid), &gEfiTpmDeviceInstanceT= pm20DtpmGuid)){ DEBUG ((EFI_D_ERROR, "No TPM2 DTPM instance required!\n")); return EFI_UNSUPPORTED; } - Status =3D PublishAcpiTable (); + // Register a root handler to communicate the NVS region and SMI channel= between MM and DXE + mReadyToLockHandle =3D NULL; + Status =3D gMmst->MmiHandlerRegister (TpmNvsCommunciate, &gTpmNvsMmGuid,= &mReadyToLockHandle); ASSERT_EFI_ERROR (Status); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "[%a] Failed to register NVS communicate as root = MM handler - %r!\n", __FUNCTION__, Status)); + goto Cleanup; + } // // Get the Sw dispatch protocol and register SMI callback functions. // Status =3D gMmst->MmLocateProtocol (&gEfiSmmSwDispatch2ProtocolGuid, NUL= L, (VOID**)&SwDispatch); ASSERT_EFI_ERROR (Status); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "[%a] Failed to locate Sw dispatch protocol - %r!= \n", __FUNCTION__, Status)); + goto Cleanup; + } + + PpSwHandle =3D NULL; SwContext.SwSmiInputValue =3D (UINTN) -1; - Status =3D SwDispatch->Register (SwDispatch, PhysicalPresenceCallback, &= SwContext, &SwHandle); + Status =3D SwDispatch->Register (SwDispatch, PhysicalPresenceCallback, &= SwContext, &PpSwHandle); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { - return Status; + DEBUG ((DEBUG_ERROR, "[%a] Failed to register PP callback as SW MM han= dler - %r!\n", __FUNCTION__, Status)); + goto Cleanup; } - mTcgNvs->PhysicalPresence.SoftwareSmi =3D (UINT8) SwContext.SwSmiInputVa= lue; + mPpSoftwareSmi =3D SwContext.SwSmiInputValue; + McSwHandle =3D NULL; SwContext.SwSmiInputValue =3D (UINTN) -1; - Status =3D SwDispatch->Register (SwDispatch, MemoryClearCallback, &SwCon= text, &SwHandle); + Status =3D SwDispatch->Register (SwDispatch, MemoryClearCallback, &SwCon= text, &McSwHandle); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { - return Status; + DEBUG ((DEBUG_ERROR, "[%a] Failed to register MC callback as SW MM han= dler - %r!\n", __FUNCTION__, Status)); + goto Cleanup; } - mTcgNvs->MemoryClear.SoftwareSmi =3D (UINT8) SwContext.SwSmiInputValue; + mMcSoftwareSmi =3D SwContext.SwSmiInputValue; // // Locate SmmVariableProtocol. // Status =3D gMmst->MmLocateProtocol (&gEfiSmmVariableProtocolGuid, NULL, = (VOID**)&mSmmVariable); ASSERT_EFI_ERROR (Status); + if (EFI_ERROR (Status)) { + // Should not happen + DEBUG ((DEBUG_ERROR, "[%a] Failed to locate SMM variable protocol - %r= !\n", __FUNCTION__, Status)); + goto Cleanup; + } - // - // Set TPM2 ACPI table - // - Status =3D PublishTpm2 (); + // Turn off the light before leaving the room... at least, take a remote= ... + NotifyHandle =3D NULL; + Status =3D gMmst->MmRegisterProtocolNotify (&gEfiMmReadyToLockProtocolGu= id, TcgMmReadyToLock, &NotifyHandle); ASSERT_EFI_ERROR (Status); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "[%a] Failed to register ready to lock notificati= on - %r!\n", __FUNCTION__, Status)); + goto Cleanup; + } + Tcg2NotifyMmReady (); - return EFI_SUCCESS; +Cleanup: + if (EFI_ERROR (Status)) { + // Something is whacked, clean up the mess... + if (NotifyHandle !=3D NULL) { + gMmst->MmRegisterProtocolNotify (&gEfiMmReadyToLockProtocolGuid, NUL= L, &NotifyHandle); + } + if (McSwHandle !=3D NULL && SwDispatch !=3D NULL) { + SwDispatch->UnRegister (SwDispatch, McSwHandle); + } + if (PpSwHandle !=3D NULL && SwDispatch !=3D NULL) { + SwDispatch->UnRegister (SwDispatch, PpSwHandle); + } + if (mReadyToLockHandle !=3D NULL) { + gMmst->MmiHandlerUnRegister (mReadyToLockHandle); + } + } + + return Status; } diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c b/SecurityPkg/Tcg/= Tcg2Smm/Tcg2TraditionalMm.c new file mode 100644 index 000000000000..5930090b4e46 --- /dev/null +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c @@ -0,0 +1,82 @@ +/** @file + TCG2 SMM driver that updates TPM2 items in ACPI table and registers + SMI2 callback functions for Tcg2 physical presence, ClearMemory, and + sample for dTPM StartMethod. + + Caution: This module requires additional review when modified. + This driver will have external input - variable and ACPINvs data in SMM = mode. + This external input must be validated carefully to avoid security issue. + + PhysicalPresenceCallback() and MemoryClearCallback() will receive untrus= ted input and do some check. + +Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "Tcg2Smm.h" +#include +#include + +/** + Notify the system that the SMM variable driver is ready. +**/ +VOID +Tcg2NotifyMmReady ( + VOID + ) +{ + EFI_STATUS Status; + EFI_HANDLE Handle; + + Handle =3D NULL; + Status =3D gBS->InstallProtocolInterface ( + &Handle, + &gTcg2MmSwSmiRegisteredGuid, + EFI_NATIVE_INTERFACE, + NULL + ); + ASSERT_EFI_ERROR (Status); +} + +/** + This function is an abstraction layer for implementation specific Mm buf= fer validation routine. + + @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 ov= erlap with SMRAM. + @retval FALSE This buffer is not valid per processor architecture or ove= rlap with SMRAM. +**/ +BOOLEAN +IsBufferOutsideMmValid ( + IN EFI_PHYSICAL_ADDRESS Buffer, + IN UINT64 Length + ) +{ + return SmmIsBufferOutsideSmmValid (Buffer, Length); +} + +/** + The driver's entry point. + + It install callbacks for TPM physical presence and MemoryClear, and loca= te + SMM variable to be used in the callback function. + + @param[in] ImageHandle The firmware allocated handle for the EFI image. + @param[in] SystemTable A pointer to the EFI System Table. + + @retval EFI_SUCCESS The entry point is executed successfully. + @retval Others Some error occurs when executing this entry poin= t. + +**/ +EFI_STATUS +EFIAPI +InitializeTcgSmm ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + return InitializeTcgCommon (); +} diff --git a/SecurityPkg/Include/Guid/TpmNvsMm.h b/SecurityPkg/Include/Guid= /TpmNvsMm.h new file mode 100644 index 000000000000..a6e8e1f30f95 --- /dev/null +++ b/SecurityPkg/Include/Guid/TpmNvsMm.h @@ -0,0 +1,68 @@ +/** @file + TPM NVS MM guid, used for exchanging information, including SWI value an= d NVS region + information, for patching TPM ACPI table. + +Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __TCG2_NVS_MM_H__ +#define __TCG2_NVS_MM_H__ + +#define MM_TPM_NVS_HOB_GUID \ + { 0xc96c76eb, 0xbc78, 0x429c, { 0x9f, 0x4b, 0xda, 0x51, 0x78, 0xc2, 0x84= , 0x57 }} + +extern EFI_GUID gTpmNvsMmGuid; + +#pragma pack(1) +typedef struct { + UINT8 SoftwareSmi; + UINT32 Parameter; + UINT32 Response; + UINT32 Request; + UINT32 RequestParameter; + UINT32 LastRequest; + UINT32 ReturnCode; +} PHYSICAL_PRESENCE_NVS; + +typedef struct { + UINT8 SoftwareSmi; + UINT32 Parameter; + UINT32 Request; + UINT32 ReturnCode; +} MEMORY_CLEAR_NVS; + +typedef struct { + PHYSICAL_PRESENCE_NVS PhysicalPresence; + MEMORY_CLEAR_NVS MemoryClear; + UINT32 PPRequestUserConfirm; + UINT32 TpmIrqNum; + BOOLEAN IsShortFormPkgLength; +} TCG_NVS; + +typedef struct { + UINT8 OpRegionOp; + UINT32 NameString; + UINT8 RegionSpace; + UINT8 DWordPrefix; + UINT32 RegionOffset; + UINT8 BytePrefix; + UINT8 RegionLen; +} AML_OP_REGION_32_8; + +typedef struct { + UINT64 Function; + UINT64 ReturnStatus; + EFI_PHYSICAL_ADDRESS TargetAddress; + UINT64 RegisteredPpSwiValue; + UINT64 RegisteredMcSwiValue; +} TPM_NVS_MM_COMM_BUFFER; +#pragma pack() + +typedef enum { + TpmNvsMmExchangeInfo, +} TPM_NVS_MM_FUNCTION; + +#endif // __TCG_SMM_H__ diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec index 1b7d62e802b3..0970cae5c75e 100644 --- a/SecurityPkg/SecurityPkg.dec +++ b/SecurityPkg/SecurityPkg.dec @@ -183,6 +183,13 @@ [Guids] ## Include/OpalPasswordExtraInfoVariable.h gOpalExtraInfoVariableGuid =3D {0x44a2ad5d, 0x612c, 0x47b3, {0xb0, 0x6e= , 0xc8, 0xf5, 0x0b, 0xfb, 0xf0, 0x7d}} + ## GUID used to exchange registered SWI value and NVS region between Tcg= 2Acpi and Tcg2Smm. + ## Include/Guid/TpmNvsMm.h + gTpmNvsMmGuid =3D { 0xc96c76eb, 0xbc78, 0x429c, { 0= x9f, 0x4b, 0xda, 0x51, 0x78, 0xc2, 0x84, 0x57 }} + + ## GUID used to enforce loading order between Tcg2Acpi and Tcg2Smm + gTcg2MmSwSmiRegisteredGuid =3D { 0x9d4548b9, 0xa48d, 0x4db4, { 0= x9a, 0x68, 0x32, 0xc5, 0x13, 0x9e, 0x20, 0x18 } } + [Ppis] ## The PPI GUID for that TPM physical presence should be locked. diff --git a/SecurityPkg/SecurityPkg.dsc b/SecurityPkg/SecurityPkg.dsc index 618420a56c33..928bff72baa3 100644 --- a/SecurityPkg/SecurityPkg.dsc +++ b/SecurityPkg/SecurityPkg.dsc @@ -317,6 +317,7 @@ [Components.IA32, Components.X64] SecurityPkg/Tcg/MemoryOverwriteRequestControlLock/TcgMorLockSmm.inf SecurityPkg/Tcg/TcgSmm/TcgSmm.inf SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf + SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.inf SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/SmmTcg2PhysicalPresenceLi= b.inf SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/StandaloneMmTcg2PhysicalP= resenceLib.inf diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf b/SecurityPkg/Tcg/Tcg2Acpi= /Tcg2Acpi.inf similarity index 76% copy from SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf copy to SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.inf index 872ed27cbe71..d8e06881c01d 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf +++ b/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.inf @@ -13,8 +13,8 @@ # "Errata for PC Client Specific Platform Firmware Profile Specificati= on Version 1.0 Revision 1.03" # # This driver implements TPM 2.0 definition block in ACPI table and -# registers SMI callback functions for Tcg2 physical presence and -# MemoryClear to handle the requests from ACPI method. +# populates registered SMI callback functions for Tcg2 physical presence +# and MemoryClear to handle the requests for ACPI method. # # Caution: This module requires additional review when modified. # This driver will have external input - variable and ACPINvs data in SMM= mode. @@ -28,17 +28,15 @@ [Defines] INF_VERSION =3D 0x00010005 - BASE_NAME =3D Tcg2Smm - MODULE_UNI_FILE =3D Tcg2Smm.uni - FILE_GUID =3D 44A20657-10B8-4049-A148-ACD8812AF257 - MODULE_TYPE =3D DXE_SMM_DRIVER + BASE_NAME =3D Tcg2Acpi + FILE_GUID =3D 0D4BBF18-C2CC-4C23-BD63-BFDAD4C710D0 + MODULE_TYPE =3D DXE_DRIVER PI_SPECIFICATION_VERSION =3D 0x0001000A VERSION_STRING =3D 1.0 - ENTRY_POINT =3D InitializeTcgSmm + ENTRY_POINT =3D InitializeTcgAcpi [Sources] - Tcg2Smm.h - Tcg2Smm.c + Tcg2Acpi.c Tpm.asl [Packages] @@ -50,7 +48,6 @@ [LibraryClasses] BaseLib BaseMemoryLib UefiDriverEntryPoint - MmServicesTableLib UefiBootServicesTableLib DebugLib DxeServicesLib @@ -60,16 +57,13 @@ [LibraryClasses] PcdLib [Guids] - ## SOMETIMES_PRODUCES ## Variable:L"MemoryOverwriteRequestControl" - ## SOMETIMES_CONSUMES ## Variable:L"MemoryOverwriteRequestControl" - gEfiMemoryOverwriteControlDataGuid - gEfiTpmDeviceInstanceTpm20DtpmGuid ## PRODUCE= S ## GUID # TPM device identifier + gTpmNvsMmGuid ## CONSUME= S + gEdkiiPiSmmCommunicationRegionTableGuid ## CONSUME= S [Protocols] - gEfiSmmSwDispatch2ProtocolGuid ## CONSUME= S - gEfiSmmVariableProtocolGuid ## CONSUME= S gEfiAcpiTableProtocolGuid ## CONSUME= S + gEfiMmCommunicationProtocolGuid ## CONSUME= S [FixedPcd] gEfiSecurityPkgTokenSpaceGuid.PcdSmiCommandIoPort ## CONSUME= S @@ -93,9 +87,5 @@ [Pcd] [Depex] gEfiAcpiTableProtocolGuid AND - gEfiSmmSwDispatch2ProtocolGuid AND - gEfiSmmVariableProtocolGuid AND + gTcg2MmSwSmiRegisteredGuid AND gEfiTcg2ProtocolGuid - -[UserExtensions.TianoCore."ExtraFiles"] - Tcg2SmmExtra.uni diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tpm.asl b/SecurityPkg/Tcg/Tcg2Acpi/Tpm= .asl similarity index 100% rename from SecurityPkg/Tcg/Tcg2Smm/Tpm.asl rename to SecurityPkg/Tcg/Tcg2Acpi/Tpm.asl diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h b/SecurityPkg/Tcg/Tcg2Smm/Tc= g2Smm.h index d7328c8f2ac9..d7f78aa43275 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h @@ -2,6 +2,7 @@ The header file for Tcg2 SMM driver. Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -9,13 +10,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef __TCG2_SMM_H__ #define __TCG2_SMM_H__ -#include -#include -#include +#include #include #include +#include +#include #include #include #include @@ -25,56 +26,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include -#include -#include -#include -#include #include #include #include -#include #include #include #include -#pragma pack(1) -typedef struct { - UINT8 SoftwareSmi; - UINT32 Parameter; - UINT32 Response; - UINT32 Request; - UINT32 RequestParameter; - UINT32 LastRequest; - UINT32 ReturnCode; -} PHYSICAL_PRESENCE_NVS; - -typedef struct { - UINT8 SoftwareSmi; - UINT32 Parameter; - UINT32 Request; - UINT32 ReturnCode; -} MEMORY_CLEAR_NVS; - -typedef struct { - PHYSICAL_PRESENCE_NVS PhysicalPresence; - MEMORY_CLEAR_NVS MemoryClear; - UINT32 PPRequestUserConfirm; - UINT32 TpmIrqNum; - BOOLEAN IsShortFormPkgLength; -} TCG_NVS; - -typedef struct { - UINT8 OpRegionOp; - UINT32 NameString; - UINT8 RegionSpace; - UINT8 DWordPrefix; - UINT32 RegionOffset; - UINT8 BytePrefix; - UINT8 RegionLen; -} AML_OP_REGION_32_8; -#pragma pack() - // // The definition for TCG MOR // @@ -87,36 +46,42 @@ typedef struct { #define MOR_REQUEST_SUCCESS 0 #define MOR_REQUEST_GENERAL_FAILURE 1 -// -// Physical Presence Interface Version supported by Platform -// -#define PHYSICAL_PRESENCE_VERSION_TAG "$PV" -#define PHYSICAL_PRESENCE_VERSION_SIZE 4 - -// -// PNP _HID for TPM2 device -// -#define TPM_HID_TAG "NNNN00= 00" -#define TPM_HID_PNP_SIZE 8 -#define TPM_HID_ACPI_SIZE 9 - -#define TPM_PRS_RESL "RESL" -#define TPM_PRS_RESS "RESS" -#define TPM_PRS_RES_NAME_SIZE 4 -// -// Minimum PRS resource template size -// 1 byte for BufferOp -// 1 byte for PkgLength -// 2 bytes for BufferSize -// 12 bytes for Memory32Fixed descriptor -// 5 bytes for Interrupt descriptor -// 2 bytes for END Tag -// -#define TPM_POS_RES_TEMPLATE_MIN_SIZE (1 + 1 = + 2 + 12 + 5 + 2) - -// -// Max Interrupt buffer size for PRS interrupt resource -// Now support 15 interrupts in maxmum -// -#define MAX_PRS_INT_BUF_SIZE (15*4) +/** + Notify the system that the SMM variable driver is ready. +**/ +VOID +Tcg2NotifyMmReady ( + VOID + ); + +/** + This function is an abstraction layer for implementation specific Mm buf= fer validation routine. + + @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 ov= erlap with SMRAM. + @retval FALSE This buffer is not valid per processor architecture or ove= rlap with SMRAM. +**/ +BOOLEAN +IsBufferOutsideMmValid ( + IN EFI_PHYSICAL_ADDRESS Buffer, + IN UINT64 Length + ); + +/** + The driver's common initialization routine. + + It install callbacks for TPM physical presence and MemoryClear, and loca= te + SMM variable to be used in the callback function. + + @retval EFI_SUCCESS The entry point is executed successfully. + @retval Others Some error occurs when executing this entry poin= t. + +**/ +EFI_STATUS +InitializeTcgCommon ( + VOID + ); + #endif // __TCG_SMM_H__ diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf b/SecurityPkg/Tcg/Tcg2Smm/= Tcg2Smm.inf index 872ed27cbe71..096338d0ef47 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf @@ -39,7 +39,7 @@ [Defines] [Sources] Tcg2Smm.h Tcg2Smm.c - Tpm.asl + Tcg2TraditionalMm.c [Packages] MdePkg/MdePkg.dec @@ -58,6 +58,7 @@ [LibraryClasses] Tpm2CommandLib Tcg2PhysicalPresenceLib PcdLib + SmmMemLib [Guids] ## SOMETIMES_PRODUCES ## Variable:L"MemoryOverwriteRequestControl" @@ -65,34 +66,18 @@ [Guids] gEfiMemoryOverwriteControlDataGuid gEfiTpmDeviceInstanceTpm20DtpmGuid ## PRODUCE= S ## GUID # TPM device identifier + gTcg2MmSwSmiRegisteredGuid ## PRODUCE= S + gTpmNvsMmGuid ## CONSUME= S [Protocols] gEfiSmmSwDispatch2ProtocolGuid ## CONSUME= S gEfiSmmVariableProtocolGuid ## CONSUME= S - gEfiAcpiTableProtocolGuid ## CONSUME= S - -[FixedPcd] - gEfiSecurityPkgTokenSpaceGuid.PcdSmiCommandIoPort ## CONSUME= S + gEfiMmReadyToLockProtocolGuid ## CONSUME= S [Pcd] gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid ## CONSUME= S - gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemId ## SOMETIM= ES_CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemTableId ## SOMETIM= ES_CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemRevision ## SOMETIM= ES_CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultCreatorId ## SOMETIM= ES_CONSUMES - gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultCreatorRevision ## SOMETIM= ES_CONSUMES - gEfiSecurityPkgTokenSpaceGuid.PcdTpmBaseAddress ## CONSUME= S - gEfiSecurityPkgTokenSpaceGuid.PcdTcgPhysicalPresenceInterfaceVer ## CON= SUMES - gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableRev ## CON= SUMES - gEfiSecurityPkgTokenSpaceGuid.PcdTpmPlatformClass ## SOM= ETIMES_CONSUMES - gEfiSecurityPkgTokenSpaceGuid.PcdTpm2CurrentIrqNum ## CONSUME= S - gEfiSecurityPkgTokenSpaceGuid.PcdTpm2PossibleIrqNumBuf ## CONSUME= S - gEfiSecurityPkgTokenSpaceGuid.PcdActiveTpmInterfaceType ## CONSUME= S - gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableLaml ## CONSUME= S - gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableLasa ## CONSUME= S [Depex] - gEfiAcpiTableProtocolGuid AND gEfiSmmSwDispatch2ProtocolGuid AND gEfiSmmVariableProtocolGuid AND gEfiTcg2ProtocolGuid -- 2.30.0.windows.1 --_000_MWHPR06MB310237B5CBEC479B1C78CBC1F3819MWHPR06MB3102namp_ Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable

Hi Jiewen/Jian/Qi/Rahul,

 

This patch is intended to separate the Tcg2Smm drive= r into DXE and SMM drivers based on their functionalities. Could you please= provide feedback? It is a relatively heavy modification, please let me kno= w if you have suggestions on how to break them down into smaller pieces. Thanks in advance.

 

Regards,

Kun

 

From: Kun Qin
Sent: Tuesday, February 9, 2021 17:25
To: devel@edk2.groups.io=
Cc: Jiewen Yao; Jian J Wang; Qi Zhang; Rahul Kumar
Subject: [PATCH v2 4/6] SecurityPkg: Tcg2Smm: Separate Tcg2Smm into = 2 modules

 

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

This change separated the original Tcg2Smm module into 2 drivers: the
SMM driver that registers callback for physical presence and memory
clear; the Tcg2Acpi driver that patches and publishes ACPI table for
runtime use.

Tcg2Smm introduced an SMI root handler to allow Tcg2Acpi to communicate
the NVS region used by Tpm.asl and exchange the registered SwSmiValue.

Lastly, Tcg2Smm driver will publish gTcg2MmSwSmiRegisteredGuid at the end of entrypoint to ensure Tcg2Acpi to load after Tcg2Smm is ready to
communicate.

Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Jian J Wang <jian.j.wang@intel.com>
Cc: Qi Zhang <qi1.zhang@intel.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>

Signed-off-by: Kun Qin <kun.q@outlook.com>
---

Notes:
    v2:
    - Newly added in v2.
   
    v2:
    - Newly added.

 SecurityPkg/Tcg/{Tcg2Smm/Tcg2Smm.c =3D> Tcg2Acpi/Tcg2Acpi.c} =     | 350 ++++----
 SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c      =             &nb= sp;           | 850 ++++-= ---------------
 SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c    &n= bsp;            = ;   |  82 ++
 SecurityPkg/Include/Guid/TpmNvsMm.h     &nbs= p;            &= nbsp;         |  68 ++
 SecurityPkg/SecurityPkg.dec       =             &nb= sp;            =     |   7 +
 SecurityPkg/SecurityPkg.dsc       =             &nb= sp;            =     |   1 +
 SecurityPkg/Tcg/{Tcg2Smm/Tcg2Smm.inf =3D> Tcg2Acpi/Tcg2Acpi.inf} |=   32 +-
 SecurityPkg/Tcg/{Tcg2Smm =3D> Tcg2Acpi}/Tpm.asl   &= nbsp;           &nbs= p;  |   0
 SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h      =             &nb= sp;           | 119 +--  SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf     &nbs= p;            &= nbsp;         |  25 +-
 10 files changed, 542 insertions(+), 992 deletions(-)

diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c b/SecurityPkg/Tcg/Tcg2Acpi/T= cg2Acpi.c
similarity index 72%
copy from SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c
copy to SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c
index 08105c3692ba..7080df81efe7 100644
--- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c
+++ b/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.c
@@ -1,20 +1,74 @@
 /** @file
-  It updates TPM2 items in ACPI table and registers SMI2 callback
-  functions for Tcg2 physical presence, ClearMemory, and sample
-  for dTPM StartMethod.
+  This driver implements TPM 2.0 definition block in ACPI table and +  populates registered SMI callback functions for Tcg2 physical prese= nce
+  and MemoryClear to handle the requests for ACPI method.
 
   Caution: This module requires additional review when modified.=
   This driver will have external input - variable and ACPINvs da= ta in SMM mode.
   This external input must be validated carefully to avoid secur= ity issue.
 
-  PhysicalPresenceCallback() and MemoryClearCallback() will receive u= ntrusted input and do some check.
-
 Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<= ;BR>
+Copyright (c) Microsoft Corporation.
 SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 
-#include "Tcg2Smm.h"
+#include <PiDxe.h>
+
+#include <IndustryStandard/Tpm2Acpi.h>
+
+#include <Guid/TpmInstance.h>
+#include <Guid/TpmNvsMm.h>
+#include <Guid/PiSmmCommunicationRegionTable.h>
+
+#include <Protocol/AcpiTable.h>
+#include <Protocol/Tcg2Protocol.h>
+#include <Protocol/MmCommunication.h>
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DxeServicesLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/DebugLib.h>
+#include <Library/PcdLib.h>
+#include <Library/PrintLib.h>
+#include <Library/TpmMeasurementLib.h>
+#include <Library/Tpm2DeviceLib.h>
+#include <Library/Tpm2CommandLib.h>
+#include <Library/UefiLib.h>
+
+//
+// Physical Presence Interface Version supported by Platform
+//
+#define PHYSICAL_PRESENCE_VERSION_TAG      &= nbsp;           &nbs= p;           "$PV&qu= ot;
+#define PHYSICAL_PRESENCE_VERSION_SIZE      =             &nb= sp;          4
+
+//
+// PNP _HID for TPM2 device
+//
+#define TPM_HID_TAG         &= nbsp;           &nbs= p;            &= nbsp;           &nbs= p; "NNNN0000"
+#define TPM_HID_PNP_SIZE        &n= bsp;            = ;            &n= bsp;         8
+#define TPM_HID_ACPI_SIZE        &= nbsp;           &nbs= p;            &= nbsp;        9
+
+#define TPM_PRS_RESL         =             &nb= sp;            =              &q= uot;RESL"
+#define TPM_PRS_RESS         =             &nb= sp;            =              &q= uot;RESS"
+#define TPM_PRS_RES_NAME_SIZE       &nb= sp;            =             &nb= sp;     4
+//
+// Minimum PRS resource template size
+//  1 byte    for  BufferOp
+//  1 byte    for  PkgLength
+//  2 bytes   for  BufferSize
+//  12 bytes  for  Memory32Fixed descriptor
+//  5 bytes   for  Interrupt descriptor
+//  2 bytes   for  END Tag
+//
+#define TPM_POS_RES_TEMPLATE_MIN_SIZE      &= nbsp;           &nbs= p;           (1 + 1 + 2 += 12 + 5 + 2)
+
+//
+// Max Interrupt buffer size for PRS interrupt resource
+// Now support 15 interrupts in maxmum
+//
+#define MAX_PRS_INT_BUF_SIZE       &nbs= p;            &= nbsp;           &nbs= p;      (15*4)
 
 #pragma pack(1)
 
@@ -49,142 +103,8 @@ EFI_TPM2_ACPI_TABLE_V4  mTpm2AcpiTemplate =3D {    EFI_TPM2_ACPI_TABLE_START_METHOD_TIS, // StartMethod
 };
 
-EFI_SMM_VARIABLE_PROTOCOL  *mSmmVariable;
 TCG_NVS          &n= bsp;         *mTcgNvs;
 
-/**
-  Software SMI callback for TPM physical presence which is called fro= m ACPI method.
-
-  Caution: This function may receive untrusted input.
-  Variable and ACPINvs are external input, so this function will vali= date
-  its data structure to be valid value.
-
-  @param[in]      DispatchHandle  The u= nique handle assigned to this handler by SmiHandlerRegister().
-  @param[in]      Context   &= nbsp;     Points to an optional handler context which w= as specified when the
-            &n= bsp;            = ;         handler was registered. -  @param[in, out] CommBuffer      A pointer = to a collection of data in memory that will
-            &n= bsp;            = ;         be conveyed from a non-SM= M environment into an SMM environment.
-  @param[in, out] CommBufferSize  The size of the CommBuffer. -
-  @retval EFI_SUCCESS        =      The interrupt was handled successfully.
-
-**/
-EFI_STATUS
-EFIAPI
-PhysicalPresenceCallback (
-  IN EFI_HANDLE         =          DispatchHandle,
-  IN CONST VOID         =          *Context,
-  IN OUT VOID         &n= bsp;          *CommBuffer,
-  IN OUT UINTN         &= nbsp;         *CommBufferSize
-  )
-{
-  UINT32          &= nbsp;     MostRecentRequest;
-  UINT32          &= nbsp;     Response;
-  UINT32          &= nbsp;     OperationRequest;
-  UINT32          &= nbsp;     RequestParameter;
-
-
-  if (mTcgNvs->PhysicalPresence.Parameter =3D=3D TCG_ACPI_FUNCTION= _RETURN_REQUEST_RESPONSE_TO_OS) {
-    mTcgNvs->PhysicalPresence.ReturnCode =3D Tcg2Physica= lPresenceLibReturnOperationResponseToOsFunction (
-            &n= bsp;            = ;            &n= bsp;       &MostRecentRequest,
-            &n= bsp;            = ;            &n= bsp;       &Response
-            &n= bsp;            = ;            &n= bsp;       );
-    mTcgNvs->PhysicalPresence.LastRequest =3D MostRecent= Request;
-    mTcgNvs->PhysicalPresence.Response =3D Response;
-    return EFI_SUCCESS;
-  } else if ((mTcgNvs->PhysicalPresence.Parameter =3D=3D TCG_ACPI_= FUNCTION_SUBMIT_REQUEST_TO_BIOS)
-          || (mTcgNvs->Phy= sicalPresence.Parameter =3D=3D TCG_ACPI_FUNCTION_SUBMIT_REQUEST_TO_BIOS_2))= {
-
-    OperationRequest =3D mTcgNvs->PhysicalPresence.Reque= st;
-    RequestParameter =3D mTcgNvs->PhysicalPresence.Reque= stParameter;
-    mTcgNvs->PhysicalPresence.ReturnCode =3D Tcg2Physica= lPresenceLibSubmitRequestToPreOSFunctionEx (
-            &n= bsp;            = ;            &n= bsp;       &OperationRequest,
-            &n= bsp;            = ;            &n= bsp;       &RequestParameter
-            &n= bsp;            = ;            &n= bsp;       );
-    mTcgNvs->PhysicalPresence.Request =3D OperationReque= st;
-    mTcgNvs->PhysicalPresence.RequestParameter =3D Reque= stParameter;
-  } else if (mTcgNvs->PhysicalPresence.Parameter =3D=3D TCG_ACPI_F= UNCTION_GET_USER_CONFIRMATION_STATUS_FOR_REQUEST) {
-    mTcgNvs->PhysicalPresence.ReturnCode =3D Tcg2Physica= lPresenceLibGetUserConfirmationStatusFunction (mTcgNvs->PPRequestUserCon= firm);
-  }
-
-  return EFI_SUCCESS;
-}
-
-
-/**
-  Software SMI callback for MemoryClear which is called from ACPI met= hod.
-
-  Caution: This function may receive untrusted input.
-  Variable and ACPINvs are external input, so this function will vali= date
-  its data structure to be valid value.
-
-  @param[in]      DispatchHandle  The u= nique handle assigned to this handler by SmiHandlerRegister().
-  @param[in]      Context   &= nbsp;     Points to an optional handler context which w= as specified when the
-            &n= bsp;            = ;         handler was registered. -  @param[in, out] CommBuffer      A pointer = to a collection of data in memory that will
-            &n= bsp;            = ;         be conveyed from a non-SM= M environment into an SMM environment.
-  @param[in, out] CommBufferSize  The size of the CommBuffer. -
-  @retval EFI_SUCCESS        =      The interrupt was handled successfully.
-
-**/
-EFI_STATUS
-EFIAPI
-MemoryClearCallback (
-  IN EFI_HANDLE         =          DispatchHandle,
-  IN CONST VOID         =          *Context,
-  IN OUT VOID         &n= bsp;          *CommBuffer,
-  IN OUT UINTN         &= nbsp;         *CommBufferSize
-  )
-{
-  EFI_STATUS         &nb= sp;           Status;
-  UINTN          &n= bsp;            = ;   DataSize;
-  UINT8          &n= bsp;            = ;   MorControl;
-
-  mTcgNvs->MemoryClear.ReturnCode =3D MOR_REQUEST_SUCCESS;
-  if (mTcgNvs->MemoryClear.Parameter =3D=3D ACPI_FUNCTION_DSM_MEMO= RY_CLEAR_INTERFACE) {
-    MorControl =3D (UINT8) mTcgNvs->MemoryClear.Request;=
-  } else if (mTcgNvs->MemoryClear.Parameter =3D=3D ACPI_FUNCTION_P= TS_CLEAR_MOR_BIT) {
-    DataSize =3D sizeof (UINT8);
-    Status =3D mSmmVariable->SmmGetVariable (
-            &n= bsp;            = ;    MEMORY_OVERWRITE_REQUEST_VARIABLE_NAME,
-            &n= bsp;            = ;    &gEfiMemoryOverwriteControlDataGuid,
-            &n= bsp;            = ;    NULL,
-            &n= bsp;            = ;    &DataSize,
-            &n= bsp;            = ;    &MorControl
-            &n= bsp;            = ;    );
-    if (EFI_ERROR (Status)) {
-      mTcgNvs->MemoryClear.ReturnCode =3D MOR_= REQUEST_GENERAL_FAILURE;
-      DEBUG ((EFI_D_ERROR, "[TPM] Get MOR va= riable failure! Status =3D %r\n", Status));
-      return EFI_SUCCESS;
-    }
-
-    if (MOR_CLEAR_MEMORY_VALUE (MorControl) =3D=3D 0x0) { -      return EFI_SUCCESS;
-    }
-    MorControl &=3D ~MOR_CLEAR_MEMORY_BIT_MASK;
-  } else {
-    mTcgNvs->MemoryClear.ReturnCode =3D MOR_REQUEST_GENE= RAL_FAILURE;
-    DEBUG ((EFI_D_ERROR, "[TPM] MOR Parameter error! P= arameter =3D %x\n", mTcgNvs->MemoryClear.Parameter));
-    return EFI_SUCCESS;
-  }
-
-  DataSize =3D sizeof (UINT8);
-  Status =3D mSmmVariable->SmmSetVariable (
-            &n= bsp;            = ;  MEMORY_OVERWRITE_REQUEST_VARIABLE_NAME,
-            &n= bsp;            = ;  &gEfiMemoryOverwriteControlDataGuid,
-            &n= bsp;            = ;  EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_V= ARIABLE_RUNTIME_ACCESS,
-            &n= bsp;            = ;  DataSize,
-            &n= bsp;            = ;  &MorControl
-            &n= bsp;            = ;  );
-  if (EFI_ERROR (Status)) {
-    mTcgNvs->MemoryClear.ReturnCode =3D MOR_REQUEST_GENE= RAL_FAILURE;
-    DEBUG ((EFI_D_ERROR, "[TPM] Set MOR variable failu= re! Status =3D %r\n", Status));
-  }
-
-  return EFI_SUCCESS;
-}
-
 /**
   Find the operation region in TCG ACPI table by given Name and = Size,
   and initialize it if the region is found.
@@ -232,6 +152,103 @@ AssignOpRegion (
   return (VOID *) (UINTN) MemoryAddress;
 }
 
+/**
+  Locate the MM communication buffer and protocol, then use it to exc= hange information with
+  Tcg2StandaloneMmm on NVS address and SMI value.
+
+  @param[in, out] TcgNvs       &nb= sp; The NVS subject to send to MM environment.
+
+  @return          =             &nb= sp; The status for locating MM common buffer, communicate to MM, etc.
+
+**/
+EFI_STATUS
+EFIAPI
+ExchangeCommonBuffer (
+  IN OUT  TCG_NVS        = ;         *TcgNvs
+)
+{
+  EFI_STATUS         &nb= sp;            =           Status;
+  EFI_MM_COMMUNICATION_PROTOCOL      &n= bsp;      *MmCommunication;
+  EDKII_PI_SMM_COMMUNICATION_REGION_TABLE   *PiSmmCommunica= tionRegionTable;
+  EFI_MEMORY_DESCRIPTOR       &nbs= p;             = *MmCommMemRegion;
+  EFI_MM_COMMUNICATE_HEADER       =           *CommHeader;
+  TPM_NVS_MM_COMM_BUFFER       &nb= sp;            *Comm= Buffer;
+  UINTN          &n= bsp;            = ;            &n= bsp; CommBufferSize;
+  UINTN          &n= bsp;            = ;            &n= bsp; Index;
+
+  // Step 0: Sanity check for input argument
+  if (TcgNvs =3D=3D NULL) {
+    DEBUG ((DEBUG_ERROR, "%a - Input argument is NULL!= \n", __FUNCTION__));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // Step 1: Grab the common buffer header
+  Status =3D EfiGetSystemConfigurationTable (&gEdkiiPiSmmCommunic= ationRegionTableGuid, (VOID**) &PiSmmCommunicationRegionTable);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "%a - Failed to locate SMM co= mmunciation common buffer - %r!\n", __FUNCTION__, Status));
+    return Status;
+  }
+
+  // Step 2: Grab one that is large enough to hold TPM_NVS_MM_COMM_BU= FFER, the IPL one should be sufficient
+  CommBufferSize =3D 0;
+  MmCommMemRegion =3D (EFI_MEMORY_DESCRIPTOR*) (PiSmmCommunicationReg= ionTable + 1);
+  for (Index =3D 0; Index < PiSmmCommunicationRegionTable->Numb= erOfEntries; Index++) {
+    if (MmCommMemRegion->Type =3D=3D EfiConventionalMemo= ry) {
+      CommBufferSize =3D EFI_PAGES_TO_SIZE ((UINT= N)MmCommMemRegion->NumberOfPages);
+      if (CommBufferSize >=3D (sizeof (TPM_NVS= _MM_COMM_BUFFER) + OFFSET_OF (EFI_MM_COMMUNICATE_HEADER, Data))) {
+        break;
+      }
+    }
+    MmCommMemRegion =3D (EFI_MEMORY_DESCRIPTOR*)((UINT8*)Mm= CommMemRegion + PiSmmCommunicationRegionTable->DescriptorSize);
+  }
+
+  if (Index >=3D PiSmmCommunicationRegionTable->NumberOfEntries= ) {
+    // Could not find one that meets our goal...
+    DEBUG ((DEBUG_ERROR, "%a - Could not find a common= buffer that is big enough for NVS!\n", __FUNCTION__));
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  // Step 3: Start to populate contents
+  // Step 3.1: MM Communication common header
+  CommHeader =3D (EFI_MM_COMMUNICATE_HEADER *) (UINTN) MmCommMemRegio= n->PhysicalStart;
+  CommBufferSize =3D sizeof (TPM_NVS_MM_COMM_BUFFER) + OFFSET_OF (EFI= _MM_COMMUNICATE_HEADER, Data);
+  ZeroMem (CommHeader, CommBufferSize);
+  CopyGuid (&CommHeader->HeaderGuid, &gTpmNvsMmGuid);
+  CommHeader->MessageLength =3D sizeof (TPM_NVS_MM_COMM_BUFFER); +
+  // Step 3.2: TPM_NVS_MM_COMM_BUFFER content per our needs
+  CommBuffer =3D (TPM_NVS_MM_COMM_BUFFER *) (CommHeader->Data); +  CommBuffer->Function =3D TpmNvsMmExchangeInfo;
+  CommBuffer->TargetAddress =3D (EFI_PHYSICAL_ADDRESS) (UINTN) Tcg= Nvs;
+
+  // Step 4: Locate the protocol and signal Mmi.
+  Status =3D gBS->LocateProtocol (&gEfiMmCommunicationProtocol= Guid, NULL, (VOID**) &MmCommunication);
+  if (!EFI_ERROR (Status)) {
+    Status =3D MmCommunication->Communicate (MmCommunica= tion, CommHeader, &CommBufferSize);
+    DEBUG ((DEBUG_INFO, "%a - Communicate() =3D %r\n&q= uot;, __FUNCTION__, Status));
+  }
+  else {
+    DEBUG ((DEBUG_ERROR, "%a - Failed to locate MmComm= unication protocol - %r\n", __FUNCTION__, Status));
+    return Status;
+  }
+
+  // Step 5: If everything goes well, populate the channel number
+  if (!EFI_ERROR (CommBuffer->ReturnStatus)) {
+    // Need to demote to UINT8 according to SMI value defin= ition
+    TcgNvs->PhysicalPresence.SoftwareSmi =3D (UINT8) Com= mBuffer->RegisteredPpSwiValue;
+    TcgNvs->MemoryClear.SoftwareSmi =3D (UINT8) CommBuff= er->RegisteredMcSwiValue;
+    DEBUG ((
+      DEBUG_INFO,
+      "%a Communication returned software SM= I value. PP: 0x%x; MC: 0x%x.\n",
+      __FUNCTION__,
+      TcgNvs->PhysicalPresence.SoftwareSmi, +      TcgNvs->MemoryClear.SoftwareSmi
+      ));
+  }
+
+  return (EFI_STATUS) CommBuffer->ReturnStatus;
+}
+
 /**
   Patch version string of Physical Presence interface supported = by platform. The initial string tag in TPM
 ACPI table is "$PV".
@@ -259,7 +276,7 @@ UpdatePPVersion (
        DataPtr +=3D 1) {
     if (AsciiStrCmp((CHAR8 *)DataPtr,  PHYSICAL_P= RESENCE_VERSION_TAG) =3D=3D 0) {
       Status =3D AsciiStrCpyS((CHAR8 *)DataP= tr, PHYSICAL_PRESENCE_VERSION_SIZE, PPVer);
-      DEBUG((EFI_D_INFO, "TPM2 Physical Pres= ence Interface Version update status 0x%x\n", Status));
+      DEBUG((DEBUG_INFO, "TPM2 Physical Pres= ence Interface Version update status 0x%x\n", Status));
       return Status;
     }
   }
@@ -548,7 +565,7 @@ UpdateHID (
   //
   Status =3D Tpm2GetCapabilityManufactureID(&ManufacturerID)= ;
   if (!EFI_ERROR(Status)) {
-    DEBUG((EFI_D_INFO, "TPM_PT_MANUFACTURER 0x%08x\n&q= uot;, ManufacturerID));
+    DEBUG((DEBUG_INFO, "TPM_PT_MANUFACTURER 0x%08x\n&q= uot;, ManufacturerID));
     //
     // ManufacturerID defined in TCG Vendor ID Registr= y
     // may tailed with 0x00 or 0x20
@@ -568,15 +585,15 @@ UpdateHID (
       PnpHID =3D FALSE;
     }
   } else {
-    DEBUG ((EFI_D_ERROR, "Get TPM_PT_MANUFACTURER fail= ed %x!\n", Status));
+    DEBUG ((DEBUG_ERROR, "Get TPM_PT_MANUFACTURER fail= ed %x!\n", Status));
     ASSERT(FALSE);
     return Status;
   }
 
   Status =3D Tpm2GetCapabilityFirmwareVersion(&FirmwareVersi= on1, &FirmwareVersion2);
   if (!EFI_ERROR(Status)) {
-    DEBUG((EFI_D_INFO, "TPM_PT_FIRMWARE_VERSION_1 0x%x= \n", FirmwareVersion1));
-    DEBUG((EFI_D_INFO, "TPM_PT_FIRMWARE_VERSION_2 0x%x= \n", FirmwareVersion2));
+    DEBUG((DEBUG_INFO, "TPM_PT_FIRMWARE_VERSION_1 0x%x= \n", FirmwareVersion1));
+    DEBUG((DEBUG_INFO, "TPM_PT_FIRMWARE_VERSION_2 0x%x= \n", FirmwareVersion2));
     //
     //   #### is Firmware Version 1
     //
@@ -587,7 +604,7 @@ UpdateHID (
     }
 
   } else {
-    DEBUG ((EFI_D_ERROR, "Get TPM_PT_FIRMWARE_VERSION_= X failed %x!\n", Status));
+    DEBUG ((DEBUG_ERROR, "Get TPM_PT_FIRMWARE_VERSION_= X failed %x!\n", Status));
     ASSERT(FALSE);
     return Status;
   }
@@ -615,7 +632,7 @@ UpdateHID (
     }
   }
 
-  DEBUG((EFI_D_ERROR, "TPM2 ACPI HID TAG for patch not found!\n&= quot;));
+  DEBUG((DEBUG_ERROR, "TPM2 ACPI HID TAG for patch not found!\n&= quot;));
   return EFI_NOT_FOUND;
 }
 
@@ -716,6 +733,8 @@ PublishAcpiTable (
   mTcgNvs->TpmIrqNum       = ;     =3D PcdGet32(PcdTpm2CurrentIrqNum);
   mTcgNvs->IsShortFormPkgLength =3D IsShortFormPkgLength;
 
+  Status =3D ExchangeCommonBuffer (mTcgNvs);
+
   //
   // Publish the TPM ACPI table. Table is re-checksummed.
   //
@@ -806,7 +825,7 @@ PublishTpm2 (
   case Tpm2PtpInterfaceTis:
     break;
   default:
-    DEBUG((EFI_D_ERROR, "TPM2 InterfaceType get error!= %d\n", InterfaceType));
+    DEBUG((DEBUG_ERROR, "TPM2 InterfaceType get error!= %d\n", InterfaceType));
     break;
   }
 
@@ -849,58 +868,27 @@ PublishTpm2 (
 **/
 EFI_STATUS
 EFIAPI
-InitializeTcgSmm (
+InitializeTcgAcpi (
   IN EFI_HANDLE        &= nbsp;         ImageHandle,
   IN EFI_SYSTEM_TABLE       &= nbsp;    *SystemTable
   )
 {
   EFI_STATUS        &nbs= p;            Status= ;
-  EFI_SMM_SW_DISPATCH2_PROTOCOL  *SwDispatch;
-  EFI_SMM_SW_REGISTER_CONTEXT    SwContext;
-  EFI_HANDLE         &nb= sp;           SwHandle;  
   if (!CompareGuid (PcdGetPtr(PcdTpmInstanceGuid), &gEfiTpmD= eviceInstanceTpm20DtpmGuid)){
-    DEBUG ((EFI_D_ERROR, "No TPM2 DTPM instance requir= ed!\n"));
+    DEBUG ((DEBUG_ERROR, "No TPM2 DTPM instance requir= ed!\n"));
     return EFI_UNSUPPORTED;
   }
 
   Status =3D PublishAcpiTable ();
   ASSERT_EFI_ERROR (Status);
 
-  //
-  // Get the Sw dispatch protocol and register SMI callback functions= .
-  //
-  Status =3D gMmst->MmLocateProtocol (&gEfiSmmSwDispatch2Proto= colGuid, NULL, (VOID**)&SwDispatch);
-  ASSERT_EFI_ERROR (Status);
-  SwContext.SwSmiInputValue =3D (UINTN) -1;
-  Status =3D SwDispatch->Register (SwDispatch, PhysicalPresenceCal= lback, &SwContext, &SwHandle);
-  ASSERT_EFI_ERROR (Status);
-  if (EFI_ERROR (Status)) {
-    return Status;
-  }
-  mTcgNvs->PhysicalPresence.SoftwareSmi =3D (UINT8) SwContext.SwSm= iInputValue;
-
-  SwContext.SwSmiInputValue =3D (UINTN) -1;
-  Status =3D SwDispatch->Register (SwDispatch, MemoryClearCallback= , &SwContext, &SwHandle);
-  ASSERT_EFI_ERROR (Status);
-  if (EFI_ERROR (Status)) {
-    return Status;
-  }
-  mTcgNvs->MemoryClear.SoftwareSmi =3D (UINT8) SwContext.SwSmiInpu= tValue;
-
-  //
-  // Locate SmmVariableProtocol.
-  //
-  Status =3D gMmst->MmLocateProtocol (&gEfiSmmVariableProtocol= Guid, NULL, (VOID**)&mSmmVariable);
-  ASSERT_EFI_ERROR (Status);
-
   //
   // Set TPM2 ACPI table
   //
   Status =3D PublishTpm2 ();
   ASSERT_EFI_ERROR (Status);
 
-
   return EFI_SUCCESS;
 }
 
diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c b/SecurityPkg/Tcg/Tcg2Smm/Tc= g2Smm.c
index 08105c3692ba..977ea3b1dfd2 100644
--- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c
+++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c
@@ -10,47 +10,95 @@
   PhysicalPresenceCallback() and MemoryClearCallback() will rece= ive untrusted input and do some check.
 
 Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<= ;BR>
+Copyright (c) Microsoft Corporation.
 SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 
 #include "Tcg2Smm.h"
 
-#pragma pack(1)
-
-typedef struct {
-  EFI_ACPI_DESCRIPTION_HEADER Header;
-  // Flags field is replaced in version 4 and above
-  //    BIT0~15:  PlatformClass   =    This field is only valid for version 4 and above
-  //    BIT16~31: Reserved
-  UINT32          &= nbsp;           Flags; -  UINT64          &= nbsp;           AddressOf= ControlArea;
-  UINT32          &= nbsp;           StartMeth= od;
-  UINT8          &n= bsp;            Plat= formSpecificParameters[12];  // size up to 12
-  UINT32          &= nbsp;           Laml;&nbs= p;            &= nbsp;            // = Optional
-  UINT64          &= nbsp;           Lasa;&nbs= p;            &= nbsp;            // = Optional
-} EFI_TPM2_ACPI_TABLE_V4;
-
-#pragma pack()
-
-EFI_TPM2_ACPI_TABLE_V4  mTpm2AcpiTemplate =3D {
-  {
-    EFI_ACPI_5_0_TRUSTED_COMPUTING_PLATFORM_2_TABLE_SIGNATU= RE,
-    sizeof (mTpm2AcpiTemplate),
-    EFI_TPM2_ACPI_TABLE_REVISION,
-    //
-    // Compiler initializes the remaining bytes to 0
-    // These fields should be filled in in production
-    //
-  },
-  0, // BIT0~15:  PlatformClass
-     // BIT16~31: Reserved
-  0, // Control Area
-  EFI_TPM2_ACPI_TABLE_START_METHOD_TIS, // StartMethod
-};
-
-EFI_SMM_VARIABLE_PROTOCOL  *mSmmVariable;
-TCG_NVS           &= nbsp;        *mTcgNvs;
+EFI_SMM_VARIABLE_PROTOCOL  *mSmmVariable =3D NULL;
+TCG_NVS           &= nbsp;        *mTcgNvs =3D NULL;
+UINTN           &nb= sp;           mPpSoftware= Smi;
+UINTN           &nb= sp;           mMcSoftware= Smi;
+EFI_HANDLE          &nbs= p;       mReadyToLockHandle;
+
+/**
+  Communication service SMI Handler entry.
+
+  This handler takes requests to exchange Mmi channel and Nvs address= between MM and DXE.
+
+  Caution: This function may receive untrusted input.
+  Communicate buffer and buffer size are external input, so this func= tion will do basic validation.
+
+  @param[in]      DispatchHandle  =   The unique handle assigned to this handler by SmiHandlerRegister().<= br> +  @param[in]      RegisterContext  = ; Points to an optional handler context which was specified when the
+            &n= bsp;            = ;           handler was r= egistered.
+  @param[in, out] CommBuffer       = ; A pointer to a collection of data in memory that will
+            &n= bsp;            = ;           be conveyed f= rom a non-SMM environment into an SMM environment.
+  @param[in, out] CommBufferSize    The size of the Co= mmBuffer.
+
+  @retval EFI_SUCCESS        =        The interrupt was handled and quiesced= . No other handlers
+            &n= bsp;            = ;           should still = be called.
+  @retval EFI_UNSUPPORTED       &n= bsp;   An unknown test function was requested.
+  @retval EFI_ACCESS_DENIED       =   Part of the communication buffer lies in an invalid region.
+
+**/
+EFI_STATUS
+EFIAPI
+TpmNvsCommunciate (
+  IN     EFI_HANDLE     =             &nb= sp; DispatchHandle,
+  IN     CONST VOID     =             &nb= sp; *RegisterContext,
+  IN OUT VOID         &n= bsp;            = ;   *CommBuffer,
+  IN OUT UINTN         &= nbsp;           &nbs= p;  *CommBufferSize
+  )
+{
+  EFI_STATUS         &nb= sp;      Status;
+  UINTN          &n= bsp;          TempCommBufferSi= ze;
+  TPM_NVS_MM_COMM_BUFFER    *CommParams;
+
+  DEBUG ((DEBUG_VERBOSE, "%a()\n", __FUNCTION__));
+
+  //
+  // If input is invalid, stop processing this SMI
+  //
+  if (CommBuffer =3D=3D NULL || CommBufferSize =3D=3D NULL) {
+    return EFI_SUCCESS;
+  }
+
+  TempCommBufferSize =3D *CommBufferSize;
+
+  if(TempCommBufferSize !=3D sizeof (TPM_NVS_MM_COMM_BUFFER)) {
+    DEBUG ((DEBUG_ERROR, "[%a] MM Communication buffer= size is invalid for this handler!\n", __FUNCTION__));
+    return EFI_ACCESS_DENIED;
+  }
+  if (!IsBufferOutsideMmValid ((UINTN) CommBuffer, TempCommBufferSize= )) {
+    DEBUG ((DEBUG_ERROR, "[%a] - MM Communication buff= er in invalid location!\n", __FUNCTION__));
+    return EFI_ACCESS_DENIED;
+  }
+
+  //
+  // Farm out the job to individual functions based on what was reque= sted.
+  //
+  CommParams =3D (TPM_NVS_MM_COMM_BUFFER*) CommBuffer;
+  Status =3D EFI_SUCCESS;
+  switch (CommParams->Function) {
+    case TpmNvsMmExchangeInfo:
+      DEBUG ((DEBUG_VERBOSE, "[%a] - Functio= n requested: MM_EXCHANGE_NVS_INFO\n", __FUNCTION__));
+      CommParams->RegisteredPpSwiValue =3D mPp= SoftwareSmi;
+      CommParams->RegisteredMcSwiValue =3D mMc= SoftwareSmi;
+      mTcgNvs =3D (TCG_NVS*) (UINTN) CommParams-&= gt;TargetAddress;
+      break;
+
+    default:
+      DEBUG ((DEBUG_INFO, "[%a] - Unknown fu= nction %d!\n", __FUNCTION__, CommParams->Function));
+      Status =3D EFI_UNSUPPORTED;
+      break;
+  }
+
+  CommParams->ReturnStatus =3D (UINT64) Status;
+  return EFI_SUCCESS;
+}
 
 /**
   Software SMI callback for TPM physical presence which is calle= d from ACPI method.
@@ -186,721 +234,137 @@ MemoryClearCallback (
 }
 
 /**
-  Find the operation region in TCG ACPI table by given Name and Size,=
-  and initialize it if the region is found.
+  Notification for SMM ReadyToLock protocol.
 
-  @param[in, out] Table       &nbs= p;  The TPM item in ACPI table.
-  @param[in]      Name   &nbs= p;       The name string to find in TPM table= .
-  @param[in]      Size   &nbs= p;       The size of the region to find.
+  @param[in] Protocol   Points to the protocol's unique ide= ntifier.
+  @param[in] Interface  Points to the interface instance.
+  @param[in] Handle     The handle on which the i= nterface was installed.
 
-  @return          =             &nb= sp; The allocated address for the found region.
-
-**/
-VOID *
-AssignOpRegion (
-  EFI_ACPI_DESCRIPTION_HEADER    *Table,
-  UINT32          &= nbsp;           &nbs= p;  Name,
-  UINT16          &= nbsp;           &nbs= p;  Size
-  )
-{
-  EFI_STATUS         &nb= sp;           Status;
-  AML_OP_REGION_32_8        &= nbsp;    *OpRegion;
-  EFI_PHYSICAL_ADDRESS        = ;   MemoryAddress;
-
-  MemoryAddress =3D SIZE_4GB - 1;
-
-  //
-  // Patch some pointers for the ASL code before loading the SSDT. -  //
-  for (OpRegion  =3D (AML_OP_REGION_32_8 *) (Table + 1);
-       OpRegion <=3D (AML_OP_REGION_32_8 = *) ((UINT8 *) Table + Table->Length);
-       OpRegion  =3D (AML_OP_REGION_32_= 8 *) ((UINT8 *) OpRegion + 1)) {
-    if ((OpRegion->OpRegionOp  =3D=3D AML_EXT_REGIO= N_OP) &&
-        (OpRegion->NameString  = =3D=3D Name) &&
-        (OpRegion->DWordPrefix =3D= =3D AML_DWORD_PREFIX) &&
-        (OpRegion->BytePrefix  = =3D=3D AML_BYTE_PREFIX)) {
-
-      Status =3D gBS->AllocatePages(AllocateMa= xAddress, EfiACPIMemoryNVS, EFI_SIZE_TO_PAGES (Size), &MemoryAddress);<= br> -      ASSERT_EFI_ERROR (Status);
-      ZeroMem ((VOID *)(UINTN)MemoryAddress, Size= );
-      OpRegion->RegionOffset =3D (UINT32) (UIN= TN) MemoryAddress;
-      OpRegion->RegionLen    = =3D (UINT8) Size;
-      break;
-    }
-  }
-
-  return (VOID *) (UINTN) MemoryAddress;
-}
-
-/**
-  Patch version string of Physical Presence interface supported by pl= atform. The initial string tag in TPM
-ACPI table is "$PV".
-
-  @param[in, out] Table       &nbs= p;  The TPM item in ACPI table.
-  @param[in]      PPVer   &nb= sp;      Version string of Physical Presence inter= face supported by platform.
-
-  @return          =             &nb= sp; The allocated address for the found region.
-
-**/
-EFI_STATUS
-UpdatePPVersion (
-  EFI_ACPI_DESCRIPTION_HEADER    *Table,
-  CHAR8          &n= bsp;            = ;   *PPVer
-  )
-{
-  EFI_STATUS  Status;
-  UINT8       *DataPtr;
-
-  //
-  // Patch some pointers for the ASL code before loading the SSDT. -  //
-  for (DataPtr  =3D (UINT8 *)(Table + 1);
-       DataPtr <=3D (UINT8 *) ((UINT8 *) = Table + Table->Length - PHYSICAL_PRESENCE_VERSION_SIZE);
-       DataPtr +=3D 1) {
-    if (AsciiStrCmp((CHAR8 *)DataPtr,  PHYSICAL_PRESEN= CE_VERSION_TAG) =3D=3D 0) {
-      Status =3D AsciiStrCpyS((CHAR8 *)DataPtr, P= HYSICAL_PRESENCE_VERSION_SIZE, PPVer);
-      DEBUG((EFI_D_INFO, "TPM2 Physical Pres= ence Interface Version update status 0x%x\n", Status));
-      return Status;
-    }
-  }
-
-  return EFI_NOT_FOUND;
-}
-
-/**
-  Patch interrupt resources returned by TPM _PRS. ResourceTemplate to= patch is determined by input
-  interrupt buffer size. BufferSize, PkgLength and interrupt descript= or in ByteList need to be patched
-
-  @param[in, out] Table       &nbs= p;    The TPM item in ACPI table.
-  @param[in]      IrqBuffer   = ;     Input new IRQ buffer.
-  @param[in]      IrqBuffserSize  = Input new IRQ buffer size.
-  @param[out]     IsShortFormPkgLength  = ; If _PRS returns Short length Package(ACPI spec 20.2.4).
-
-  @return          =             &nb= sp;   patch status.
-
-**/
-EFI_STATUS
-UpdatePossibleResource (
-  IN OUT  EFI_ACPI_DESCRIPTION_HEADER    *Table,<= br> -  IN      UINT32    &nbs= p;            &= nbsp;       *IrqBuffer,
-  IN      UINT32    &nbs= p;            &= nbsp;       IrqBuffserSize,
-  OUT     BOOLEAN     &n= bsp;            = ;      *IsShortFormPkgLength
-  )
-{
-  UINT8       *DataPtr;
-  UINT8       *DataEndPtr;
-  UINT32      NewPkgLength;
-  UINT32      OrignalPkgLength;
-
-  NewPkgLength     =3D 0;
-  OrignalPkgLength =3D 0;
-  DataEndPtr       =3D NULL;
-
-  //
-  // Follow ACPI spec
-  //           6.4.= 3   Extend Interrupt Descriptor.
-  //           19.3= .3 ASL Resource Template
-  //           20&n= bsp;     AML specification
-  // to patch TPM ACPI object _PRS returned ResourceTemplate() contai= ning 2 resource descriptors and an auto appended End Tag
-  //
-  //  AML data is organized by following rule.
-  //  Code need to patch BufferSize and PkgLength and interrupt = descriptor in ByteList
-  //
-  // =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D  Buffer =3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
-  //           DefB= uffer :=3D BufferOp PkgLength BufferSize ByteList
-  //           = ; BufferOp :=3D 0x11
-  //
-  // =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3DPkgLength=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
-  //          PkgLength = :=3D PkgLeadByte |
-  //           = ;            &n= bsp;      <PkgLeadByte ByteData> |
-  //           = ;            &n= bsp;      <PkgLeadByte ByteData ByteData> |<= br> -  //           = ;            &n= bsp;      <PkgLeadByte ByteData ByteData ByteDa= ta>
-  //
-  //       PkgLeadByte :=3D <bit 7-6= : ByteData count that follows (0-3)>
-  //           = ;            &n= bsp;       <bit 5-4: Only used if PkgLengt= h <=3D 63 >
-  //           = ;            &n= bsp;       <bit 3-0: Least significant pac= kage length nybble>
-  //
-  //=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3DBufferSize=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
-  //        BufferSize :=3D Intege= r
-  //           Inte= ger :=3D ByteConst|WordConst|DwordConst....
-  //
-  //           Byte= Const :=3D BytePrefix ByteData
-  //
-  //=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3DByteList=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
-  //          ByteList := =3D ByteData ByteList
-  //
-  //=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
-
-  //
-  // 1. Check TPM_PRS_RESS with PkgLength <=3D63 can hold the inpu= t interrupt number buffer for patching
-  //
-  for (DataPtr  =3D (UINT8 *)(Table + 1);
-       DataPtr < (UINT8 *) ((UINT8 *) Tab= le + Table->Length - (TPM_PRS_RES_NAME_SIZE + TPM_POS_RES_TEMPLATE_MIN_S= IZE));
-       DataPtr +=3D 1) {
-    if (CompareMem(DataPtr, TPM_PRS_RESS, TPM_PRS_RES_NAME_= SIZE) =3D=3D 0) {
-      //
-      // Jump over object name & BufferOp
-      //
-      DataPtr +=3D TPM_PRS_RES_NAME_SIZE + 1;
-
-      if ((*DataPtr & (BIT7|BIT6)) =3D=3D 0) = {
-        OrignalPkgLength =3D (UINT32)*D= ataPtr;
-        DataEndPtr   &nb= sp;   =3D DataPtr + OrignalPkgLength;
-
-        //
-        // Jump over PkgLength =3D PkgL= eadByte only
-        //
-        NewPkgLength++;
-
-        //
-        // Jump over BufferSize
-        //
-        if (*(DataPtr + 1) =3D=3D AML_B= YTE_PREFIX) {
-          NewPkgLength +=3D 2= ;
-        } else if (*(DataPtr + 1) =3D= =3D AML_WORD_PREFIX) {
-          NewPkgLength +=3D 3= ;
-        } else if (*(DataPtr + 1) =3D= =3D AML_DWORD_PREFIX) {
-          NewPkgLength +=3D 5= ;
-        } else {
-          ASSERT(FALSE);
-          return EFI_UNSUPPOR= TED;
-        }
-      } else {
-        ASSERT(FALSE);
-        return EFI_UNSUPPORTED;
-      }
-
-      //
-      // Include Memory32Fixed Descriptor (12 Byt= es) + Interrupt Descriptor header(5 Bytes) + End Tag(2 Bytes)
-      //
-      NewPkgLength +=3D 19 + IrqBuffserSize;
-      if (NewPkgLength > 63) {
-        break;
-      }
-
-      if (NewPkgLength > OrignalPkgLength) { -        ASSERT(FALSE);
-        return EFI_INVALID_PARAMETER; -      }
-
-      //
-      // 1.1 Patch PkgLength
-      //
-      *DataPtr =3D (UINT8)NewPkgLength;
-
-      //
-      // 1.2 Patch BufferSize =3D sizeof(Memory32= Fixed Descriptor + Interrupt Descriptor + End Tag).
-      //      It is Litt= le endian. So only patch lowest byte of BufferSize due to current interrupt= number limit.
-      //
-      *(DataPtr + 2) =3D (UINT8)(IrqBuffserSize += 19);
-
-      //
-      // Notify _PRS to report short formed Resou= rceTemplate
-      //
-      *IsShortFormPkgLength =3D TRUE;
-
-      break;
-    }
-  }
-
-  //
-  // 2. Use TPM_PRS_RESL with PkgLength > 63 to hold longer input = interrupt number buffer for patching
-  //
-  if (NewPkgLength > 63) {
-    NewPkgLength     =3D 0;
-    OrignalPkgLength =3D 0;
-    for (DataPtr  =3D (UINT8 *)(Table + 1);
-         DataPtr < (UINT8 *) ((= UINT8 *) Table + Table->Length - (TPM_PRS_RES_NAME_SIZE + TPM_POS_RES_TE= MPLATE_MIN_SIZE));
-         DataPtr +=3D 1) {
-      if (CompareMem(DataPtr, TPM_PRS_RESL, TPM_P= RS_RES_NAME_SIZE) =3D=3D 0) {
-        //
-        // Jump over object name & = BufferOp
-        //
-        DataPtr +=3D TPM_PRS_RES_NAME_S= IZE + 1;
-
-        if ((*DataPtr & (BIT7|BIT6)= ) !=3D 0) {
-          OrignalPkgLength = =3D (UINT32)(*(DataPtr + 1) << 4) + (*DataPtr & 0x0F);
-          DataEndPtr &nb= sp;     =3D DataPtr + OrignalPkgLength;
-          //
-          // Jump over PkgLen= gth =3D PkgLeadByte + ByteData length
-          //
-          NewPkgLength +=3D 1= + ((*DataPtr & (BIT7|BIT6)) >> 6);
-
-          //
-          // Jump over Buffer= Size
-          //
-          if (*(DataPtr + New= PkgLength) =3D=3D AML_BYTE_PREFIX) {
-            NewPkgL= ength +=3D 2;
-          } else if (*(DataPt= r + NewPkgLength) =3D=3D AML_WORD_PREFIX) {
-            NewPkgL= ength +=3D 3;
-          } else if (*(DataPt= r + NewPkgLength) =3D=3D AML_DWORD_PREFIX) {
-            NewPkgL= ength +=3D 5;
-          } else {
-            ASSERT(= FALSE);
-            return = EFI_UNSUPPORTED;
-          }
-        } else {
-          ASSERT(FALSE);
-          return EFI_UNSUPPOR= TED;
-        }
-
-        //
-        // Include Memory32Fixed Descri= ptor (12 Bytes) + Interrupt Descriptor header(5 Bytes) + End Tag(2  By= tes)
-        //
-        NewPkgLength +=3D 19 + IrqBuffs= erSize;
-
-        if (NewPkgLength > OrignalPk= gLength) {
-          ASSERT(FALSE);
-          return EFI_INVALID_= PARAMETER;
-        }
-
-        //
-        // 2.1 Patch PkgLength. Only pa= tch PkgLeadByte and first ByteData
-        //
-        *DataPtr =3D (UINT8)((*DataPtr)= & 0xF0) | (NewPkgLength & 0x0F);
-        *(DataPtr + 1) =3D (UINT8)((New= PkgLength & 0xFF0) >> 4);
-
-        //
-        // 2.2 Patch BufferSize =3D siz= eof(Memory32Fixed Descriptor + Interrupt Descriptor + End Tag).
-        //     It i= s Little endian. Only patch lowest byte of BufferSize due to current interr= upt number limit.
-        //
-        *(DataPtr + 2 + ((*DataPtr &= ; (BIT7|BIT6)) >> 6)) =3D (UINT8)(IrqBuffserSize + 19);
-
-        //
-        // Notify _PRS to report long f= ormed ResourceTemplate
-        //
-        *IsShortFormPkgLength =3D FALSE= ;
-        break;
-      }
-    }
-  }
-
-  if (DataPtr >=3D (UINT8 *) ((UINT8 *) Table + Table->Length -= (TPM_PRS_RES_NAME_SIZE + TPM_POS_RES_TEMPLATE_MIN_SIZE))) {
-    return EFI_NOT_FOUND;
-  }
-
-  //
-  // 3. Move DataPtr to Interrupt descriptor header and patch interru= pt descriptor.
-  //     5 bytes for interrupt descriptor header,= 2 bytes for End Tag
-  //
-  DataPtr +=3D NewPkgLength - (5 + IrqBuffserSize + 2);
-  //
-  //   3.1 Patch Length bit[7:0] of Interrupt descriptor pa= tch interrupt descriptor
-  //
-  *(DataPtr + 1) =3D (UINT8)(2 + IrqBuffserSize);
-  //
-  //   3.2 Patch Interrupt Table Length
-  //
-  *(DataPtr + 4) =3D (UINT8)(IrqBuffserSize / sizeof(UINT32));
-  //
-  //   3.3 Copy patched InterruptNumBuffer
-  //
-  CopyMem(DataPtr + 5, IrqBuffer, IrqBuffserSize);
-
-  //
-  // 4. Jump over Interrupt descriptor and Patch END Tag, set Checksu= m field to 0
-  //
-  DataPtr       +=3D 5 + IrqBuffserSize= ;
-  *DataPtr       =3D ACPI_END_TAG_DESCR= IPTOR;
-  *(DataPtr + 1) =3D 0;
-
-  //
-  // 5. Jump over new ResourceTemplate. Stuff rest bytes to NOOP
-  //
-  DataPtr +=3D 2;
-  if (DataPtr < DataEndPtr) {
-    SetMem(DataPtr, (UINTN)DataEndPtr - (UINTN)DataPtr, AML= _NOOP_OP);
-  }
-
-  return EFI_SUCCESS;
-}
-
-/**
-  Patch TPM2 device HID string.  The initial string tag in TPM2 = ACPI table is "NNN0000".
-
-  @param[in, out] Table       &nbs= p;  The TPM2 SSDT ACPI table.
-
-  @return          =             &nb= sp;        HID Update status.
-
-**/
-EFI_STATUS
-UpdateHID (
-  EFI_ACPI_DESCRIPTION_HEADER    *Table
-  )
-{
-  EFI_STATUS  Status;
-  UINT8       *DataPtr;
-  CHAR8       Hid[TPM_HID_ACPI_SIZE]; -  UINT32      ManufacturerID;
-  UINT32      FirmwareVersion1;
-  UINT32      FirmwareVersion2;
-  BOOLEAN     PnpHID;
-
-  PnpHID =3D TRUE;
-
-  //
-  // Initialize HID with Default PNP string
-  //
-  ZeroMem(Hid, TPM_HID_ACPI_SIZE);
-
-  //
-  // Get Manufacturer ID
-  //
-  Status =3D Tpm2GetCapabilityManufactureID(&ManufacturerID);
-  if (!EFI_ERROR(Status)) {
-    DEBUG((EFI_D_INFO, "TPM_PT_MANUFACTURER 0x%08x\n&q= uot;, ManufacturerID));
-    //
-    // ManufacturerID defined in TCG Vendor ID Registry
-    // may tailed with 0x00 or 0x20
-    //
-    if ((ManufacturerID >> 24) =3D=3D 0x00 || ((Manuf= acturerID >> 24) =3D=3D 0x20)) {
-      //
-      //  HID containing PNP ID "NNN###= #"
-      //   NNN is uppercase letter for = Vendor ID specified by manufacturer
-      //
-      CopyMem(Hid, &ManufacturerID, 3);
-    } else {
-      //
-      //  HID containing ACP ID "NNNN##= ##"
-      //   NNNN is uppercase letter for= Vendor ID specified by manufacturer
-      //
-      CopyMem(Hid, &ManufacturerID, 4);
-      PnpHID =3D FALSE;
-    }
-  } else {
-    DEBUG ((EFI_D_ERROR, "Get TPM_PT_MANUFACTURER fail= ed %x!\n", Status));
-    ASSERT(FALSE);
-    return Status;
-  }
-
-  Status =3D Tpm2GetCapabilityFirmwareVersion(&FirmwareVersion1, = &FirmwareVersion2);
-  if (!EFI_ERROR(Status)) {
-    DEBUG((EFI_D_INFO, "TPM_PT_FIRMWARE_VERSION_1 0x%x= \n", FirmwareVersion1));
-    DEBUG((EFI_D_INFO, "TPM_PT_FIRMWARE_VERSION_2 0x%x= \n", FirmwareVersion2));
-    //
-    //   #### is Firmware Version 1
-    //
-    if (PnpHID) {
-      AsciiSPrint(Hid + 3, TPM_HID_PNP_SIZE - 3, = "%02d%02d", ((FirmwareVersion1 & 0xFFFF0000) >> 16), (F= irmwareVersion1 & 0x0000FFFF));
-    } else {
-      AsciiSPrint(Hid + 4, TPM_HID_ACPI_SIZE - 4,= "%02d%02d", ((FirmwareVersion1 & 0xFFFF0000) >> 16), (= FirmwareVersion1 & 0x0000FFFF));
-    }
-
-  } else {
-    DEBUG ((EFI_D_ERROR, "Get TPM_PT_FIRMWARE_VERSION_= X failed %x!\n", Status));
-    ASSERT(FALSE);
-    return Status;
-  }
-
-  //
-  // Patch HID in ASL code before loading the SSDT.
-  //
-  for (DataPtr  =3D (UINT8 *)(Table + 1);
-       DataPtr <=3D (UINT8 *) ((UINT8 *) = Table + Table->Length - TPM_HID_PNP_SIZE);
-       DataPtr +=3D 1) {
-    if (AsciiStrCmp((CHAR8 *)DataPtr,  TPM_HID_TAG) = =3D=3D 0) {
-      if (PnpHID) {
-        CopyMem(DataPtr, Hid, TPM_HID_P= NP_SIZE);
-        //
-        // if HID is PNP ID, patch the = last byte in HID TAG to Noop
-        //
-        *(DataPtr + TPM_HID_PNP_SIZE) = =3D AML_NOOP_OP;
-      } else {
-
-        CopyMem(DataPtr, Hid, TPM_HID_A= CPI_SIZE);
-      }
-      DEBUG((DEBUG_INFO, "TPM2 ACPI _HID is = patched to %a\n", DataPtr));
-
-      return Status;
-    }
-  }
-
-  DEBUG((EFI_D_ERROR, "TPM2 ACPI HID TAG for patch not found!\n&= quot;));
-  return EFI_NOT_FOUND;
-}
-
-/**
-  Initialize and publish TPM items in ACPI table.
-
-  @retval   EFI_SUCCESS     The TCG ACP= I table is published successfully.
-  @retval   Others       = ;   The TCG ACPI table is not published.
-
-**/
-EFI_STATUS
-PublishAcpiTable (
-  VOID
-  )
-{
-  EFI_STATUS         &nb= sp;           Status;
-  EFI_ACPI_TABLE_PROTOCOL        *= AcpiTable;
-  UINTN          &n= bsp;            = ;   TableKey;
-  EFI_ACPI_DESCRIPTION_HEADER    *Table;
-  UINTN          &n= bsp;            = ;   TableSize;
-  UINT32          &= nbsp;           &nbs= p;  *PossibleIrqNumBuf;
-  UINT32          &= nbsp;           &nbs= p;  PossibleIrqNumBufSize;
-  BOOLEAN          =             &nb= sp; IsShortFormPkgLength;
-
-  IsShortFormPkgLength =3D FALSE;
-
-  Status =3D GetSectionFromFv (
-             &= amp;gEfiCallerIdGuid,
-             E= FI_SECTION_RAW,
-             0= ,
-             (= VOID **) &Table,
-             &= amp;TableSize
-             )= ;
-  ASSERT_EFI_ERROR (Status);
-
-  //
-  // Measure to PCR[0] with event EV_POST_CODE ACPI DATA.
-  // The measurement has to be done before any update.
-  // Otherwise, the PCR record would be different after TPM FW update=
-  // or the PCD configuration change.
-  //
-  TpmMeasureAndLogData(
-    0,
-    EV_POST_CODE,
-    EV_POSTCODE_INFO_ACPI_DATA,
-    ACPI_DATA_LEN,
-    Table,
-    TableSize
-    );
-
-  //
-  // Update Table version before measuring it to PCR
-  //
-  Status =3D UpdatePPVersion(Table, (CHAR8 *)PcdGetPtr(PcdTcgPhysical= PresenceInterfaceVer));
-  ASSERT_EFI_ERROR (Status);
-
-  DEBUG ((
-    DEBUG_INFO,
-    "Current physical presence interface version - %a\= n",
-    (CHAR8 *) PcdGetPtr(PcdTcgPhysicalPresenceInterfaceVer)=
-    ));
-
-  //
-  // Update TPM2 HID after measuring it to PCR
-  //
-  Status =3D UpdateHID(Table);
-  if (EFI_ERROR(Status)) {
-    return Status;
-  }
-
-  if (PcdGet32(PcdTpm2CurrentIrqNum) !=3D 0) {
-    //
-    // Patch _PRS interrupt resource only when TPM interrup= t is supported
-    //
-    PossibleIrqNumBuf     =3D (UINT32 *= )PcdGetPtr(PcdTpm2PossibleIrqNumBuf);
-    PossibleIrqNumBufSize =3D (UINT32)PcdGetSize(PcdTpm2Pos= sibleIrqNumBuf);
-
-    if (PossibleIrqNumBufSize <=3D MAX_PRS_INT_BUF_SIZE = && (PossibleIrqNumBufSize % sizeof(UINT32)) =3D=3D 0) {
-      Status =3D UpdatePossibleResource(Table, Po= ssibleIrqNumBuf, PossibleIrqNumBufSize, &IsShortFormPkgLength);
-      DEBUG ((
-        DEBUG_INFO,
-        "UpdatePossibleResource st= atus - %x. TPM2 service may not ready in OS.\n",
-        Status
-        ));
-    } else {
-      DEBUG ((
-        DEBUG_INFO,
-        "PcdTpm2PossibleIrqNumBuf = size %x is not correct. TPM2 service may not ready in OS.\n",
-        PossibleIrqNumBufSize
-      ));
-    }
-  }
-
-  ASSERT (Table->OemTableId =3D=3D SIGNATURE_64 ('T', 'p', 'm', '2= ', 'T', 'a', 'b', 'l'));
-  CopyMem (Table->OemId, PcdGetPtr (PcdAcpiDefaultOemId), sizeof (= Table->OemId) );
-  mTcgNvs =3D AssignOpRegion (Table, SIGNATURE_32 ('T', 'N', 'V', 'S'= ), (UINT16) sizeof (TCG_NVS));
-  ASSERT (mTcgNvs !=3D NULL);
-  mTcgNvs->TpmIrqNum       &nbs= p;    =3D PcdGet32(PcdTpm2CurrentIrqNum);
-  mTcgNvs->IsShortFormPkgLength =3D IsShortFormPkgLength;
-
-  //
-  // Publish the TPM ACPI table. Table is re-checksummed.
-  //
-  Status =3D gBS->LocateProtocol (&gEfiAcpiTableProtocolGuid, = NULL, (VOID **) &AcpiTable);
-  ASSERT_EFI_ERROR (Status);
-
-  TableKey =3D 0;
-  Status =3D AcpiTable->InstallAcpiTable (
-            &n= bsp;           AcpiTable,=
-            &n= bsp;           Table,
-            &n= bsp;           TableSize,=
-            &n= bsp;           &Table= Key
-            &n= bsp;           );
-  ASSERT_EFI_ERROR (Status);
-
-  return Status;
-}
-
-/**
-  Publish TPM2 ACPI table
-
-  @retval   EFI_SUCCESS     The TPM2 AC= PI table is published successfully.
-  @retval   Others       = ;   The TPM2 ACPI table is not published.
+  @retval EFI_SUCCESS   Notification runs successfully.
 
 **/
 EFI_STATUS
-PublishTpm2 (
-  VOID
-  )
+EFIAPI
+TcgMmReadyToLock (
+  IN CONST EFI_GUID  *Protocol,
+  IN VOID          =   *Interface,
+  IN EFI_HANDLE      Handle
+)
 {
-  EFI_STATUS         &nb= sp;           Status;
-  EFI_ACPI_TABLE_PROTOCOL        *= AcpiTable;
-  UINTN          &n= bsp;            = ;   TableKey;
-  UINT64          &= nbsp;           &nbs= p;  OemTableId;
-  EFI_TPM2_ACPI_CONTROL_AREA     *ControlArea; -  TPM2_PTP_INTERFACE_TYPE        I= nterfaceType;
-
-  //
-  // Measure to PCR[0] with event EV_POST_CODE ACPI DATA.
-  // The measurement has to be done before any update.
-  // Otherwise, the PCR record would be different after event log upd= ate
-  // or the PCD configuration change.
-  //
-  TpmMeasureAndLogData(
-    0,
-    EV_POST_CODE,
-    EV_POSTCODE_INFO_ACPI_DATA,
-    ACPI_DATA_LEN,
-    &mTpm2AcpiTemplate,
-    mTpm2AcpiTemplate.Header.Length
-    );
-
-  mTpm2AcpiTemplate.Header.Revision =3D PcdGet8(PcdTpm2AcpiTableRev);=
-  DEBUG((DEBUG_INFO, "Tpm2 ACPI table revision is %d\n", mT= pm2AcpiTemplate.Header.Revision));
-
-  //
-  // PlatformClass is only valid for version 4 and above
-  //    BIT0~15:  PlatformClass
-  //    BIT16~31: Reserved
-  //
-  if (mTpm2AcpiTemplate.Header.Revision >=3D EFI_TPM2_ACPI_TABLE_R= EVISION_4) {
-    mTpm2AcpiTemplate.Flags =3D (mTpm2AcpiTemplate.Flags &a= mp; 0xFFFF0000) | PcdGet8(PcdTpmPlatformClass);
-    DEBUG((DEBUG_INFO, "Tpm2 ACPI table PlatformClass = is %d\n", (mTpm2AcpiTemplate.Flags & 0x0000FFFF)));
-  }
-
-  mTpm2AcpiTemplate.Laml =3D PcdGet32(PcdTpm2AcpiTableLaml);
-  mTpm2AcpiTemplate.Lasa =3D PcdGet64(PcdTpm2AcpiTableLasa);
-  if ((mTpm2AcpiTemplate.Header.Revision < EFI_TPM2_ACPI_TABLE_REV= ISION_4) ||
-      (mTpm2AcpiTemplate.Laml =3D=3D 0) || (mTpm2= AcpiTemplate.Lasa =3D=3D 0)) {
-    //
-    // If version is smaller than 4 or Laml/Lasa is not val= id, rollback to original Length.
-    //
-    mTpm2AcpiTemplate.Header.Length =3D sizeof(EFI_TPM2_ACP= I_TABLE);
-  }
+  EFI_STATUS Status;
 
-  InterfaceType =3D PcdGet8(PcdActiveTpmInterfaceType);
-  switch (InterfaceType) {
-  case Tpm2PtpInterfaceCrb:
-    mTpm2AcpiTemplate.StartMethod =3D EFI_TPM2_ACPI_TABLE_S= TART_METHOD_COMMAND_RESPONSE_BUFFER_INTERFACE;
-    mTpm2AcpiTemplate.AddressOfControlArea =3D PcdGet64 (Pc= dTpmBaseAddress) + 0x40;
-    ControlArea =3D (EFI_TPM2_ACPI_CONTROL_AREA *)(UINTN)mT= pm2AcpiTemplate.AddressOfControlArea;
-    ControlArea->CommandSize  =3D 0xF80;
-    ControlArea->ResponseSize =3D 0xF80;
-    ControlArea->Command      = =3D PcdGet64 (PcdTpmBaseAddress) + 0x80;
-    ControlArea->Response     =3D Pc= dGet64 (PcdTpmBaseAddress) + 0x80;
-    break;
-  case Tpm2PtpInterfaceFifo:
-  case Tpm2PtpInterfaceTis:
-    break;
-  default:
-    DEBUG((EFI_D_ERROR, "TPM2 InterfaceType get error!= %d\n", InterfaceType));
-    break;
+  if (mReadyToLockHandle !=3D NULL) {
+    Status =3D gMmst->MmiHandlerUnRegister (mReadyToLock= Handle);
+    mReadyToLockHandle =3D NULL;
   }
-
-  CopyMem (mTpm2AcpiTemplate.Header.OemId, PcdGetPtr (PcdAcpiDefaultO= emId), sizeof (mTpm2AcpiTemplate.Header.OemId));
-  OemTableId =3D PcdGet64 (PcdAcpiDefaultOemTableId);
-  CopyMem (&mTpm2AcpiTemplate.Header.OemTableId, &OemTableId,= sizeof (UINT64));
-  mTpm2AcpiTemplate.Header.OemRevision      = =3D PcdGet32 (PcdAcpiDefaultOemRevision);
-  mTpm2AcpiTemplate.Header.CreatorId     &nb= sp;  =3D PcdGet32 (PcdAcpiDefaultCreatorId);
-  mTpm2AcpiTemplate.Header.CreatorRevision  =3D PcdGet32 (PcdAcp= iDefaultCreatorRevision);
-
-  //
-  // Construct ACPI table
-  //
-  Status =3D gBS->LocateProtocol (&gEfiAcpiTableProtocolGuid, = NULL, (VOID **) &AcpiTable);
-  ASSERT_EFI_ERROR (Status);
-
-  Status =3D AcpiTable->InstallAcpiTable (
-            &n= bsp;           AcpiTable,=
-            &n= bsp;           &mTpm2= AcpiTemplate,
-            &n= bsp;           mTpm2AcpiT= emplate.Header.Length,
-            &n= bsp;           &Table= Key
-            &n= bsp;           );
-  ASSERT_EFI_ERROR (Status);
-
   return Status;
 }
 
 /**
-  The driver's entry point.
+  The driver's common initialization routine.
 
   It install callbacks for TPM physical presence and MemoryClear= , and locate
   SMM variable to be used in the callback function.
 
-  @param[in] ImageHandle  The firmware allocated handle for the = EFI image.
-  @param[in] SystemTable  A pointer to the EFI System Table.
-
   @retval EFI_SUCCESS     The entry point is= executed successfully.
   @retval Others        =   Some error occurs when executing this entry point.
 
 **/
 EFI_STATUS
-EFIAPI
-InitializeTcgSmm (
-  IN EFI_HANDLE         =          ImageHandle,
-  IN EFI_SYSTEM_TABLE        =     *SystemTable
+InitializeTcgCommon (
+  VOID
   )
 {
   EFI_STATUS        &nbs= p;            Status= ;
   EFI_SMM_SW_DISPATCH2_PROTOCOL  *SwDispatch;
   EFI_SMM_SW_REGISTER_CONTEXT    SwContext;
-  EFI_HANDLE         &nb= sp;           SwHandle; +  EFI_HANDLE         &nb= sp;           PpSwHandle;=
+  EFI_HANDLE         &nb= sp;           McSwHandle;=
+  EFI_HANDLE         &nb= sp;           NotifyHandl= e;
 
   if (!CompareGuid (PcdGetPtr(PcdTpmInstanceGuid), &gEfiTpmD= eviceInstanceTpm20DtpmGuid)){
     DEBUG ((EFI_D_ERROR, "No TPM2 DTPM instance r= equired!\n"));
     return EFI_UNSUPPORTED;
   }
 
-  Status =3D PublishAcpiTable ();
+  // Register a root handler to communicate the NVS region and SMI ch= annel between MM and DXE
+  mReadyToLockHandle =3D NULL;
+  Status =3D gMmst->MmiHandlerRegister (TpmNvsCommunciate, &gT= pmNvsMmGuid, &mReadyToLockHandle);
   ASSERT_EFI_ERROR (Status);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "[%a] Failed to register NVS = communicate as root MM handler - %r!\n", __FUNCTION__, Status));
+    goto Cleanup;
+  }
 
   //
   // Get the Sw dispatch protocol and register SMI callback func= tions.
   //
   Status =3D gMmst->MmLocateProtocol (&gEfiSmmSwDispatch2= ProtocolGuid, NULL, (VOID**)&SwDispatch);
   ASSERT_EFI_ERROR (Status);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "[%a] Failed to locate Sw dis= patch protocol - %r!\n", __FUNCTION__, Status));
+    goto Cleanup;
+  }
+
+  PpSwHandle =3D NULL;
   SwContext.SwSmiInputValue =3D (UINTN) -1;
-  Status =3D SwDispatch->Register (SwDispatch, PhysicalPresenceCal= lback, &SwContext, &SwHandle);
+  Status =3D SwDispatch->Register (SwDispatch, PhysicalPresenceCal= lback, &SwContext, &PpSwHandle);
   ASSERT_EFI_ERROR (Status);
   if (EFI_ERROR (Status)) {
-    return Status;
+    DEBUG ((DEBUG_ERROR, "[%a] Failed to register PP c= allback as SW MM handler - %r!\n", __FUNCTION__, Status));
+    goto Cleanup;
   }
-  mTcgNvs->PhysicalPresence.SoftwareSmi =3D (UINT8) SwContext.SwSm= iInputValue;
+  mPpSoftwareSmi =3D SwContext.SwSmiInputValue;
 
+  McSwHandle =3D NULL;
   SwContext.SwSmiInputValue =3D (UINTN) -1;
-  Status =3D SwDispatch->Register (SwDispatch, MemoryClearCallback= , &SwContext, &SwHandle);
+  Status =3D SwDispatch->Register (SwDispatch, MemoryClearCallback= , &SwContext, &McSwHandle);
   ASSERT_EFI_ERROR (Status);
   if (EFI_ERROR (Status)) {
-    return Status;
+    DEBUG ((DEBUG_ERROR, "[%a] Failed to register MC c= allback as SW MM handler - %r!\n", __FUNCTION__, Status));
+    goto Cleanup;
   }
-  mTcgNvs->MemoryClear.SoftwareSmi =3D (UINT8) SwContext.SwSmiInpu= tValue;
+  mMcSoftwareSmi =3D SwContext.SwSmiInputValue;
 
   //
   // Locate SmmVariableProtocol.
   //
   Status =3D gMmst->MmLocateProtocol (&gEfiSmmVariablePro= tocolGuid, NULL, (VOID**)&mSmmVariable);
   ASSERT_EFI_ERROR (Status);
+  if (EFI_ERROR (Status)) {
+    // Should not happen
+    DEBUG ((DEBUG_ERROR, "[%a] Failed to locate SMM va= riable protocol - %r!\n", __FUNCTION__, Status));
+    goto Cleanup;
+  }
 
-  //
-  // Set TPM2 ACPI table
-  //
-  Status =3D PublishTpm2 ();
+  // Turn off the light before leaving the room... at least, take a r= emote...
+  NotifyHandle =3D NULL;
+  Status =3D gMmst->MmRegisterProtocolNotify (&gEfiMmReadyToLo= ckProtocolGuid, TcgMmReadyToLock, &NotifyHandle);
   ASSERT_EFI_ERROR (Status);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "[%a] Failed to register read= y to lock notification - %r!\n", __FUNCTION__, Status));
+    goto Cleanup;
+  }
 
+  Tcg2NotifyMmReady ();
 
-  return EFI_SUCCESS;
+Cleanup:
+  if (EFI_ERROR (Status)) {
+    // Something is whacked, clean up the mess...
+    if (NotifyHandle !=3D NULL) {
+      gMmst->MmRegisterProtocolNotify (&gE= fiMmReadyToLockProtocolGuid, NULL, &NotifyHandle);
+    }
+    if (McSwHandle !=3D NULL && SwDispatch !=3D NUL= L) {
+      SwDispatch->UnRegister (SwDispatch, McSw= Handle);
+    }
+    if (PpSwHandle !=3D NULL && SwDispatch !=3D NUL= L) {
+      SwDispatch->UnRegister (SwDispatch, PpSw= Handle);
+    }
+    if (mReadyToLockHandle !=3D NULL) {
+      gMmst->MmiHandlerUnRegister (mReadyToLoc= kHandle);
+    }
+  }
+
+  return Status;
 }
 
diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c b/SecurityPkg/Tcg/= Tcg2Smm/Tcg2TraditionalMm.c
new file mode 100644
index 000000000000..5930090b4e46
--- /dev/null
+++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2TraditionalMm.c
@@ -0,0 +1,82 @@
+/** @file
+  TCG2 SMM driver that updates TPM2 items in ACPI table and registers=
+  SMI2 callback functions for Tcg2 physical presence, ClearMemory, an= d
+  sample for dTPM StartMethod.
+
+  Caution: This module requires additional review when modified.
+  This driver will have external input - variable and ACPINvs data in= SMM mode.
+  This external input must be validated carefully to avoid security i= ssue.
+
+  PhysicalPresenceCallback() and MemoryClearCallback() will receive u= ntrusted input and do some check.
+
+Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR&g= t;
+Copyright (c) Microsoft Corporation.
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "Tcg2Smm.h"
+#include <Library/UefiBootServicesTableLib.h>
+#include <Library/SmmMemLib.h>
+
+/**
+  Notify the system that the SMM variable driver is ready.
+**/
+VOID
+Tcg2NotifyMmReady (
+  VOID
+  )
+{
+  EFI_STATUS         &nb= sp;  Status;
+  EFI_HANDLE         &nb= sp;  Handle;
+
+  Handle =3D NULL;
+  Status =3D gBS->InstallProtocolInterface (
+            &n= bsp;     &Handle,
+            &n= bsp;     &gTcg2MmSwSmiRegisteredGuid,
+            &n= bsp;     EFI_NATIVE_INTERFACE,
+            &n= bsp;     NULL
+            &n= bsp;     );
+  ASSERT_EFI_ERROR (Status);
+}
+
+/**
+  This function is an abstraction layer for implementation specific M= m buffer validation routine.
+
+  @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 o= r overlap with SMRAM.
+**/
+BOOLEAN
+IsBufferOutsideMmValid (
+  IN EFI_PHYSICAL_ADDRESS  Buffer,
+  IN UINT64         &nbs= p;      Length
+  )
+{
+  return SmmIsBufferOutsideSmmValid (Buffer, Length);
+}
+
+/**
+  The driver's entry point.
+
+  It install callbacks for TPM physical presence and MemoryClear, and= locate
+  SMM variable to be used in the callback function.
+
+  @param[in] ImageHandle  The firmware allocated handle for the = EFI image.
+  @param[in] SystemTable  A pointer to the EFI System Table.
+
+  @retval EFI_SUCCESS     The entry point is exec= uted successfully.
+  @retval Others         = ; Some error occurs when executing this entry point.
+
+**/
+EFI_STATUS
+EFIAPI
+InitializeTcgSmm (
+  IN EFI_HANDLE         =          ImageHandle,
+  IN EFI_SYSTEM_TABLE        =     *SystemTable
+  )
+{
+  return InitializeTcgCommon ();
+}
diff --git a/SecurityPkg/Include/Guid/TpmNvsMm.h b/SecurityPkg/Include/Guid= /TpmNvsMm.h
new file mode 100644
index 000000000000..a6e8e1f30f95
--- /dev/null
+++ b/SecurityPkg/Include/Guid/TpmNvsMm.h
@@ -0,0 +1,68 @@
+/** @file
+  TPM NVS MM guid, used for exchanging information, including SWI val= ue and NVS region
+  information, for patching TPM ACPI table.
+
+Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR&g= t;
+Copyright (c) Microsoft Corporation.
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef __TCG2_NVS_MM_H__
+#define __TCG2_NVS_MM_H__
+
+#define MM_TPM_NVS_HOB_GUID \
+  { 0xc96c76eb, 0xbc78, 0x429c, { 0x9f, 0x4b, 0xda, 0x51, 0x78, 0xc2,= 0x84, 0x57 }}
+
+extern EFI_GUID gTpmNvsMmGuid;
+
+#pragma pack(1)
+typedef struct {
+  UINT8          &n= bsp;       SoftwareSmi;
+  UINT32          &= nbsp;      Parameter;
+  UINT32          &= nbsp;      Response;
+  UINT32          &= nbsp;      Request;
+  UINT32          &= nbsp;      RequestParameter;
+  UINT32          &= nbsp;      LastRequest;
+  UINT32          &= nbsp;      ReturnCode;
+} PHYSICAL_PRESENCE_NVS;
+
+typedef struct {
+  UINT8          &n= bsp;       SoftwareSmi;
+  UINT32          &= nbsp;      Parameter;
+  UINT32          &= nbsp;      Request;
+  UINT32          &= nbsp;      ReturnCode;
+} MEMORY_CLEAR_NVS;
+
+typedef struct {
+  PHYSICAL_PRESENCE_NVS  PhysicalPresence;
+  MEMORY_CLEAR_NVS       MemoryClear; +  UINT32          &= nbsp;      PPRequestUserConfirm;
+  UINT32          &= nbsp;      TpmIrqNum;
+  BOOLEAN          =       IsShortFormPkgLength;
+} TCG_NVS;
+
+typedef struct {
+  UINT8          &n= bsp;       OpRegionOp;
+  UINT32          &= nbsp;      NameString;
+  UINT8          &n= bsp;       RegionSpace;
+  UINT8          &n= bsp;       DWordPrefix;
+  UINT32          &= nbsp;      RegionOffset;
+  UINT8          &n= bsp;       BytePrefix;
+  UINT8          &n= bsp;       RegionLen;
+} AML_OP_REGION_32_8;
+
+typedef struct {
+  UINT64          &= nbsp;     Function;
+  UINT64          &= nbsp;     ReturnStatus;
+  EFI_PHYSICAL_ADDRESS  TargetAddress;
+  UINT64          &= nbsp;     RegisteredPpSwiValue;
+  UINT64          &= nbsp;     RegisteredMcSwiValue;
+} TPM_NVS_MM_COMM_BUFFER;
+#pragma pack()
+
+typedef enum {
+  TpmNvsMmExchangeInfo,
+} TPM_NVS_MM_FUNCTION;
+
+#endif  // __TCG_SMM_H__
diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec
index 1b7d62e802b3..0970cae5c75e 100644
--- a/SecurityPkg/SecurityPkg.dec
+++ b/SecurityPkg/SecurityPkg.dec
@@ -183,6 +183,13 @@ [Guids]
   ## Include/OpalPasswordExtraInfoVariable.h
   gOpalExtraInfoVariableGuid =3D  {0x44a2ad5d, 0x612c, 0x47= b3, {0xb0, 0x6e, 0xc8, 0xf5, 0x0b, 0xfb, 0xf0, 0x7d}}
 
+  ## GUID used to exchange registered SWI value and NVS region betwee= n Tcg2Acpi and Tcg2Smm.
+  ## Include/Guid/TpmNvsMm.h
+  gTpmNvsMmGuid         =              = =3D { 0xc96c76eb, 0xbc78, 0x429c, { 0x9f, 0x4b, 0xda, 0x51, 0x78, 0xc2, 0x8= 4, 0x57 }}
+
+  ## GUID used to enforce loading order between Tcg2Acpi and Tcg2Smm<= br> +  gTcg2MmSwSmiRegisteredGuid       = ;  =3D { 0x9d4548b9, 0xa48d, 0x4db4, { 0x9a, 0x68, 0x32, 0xc5, 0x13, 0= x9e, 0x20, 0x18 } }
+
 
 [Ppis]
   ## The PPI GUID for that TPM physical presence should be locke= d.
diff --git a/SecurityPkg/SecurityPkg.dsc b/SecurityPkg/SecurityPkg.dsc
index 618420a56c33..928bff72baa3 100644
--- a/SecurityPkg/SecurityPkg.dsc
+++ b/SecurityPkg/SecurityPkg.dsc
@@ -317,6 +317,7 @@ [Components.IA32, Components.X64]
   SecurityPkg/Tcg/MemoryOverwriteRequestControlLock/TcgMorLockSm= m.inf
   SecurityPkg/Tcg/TcgSmm/TcgSmm.inf
   SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf
+  SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.inf
   SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/SmmTcg2Physical= PresenceLib.inf
   SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/StandaloneMmTcg= 2PhysicalPresenceLib.inf
 
diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf b/SecurityPkg/Tcg/Tcg2Acpi= /Tcg2Acpi.inf
similarity index 76%
copy from SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf
copy to SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.inf
index 872ed27cbe71..d8e06881c01d 100644
--- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf
+++ b/SecurityPkg/Tcg/Tcg2Acpi/Tcg2Acpi.inf
@@ -13,8 +13,8 @@
 #     "Errata for PC Client Specific Platfor= m Firmware Profile Specification Version 1.0 Revision 1.03"
 #
 #  This driver implements TPM 2.0 definition block in ACPI table= and
-#  registers SMI callback functions for Tcg2 physical presence and -#  MemoryClear to handle the requests from ACPI method.
+#  populates registered SMI callback functions for Tcg2 physical pres= ence
+#  and MemoryClear to handle the requests for ACPI method.
 #
 #  Caution: This module requires additional review when modified= .
 #  This driver will have external input - variable and ACPINvs d= ata in SMM mode.
@@ -28,17 +28,15 @@
 
 [Defines]
   INF_VERSION        &nb= sp;           =3D 0x00010= 005
-  BASE_NAME         &nbs= p;            =3D Tc= g2Smm
-  MODULE_UNI_FILE        &nbs= p;       =3D Tcg2Smm.uni
-  FILE_GUID         &nbs= p;            =3D 44= A20657-10B8-4049-A148-ACD8812AF257
-  MODULE_TYPE         &n= bsp;          =3D DXE_SMM_DRIV= ER
+  BASE_NAME         &nbs= p;            =3D Tc= g2Acpi
+  FILE_GUID         &nbs= p;            =3D 0D= 4BBF18-C2CC-4C23-BD63-BFDAD4C710D0
+  MODULE_TYPE         &n= bsp;          =3D DXE_DRIVER    PI_SPECIFICATION_VERSION       = =3D 0x0001000A
   VERSION_STRING        =          =3D 1.0
-  ENTRY_POINT         &n= bsp;          =3D InitializeTc= gSmm
+  ENTRY_POINT         &n= bsp;          =3D InitializeTc= gAcpi
 
 [Sources]
-  Tcg2Smm.h
-  Tcg2Smm.c
+  Tcg2Acpi.c
   Tpm.asl
 
 [Packages]
@@ -50,7 +48,6 @@ [LibraryClasses]
   BaseLib
   BaseMemoryLib
   UefiDriverEntryPoint
-  MmServicesTableLib
   UefiBootServicesTableLib
   DebugLib
   DxeServicesLib
@@ -60,16 +57,13 @@ [LibraryClasses]
   PcdLib
 
 [Guids]
-  ## SOMETIMES_PRODUCES ## Variable:L"MemoryOverwriteRequestCont= rol"
-  ## SOMETIMES_CONSUMES ## Variable:L"MemoryOverwriteRequestCont= rol"
-  gEfiMemoryOverwriteControlDataGuid
-
   gEfiTpmDeviceInstanceTpm20DtpmGuid    &nbs= p;            &= nbsp;          ## PRODUCES&nbs= p;          ## GUID  = ;     # TPM device identifier
+  gTpmNvsMmGuid         =             &nb= sp;            =             &nb= sp;  ## CONSUMES
+  gEdkiiPiSmmCommunicationRegionTableGuid    &nbs= p;            &= nbsp;     ## CONSUMES
 
 [Protocols]
-  gEfiSmmSwDispatch2ProtocolGuid      &= nbsp;           &nbs= p;             = ## CONSUMES
-  gEfiSmmVariableProtocolGuid      &nbs= p;            &= nbsp;           &nbs= p;   ## CONSUMES
   gEfiAcpiTableProtocolGuid      &= nbsp;           &nbs= p;            &= nbsp;     ## CONSUMES
+  gEfiMmCommunicationProtocolGuid      =             &nb= sp;            ## CO= NSUMES
 
 [FixedPcd]
   gEfiSecurityPkgTokenSpaceGuid.PcdSmiCommandIoPort  &= nbsp;          ## CONSUMES
@@ -93,9 +87,5 @@ [Pcd]
 
 [Depex]
   gEfiAcpiTableProtocolGuid AND
-  gEfiSmmSwDispatch2ProtocolGuid AND
-  gEfiSmmVariableProtocolGuid AND
+  gTcg2MmSwSmiRegisteredGuid AND
   gEfiTcg2ProtocolGuid
-
-[UserExtensions.TianoCore."ExtraFiles"]
-  Tcg2SmmExtra.uni
diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tpm.asl b/SecurityPkg/Tcg/Tcg2Acpi/Tpm= .asl
similarity index 100%
rename from SecurityPkg/Tcg/Tcg2Smm/Tpm.asl
rename to SecurityPkg/Tcg/Tcg2Acpi/Tpm.asl
diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h b/SecurityPkg/Tcg/Tcg2Smm/Tc= g2Smm.h
index d7328c8f2ac9..d7f78aa43275 100644
--- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h
+++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.h
@@ -2,6 +2,7 @@
   The header file for Tcg2 SMM driver.
 
 Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<= ;BR>
+Copyright (c) Microsoft Corporation.
 SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
@@ -9,13 +10,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #ifndef __TCG2_SMM_H__
 #define __TCG2_SMM_H__
 
-#include <PiDxe.h>
-#include <IndustryStandard/Acpi.h>
-#include <IndustryStandard/Tpm2Acpi.h>
+#include <PiMm.h>
 
 #include <Guid/MemoryOverwriteControl.h>
 #include <Guid/TpmInstance.h>
+#include <Guid/TpmNvsMm.h>
 
+#include <Protocol/MmReadyToLock.h>
 #include <Protocol/SmmSwDispatch2.h>
 #include <Protocol/AcpiTable.h>
 #include <Protocol/SmmVariable.h>
@@ -25,56 +26,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 #include <Library/BaseMemoryLib.h>
 #include <Library/DebugLib.h>
 #include <Library/MmServicesTableLib.h>
-#include <Library/UefiDriverEntryPoint.h>
-#include <Library/UefiBootServicesTableLib.h>
-#include <Library/DxeServicesLib.h>
-#include <Library/TpmMeasurementLib.h>
 #include <Library/Tpm2CommandLib.h>
 #include <Library/Tcg2PhysicalPresenceLib.h>
 #include <Library/IoLib.h>
-#include <Library/PrintLib.h>
 #include <Library/PcdLib.h>
 #include <Library/Tpm2DeviceLib.h>
 
 #include <IndustryStandard/TpmPtp.h>
 
-#pragma pack(1)
-typedef struct {
-  UINT8          &n= bsp;       SoftwareSmi;
-  UINT32          &= nbsp;      Parameter;
-  UINT32          &= nbsp;      Response;
-  UINT32          &= nbsp;      Request;
-  UINT32          &= nbsp;      RequestParameter;
-  UINT32          &= nbsp;      LastRequest;
-  UINT32          &= nbsp;      ReturnCode;
-} PHYSICAL_PRESENCE_NVS;
-
-typedef struct {
-  UINT8          &n= bsp;       SoftwareSmi;
-  UINT32          &= nbsp;      Parameter;
-  UINT32          &= nbsp;      Request;
-  UINT32          &= nbsp;      ReturnCode;
-} MEMORY_CLEAR_NVS;
-
-typedef struct {
-  PHYSICAL_PRESENCE_NVS  PhysicalPresence;
-  MEMORY_CLEAR_NVS       MemoryClear; -  UINT32          &= nbsp;      PPRequestUserConfirm;
-  UINT32          &= nbsp;      TpmIrqNum;
-  BOOLEAN          =       IsShortFormPkgLength;
-} TCG_NVS;
-
-typedef struct {
-  UINT8          &n= bsp;       OpRegionOp;
-  UINT32          &= nbsp;      NameString;
-  UINT8          &n= bsp;       RegionSpace;
-  UINT8          &n= bsp;       DWordPrefix;
-  UINT32          &= nbsp;      RegionOffset;
-  UINT8          &n= bsp;       BytePrefix;
-  UINT8          &n= bsp;       RegionLen;
-} AML_OP_REGION_32_8;
-#pragma pack()
-
 //
 // The definition for TCG MOR
 //
@@ -87,36 +46,42 @@ typedef struct {
 #define MOR_REQUEST_SUCCESS       =             &nb= sp;            =         0
 #define MOR_REQUEST_GENERAL_FAILURE     &nbs= p;            &= nbsp;           &nbs= p; 1
 
-//
-// Physical Presence Interface Version supported by Platform
-//
-#define PHYSICAL_PRESENCE_VERSION_TAG      &= nbsp;           &nbs= p;           "$PV&qu= ot;
-#define PHYSICAL_PRESENCE_VERSION_SIZE      =             &nb= sp;          4
-
-//
-// PNP _HID for TPM2 device
-//
-#define TPM_HID_TAG         &= nbsp;           &nbs= p;            &= nbsp;           &nbs= p; "NNNN0000"
-#define TPM_HID_PNP_SIZE        &n= bsp;            = ;            &n= bsp;         8
-#define TPM_HID_ACPI_SIZE        &= nbsp;           &nbs= p;            &= nbsp;        9
-
-#define TPM_PRS_RESL         =             &nb= sp;            =              &q= uot;RESL"
-#define TPM_PRS_RESS         =             &nb= sp;            =              &q= uot;RESS"
-#define TPM_PRS_RES_NAME_SIZE       &nb= sp;            =             &nb= sp;     4
-//
-// Minimum PRS resource template size
-//  1 byte    for  BufferOp
-//  1 byte    for  PkgLength
-//  2 bytes   for  BufferSize
-//  12 bytes  for  Memory32Fixed descriptor
-//  5 bytes   for  Interrupt descriptor
-//  2 bytes   for  END Tag
-//
-#define TPM_POS_RES_TEMPLATE_MIN_SIZE      &= nbsp;           &nbs= p;           (1 + 1 + 2 += 12 + 5 + 2)
-
-//
-// Max Interrupt buffer size for PRS interrupt resource
-// Now support 15 interrupts in maxmum
-//
-#define MAX_PRS_INT_BUF_SIZE       &nbs= p;            &= nbsp;           &nbs= p;      (15*4)
+/**
+  Notify the system that the SMM variable driver is ready.
+**/
+VOID
+Tcg2NotifyMmReady (
+  VOID
+  );
+
+/**
+  This function is an abstraction layer for implementation specific M= m buffer validation routine.
+
+  @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 o= r overlap with SMRAM.
+**/
+BOOLEAN
+IsBufferOutsideMmValid (
+  IN EFI_PHYSICAL_ADDRESS  Buffer,
+  IN UINT64         &nbs= p;      Length
+  );
+
+/**
+  The driver's common initialization routine.
+
+  It install callbacks for TPM physical presence and MemoryClear, and= locate
+  SMM variable to be used in the callback function.
+
+  @retval EFI_SUCCESS     The entry point is exec= uted successfully.
+  @retval Others         = ; Some error occurs when executing this entry point.
+
+**/
+EFI_STATUS
+InitializeTcgCommon (
+  VOID
+  );
+
 #endif  // __TCG_SMM_H__
diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf b/SecurityPkg/Tcg/Tcg2Smm/= Tcg2Smm.inf
index 872ed27cbe71..096338d0ef47 100644
--- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf
+++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.inf
@@ -39,7 +39,7 @@ [Defines]
 [Sources]
   Tcg2Smm.h
   Tcg2Smm.c
-  Tpm.asl
+  Tcg2TraditionalMm.c
 
 [Packages]
   MdePkg/MdePkg.dec
@@ -58,6 +58,7 @@ [LibraryClasses]
   Tpm2CommandLib
   Tcg2PhysicalPresenceLib
   PcdLib
+  SmmMemLib
 
 [Guids]
   ## SOMETIMES_PRODUCES ## Variable:L"MemoryOverwriteReques= tControl"
@@ -65,34 +66,18 @@ [Guids]
   gEfiMemoryOverwriteControlDataGuid
 
   gEfiTpmDeviceInstanceTpm20DtpmGuid    &nbs= p;            &= nbsp;          ## PRODUCES&nbs= p;          ## GUID  = ;     # TPM device identifier
+  gTcg2MmSwSmiRegisteredGuid       = ;            &n= bsp;            = ;    ## PRODUCES
+  gTpmNvsMmGuid         =             &nb= sp;            =             &nb= sp;  ## CONSUMES
 
 [Protocols]
   gEfiSmmSwDispatch2ProtocolGuid     &n= bsp;            = ;            &n= bsp; ## CONSUMES
   gEfiSmmVariableProtocolGuid      = ;            &n= bsp;            = ;    ## CONSUMES
-  gEfiAcpiTableProtocolGuid       =             &nb= sp;            =      ## CONSUMES
-
-[FixedPcd]
-  gEfiSecurityPkgTokenSpaceGuid.PcdSmiCommandIoPort   =           ## CONSUMES
+  gEfiMmReadyToLockProtocolGuid      &n= bsp;            = ;            &n= bsp; ## CONSUMES
 
 [Pcd]
   gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid  &n= bsp;           ## CONSUME= S
-  gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemId   = ;         ## SOMETIMES_CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemTableId  =      ## SOMETIMES_CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultOemRevision  = ;    ## SOMETIMES_CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultCreatorId  &= nbsp;     ## SOMETIMES_CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultCreatorRevision  = ## SOMETIMES_CONSUMES
-  gEfiSecurityPkgTokenSpaceGuid.PcdTpmBaseAddress   &n= bsp;           ## CONSUME= S
-  gEfiSecurityPkgTokenSpaceGuid.PcdTcgPhysicalPresenceInterfaceVer&nb= sp; ## CONSUMES
-  gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableRev   =             &nb= sp; ## CONSUMES
-  gEfiSecurityPkgTokenSpaceGuid.PcdTpmPlatformClass   =             &nb= sp; ## SOMETIMES_CONSUMES
-  gEfiSecurityPkgTokenSpaceGuid.PcdTpm2CurrentIrqNum   = ;         ## CONSUMES
-  gEfiSecurityPkgTokenSpaceGuid.PcdTpm2PossibleIrqNumBuf  &= nbsp;     ## CONSUMES
-  gEfiSecurityPkgTokenSpaceGuid.PcdActiveTpmInterfaceType  =      ## CONSUMES
-  gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableLaml   = ;         ## CONSUMES
-  gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableLasa   = ;         ## CONSUMES
 
 [Depex]
-  gEfiAcpiTableProtocolGuid AND
   gEfiSmmSwDispatch2ProtocolGuid AND
   gEfiSmmVariableProtocolGuid AND
   gEfiTcg2ProtocolGuid
--
2.30.0.windows.1

 

--_000_MWHPR06MB310237B5CBEC479B1C78CBC1F3819MWHPR06MB3102namp_--