public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib
@ 2024-04-15 13:30 Wu, Jiaxin
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 01/10] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
                   ` (10 more replies)
  0 siblings, 11 replies; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:30 UTC (permalink / raw)
  To: devel
  Cc: Ray Ni, Zeng Star, Gerd Hoffmann, Rahul Kumar, Guo Dong,
	Sean Rhodes, James Lu, Gua Guo, Ard Biesheuvel, Jiewen Yao,
	Abdul Lateef Attar, Abner Chang, Tom Lendacky

Intel plans to separate the smbase relocation logic from
PiSmmCpuDxeSmm driver, and the related behavior will be
moved to the new interface defined by the SmmRelocationLib
class.

The SmmRelocationLib class provides the SmmRelocationInit()
interface for platform to do the smbase relocation, which
shall provide below 2 functionalities:
1. Relocate smbases for each processor.
2. Create the gSmmBaseHobGuid HOB.

With SmmRelocationLib, PiSmmCpuDxeSmm driver (which runs at
a later phase) can be simplfied as below for SMM init:
1. Consume the gSmmBaseHobGuid HOB for the relocated smbases
for each Processor.
2. Execute the early SMM Init.

Cc: Ray Ni <ray.ni@intel.com>
Cc: Zeng Star <star.zeng@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Cc: Guo Dong <guo.dong@intel.com>
Cc: Sean Rhodes <sean@starlabs.systems>
Cc: James Lu <james.lu@intel.com>
Cc: Gua Guo <gua.guo@intel.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Abdul Lateef Attar <AbdulLateef.Attar@amd.com>
Cc: Abner Chang <abner.chang@amd.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>

Jiaxin Wu (10):
  UefiCpuPkg: Add SmmRelocationLib class
  UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance
  UefiCpuPkg/SmmRelocationLib: Add library instance for AMD
  OvmfPkg/SmmRelocationLib: Add library instance for OVMF
  OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  OvmfPkg: Refine SmmAccess implementation
  OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not
  OvmfPkg/PlatformPei: Relocate SmBases in PEI phase
  UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib
  UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic

 OvmfPkg/AmdSev/AmdSevX64.dsc                       |   3 +
 OvmfPkg/CloudHv/CloudHvX64.dsc                     |   2 +
 OvmfPkg/Library/PlatformInitLib/MemDetect.c        | 104 ++--
 .../Library/PlatformInitLib/PlatformInitLib.inf    |   6 +-
 .../Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c  |  33 +-
 .../Library/SmmRelocationLib}/Ia32/Semaphore.c     |  13 +-
 OvmfPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm | 148 +++++
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 140 +++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 599 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  61 +++
 .../SmmRelocationLib/SmramSaveStateConfig.c        | 107 ++++
 .../Library/SmmRelocationLib}/X64/Semaphore.c      |  13 +-
 .../Library/SmmRelocationLib}/X64/SmmInit.nasm     |  86 ++-
 OvmfPkg/Microvm/MicrovmX64.dsc                     |   3 +
 OvmfPkg/OvmfPkgIa32.dsc                            |   2 +
 OvmfPkg/OvmfPkgIa32X64.dsc                         |   2 +
 OvmfPkg/OvmfPkgX64.dsc                             |   1 +
 OvmfPkg/PlatformPei/Platform.c                     |   3 +
 OvmfPkg/PlatformPei/Platform.h                     |   5 +
 OvmfPkg/PlatformPei/PlatformPei.inf                |   5 +-
 OvmfPkg/PlatformPei/SmmRelocation.c                |  80 +++
 OvmfPkg/SmmAccess/SmmAccess2Dxe.c                  |   4 +-
 OvmfPkg/SmmAccess/SmmAccess2Dxe.inf                |   5 +
 OvmfPkg/SmmAccess/SmmAccessPei.c                   |  88 +--
 OvmfPkg/SmmAccess/SmmAccessPei.inf                 |   7 +-
 OvmfPkg/SmmAccess/SmramInternal.c                  |  73 +--
 OvmfPkg/SmmAccess/SmramInternal.h                  |  18 +-
 UefiCpuPkg/Include/Library/SmmRelocationLib.h      |  42 ++
 .../SmmRelocationLib/AmdSmmRelocationLib.inf       |  61 +++
 .../SmmRelocationLib/AmdSmramSaveStateConfig.c     | 132 +++++
 .../SmmRelocationLib}/Ia32/Semaphore.c             |  13 +-
 .../Library/SmmRelocationLib/Ia32/SmmInit.nasm     | 148 +++++
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 140 +++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 599 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  62 +++
 .../SmmRelocationLib/SmramSaveStateConfig.c        | 139 +++++
 .../SmmRelocationLib}/X64/Semaphore.c              |  13 +-
 .../SmmRelocationLib}/X64/SmmInit.nasm             |  86 ++-
 UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c                  |  21 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm        |  96 ----
 UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c              |  10 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c         | 331 +-----------
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h         | 103 +---
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf       |   4 -
 UefiCpuPkg/PiSmmCpuDxeSmm/SmmMpPerf.h              |   2 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c         |  69 ---
 UefiCpuPkg/UefiCpuPkg.dec                          |   3 +
 UefiCpuPkg/UefiCpuPkg.dsc                          |   2 +
 UefiPayloadPkg/UefiPayloadPkg.dsc                  |   2 +
 49 files changed, 2833 insertions(+), 856 deletions(-)
 copy {UefiCpuPkg/PiSmmCpuDxeSmm => OvmfPkg/Library/SmmRelocationLib}/Ia32/Semaphore.c (72%)
 create mode 100644 OvmfPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
 create mode 100644 OvmfPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
 create mode 100644 OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.c
 create mode 100644 OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 create mode 100644 OvmfPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
 copy {UefiCpuPkg/PiSmmCpuDxeSmm => OvmfPkg/Library/SmmRelocationLib}/X64/Semaphore.c (78%)
 copy {UefiCpuPkg/PiSmmCpuDxeSmm => OvmfPkg/Library/SmmRelocationLib}/X64/SmmInit.nasm (59%)
 create mode 100644 OvmfPkg/PlatformPei/SmmRelocation.c
 create mode 100644 UefiCpuPkg/Include/Library/SmmRelocationLib.h
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
 rename UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/Ia32/Semaphore.c (72%)
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
 rename UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/X64/Semaphore.c (78%)
 rename UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/X64/SmmInit.nasm (59%)
 delete mode 100644 UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm

-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117775): https://edk2.groups.io/g/devel/message/117775
Mute This Topic: https://groups.io/mt/105535804/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 19+ messages in thread

* [edk2-devel] [PATCH v2 01/10] UefiCpuPkg: Add SmmRelocationLib class
  2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
@ 2024-04-15 13:30 ` Wu, Jiaxin
  2024-04-16  1:50   ` Ni, Ray
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 02/10] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance Wu, Jiaxin
                   ` (9 subsequent siblings)
  10 siblings, 1 reply; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:30 UTC (permalink / raw)
  To: devel; +Cc: Ray Ni, Zeng Star, Gerd Hoffmann, Rahul Kumar

Intel plans to separate the smbase relocation logic from
PiSmmCpuDxeSmm driver, and the related behavior will be
moved to the new interface defined by the SmmRelocationLib
class.

The SmmRelocationLib class provides the SmmRelocationInit()
interface for platform to do the smbase relocation, which
shall provide below 2 functionalities:
1. Relocate smbases for each processor.
2. Create the gSmmBaseHobGuid HOB.

With SmmRelocationLib, PiSmmCpuDxeSmm driver (which runs at
a later phase) shall:
1. Consume the gSmmBaseHobGuid HOB for the relocated smbases
for each Processor.
2. Execute the early SMM Init.

This patch just provides the SmmRelocationLib class.

Cc: Ray Ni <ray.ni@intel.com>
Cc: Zeng Star <star.zeng@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 UefiCpuPkg/Include/Library/SmmRelocationLib.h | 42 +++++++++++++++++++++++++++
 UefiCpuPkg/UefiCpuPkg.dec                     |  3 ++
 2 files changed, 45 insertions(+)
 create mode 100644 UefiCpuPkg/Include/Library/SmmRelocationLib.h

diff --git a/UefiCpuPkg/Include/Library/SmmRelocationLib.h b/UefiCpuPkg/Include/Library/SmmRelocationLib.h
new file mode 100644
index 0000000000..999a5b46d1
--- /dev/null
+++ b/UefiCpuPkg/Include/Library/SmmRelocationLib.h
@@ -0,0 +1,42 @@
+/** @file
+  Header file for SMM Relocation Library.
+
+  The SmmRelocationLib class provides the SmmRelocationInit()
+  interface for platform to do the smbase relocation, which
+  shall provide below 2 functionalities:
+  1. Relocate SmBases for each processor.
+  2. Create the SmBase HOB (gSmmBaseHobGuid).
+
+  With SmmRelocationLib, PiSmmCpuDxeSmm driver (which runs at a later phase)
+  shall:
+  1. Consume the gSmmBaseHobGuid for the relocated smbase for each Processor.
+  2. Execute early SMM init.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef SMM_RELOCATION_LIB_H_
+#define SMM_RELOCATION_LIB_H_
+
+#include <Ppi/MpServices2.h>
+
+/**
+  CPU SmmBase Relocation Init.
+
+  This function is to relocate CPU SmmBase.
+
+  @param[in] MpServices2        Pointer to this instance of the MpServices.
+
+  @retval EFI_SUCCESS           CPU SmmBase Relocated successfully.
+  @retval Others                CPU SmmBase Relocation failed.
+
+**/
+EFI_STATUS
+EFIAPI
+SmmRelocationInit (
+  IN EDKII_PEI_MP_SERVICES2_PPI  *MpServices2
+  );
+
+#endif
diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec
index 571b59b36f..1d7890f19e 100644
--- a/UefiCpuPkg/UefiCpuPkg.dec
+++ b/UefiCpuPkg/UefiCpuPkg.dec
@@ -65,10 +65,13 @@
   MmSaveStateLib|Include/Library/MmSaveStateLib.h
 
   ## @libraryclass   Provides functions for SMM CPU Sync Operation.
   SmmCpuSyncLib|Include/Library/SmmCpuSyncLib.h
 
+  ## @libraryclass   Provides functions for SMM Relocation Operation.
+  SmmRelocationLib|Include/Library/SmmRelocationLib.h
+
 [LibraryClasses.RISCV64]
   ##  @libraryclass  Provides functions to manage MMU features on RISCV64 CPUs.
   ##
   RiscVMmuLib|Include/Library/BaseRiscVMmuLib.h
 
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117776): https://edk2.groups.io/g/devel/message/117776
Mute This Topic: https://groups.io/mt/105535805/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 19+ messages in thread

* [edk2-devel] [PATCH v2 02/10] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance
  2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 01/10] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
@ 2024-04-15 13:30 ` Wu, Jiaxin
  2024-04-16  3:19   ` Ni, Ray
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 03/10] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD Wu, Jiaxin
                   ` (8 subsequent siblings)
  10 siblings, 1 reply; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:30 UTC (permalink / raw)
  To: devel; +Cc: Ray Ni, Zeng Star, Gerd Hoffmann, Rahul Kumar

This patch separates the smbase relocation logic from
PiSmmCpuDxeSmm driver, and moves to the
SmmRelocationInit interface.

Platform shall consume the interface for the smbase
relocation if need SMM support.

Note:
Before using SmmRelocationLib, the PiSmmCpuDxeSmm driver
allocates the SMRAM to be used for SMI handler and Save
state area of each processor from Smst->AllocatePages().
With SmmRelocationLib, the SMRAM allocation for SMI
handlers and Save state areas is moved to early PEI
phase (Smst->AllocatePages() service is not available).
So, the allocation is done by splitting the SMRAM out of
the SMRAM regions reported from gEfiSmmSMramMemoryGuid.

So, Platform must produce the gEfiSmmSMramMemoryGuid HOB
for SmmRelocationLib usage.

Cc: Ray Ni <ray.ni@intel.com>
Cc: Zeng Star <star.zeng@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 .../SmmRelocationLib}/Ia32/Semaphore.c             |  13 +-
 .../Library/SmmRelocationLib/Ia32/SmmInit.nasm     | 148 +++++
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 140 +++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 599 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  62 +++
 .../SmmRelocationLib/SmramSaveStateConfig.c        | 139 +++++
 .../SmmRelocationLib}/X64/Semaphore.c              |  13 +-
 .../SmmRelocationLib}/X64/SmmInit.nasm             |  86 ++-
 UefiCpuPkg/UefiCpuPkg.dsc                          |   1 +
 9 files changed, 1173 insertions(+), 28 deletions(-)
 copy UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/Ia32/Semaphore.c (72%)
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
 copy UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/X64/Semaphore.c (78%)
 copy UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/X64/SmmInit.nasm (59%)

diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
similarity index 72%
copy from UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c
copy to UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
index a9fcc89dda..ace3221cfc 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
@@ -1,15 +1,15 @@
 /** @file
-Semaphore mechanism to indicate to the BSP that an AP has exited SMM
-after SMBASE relocation.
+  Semaphore mechanism to indicate to the BSP that an AP has exited SMM
+  after SMBASE relocation.
 
-Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>
-SPDX-License-Identifier: BSD-2-Clause-Patent
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 
-#include "PiSmmCpuDxeSmm.h"
+#include "InternalSmmRelocationLib.h"
 
 UINTN             mSmmRelocationOriginalAddress;
 volatile BOOLEAN  *mRebasedFlag;
 
 /**
@@ -30,11 +30,12 @@ SemaphoreHook (
 {
   SMRAM_SAVE_STATE_MAP  *CpuState;
 
   mRebasedFlag = RebasedFlag;
 
-  CpuState                      = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+  CpuState = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+
   mSmmRelocationOriginalAddress = (UINTN)HookReturnFromSmm (
                                            CpuIndex,
                                            CpuState,
                                            (UINT64)(UINTN)&SmmRelocationSemaphoreComplete,
                                            (UINT64)(UINTN)&SmmRelocationSemaphoreComplete
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
new file mode 100644
index 0000000000..931dd17439
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
@@ -0,0 +1,148 @@
+;------------------------------------------------------------------------------ ;
+; Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+; SPDX-License-Identifier: BSD-2-Clause-Patent
+;
+; Module Name:
+;
+;   SmmInit.nasm
+;
+; Abstract:
+;
+;   Functions for relocating SMBASE's for all processors
+;
+;-------------------------------------------------------------------------------
+
+%include "StuffRsbNasm.inc"
+
+global  ASM_PFX(gcSmmInitIdtr)
+global  ASM_PFX(gcSmmInitGdtr)
+
+extern ASM_PFX(SmmInitHandler)
+extern ASM_PFX(mRebasedFlag)
+extern ASM_PFX(mSmmRelocationOriginalAddress)
+
+global ASM_PFX(gPatchSmmCr3)
+global ASM_PFX(gPatchSmmCr4)
+global ASM_PFX(gPatchSmmCr0)
+global ASM_PFX(gPatchSmmInitStack)
+global ASM_PFX(gcSmmInitSize)
+global ASM_PFX(gcSmmInitTemplate)
+
+%define PROTECT_MODE_CS 0x8
+%define PROTECT_MODE_DS 0x20
+
+    SECTION .data
+
+NullSeg: DQ 0                   ; reserved by architecture
+CodeSeg32:
+            DW      -1                  ; LimitLow
+            DW      0                   ; BaseLow
+            DB      0                   ; BaseMid
+            DB      0x9b
+            DB      0xcf                ; LimitHigh
+            DB      0                   ; BaseHigh
+ProtModeCodeSeg32:
+            DW      -1                  ; LimitLow
+            DW      0                   ; BaseLow
+            DB      0                   ; BaseMid
+            DB      0x9b
+            DB      0xcf                ; LimitHigh
+            DB      0                   ; BaseHigh
+ProtModeSsSeg32:
+            DW      -1                  ; LimitLow
+            DW      0                   ; BaseLow
+            DB      0                   ; BaseMid
+            DB      0x93
+            DB      0xcf                ; LimitHigh
+            DB      0                   ; BaseHigh
+DataSeg32:
+            DW      -1                  ; LimitLow
+            DW      0                   ; BaseLow
+            DB      0                   ; BaseMid
+            DB      0x93
+            DB      0xcf                ; LimitHigh
+            DB      0                   ; BaseHigh
+CodeSeg16:
+            DW      -1
+            DW      0
+            DB      0
+            DB      0x9b
+            DB      0x8f
+            DB      0
+DataSeg16:
+            DW      -1
+            DW      0
+            DB      0
+            DB      0x93
+            DB      0x8f
+            DB      0
+CodeSeg64:
+            DW      -1                  ; LimitLow
+            DW      0                   ; BaseLow
+            DB      0                   ; BaseMid
+            DB      0x9b
+            DB      0xaf                ; LimitHigh
+            DB      0                   ; BaseHigh
+GDT_SIZE equ $ - NullSeg
+
+ASM_PFX(gcSmmInitGdtr):
+    DW      GDT_SIZE - 1
+    DD      NullSeg
+
+ASM_PFX(gcSmmInitIdtr):
+    DW      0
+    DD      0
+
+
+    SECTION .text
+
+global ASM_PFX(SmmStartup)
+
+BITS 16
+ASM_PFX(SmmStartup):
+    mov     eax, strict dword 0         ; source operand will be patched
+ASM_PFX(gPatchSmmCr3):
+    mov     cr3, eax
+o32 lgdt    [cs:ebp + (ASM_PFX(gcSmmInitGdtr) - ASM_PFX(SmmStartup))]
+    mov     eax, strict dword 0         ; source operand will be patched
+ASM_PFX(gPatchSmmCr4):
+    mov     cr4, eax
+    mov     eax, strict dword 0         ; source operand will be patched
+ASM_PFX(gPatchSmmCr0):
+    mov     di, PROTECT_MODE_DS
+    mov     cr0, eax
+    jmp     PROTECT_MODE_CS : dword @32bit
+
+BITS 32
+@32bit:
+    mov     ds, edi
+    mov     es, edi
+    mov     fs, edi
+    mov     gs, edi
+    mov     ss, edi
+    mov     esp, strict dword 0         ; source operand will be patched
+ASM_PFX(gPatchSmmInitStack):
+    call    ASM_PFX(SmmInitHandler)
+    StuffRsb32
+    rsm
+
+BITS 16
+ASM_PFX(gcSmmInitTemplate):
+    mov ebp, ASM_PFX(SmmStartup)
+    sub ebp, 0x30000
+    jmp ebp
+
+ASM_PFX(gcSmmInitSize): DW $ - ASM_PFX(gcSmmInitTemplate)
+
+BITS 32
+global ASM_PFX(SmmRelocationSemaphoreComplete)
+ASM_PFX(SmmRelocationSemaphoreComplete):
+    push    eax
+    mov     eax, [ASM_PFX(mRebasedFlag)]
+    mov     byte [eax], 1
+    pop     eax
+    jmp     [ASM_PFX(mSmmRelocationOriginalAddress)]
+
+global ASM_PFX(SmmInitFixupAddress)
+ASM_PFX(SmmInitFixupAddress):
+    ret
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
new file mode 100644
index 0000000000..b852f4956c
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
@@ -0,0 +1,140 @@
+/** @file
+  SMM Relocation Lib for each processor.
+
+  This Lib produces the SMM_BASE_HOB in HOB database which tells
+  the PiSmmCpuDxeSmm driver (runs at a later phase) about the new
+  SMBASE for each processor. PiSmmCpuDxeSmm driver installs the
+  SMI handler at the SMM_BASE_HOB.SmBase[Index]+0x8000 for processor
+  Index.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef INTERNAL_SMM_RELOCATION_LIB_H_
+#define INTERNAL_SMM_RELOCATION_LIB_H_
+
+#include <PiPei.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/CpuExceptionHandlerLib.h>
+#include <Library/DebugLib.h>
+#include <Library/HobLib.h>
+#include <Library/LocalApicLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/PcdLib.h>
+#include <Library/PeimEntryPoint.h>
+#include <Library/PeiServicesLib.h>
+#include <Library/SmmRelocationLib.h>
+#include <Guid/SmramMemoryReserve.h>
+#include <Guid/SmmBaseHob.h>
+#include <Register/Intel/Cpuid.h>
+#include <Register/Intel/SmramSaveStateMap.h>
+#include <Protocol/MmCpu.h>
+
+extern UINT64  *mSmBaseForAllCpus;
+
+extern IA32_DESCRIPTOR  gcSmmInitGdtr;
+extern IA32_DESCRIPTOR  gcSmmInitIdtr;
+extern CONST UINT16     gcSmmInitSize;
+extern CONST UINT8      gcSmmInitTemplate[];
+
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr0;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr3;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr4;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmInitStack;
+
+//
+// The size 0x20 must be bigger than
+// the size of template code of SmmInit. Currently,
+// the size of SmmInit requires the 0x16 Bytes buffer
+// at least.
+//
+#define BACK_BUF_SIZE  0x20
+
+#define CR4_CET_ENABLE  BIT23
+
+//
+// EFER register LMA bit
+//
+#define LMA  BIT10
+
+/**
+  This function configures the SmBase on the currently executing CPU.
+
+  @param[in]     CpuIndex             The index of the CPU.
+  @param[in,out] CpuState             Pointer to SMRAM Save State Map for the
+                                      currently executing CPU. On out, SmBase is
+                                      updated to the new value.
+
+**/
+VOID
+EFIAPI
+ConfigureSmBase (
+  IN     UINTN                 CpuIndex,
+  IN OUT SMRAM_SAVE_STATE_MAP  *CpuState
+  );
+
+/**
+  Semaphore operation for all processor relocate SMMBase.
+**/
+VOID
+EFIAPI
+SmmRelocationSemaphoreComplete (
+  VOID
+  );
+
+/**
+  Hook the code executed immediately after an RSM instruction on the currently
+  executing CPU.  The mode of code executed immediately after RSM must be
+  detected, and the appropriate hook must be selected.  Always clear the auto
+  HALT restart flag if it is set.
+
+  @param[in]     CpuIndex                 The processor index for the currently
+                                          executing CPU.
+  @param[in,out] CpuState                 Pointer to SMRAM Save State Map for the
+                                          currently executing CPU.
+  @param[in]     NewInstructionPointer32  Instruction pointer to use if resuming to
+                                          32-bit mode from 64-bit SMM.
+  @param[in]     NewInstructionPointer    Instruction pointer to use if resuming to
+                                          same mode as SMM.
+
+  @retval The value of the original instruction pointer before it was hooked.
+
+**/
+UINT64
+EFIAPI
+HookReturnFromSmm (
+  IN     UINTN                 CpuIndex,
+  IN OUT SMRAM_SAVE_STATE_MAP  *CpuState,
+  IN     UINT64                NewInstructionPointer32,
+  IN     UINT64                NewInstructionPointer
+  );
+
+/**
+  Hook return address of SMM Save State so that semaphore code
+  can be executed immediately after AP exits SMM to indicate to
+  the BSP that an AP has exited SMM after SMBASE relocation.
+
+  @param[in] CpuIndex     The processor index.
+  @param[in] RebasedFlag  A pointer to a flag that is set to TRUE
+                          immediately after AP exits SMM.
+
+**/
+VOID
+SemaphoreHook (
+  IN UINTN             CpuIndex,
+  IN volatile BOOLEAN  *RebasedFlag
+  );
+
+/**
+  This function fixes up the address of the global variable or function
+  referred in SmmInit assembly files to be the absolute address.
+**/
+VOID
+EFIAPI
+SmmInitFixupAddress (
+  );
+
+#endif
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
new file mode 100644
index 0000000000..5af83ef4f0
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
@@ -0,0 +1,599 @@
+/** @file
+  SMM Relocation Lib for each processor.
+
+  This Lib produces the SMM_BASE_HOB in HOB database which tells
+  the PiSmmCpuDxeSmm driver (runs at a later phase) about the new
+  SMBASE for each processor. PiSmmCpuDxeSmm driver installs the
+  SMI handler at the SMM_BASE_HOB.SmBase[Index]+0x8000 for processor
+  Index.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#include "InternalSmmRelocationLib.h"
+
+UINTN   mMaxNumberOfCpus   = 1;
+UINTN   mNumberOfCpus      = 1;
+UINT64  *mSmBaseForAllCpus = NULL;
+
+//
+// Record all Processors Info
+//
+EFI_PROCESSOR_INFORMATION  *mProcessorInfo = NULL;
+
+//
+// SmBase Rebased or not
+//
+volatile BOOLEAN  *mRebased;
+
+/**
+  C function for SMI handler. To change all processor's SMMBase Register.
+
+**/
+VOID
+EFIAPI
+SmmInitHandler (
+  VOID
+  )
+{
+  UINT32  ApicId;
+  UINTN   Index;
+
+  SMRAM_SAVE_STATE_MAP  *CpuState;
+
+  //
+  // Update SMM IDT entries' code segment and load IDT
+  //
+  AsmWriteIdtr (&gcSmmInitIdtr);
+  ApicId = GetApicId ();
+
+  ASSERT (mNumberOfCpus <= mMaxNumberOfCpus);
+
+  for (Index = 0; Index < mNumberOfCpus; Index++) {
+    if (ApicId == (UINT32)mProcessorInfo[Index].ProcessorId) {
+      //
+      // Configure SmBase.
+      //
+      CpuState = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+      ConfigureSmBase (Index, CpuState);
+
+      //
+      // Hook return after RSM to set SMM re-based flag
+      // SMM re-based flag can't be set before RSM, because SMM save state context might be override
+      // by next AP flow before it take effect.
+      //
+      SemaphoreHook (Index, &mRebased[Index]);
+      return;
+    }
+  }
+
+  ASSERT (FALSE);
+}
+
+/**
+  This routine will split SmramReserve HOB to reserve SmmRelocationSize for Smm relocated memory.
+
+  @param[in]       SmmRelocationSize   SmmRelocationSize for all processors.
+  @param[in,out]   SmmRelocationStart  Return the start address of Smm relocated memory in SMRAM.
+
+  @retval EFI_SUCCESS           The gEfiSmmSmramMemoryGuid is split successfully.
+  @retval EFI_DEVICE_ERROR      Failed to build new HOB for gEfiSmmSmramMemoryGuid.
+  @retval EFI_NOT_FOUND         The gEfiSmmSmramMemoryGuid is not found.
+
+**/
+EFI_STATUS
+SplitSmramHobForSmmRelocation (
+  IN     UINT64                SmmRelocationSize,
+  IN OUT EFI_PHYSICAL_ADDRESS  *SmmRelocationStart
+  )
+{
+  EFI_HOB_GUID_TYPE               *GuidHob;
+  EFI_SMRAM_HOB_DESCRIPTOR_BLOCK  *DescriptorBlock;
+  EFI_SMRAM_HOB_DESCRIPTOR_BLOCK  *NewDescriptorBlock;
+  UINTN                           BufferSize;
+  UINTN                           SmramRanges;
+
+  NewDescriptorBlock = NULL;
+
+  //
+  // Retrieve the GUID HOB data that contains the set of SMRAM descriptors
+  //
+  GuidHob = GetFirstGuidHob (&gEfiSmmSmramMemoryGuid);
+  if (GuidHob == NULL) {
+    return EFI_NOT_FOUND;
+  }
+
+  DescriptorBlock = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)GET_GUID_HOB_DATA (GuidHob);
+
+  //
+  // Allocate one extra EFI_SMRAM_DESCRIPTOR to describe SMRAM memory that contains a pointer
+  // to the Smm relocated memory.
+  //
+  SmramRanges = DescriptorBlock->NumberOfSmmReservedRegions;
+  BufferSize  = sizeof (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK) + (SmramRanges * sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  NewDescriptorBlock = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)BuildGuidHob (
+                                                           &gEfiSmmSmramMemoryGuid,
+                                                           BufferSize
+                                                           );
+  ASSERT (NewDescriptorBlock != NULL);
+  if (NewDescriptorBlock == NULL) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  //
+  // Copy old EFI_SMRAM_HOB_DESCRIPTOR_BLOCK to new allocated region
+  //
+  CopyMem ((VOID *)NewDescriptorBlock, DescriptorBlock, BufferSize - sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  //
+  // Increase the number of SMRAM descriptors by 1 to make room for the ALLOCATED descriptor of size EFI_PAGE_SIZE
+  //
+  NewDescriptorBlock->NumberOfSmmReservedRegions = (UINT32)(SmramRanges + 1);
+
+  ASSERT (SmramRanges >= 1);
+  //
+  // Copy last entry to the end - we assume TSEG is last entry.
+  //
+  CopyMem (&NewDescriptorBlock->Descriptor[SmramRanges], &NewDescriptorBlock->Descriptor[SmramRanges - 1], sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  //
+  // Update the entry in the array with a size of SmmRelocationSize and put into the ALLOCATED state
+  //
+  NewDescriptorBlock->Descriptor[SmramRanges - 1].PhysicalSize = SmmRelocationSize;
+  NewDescriptorBlock->Descriptor[SmramRanges - 1].RegionState |= EFI_ALLOCATED;
+
+  //
+  // Return the start address of Smm relocated memory in SMRAM.
+  //
+  if (SmmRelocationStart != NULL) {
+    *SmmRelocationStart = NewDescriptorBlock->Descriptor[SmramRanges - 1].CpuStart;
+  }
+
+  //
+  // Reduce the size of the last SMRAM descriptor by SmmRelocationSize
+  //
+  NewDescriptorBlock->Descriptor[SmramRanges].PhysicalStart += SmmRelocationSize;
+  NewDescriptorBlock->Descriptor[SmramRanges].CpuStart      += SmmRelocationSize;
+  NewDescriptorBlock->Descriptor[SmramRanges].PhysicalSize  -= SmmRelocationSize;
+
+  //
+  // Last step, we can scrub old one
+  //
+  ZeroMem (&GuidHob->Name, sizeof (GuidHob->Name));
+
+  return EFI_SUCCESS;
+}
+
+/**
+  This function will create SmBase for all CPUs.
+
+  @param[in] SmBaseForAllCpus    Pointer to SmBase for all CPUs.
+
+  @retval EFI_SUCCESS           Create SmBase for all CPUs successfully.
+  @retval Others                Failed to create SmBase for all CPUs.
+
+**/
+EFI_STATUS
+CreateSmmBaseHob (
+  IN UINT64  *SmBaseForAllCpus
+  )
+{
+  UINTN              Index;
+  SMM_BASE_HOB_DATA  *SmmBaseHobData;
+  UINT32             CpuCount;
+  UINT32             NumberOfProcessorsInHob;
+  UINT32             MaxCapOfProcessorsInHob;
+  UINT32             HobCount;
+
+  SmmBaseHobData          = NULL;
+  CpuCount                = 0;
+  NumberOfProcessorsInHob = 0;
+  MaxCapOfProcessorsInHob = 0;
+  HobCount                = 0;
+
+  //
+  // Count the HOB instance maximum capacity of CPU (MaxCapOfProcessorsInHob) since the max HobLength is 0xFFF8.
+  //
+  MaxCapOfProcessorsInHob = (0xFFF8 - sizeof (EFI_HOB_GUID_TYPE) - sizeof (SMM_BASE_HOB_DATA)) / sizeof (UINT64) + 1;
+  DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - MaxCapOfProcessorsInHob: %03x\n", MaxCapOfProcessorsInHob));
+
+  //
+  // Create Guided SMM Base HOB Instances.
+  //
+  while (CpuCount != mMaxNumberOfCpus) {
+    NumberOfProcessorsInHob = MIN ((UINT32)mMaxNumberOfCpus - CpuCount, MaxCapOfProcessorsInHob);
+
+    SmmBaseHobData = BuildGuidHob (
+                       &gSmmBaseHobGuid,
+                       sizeof (SMM_BASE_HOB_DATA) + sizeof (UINT64) * NumberOfProcessorsInHob
+                       );
+    if (SmmBaseHobData == NULL) {
+      return EFI_OUT_OF_RESOURCES;
+    }
+
+    SmmBaseHobData->ProcessorIndex     = CpuCount;
+    SmmBaseHobData->NumberOfProcessors = NumberOfProcessorsInHob;
+
+    DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->ProcessorIndex: %03x\n", HobCount, SmmBaseHobData->ProcessorIndex));
+    DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->NumberOfProcessors: %03x\n", HobCount, SmmBaseHobData->NumberOfProcessors));
+    for (Index = 0; Index < SmmBaseHobData->NumberOfProcessors; Index++) {
+      //
+      // Calculate the new SMBASE address
+      //
+      SmmBaseHobData->SmBase[Index] = SmBaseForAllCpus[Index + CpuCount];
+      DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->SmBase[%03x]: %08x\n", HobCount, Index, SmmBaseHobData->SmBase[Index]));
+    }
+
+    CpuCount += NumberOfProcessorsInHob;
+    HobCount++;
+    SmmBaseHobData = NULL;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Relocate SmmBases for each processor.
+  Execute on first boot and all S3 resumes
+
+**/
+VOID
+SmmRelocateBases (
+  VOID
+  )
+{
+  UINT8                 BakBuf[BACK_BUF_SIZE];
+  SMRAM_SAVE_STATE_MAP  BakBuf2;
+  SMRAM_SAVE_STATE_MAP  *CpuStatePtr;
+  UINT8                 *U8Ptr;
+  UINTN                 Index;
+  UINTN                 BspIndex;
+  UINT32                BspApicId;
+
+  //
+  // Make sure the reserved size is large enough for procedure SmmInitTemplate.
+  //
+  ASSERT (sizeof (BakBuf) >= gcSmmInitSize);
+
+  //
+  // Patch ASM code template with current CR0, CR3, and CR4 values
+  //
+  PatchInstructionX86 (gPatchSmmCr0, AsmReadCr0 (), 4);
+  PatchInstructionX86 (gPatchSmmCr3, AsmReadCr3 (), 4);
+  PatchInstructionX86 (gPatchSmmCr4, AsmReadCr4 () & (~CR4_CET_ENABLE), 4);
+
+  U8Ptr       = (UINT8 *)(UINTN)(SMM_DEFAULT_SMBASE + SMM_HANDLER_OFFSET);
+  CpuStatePtr = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+
+  //
+  // Backup original contents at address 0x38000
+  //
+  CopyMem (BakBuf, U8Ptr, sizeof (BakBuf));
+  CopyMem (&BakBuf2, CpuStatePtr, sizeof (BakBuf2));
+
+  //
+  // Load image for relocation
+  //
+  CopyMem (U8Ptr, gcSmmInitTemplate, gcSmmInitSize);
+
+  //
+  // Retrieve the local APIC ID of current processor
+  //
+  BspApicId = GetApicId ();
+
+  //
+  // Relocate SM bases for all APs
+  // This is APs' 1st SMI - rebase will be done here, and APs' default SMI handler will be overridden by gcSmmInitTemplate
+  //
+  BspIndex = (UINTN)-1;
+  for (Index = 0; Index < mNumberOfCpus; Index++) {
+    mRebased[Index] = FALSE;
+    if (BspApicId != (UINT32)mProcessorInfo[Index].ProcessorId) {
+      SendSmiIpi ((UINT32)mProcessorInfo[Index].ProcessorId);
+      //
+      // Wait for this AP to finish its 1st SMI
+      //
+      while (!mRebased[Index]) {
+      }
+    } else {
+      //
+      // BSP will be Relocated later
+      //
+      BspIndex = Index;
+    }
+  }
+
+  //
+  // Relocate BSP's SMM base
+  //
+  ASSERT (BspIndex != (UINTN)-1);
+  SendSmiIpi (BspApicId);
+
+  //
+  // Wait for the BSP to finish its 1st SMI
+  //
+  while (!mRebased[BspIndex]) {
+  }
+
+  //
+  // Restore contents at address 0x38000
+  //
+  CopyMem (CpuStatePtr, &BakBuf2, sizeof (BakBuf2));
+  CopyMem (U8Ptr, BakBuf, sizeof (BakBuf));
+}
+
+/**
+  This function will initialize SmBase for all CPUs.
+
+  @param[in,out] SmBaseForAllCpus    Pointer to SmBase for all CPUs.
+
+  @retval EFI_SUCCESS           Initialize SmBase for all CPUs successfully.
+  @retval Others                Failed to initialize SmBase for all CPUs.
+
+**/
+EFI_STATUS
+InitSmBaseForAllCpus (
+  IN OUT UINT64  **SmBaseForAllCpus
+  )
+{
+  EFI_STATUS            Status;
+  UINTN                 TileSize;
+  UINT64                SmmRelocationSize;
+  EFI_PHYSICAL_ADDRESS  SmmRelocationStart;
+  UINTN                 Index;
+
+  SmmRelocationStart = 0;
+
+  ASSERT (SmBaseForAllCpus != NULL);
+
+  //
+  // Calculate SmmRelocationSize for all of the tiles.
+  //
+  // The CPU save state and code for the SMI entry point are tiled within an SMRAM
+  // allocated buffer. The minimum size of this buffer for a uniprocessor system
+  // is 32 KB, because the entry point is SMBASE + 32KB, and CPU save state area
+  // just below SMBASE + 64KB. If more than one CPU is present in the platform,
+  // then the SMI entry point and the CPU save state areas can be tiles to minimize
+  // the total amount SMRAM required for all the CPUs. The tile size can be computed
+  // by adding the CPU save state size, any extra CPU specific context, and
+  // the size of code that must be placed at the SMI entry point to transfer
+  // control to a C function in the native SMM execution mode. This size is
+  // rounded up to the nearest power of 2 to give the tile size for a each CPU.
+  // The total amount of memory required is the maximum number of CPUs that
+  // platform supports times the tile size.
+  //
+  TileSize          = SIZE_8KB;
+  SmmRelocationSize = EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (SIZE_32KB + TileSize * (mMaxNumberOfCpus - 1)));
+
+  //
+  // Split SmramReserve HOB to reserve SmmRelocationSize for Smm relocated memory
+  //
+  Status = SplitSmramHobForSmmRelocation (
+             SmmRelocationSize,
+             &SmmRelocationStart
+             );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  ASSERT (SmmRelocationStart != 0);
+  DEBUG ((DEBUG_INFO, "InitSmBaseForAllCpus - SmmRelocationSize: 0x%08x\n", SmmRelocationSize));
+  DEBUG ((DEBUG_INFO, "InitSmBaseForAllCpus - SmmRelocationStart: 0x%08x\n", SmmRelocationStart));
+
+  //
+  // Init SmBaseForAllCpus
+  //
+  *SmBaseForAllCpus = (UINT64 *)AllocatePages (EFI_SIZE_TO_PAGES (sizeof (UINT64) * mMaxNumberOfCpus));
+  if (*SmBaseForAllCpus == NULL) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
+    //
+    // Return each SmBase in SmBaseForAllCpus
+    //
+    (*SmBaseForAllCpus)[Index] = (UINTN)(SmmRelocationStart)+ Index * TileSize - SMM_HANDLER_OFFSET;
+    DEBUG ((DEBUG_INFO, "InitSmBaseForAllCpus - SmBase For CPU[%03x]: %08x\n", Index, (*SmBaseForAllCpus)[Index]));
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Initialize IDT to setup exception handlers in SMM.
+
+**/
+VOID
+InitSmmIdt (
+  VOID
+  )
+{
+  EFI_STATUS              Status;
+  BOOLEAN                 InterruptState;
+  IA32_DESCRIPTOR         PeiIdtr;
+  CONST EFI_PEI_SERVICES  **PeiServices;
+
+  //
+  // There are 32 (not 255) entries in it since only processor
+  // generated exceptions will be handled.
+  //
+  gcSmmInitIdtr.Limit = (sizeof (IA32_IDT_GATE_DESCRIPTOR) * 32) - 1;
+
+  //
+  // Allocate for IDT.
+  // sizeof (UINTN) is for the PEI Services Table pointer.
+  //
+  gcSmmInitIdtr.Base = (UINTN)AllocateZeroPool (gcSmmInitIdtr.Limit + 1 + sizeof (UINTN));
+  ASSERT (gcSmmInitIdtr.Base != 0);
+  gcSmmInitIdtr.Base += sizeof (UINTN);
+
+  //
+  // Disable Interrupt, save InterruptState and save PEI IDT table
+  //
+  InterruptState = SaveAndDisableInterrupts ();
+  AsmReadIdtr (&PeiIdtr);
+
+  //
+  // Save the PEI Services Table pointer
+  // The PEI Services Table pointer will be stored in the sizeof (UINTN) bytes
+  // immediately preceding the IDT in memory.
+  //
+  PeiServices                                       = (CONST EFI_PEI_SERVICES **)(*(UINTN *)(PeiIdtr.Base - sizeof (UINTN)));
+  (*(UINTN *)(gcSmmInitIdtr.Base - sizeof (UINTN))) = (UINTN)PeiServices;
+
+  //
+  // Load SMM temporary IDT table
+  //
+  AsmWriteIdtr (&gcSmmInitIdtr);
+
+  //
+  // Setup SMM default exception handlers, SMM IDT table
+  // will be updated and saved in gcSmmInitIdtr
+  //
+  Status = InitializeCpuExceptionHandlers (NULL);
+  ASSERT_EFI_ERROR (Status);
+
+  //
+  // Restore PEI IDT table and CPU InterruptState
+  //
+  AsmWriteIdtr ((IA32_DESCRIPTOR *)&PeiIdtr);
+  SetInterruptState (InterruptState);
+}
+
+/**
+  CPU SmmBase Relocation Init.
+
+  This function is to relocate CPU SmmBase.
+
+  @param[in] MpServices2        Pointer to this instance of the MpServices.
+
+  @retval EFI_SUCCESS           CPU SmmBase Relocated successfully.
+  @retval Others                CPU SmmBase Relocation failed.
+
+**/
+EFI_STATUS
+EFIAPI
+SmmRelocationInit (
+  IN EDKII_PEI_MP_SERVICES2_PPI  *MpServices2
+  )
+{
+  EFI_STATUS  Status;
+  UINTN       NumberOfEnabledCpus;
+  UINTN       SmmStackSize;
+  UINT8       *SmmStacks;
+  UINTN       Index;
+
+  SmmStacks = NULL;
+
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit Start \n"));
+  if (MpServices2 == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  //
+  // Fix up the address of the global variable or function referred in
+  // SmmInit assembly files to be the absolute address
+  //
+  SmmInitFixupAddress ();
+
+  //
+  // Patch SMI stack for SMM base relocation
+  // Note: No need allocate stack for all CPUs since the relocation
+  // occurs serially for each CPU
+  //
+  SmmStackSize = EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (PcdGet32 (PcdCpuSmmStackSize)));
+  SmmStacks    = (UINT8 *)AllocatePages (EFI_SIZE_TO_PAGES (SmmStackSize));
+  if (SmmStacks == NULL) {
+    Status = EFI_OUT_OF_RESOURCES;
+    goto ON_EXIT;
+  }
+
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit - SmmStacks: 0x%x\n", SmmStacks));
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit - SmmStackSize: 0x%x\n", SmmStackSize));
+
+  PatchInstructionX86 (
+    gPatchSmmInitStack,
+    (UINTN)(SmmStacks + SmmStackSize - sizeof (UINTN)),
+    sizeof (UINTN)
+    );
+
+  //
+  // Initialize the SMM IDT for SMM base relocation
+  //
+  InitSmmIdt ();
+
+  //
+  // Get the number of processors
+  //
+  Status = MpServices2->GetNumberOfProcessors (
+                          MpServices2,
+                          &mNumberOfCpus,
+                          &NumberOfEnabledCpus
+                          );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  if (FeaturePcdGet (PcdCpuHotPlugSupport)) {
+    mMaxNumberOfCpus = PcdGet32 (PcdCpuMaxLogicalProcessorNumber);
+  } else {
+    mMaxNumberOfCpus = mNumberOfCpus;
+  }
+
+  //
+  // Retrieve the Processor Info for all CPUs
+  //
+  mProcessorInfo = (EFI_PROCESSOR_INFORMATION *)AllocatePool (sizeof (EFI_PROCESSOR_INFORMATION) * mMaxNumberOfCpus);
+  if (mProcessorInfo == NULL) {
+    Status = EFI_OUT_OF_RESOURCES;
+    goto ON_EXIT;
+  }
+
+  for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
+    if (Index < mNumberOfCpus) {
+      Status = MpServices2->GetProcessorInfo (MpServices2, Index | CPU_V2_EXTENDED_TOPOLOGY, &mProcessorInfo[Index]);
+      if (EFI_ERROR (Status)) {
+        goto ON_EXIT;
+      }
+    }
+  }
+
+  //
+  // Initialize the SmBase for all CPUs
+  //
+  Status = InitSmBaseForAllCpus (&mSmBaseForAllCpus);
+  if (EFI_ERROR (Status)) {
+    goto ON_EXIT;
+  }
+
+  //
+  // Relocate SmmBases for each processor.
+  // Allocate mRebased as the flag to indicate the relocation is done for each CPU.
+  //
+  mRebased = (BOOLEAN *)AllocateZeroPool (sizeof (BOOLEAN) * mMaxNumberOfCpus);
+  if (mRebased == NULL) {
+    Status = EFI_OUT_OF_RESOURCES;
+    goto ON_EXIT;
+  }
+
+  SmmRelocateBases ();
+
+  //
+  // Create the SmBase HOB for all CPUs
+  //
+  Status = CreateSmmBaseHob (mSmBaseForAllCpus);
+
+ON_EXIT:
+  if (SmmStacks != NULL) {
+    FreePages (SmmStacks, EFI_SIZE_TO_PAGES (SmmStackSize));
+  }
+
+  if (mSmBaseForAllCpus != NULL) {
+    FreePages (mSmBaseForAllCpus, EFI_SIZE_TO_PAGES (sizeof (UINT64) * mMaxNumberOfCpus));
+  }
+
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit Done\n"));
+  return Status;
+}
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
new file mode 100644
index 0000000000..6581fa2dad
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
@@ -0,0 +1,62 @@
+## @file
+# SMM Relocation Lib for each processor.
+#
+# This Lib produces the SMM_BASE_HOB in HOB database which tells
+# the PiSmmCpuDxeSmm driver (runs at a later phase) about the new
+# SMBASE for each processor. PiSmmCpuDxeSmm driver installs the
+# SMI handler at the SMM_BASE_HOB.SmBase[Index]+0x8000 for processor
+# Index.
+#
+# Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 0x00010005
+  BASE_NAME                      = SmmRelocationLib
+  FILE_GUID                      = 853E97B3-790C-4EA3-945C-8F622FC47FE8
+  MODULE_TYPE                    = PEIM
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = SmmRelocationLib
+
+[Sources]
+  InternalSmmRelocationLib.h
+  SmramSaveStateConfig.c
+  SmmRelocationLib.c
+
+[Sources.Ia32]
+  Ia32/Semaphore.c
+  Ia32/SmmInit.nasm
+
+[Sources.X64]
+  X64/Semaphore.c
+  X64/SmmInit.nasm
+
+[Packages]
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
+  UefiCpuPkg/UefiCpuPkg.dec
+
+[LibraryClasses]
+  BaseLib
+  BaseMemoryLib
+  CpuExceptionHandlerLib
+  CpuLib
+  DebugLib
+  HobLib
+  LocalApicLib
+  MemoryAllocationLib
+  PcdLib
+  PeiServicesLib
+
+[Guids]
+  gSmmBaseHobGuid                               ## HOB ALWAYS_PRODUCED
+  gEfiSmmSmramMemoryGuid                        ## CONSUMES
+
+[Pcd]
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackSize                     ## CONSUMES
+
+[FeaturePcd]
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugSupport                        ## CONSUMES
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
new file mode 100644
index 0000000000..fb69b2b5c5
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
@@ -0,0 +1,139 @@
+/** @file
+  Config SMRAM Save State for SmmBases Relocation.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#include "InternalSmmRelocationLib.h"
+#include <Library/CpuLib.h>
+
+/**
+  Determine the mode of the CPU at the time an SMI occurs
+
+  @retval EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT   32 bit.
+  @retval EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT   64 bit.
+
+**/
+UINT8
+CheckMmSaveStateRegisterLma (
+  VOID
+  )
+{
+  CPUID_VERSION_INFO_EAX      RegEax;
+  CPUID_EXTENDED_CPU_SIG_EDX  RegEdx;
+  UINTN                       FamilyId;
+  UINTN                       ModelId;
+  UINT32                      Eax;
+  UINT8                       SmmSaveStateRegisterLma;
+
+  //
+  // Determine the mode of the CPU at the time an SMI occurs
+  //   Intel(R) 64 and IA-32 Architectures Software Developer's Manual
+  //   Volume 3C, Section 34.4.1.1
+  //
+  RegEax.Uint32 = GetCpuFamilyModel ();
+  FamilyId      = RegEax.Bits.FamilyId;
+  ModelId       = RegEax.Bits.Model;
+  if ((FamilyId == 0x06) || (FamilyId == 0x0f)) {
+    ModelId = ModelId | RegEax.Bits.ExtendedModelId << 4;
+  }
+
+  RegEdx.Uint32 = 0;
+  AsmCpuid (CPUID_EXTENDED_FUNCTION, &Eax, NULL, NULL, NULL);
+  if (Eax >= CPUID_EXTENDED_CPU_SIG) {
+    AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &(RegEdx.Uint32));
+  }
+
+  SmmSaveStateRegisterLma = EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT;
+  if (RegEdx.Bits.LM) {
+    SmmSaveStateRegisterLma = EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT;
+  }
+
+  if (FamilyId == 0x06) {
+    if ((ModelId == 0x17) || (ModelId == 0x0f) || (ModelId == 0x1c)) {
+      SmmSaveStateRegisterLma = EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT;
+    }
+  }
+
+  return SmmSaveStateRegisterLma;
+}
+
+/**
+  This function configures the SmBase on the currently executing CPU.
+
+  @param[in]     CpuIndex             The index of the CPU.
+  @param[in,out] CpuState             Pointer to SMRAM Save State Map for the
+                                      currently executing CPU. On out, SmBase is
+                                      updated to the new value.
+
+**/
+VOID
+EFIAPI
+ConfigureSmBase (
+  IN     UINTN                 CpuIndex,
+  IN OUT SMRAM_SAVE_STATE_MAP  *CpuState
+  )
+{
+  CpuState->x86.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
+}
+
+/**
+  Hook the code executed immediately after an RSM instruction on the currently
+  executing CPU.  The mode of code executed immediately after RSM must be
+  detected, and the appropriate hook must be selected.  Always clear the auto
+  HALT restart flag if it is set.
+
+  @param[in]     CpuIndex                 The processor index for the currently
+                                          executing CPU.
+  @param[in,out] CpuState                 Pointer to SMRAM Save State Map for the
+                                          currently executing CPU.
+  @param[in]     NewInstructionPointer32  Instruction pointer to use if resuming to
+                                          32-bit mode from 64-bit SMM.
+  @param[in]     NewInstructionPointer    Instruction pointer to use if resuming to
+                                          same mode as SMM.
+
+  @retval The value of the original instruction pointer before it was hooked.
+
+**/
+UINT64
+EFIAPI
+HookReturnFromSmm (
+  IN     UINTN                 CpuIndex,
+  IN OUT SMRAM_SAVE_STATE_MAP  *CpuState,
+  IN     UINT64                NewInstructionPointer32,
+  IN     UINT64                NewInstructionPointer
+  )
+{
+  UINT64  OriginalInstructionPointer;
+
+  if (CheckMmSaveStateRegisterLma () == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
+    OriginalInstructionPointer = (UINT64)CpuState->x86._EIP;
+    CpuState->x86._EIP         = (UINT32)NewInstructionPointer;
+
+    //
+    // Clear the auto HALT restart flag so the RSM instruction returns
+    // program control to the instruction following the HLT instruction.
+    //
+    if ((CpuState->x86.AutoHALTRestart & BIT0) != 0) {
+      CpuState->x86.AutoHALTRestart &= ~BIT0;
+    }
+  } else {
+    OriginalInstructionPointer = CpuState->x64._RIP;
+    if ((CpuState->x64.IA32_EFER & LMA) == 0) {
+      CpuState->x64._RIP = (UINT32)NewInstructionPointer32;
+    } else {
+      CpuState->x64._RIP = (UINT32)NewInstructionPointer;
+    }
+
+    //
+    // Clear the auto HALT restart flag so the RSM instruction returns
+    // program control to the instruction following the HLT instruction.
+    //
+    if ((CpuState->x64.AutoHALTRestart & BIT0) != 0) {
+      CpuState->x64.AutoHALTRestart &= ~BIT0;
+    }
+  }
+
+  return OriginalInstructionPointer;
+}
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
similarity index 78%
copy from UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c
copy to UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
index dafbc3390e..54d3462ef8 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
@@ -1,15 +1,15 @@
 /** @file
-Semaphore mechanism to indicate to the BSP that an AP has exited SMM
-after SMBASE relocation.
+  Semaphore mechanism to indicate to the BSP that an AP has exited SMM
+  after SMBASE relocation.
 
-Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>
-SPDX-License-Identifier: BSD-2-Clause-Patent
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 
-#include "PiSmmCpuDxeSmm.h"
+#include "InternalSmmRelocationLib.h"
 
 X86_ASSEMBLY_PATCH_LABEL  gPatchSmmRelocationOriginalAddressPtr32;
 X86_ASSEMBLY_PATCH_LABEL  gPatchRebasedFlagAddr32;
 
 UINTN             mSmmRelocationOriginalAddress;
@@ -47,11 +47,12 @@ SemaphoreHook (
     gPatchRebasedFlagAddr32,
     (UINT32)(UINTN)mRebasedFlag,
     4
     );
 
-  CpuState                      = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+  CpuState = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+
   mSmmRelocationOriginalAddress = HookReturnFromSmm (
                                     CpuIndex,
                                     CpuState,
                                     (UINT64)(UINTN)&SmmRelocationSemaphoreComplete32,
                                     (UINT64)(UINTN)&SmmRelocationSemaphoreComplete
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
similarity index 59%
copy from UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm
copy to UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
index 9cf3a6dcf9..355f59a21f 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
@@ -1,7 +1,7 @@
 ;------------------------------------------------------------------------------ ;
-; Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR>
+; Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
 ; SPDX-License-Identifier: BSD-2-Clause-Patent
 ;
 ; Module Name:
 ;
 ;   SmmInit.nasm
@@ -12,55 +12,109 @@
 ;
 ;-------------------------------------------------------------------------------
 
 %include "StuffRsbNasm.inc"
 
+global  ASM_PFX(gcSmmInitIdtr)
+global  ASM_PFX(gcSmmInitGdtr)
+
 extern ASM_PFX(SmmInitHandler)
 extern ASM_PFX(mRebasedFlag)
 extern ASM_PFX(mSmmRelocationOriginalAddress)
 
 global ASM_PFX(gPatchSmmCr3)
 global ASM_PFX(gPatchSmmCr4)
 global ASM_PFX(gPatchSmmCr0)
 global ASM_PFX(gPatchSmmInitStack)
-global ASM_PFX(gcSmiInitGdtr)
 global ASM_PFX(gcSmmInitSize)
 global ASM_PFX(gcSmmInitTemplate)
 global ASM_PFX(gPatchRebasedFlagAddr32)
 global ASM_PFX(gPatchSmmRelocationOriginalAddressPtr32)
 
 %define LONG_MODE_CS 0x38
 
+    SECTION .data
+
+NullSeg: DQ 0                   ; reserved by architecture
+CodeSeg32:
+            DW      -1                  ; LimitLow
+            DW      0                   ; BaseLow
+            DB      0                   ; BaseMid
+            DB      0x9b
+            DB      0xcf                ; LimitHigh
+            DB      0                   ; BaseHigh
+ProtModeCodeSeg32:
+            DW      -1                  ; LimitLow
+            DW      0                   ; BaseLow
+            DB      0                   ; BaseMid
+            DB      0x9b
+            DB      0xcf                ; LimitHigh
+            DB      0                   ; BaseHigh
+ProtModeSsSeg32:
+            DW      -1                  ; LimitLow
+            DW      0                   ; BaseLow
+            DB      0                   ; BaseMid
+            DB      0x93
+            DB      0xcf                ; LimitHigh
+            DB      0                   ; BaseHigh
+DataSeg32:
+            DW      -1                  ; LimitLow
+            DW      0                   ; BaseLow
+            DB      0                   ; BaseMid
+            DB      0x93
+            DB      0xcf                ; LimitHigh
+            DB      0                   ; BaseHigh
+CodeSeg16:
+            DW      -1
+            DW      0
+            DB      0
+            DB      0x9b
+            DB      0x8f
+            DB      0
+DataSeg16:
+            DW      -1
+            DW      0
+            DB      0
+            DB      0x93
+            DB      0x8f
+            DB      0
+CodeSeg64:
+            DW      -1                  ; LimitLow
+            DW      0                   ; BaseLow
+            DB      0                   ; BaseMid
+            DB      0x9b
+            DB      0xaf                ; LimitHigh
+            DB      0                   ; BaseHigh
+GDT_SIZE equ $ -   NullSeg
+
+ASM_PFX(gcSmmInitGdtr):
+    DW      GDT_SIZE - 1
+    DQ      NullSeg
+
+ASM_PFX(gcSmmInitIdtr):
+    DW      0
+    DQ      0
+
+
     DEFAULT REL
     SECTION .text
 
-ASM_PFX(gcSmiInitGdtr):
-            DW      0
-            DQ      0
-
 global ASM_PFX(SmmStartup)
 
 BITS 16
 ASM_PFX(SmmStartup):
-    mov     eax, 0x80000001             ; read capability
-    cpuid
-    mov     ebx, edx                    ; rdmsr will change edx. keep it in ebx.
     mov     eax, strict dword 0         ; source operand will be patched
 ASM_PFX(gPatchSmmCr3):
     mov     cr3, eax
-o32 lgdt    [cs:ebp + (ASM_PFX(gcSmiInitGdtr) - ASM_PFX(SmmStartup))]
+o32 lgdt    [cs:ebp + (ASM_PFX(gcSmmInitGdtr) - ASM_PFX(SmmStartup))]
     mov     eax, strict dword 0         ; source operand will be patched
 ASM_PFX(gPatchSmmCr4):
     or      ah,  2                      ; enable XMM registers access
     mov     cr4, eax
     mov     ecx, 0xc0000080             ; IA32_EFER MSR
     rdmsr
     or      ah, BIT0                    ; set LME bit
-    test    ebx, BIT20                  ; check NXE capability
-    jz      .1
-    or      ah, BIT3                    ; set NXE bit
-.1:
     wrmsr
     mov     eax, strict dword 0         ; source operand will be patched
 ASM_PFX(gPatchSmmCr0):
     mov     cr0, eax                    ; enable protected mode & paging
     jmp     LONG_MODE_CS : dword 0      ; offset will be patched to @LongMode
@@ -132,12 +186,12 @@ ASM_PFX(gPatchRebasedFlagAddr32):
     pop     eax
     jmp     dword [dword 0]                    ; destination will be patched
 ASM_PFX(gPatchSmmRelocationOriginalAddressPtr32):
 
 BITS 64
-global ASM_PFX(PiSmmCpuSmmInitFixupAddress)
-ASM_PFX(PiSmmCpuSmmInitFixupAddress):
+global ASM_PFX(SmmInitFixupAddress)
+ASM_PFX(SmmInitFixupAddress):
     lea    rax, [@LongMode]
     lea    rcx, [@PatchLongModeOffset - 6]
     mov    dword [rcx], eax
 
     lea    rax, [ASM_PFX(SmmStartup)]
diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc
index 10b33594e5..dd2ad398c0 100644
--- a/UefiCpuPkg/UefiCpuPkg.dsc
+++ b/UefiCpuPkg/UefiCpuPkg.dsc
@@ -194,10 +194,11 @@
       UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf
   }
   UefiCpuPkg/Library/MmSaveStateLib/AmdMmSaveStateLib.inf
   UefiCpuPkg/Library/MmSaveStateLib/IntelMmSaveStateLib.inf
   UefiCpuPkg/Library/SmmCpuFeaturesLib/AmdSmmCpuFeaturesLib.inf
+  UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 
 [Components.X64]
   UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf
 
 [Components.RISCV64]
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117777): https://edk2.groups.io/g/devel/message/117777
Mute This Topic: https://groups.io/mt/105535806/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 19+ messages in thread

* [edk2-devel] [PATCH v2 03/10] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD
  2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 01/10] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 02/10] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance Wu, Jiaxin
@ 2024-04-15 13:30 ` Wu, Jiaxin
  2024-04-16  3:27   ` Ni, Ray
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 04/10] OvmfPkg/SmmRelocationLib: Add library instance for OVMF Wu, Jiaxin
                   ` (7 subsequent siblings)
  10 siblings, 1 reply; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:30 UTC (permalink / raw)
  To: devel
  Cc: Abdul Lateef Attar, Abner Chang, Tom Lendacky, Ray Ni, Zeng Star,
	Gerd Hoffmann, Rahul Kumar

Due to the definition difference of SMRAM Save State,
SmmBase config in SMRAM Save State for AMD is also different.

This patch provides the AmdSmmRelocationLib library instance
to handle the SMRAM Save State difference.

Cc: Abdul Lateef Attar <AbdulLateef.Attar@amd.com>
Cc: Abner Chang <abner.chang@amd.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Zeng Star <star.zeng@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 ...mmRelocationLib.inf => AmdSmmRelocationLib.inf} |  5 +-
 ...SaveStateConfig.c => AmdSmramSaveStateConfig.c} | 93 ++++++++++------------
 UefiCpuPkg/UefiCpuPkg.dsc                          |  1 +
 3 files changed, 46 insertions(+), 53 deletions(-)
 copy UefiCpuPkg/Library/SmmRelocationLib/{SmmRelocationLib.inf => AmdSmmRelocationLib.inf} (89%)
 copy UefiCpuPkg/Library/SmmRelocationLib/{SmramSaveStateConfig.c => AmdSmramSaveStateConfig.c} (50%)

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
similarity index 89%
copy from UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
copy to UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
index 6581fa2dad..710cd1948b 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
+++ b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
@@ -13,18 +13,18 @@
 ##
 
 [Defines]
   INF_VERSION                    = 0x00010005
   BASE_NAME                      = SmmRelocationLib
-  FILE_GUID                      = 853E97B3-790C-4EA3-945C-8F622FC47FE8
+  FILE_GUID                      = 65C74DCD-0D09-494A-8BFF-A64226EB8054
   MODULE_TYPE                    = PEIM
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = SmmRelocationLib
 
 [Sources]
   InternalSmmRelocationLib.h
-  SmramSaveStateConfig.c
+  AmdSmramSaveStateConfig.c
   SmmRelocationLib.c
 
 [Sources.Ia32]
   Ia32/Semaphore.c
   Ia32/SmmInit.nasm
@@ -40,11 +40,10 @@
 
 [LibraryClasses]
   BaseLib
   BaseMemoryLib
   CpuExceptionHandlerLib
-  CpuLib
   DebugLib
   HobLib
   LocalApicLib
   MemoryAllocationLib
   PcdLib
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
similarity index 50%
copy from UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
copy to UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
index fb69b2b5c5..95a1ce8d46 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
@@ -1,14 +1,17 @@
 /** @file
   Config SMRAM Save State for SmmBases Relocation.
 
+  Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.<BR>
   Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
   SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 #include "InternalSmmRelocationLib.h"
-#include <Library/CpuLib.h>
+#include <Register/Amd/SmramSaveStateMap.h>
+
+#define EFER_ADDRESS  0XC0000080ul
 
 /**
   Determine the mode of the CPU at the time an SMI occurs
 
   @retval EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT   32 bit.
@@ -18,44 +21,18 @@
 UINT8
 CheckMmSaveStateRegisterLma (
   VOID
   )
 {
-  CPUID_VERSION_INFO_EAX      RegEax;
-  CPUID_EXTENDED_CPU_SIG_EDX  RegEdx;
-  UINTN                       FamilyId;
-  UINTN                       ModelId;
-  UINT32                      Eax;
-  UINT8                       SmmSaveStateRegisterLma;
-
-  //
-  // Determine the mode of the CPU at the time an SMI occurs
-  //   Intel(R) 64 and IA-32 Architectures Software Developer's Manual
-  //   Volume 3C, Section 34.4.1.1
-  //
-  RegEax.Uint32 = GetCpuFamilyModel ();
-  FamilyId      = RegEax.Bits.FamilyId;
-  ModelId       = RegEax.Bits.Model;
-  if ((FamilyId == 0x06) || (FamilyId == 0x0f)) {
-    ModelId = ModelId | RegEax.Bits.ExtendedModelId << 4;
-  }
+  UINT8   SmmSaveStateRegisterLma;
+  UINT32  LMAValue;
 
-  RegEdx.Uint32 = 0;
-  AsmCpuid (CPUID_EXTENDED_FUNCTION, &Eax, NULL, NULL, NULL);
-  if (Eax >= CPUID_EXTENDED_CPU_SIG) {
-    AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &(RegEdx.Uint32));
-  }
-
-  SmmSaveStateRegisterLma = EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT;
-  if (RegEdx.Bits.LM) {
-    SmmSaveStateRegisterLma = EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT;
-  }
+  SmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_32BIT;
 
-  if (FamilyId == 0x06) {
-    if ((ModelId == 0x17) || (ModelId == 0x0f) || (ModelId == 0x1c)) {
-      SmmSaveStateRegisterLma = EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT;
-    }
+  LMAValue = (UINT32)AsmReadMsr64 (EFER_ADDRESS) & LMA;
+  if (LMAValue) {
+    SmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT;
   }
 
   return SmmSaveStateRegisterLma;
 }
 
@@ -73,18 +50,32 @@ EFIAPI
 ConfigureSmBase (
   IN     UINTN                 CpuIndex,
   IN OUT SMRAM_SAVE_STATE_MAP  *CpuState
   )
 {
-  CpuState->x86.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
+  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;
+
+  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
+
+  AmdCpuState->x64.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
 }
 
 /**
-  Hook the code executed immediately after an RSM instruction on the currently
-  executing CPU.  The mode of code executed immediately after RSM must be
-  detected, and the appropriate hook must be selected.  Always clear the auto
-  HALT restart flag if it is set.
+  This function updates the SMRAM save state on the currently executing CPU
+  to resume execution at a specific address after an RSM instruction.  This
+  function must evaluate the SMRAM save state to determine the execution mode
+  the RSM instruction resumes and update the resume execution address with
+  either NewInstructionPointer32 or NewInstructionPoint.  The auto HALT restart
+  flag in the SMRAM save state must always be cleared.  This function returns
+  the value of the instruction pointer from the SMRAM save state that was
+  replaced.  If this function returns 0, then the SMRAM save state was not
+  modified.
+
+  This function is called during the very first SMI on each CPU after
+  SmmCpuFeaturesInitializeProcessor() to set a flag in normal execution mode
+  to signal that the SMBASE of each CPU has been updated before the default
+  SMBASE address is used for the first SMI to the next CPU.
 
   @param[in]     CpuIndex                 The processor index for the currently
                                           executing CPU.
   @param[in,out] CpuState                 Pointer to SMRAM Save State Map for the
                                           currently executing CPU.
@@ -103,37 +94,39 @@ HookReturnFromSmm (
   IN OUT SMRAM_SAVE_STATE_MAP  *CpuState,
   IN     UINT64                NewInstructionPointer32,
   IN     UINT64                NewInstructionPointer
   )
 {
-  UINT64  OriginalInstructionPointer;
+  UINT64                    OriginalInstructionPointer;
+  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;
 
-  if (CheckMmSaveStateRegisterLma () == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
-    OriginalInstructionPointer = (UINT64)CpuState->x86._EIP;
-    CpuState->x86._EIP         = (UINT32)NewInstructionPointer;
+  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
 
+  if (CheckMmSaveStateRegisterLma () == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
+    OriginalInstructionPointer = (UINT64)AmdCpuState->x86._EIP;
+    AmdCpuState->x86._EIP      = (UINT32)NewInstructionPointer;
     //
     // Clear the auto HALT restart flag so the RSM instruction returns
     // program control to the instruction following the HLT instruction.
     //
-    if ((CpuState->x86.AutoHALTRestart & BIT0) != 0) {
-      CpuState->x86.AutoHALTRestart &= ~BIT0;
+    if ((AmdCpuState->x86.AutoHALTRestart & BIT0) != 0) {
+      AmdCpuState->x86.AutoHALTRestart &= ~BIT0;
     }
   } else {
-    OriginalInstructionPointer = CpuState->x64._RIP;
-    if ((CpuState->x64.IA32_EFER & LMA) == 0) {
-      CpuState->x64._RIP = (UINT32)NewInstructionPointer32;
+    OriginalInstructionPointer = AmdCpuState->x64._RIP;
+    if ((AmdCpuState->x64.EFER & LMA) == 0) {
+      AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer32;
     } else {
-      CpuState->x64._RIP = (UINT32)NewInstructionPointer;
+      AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer;
     }
 
     //
     // Clear the auto HALT restart flag so the RSM instruction returns
     // program control to the instruction following the HLT instruction.
     //
-    if ((CpuState->x64.AutoHALTRestart & BIT0) != 0) {
-      CpuState->x64.AutoHALTRestart &= ~BIT0;
+    if ((AmdCpuState->x64.AutoHALTRestart & BIT0) != 0) {
+      AmdCpuState->x64.AutoHALTRestart &= ~BIT0;
     }
   }
 
   return OriginalInstructionPointer;
 }
diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc
index dd2ad398c0..0c5fdcffde 100644
--- a/UefiCpuPkg/UefiCpuPkg.dsc
+++ b/UefiCpuPkg/UefiCpuPkg.dsc
@@ -195,10 +195,11 @@
   }
   UefiCpuPkg/Library/MmSaveStateLib/AmdMmSaveStateLib.inf
   UefiCpuPkg/Library/MmSaveStateLib/IntelMmSaveStateLib.inf
   UefiCpuPkg/Library/SmmCpuFeaturesLib/AmdSmmCpuFeaturesLib.inf
   UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
+  UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
 
 [Components.X64]
   UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf
 
 [Components.RISCV64]
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117778): https://edk2.groups.io/g/devel/message/117778
Mute This Topic: https://groups.io/mt/105535807/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 19+ messages in thread

* [edk2-devel] [PATCH v2 04/10] OvmfPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
                   ` (2 preceding siblings ...)
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 03/10] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD Wu, Jiaxin
@ 2024-04-15 13:30 ` Wu, Jiaxin
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 05/10] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid Wu, Jiaxin
                   ` (6 subsequent siblings)
  10 siblings, 0 replies; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:30 UTC (permalink / raw)
  To: devel
  Cc: Ray Ni, Zeng Star, Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann,
	Rahul Kumar

There are below 2 differences between AMD & OVMF according
existing implementation:
1.The mode of the CPU check is different between the AMD & OVMF.
OVMF:
CpuSaveState->x86.SMMRevId & 0Xffff

AMD:
 LMAValue = (UINT32)AsmReadMsr64 (EFER_ADDRESS) & LMA

2.Existing SmBase configuration is different between the
AMD & OVMF.
OVMF:
 AmdCpuState->x64.SMBASE = mSmBaseForAllCpus[CpuIndex];

AMD:
 if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
   CpuSaveState->x86.SMBASE = mSmBaseForAllCpus[CpuIndex];
 } else {
   CpuSaveState->x64.SMBASE = mSmBaseForAllCpus[CpuIndex];
 }

This patch provides the SmmRelocationLib library instance
for OVMF to handle the logic difference, and it won't change
the existing implementation code logic.

Cc: Ray Ni <ray.ni@intel.com>
Cc: Zeng Star <star.zeng@intel.com>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 OvmfPkg/AmdSev/AmdSevX64.dsc                       |  3 +
 OvmfPkg/CloudHv/CloudHvX64.dsc                     |  2 +
 .../Library/SmmRelocationLib/Ia32/Semaphore.c      |  0
 .../Library/SmmRelocationLib/Ia32/SmmInit.nasm     |  0
 .../SmmRelocationLib/InternalSmmRelocationLib.h    |  0
 .../Library/SmmRelocationLib/SmmRelocationLib.c    |  0
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  3 +-
 .../SmmRelocationLib/SmramSaveStateConfig.c        | 65 +++++++---------------
 .../Library/SmmRelocationLib/X64/Semaphore.c       |  0
 .../Library/SmmRelocationLib/X64/SmmInit.nasm      |  0
 OvmfPkg/Microvm/MicrovmX64.dsc                     |  3 +
 OvmfPkg/OvmfPkgIa32.dsc                            |  2 +
 OvmfPkg/OvmfPkgIa32X64.dsc                         |  2 +
 OvmfPkg/OvmfPkgX64.dsc                             |  1 +
 14 files changed, 34 insertions(+), 47 deletions(-)
 copy {UefiCpuPkg => OvmfPkg}/Library/SmmRelocationLib/Ia32/Semaphore.c (100%)
 copy {UefiCpuPkg => OvmfPkg}/Library/SmmRelocationLib/Ia32/SmmInit.nasm (100%)
 copy {UefiCpuPkg => OvmfPkg}/Library/SmmRelocationLib/InternalSmmRelocationLib.h (100%)
 copy {UefiCpuPkg => OvmfPkg}/Library/SmmRelocationLib/SmmRelocationLib.c (100%)
 copy {UefiCpuPkg => OvmfPkg}/Library/SmmRelocationLib/SmmRelocationLib.inf (91%)
 copy UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c => OvmfPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c (64%)
 copy {UefiCpuPkg => OvmfPkg}/Library/SmmRelocationLib/X64/Semaphore.c (100%)
 copy {UefiCpuPkg => OvmfPkg}/Library/SmmRelocationLib/X64/SmmInit.nasm (100%)

diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc
index 60e916b4fd..f844268cd8 100644
--- a/OvmfPkg/AmdSev/AmdSevX64.dsc
+++ b/OvmfPkg/AmdSev/AmdSevX64.dsc
@@ -170,10 +170,13 @@
   BlobVerifierLib|OvmfPkg/AmdSev/BlobVerifierLibSevHashes/BlobVerifierLibSevHashes.inf
   MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
   PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf
   DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf
   ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
+!if $(SMM_REQUIRE) == TRUE
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
+!endif
 
 !if $(SOURCE_DEBUG_ENABLE) == TRUE
   PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
   DebugCommunicationLib|SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf
 !else
diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc
index b522fa1059..918c3dff19 100644
--- a/OvmfPkg/CloudHv/CloudHvX64.dsc
+++ b/OvmfPkg/CloudHv/CloudHvX64.dsc
@@ -183,10 +183,12 @@
   PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf
   DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf
   ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 !if $(SMM_REQUIRE) == FALSE
   LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
+!else
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 !endif
   CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
   FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
   MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
 
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c b/OvmfPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
copy to OvmfPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm b/OvmfPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
copy to OvmfPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h b/OvmfPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
copy to OvmfPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c b/OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.c
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
copy to OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.c
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf b/OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
similarity index 91%
copy from UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
copy to OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
index 6581fa2dad..5ed0f5e93c 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
+++ b/OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
@@ -13,11 +13,11 @@
 ##
 
 [Defines]
   INF_VERSION                    = 0x00010005
   BASE_NAME                      = SmmRelocationLib
-  FILE_GUID                      = 853E97B3-790C-4EA3-945C-8F622FC47FE8
+  FILE_GUID                      = 51834F51-CCE0-4743-B553-935D0C8A53FF
   MODULE_TYPE                    = PEIM
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = SmmRelocationLib
 
 [Sources]
@@ -40,11 +40,10 @@
 
 [LibraryClasses]
   BaseLib
   BaseMemoryLib
   CpuExceptionHandlerLib
-  CpuLib
   DebugLib
   HobLib
   LocalApicLib
   MemoryAllocationLib
   PcdLib
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c b/OvmfPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
similarity index 64%
copy from UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
copy to OvmfPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
index 95a1ce8d46..505b1d694a 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
+++ b/OvmfPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
@@ -1,43 +1,15 @@
 /** @file
   Config SMRAM Save State for SmmBases Relocation.
 
-  Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.<BR>
   Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
   SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 #include "InternalSmmRelocationLib.h"
 #include <Register/Amd/SmramSaveStateMap.h>
 
-#define EFER_ADDRESS  0XC0000080ul
-
-/**
-  Determine the mode of the CPU at the time an SMI occurs
-
-  @retval EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT   32 bit.
-  @retval EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT   64 bit.
-
-**/
-UINT8
-CheckMmSaveStateRegisterLma (
-  VOID
-  )
-{
-  UINT8   SmmSaveStateRegisterLma;
-  UINT32  LMAValue;
-
-  SmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_32BIT;
-
-  LMAValue = (UINT32)AsmReadMsr64 (EFER_ADDRESS) & LMA;
-  if (LMAValue) {
-    SmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT;
-  }
-
-  return SmmSaveStateRegisterLma;
-}
-
 /**
   This function configures the SmBase on the currently executing CPU.
 
   @param[in]     CpuIndex             The index of the CPU.
   @param[in,out] CpuState             Pointer to SMRAM Save State Map for the
@@ -50,15 +22,19 @@ EFIAPI
 ConfigureSmBase (
   IN     UINTN                 CpuIndex,
   IN OUT SMRAM_SAVE_STATE_MAP  *CpuState
   )
 {
-  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;
+  AMD_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
 
-  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
+  CpuSaveState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
 
-  AmdCpuState->x64.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
+  if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
+    CpuSaveState->x86.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
+  } else {
+    CpuSaveState->x64.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
+  }
 }
 
 /**
   This function updates the SMRAM save state on the currently executing CPU
   to resume execution at a specific address after an RSM instruction.  This
@@ -95,38 +71,37 @@ HookReturnFromSmm (
   IN     UINT64                NewInstructionPointer32,
   IN     UINT64                NewInstructionPointer
   )
 {
   UINT64                    OriginalInstructionPointer;
-  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;
-
-  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
+  AMD_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
 
-  if (CheckMmSaveStateRegisterLma () == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
-    OriginalInstructionPointer = (UINT64)AmdCpuState->x86._EIP;
-    AmdCpuState->x86._EIP      = (UINT32)NewInstructionPointer;
+  CpuSaveState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
+  if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
+    OriginalInstructionPointer = (UINT64)CpuSaveState->x86._EIP;
+    CpuSaveState->x86._EIP     = (UINT32)NewInstructionPointer;
     //
     // Clear the auto HALT restart flag so the RSM instruction returns
     // program control to the instruction following the HLT instruction.
     //
-    if ((AmdCpuState->x86.AutoHALTRestart & BIT0) != 0) {
-      AmdCpuState->x86.AutoHALTRestart &= ~BIT0;
+    if ((CpuSaveState->x86.AutoHALTRestart & BIT0) != 0) {
+      CpuSaveState->x86.AutoHALTRestart &= ~BIT0;
     }
   } else {
-    OriginalInstructionPointer = AmdCpuState->x64._RIP;
-    if ((AmdCpuState->x64.EFER & LMA) == 0) {
-      AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer32;
+    OriginalInstructionPointer = CpuSaveState->x64._RIP;
+    if ((CpuSaveState->x64.EFER & LMA) == 0) {
+      CpuSaveState->x64._RIP = (UINT32)NewInstructionPointer32;
     } else {
-      AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer;
+      CpuSaveState->x64._RIP = (UINT32)NewInstructionPointer;
     }
 
     //
     // Clear the auto HALT restart flag so the RSM instruction returns
     // program control to the instruction following the HLT instruction.
     //
-    if ((AmdCpuState->x64.AutoHALTRestart & BIT0) != 0) {
-      AmdCpuState->x64.AutoHALTRestart &= ~BIT0;
+    if ((CpuSaveState->x64.AutoHALTRestart & BIT0) != 0) {
+      CpuSaveState->x64.AutoHALTRestart &= ~BIT0;
     }
   }
 
   return OriginalInstructionPointer;
 }
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c b/OvmfPkg/Library/SmmRelocationLib/X64/Semaphore.c
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
copy to OvmfPkg/Library/SmmRelocationLib/X64/Semaphore.c
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm b/OvmfPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
copy to OvmfPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc
index 2c6bb83beb..91d64cb3f8 100644
--- a/OvmfPkg/Microvm/MicrovmX64.dsc
+++ b/OvmfPkg/Microvm/MicrovmX64.dsc
@@ -189,10 +189,13 @@
   FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
   MemEncryptTdxLib|OvmfPkg/Library/BaseMemEncryptTdxLib/BaseMemEncryptTdxLib.inf
   PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf
   DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf
   ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
+!if $(SMM_REQUIRE) == TRUE
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
+!endif
 
 !if $(SOURCE_DEBUG_ENABLE) == TRUE
   PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
   DebugCommunicationLib|SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf
 !else
diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
index 713f08764b..5cee69f6b5 100644
--- a/OvmfPkg/OvmfPkgIa32.dsc
+++ b/OvmfPkg/OvmfPkgIa32.dsc
@@ -188,10 +188,12 @@
   PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf
   DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf
   ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 !if $(SMM_REQUIRE) == FALSE
   LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
+!else
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 !endif
   CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
   FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
 
 !if $(SOURCE_DEBUG_ENABLE) == TRUE
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index 90b15dc270..b4e1b5d1f7 100644
--- a/OvmfPkg/OvmfPkgIa32X64.dsc
+++ b/OvmfPkg/OvmfPkgIa32X64.dsc
@@ -193,10 +193,12 @@
   PeiHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/PeiHardwareInfoLib.inf
   DxeHardwareInfoLib|OvmfPkg/Library/HardwareInfoLib/DxeHardwareInfoLib.inf
   ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
 !if $(SMM_REQUIRE) == FALSE
   LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
+!else
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 !endif
   CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
   FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
 
 !if $(SOURCE_DEBUG_ENABLE) == TRUE
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index 56c920168d..38df57264f 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -209,10 +209,11 @@
 !if $(SMM_REQUIRE) == FALSE
   LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
   CcProbeLib|OvmfPkg/Library/CcProbeLib/DxeCcProbeLib.inf
 !else
   CcProbeLib|MdePkg/Library/CcProbeLibNull/CcProbeLibNull.inf
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 !endif
   CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
   FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf
 
 !if $(SOURCE_DEBUG_ENABLE) == TRUE
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117779): https://edk2.groups.io/g/devel/message/117779
Mute This Topic: https://groups.io/mt/105535808/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 19+ messages in thread

* [edk2-devel] [PATCH v2 05/10] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
                   ` (3 preceding siblings ...)
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 04/10] OvmfPkg/SmmRelocationLib: Add library instance for OVMF Wu, Jiaxin
@ 2024-04-15 13:30 ` Wu, Jiaxin
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 06/10] OvmfPkg: Refine SmmAccess implementation Wu, Jiaxin
                   ` (5 subsequent siblings)
  10 siblings, 0 replies; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:30 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann, Ray Ni

Background:
In the PiSmmCpuDxeSmm driver, SMRAM allocation for SMI
handlers and processor Save State areas was traditionally
performed using the Smst->AllocatePages() function during
the DXE phase. The introduction of SmmRelocationLib
changes this process by moving the allocation to the PEI
phase, where Smst->AllocatePages() is not accessible.
Instead, the allocation is now handled by partitioning
the SMRAM based on the information provided by a GUID HOB
(identified by gEfiSmmSMramMemoryGuid).

This patch is to ensure that OVMF produces the
gEfiSmmSMramMemoryGuid HOB, allowing SmmRelocationLib to
reserve the necessary memory for SMBASE relocation.

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Ray Ni <ray.ni@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 OvmfPkg/Library/PlatformInitLib/MemDetect.c        | 97 +++++++++++++---------
 .../Library/PlatformInitLib/PlatformInitLib.inf    |  5 +-
 2 files changed, 64 insertions(+), 38 deletions(-)

diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c
index 7b6e5102ad..8b98256225 100644
--- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c
+++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c
@@ -1,9 +1,9 @@
 /**@file
   Memory Detection for Virtual Machines.
 
-  Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2006 - 2024, Intel Corporation. All rights reserved.<BR>
   SPDX-License-Identifier: BSD-2-Clause-Patent
 
 Module Name:
 
   MemDetect.c
@@ -41,10 +41,12 @@ Module Name:
 #include <Library/QemuFwCfgSimpleParserLib.h>
 #include <Library/TdxLib.h>
 
 #include <Library/PlatformInitLib.h>
 
+#include <Guid/SmramMemoryReserve.h>
+
 #define MEGABYTE_SHIFT  20
 
 VOID
 EFIAPI
 PlatformQemuUc32BaseInitialization (
@@ -1027,52 +1029,73 @@ PlatformQemuInitializeRam (
   //
   // Determine total memory size available
   //
   PlatformGetSystemMemorySizeBelow4gb (PlatformInfoHob);
 
-  if (PlatformInfoHob->BootMode == BOOT_ON_S3_RESUME) {
-    //
-    // Create the following memory HOB as an exception on the S3 boot path.
+  //
+  // CpuMpPei saves the original contents of the borrowed area in permanent
+  // PEI RAM, in a backup buffer allocated with the normal PEI services.
+  // CpuMpPei restores the original contents ("returns" the borrowed area) at
+  // End-of-PEI. End-of-PEI in turn is emitted by S3Resume2Pei before
+  // transferring control to the OS's wakeup vector in the FACS.
+  //
+  // We expect any other PEIMs that "borrow" memory similarly to CpuMpPei to
+  // restore the original contents. Furthermore, we expect all such PEIMs
+  // (CpuMpPei included) to claim the borrowed areas by producing memory
+  // allocation HOBs, and to honor preexistent memory allocation HOBs when
+  // looking for an area to borrow.
+  //
+  QemuInitializeRamBelow1gb (PlatformInfoHob);
+
+  if (PlatformInfoHob->SmmSmramRequire) {
+    UINT32                          TsegSize;
+    UINTN                           BufferSize;
+    UINT8                           SmramRanges;
+    EFI_PEI_HOB_POINTERS            Hob;
+    EFI_SMRAM_HOB_DESCRIPTOR_BLOCK  *SmramHobDescriptorBlock;
+
+    TsegSize = PlatformInfoHob->Q35TsegMbytes * SIZE_1MB;
+    PlatformAddMemoryRangeHob (BASE_1MB, PlatformInfoHob->LowMemory - TsegSize);
+    PlatformAddReservedMemoryBaseSizeHob (
+      PlatformInfoHob->LowMemory - TsegSize,
+      TsegSize,
+      TRUE
+      );
+
+    SmramRanges = 2;
+    BufferSize  = sizeof (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK) + (SmramRanges - 1) * sizeof (EFI_SMRAM_DESCRIPTOR);
+
+    Hob.Raw = BuildGuidHob (
+                &gEfiSmmSmramMemoryGuid,
+                BufferSize
+                );
+    ASSERT (Hob.Raw);
+
+    SmramHobDescriptorBlock                             = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)(Hob.Raw);
+    SmramHobDescriptorBlock->NumberOfSmmReservedRegions = SmramRanges;
+
     //
-    // Normally we'd create memory HOBs only on the normal boot path. However,
-    // CpuMpPei specifically needs such a low-memory HOB on the S3 path as
-    // well, for "borrowing" a subset of it temporarily, for the AP startup
-    // vector.
+    // Create first SMRAM descriptor, which contains data structures used in S3 resume.
+    // One page is enough for the data structure
     //
-    // CpuMpPei saves the original contents of the borrowed area in permanent
-    // PEI RAM, in a backup buffer allocated with the normal PEI services.
-    // CpuMpPei restores the original contents ("returns" the borrowed area) at
-    // End-of-PEI. End-of-PEI in turn is emitted by S3Resume2Pei before
-    // transferring control to the OS's wakeup vector in the FACS.
+    SmramHobDescriptorBlock->Descriptor[0].PhysicalStart = PlatformInfoHob->LowMemory - TsegSize;
+    SmramHobDescriptorBlock->Descriptor[0].CpuStart      = PlatformInfoHob->LowMemory - TsegSize;
+    SmramHobDescriptorBlock->Descriptor[0].PhysicalSize  = EFI_PAGE_SIZE;
+    SmramHobDescriptorBlock->Descriptor[0].RegionState   = EFI_SMRAM_CLOSED | EFI_CACHEABLE | EFI_ALLOCATED;
+
     //
-    // We expect any other PEIMs that "borrow" memory similarly to CpuMpPei to
-    // restore the original contents. Furthermore, we expect all such PEIMs
-    // (CpuMpPei included) to claim the borrowed areas by producing memory
-    // allocation HOBs, and to honor preexistent memory allocation HOBs when
-    // looking for an area to borrow.
+    // Create second SMRAM descriptor, which is free and will be used by SMM foundation.
     //
-    QemuInitializeRamBelow1gb (PlatformInfoHob);
+    SmramHobDescriptorBlock->Descriptor[1].PhysicalStart = SmramHobDescriptorBlock->Descriptor[0].PhysicalStart + EFI_PAGE_SIZE;
+    SmramHobDescriptorBlock->Descriptor[1].CpuStart      = SmramHobDescriptorBlock->Descriptor[0].CpuStart + EFI_PAGE_SIZE;
+    SmramHobDescriptorBlock->Descriptor[1].PhysicalSize  = TsegSize - EFI_PAGE_SIZE;
+    SmramHobDescriptorBlock->Descriptor[1].RegionState   = EFI_SMRAM_CLOSED | EFI_CACHEABLE;
   } else {
-    //
-    // Create memory HOBs
-    //
-    QemuInitializeRamBelow1gb (PlatformInfoHob);
-
-    if (PlatformInfoHob->SmmSmramRequire) {
-      UINT32  TsegSize;
-
-      TsegSize = PlatformInfoHob->Q35TsegMbytes * SIZE_1MB;
-      PlatformAddMemoryRangeHob (BASE_1MB, PlatformInfoHob->LowMemory - TsegSize);
-      PlatformAddReservedMemoryBaseSizeHob (
-        PlatformInfoHob->LowMemory - TsegSize,
-        TsegSize,
-        TRUE
-        );
-    } else {
-      PlatformAddMemoryRangeHob (BASE_1MB, PlatformInfoHob->LowMemory);
-    }
+    PlatformAddMemoryRangeHob (BASE_1MB, PlatformInfoHob->LowMemory);
+  }
 
+  if (PlatformInfoHob->BootMode != BOOT_ON_S3_RESUME) {
     //
     // If QEMU presents an E820 map, then create memory HOBs for the >=4GB RAM
     // entries. Otherwise, create a single memory HOB with the flat >=4GB
     // memory size read from the CMOS.
     //
diff --git a/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf b/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf
index 5a79d95b68..2bb1c0296f 100644
--- a/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf
+++ b/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf
@@ -1,10 +1,10 @@
 ## @file
 #  Platform Initialization Lib
 #
 #  This module provides platform specific function to detect boot mode.
-#  Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.<BR>
+#  Copyright (c) 2006 - 2024, Intel Corporation. All rights reserved.<BR>
 #
 #  SPDX-License-Identifier: BSD-2-Clause-Patent
 #
 ##
 
@@ -54,10 +54,13 @@
   PeiHardwareInfoLib
 
 [LibraryClasses.X64]
   TdxLib
 
+[Guids]
+  gEfiSmmSmramMemoryGuid
+
 [Pcd]
   gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable
 
 [FixedPcd]
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117780): https://edk2.groups.io/g/devel/message/117780
Mute This Topic: https://groups.io/mt/105535809/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 19+ messages in thread

* [edk2-devel] [PATCH v2 06/10] OvmfPkg: Refine SmmAccess implementation
  2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
                   ` (4 preceding siblings ...)
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 05/10] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid Wu, Jiaxin
@ 2024-04-15 13:30 ` Wu, Jiaxin
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 07/10] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not Wu, Jiaxin
                   ` (4 subsequent siblings)
  10 siblings, 0 replies; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:30 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann, Ray Ni

This patch refines the SmmAccess implementation:
1. SmramMap will be retrieved from the
gEfiSmmSmramMemoryGuid instead of original from
the TSEG Memory Base register.
2. Remove the gEfiAcpiVariableGuid creation, thus
the DESCRIPTOR_INDEX definition can be also cleaned.
3. The gEfiAcpiVariableGuid HOB is moved to the
OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf.

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Ray Ni <ray.ni@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 OvmfPkg/Library/PlatformInitLib/MemDetect.c        |  9 +++
 .../Library/PlatformInitLib/PlatformInitLib.inf    |  1 +
 OvmfPkg/SmmAccess/SmmAccess2Dxe.c                  |  4 +-
 OvmfPkg/SmmAccess/SmmAccess2Dxe.inf                |  5 ++
 OvmfPkg/SmmAccess/SmmAccessPei.c                   | 88 ++--------------------
 OvmfPkg/SmmAccess/SmmAccessPei.inf                 |  7 +-
 OvmfPkg/SmmAccess/SmramInternal.c                  | 73 ++++++------------
 OvmfPkg/SmmAccess/SmramInternal.h                  | 18 +----
 8 files changed, 51 insertions(+), 154 deletions(-)

diff --git a/OvmfPkg/Library/PlatformInitLib/MemDetect.c b/OvmfPkg/Library/PlatformInitLib/MemDetect.c
index 8b98256225..f451c9d80c 100644
--- a/OvmfPkg/Library/PlatformInitLib/MemDetect.c
+++ b/OvmfPkg/Library/PlatformInitLib/MemDetect.c
@@ -41,10 +41,11 @@ Module Name:
 #include <Library/QemuFwCfgSimpleParserLib.h>
 #include <Library/TdxLib.h>
 
 #include <Library/PlatformInitLib.h>
 
+#include <Guid/AcpiS3Context.h>
 #include <Guid/SmramMemoryReserve.h>
 
 #define MEGABYTE_SHIFT  20
 
 VOID
@@ -1050,10 +1051,11 @@ PlatformQemuInitializeRam (
     UINT32                          TsegSize;
     UINTN                           BufferSize;
     UINT8                           SmramRanges;
     EFI_PEI_HOB_POINTERS            Hob;
     EFI_SMRAM_HOB_DESCRIPTOR_BLOCK  *SmramHobDescriptorBlock;
+    VOID                            *GuidHob;
 
     TsegSize = PlatformInfoHob->Q35TsegMbytes * SIZE_1MB;
     PlatformAddMemoryRangeHob (BASE_1MB, PlatformInfoHob->LowMemory - TsegSize);
     PlatformAddReservedMemoryBaseSizeHob (
       PlatformInfoHob->LowMemory - TsegSize,
@@ -1080,10 +1082,17 @@ PlatformQemuInitializeRam (
     SmramHobDescriptorBlock->Descriptor[0].PhysicalStart = PlatformInfoHob->LowMemory - TsegSize;
     SmramHobDescriptorBlock->Descriptor[0].CpuStart      = PlatformInfoHob->LowMemory - TsegSize;
     SmramHobDescriptorBlock->Descriptor[0].PhysicalSize  = EFI_PAGE_SIZE;
     SmramHobDescriptorBlock->Descriptor[0].RegionState   = EFI_SMRAM_CLOSED | EFI_CACHEABLE | EFI_ALLOCATED;
 
+    //
+    // Create gEfiAcpiVariableGuid
+    //
+    GuidHob = BuildGuidHob (&gEfiAcpiVariableGuid, sizeof (EFI_SMRAM_DESCRIPTOR));
+    ASSERT (GuidHob != NULL);
+    CopyMem (GuidHob, &SmramHobDescriptorBlock->Descriptor[0], sizeof (EFI_SMRAM_DESCRIPTOR));
+
     //
     // Create second SMRAM descriptor, which is free and will be used by SMM foundation.
     //
     SmramHobDescriptorBlock->Descriptor[1].PhysicalStart = SmramHobDescriptorBlock->Descriptor[0].PhysicalStart + EFI_PAGE_SIZE;
     SmramHobDescriptorBlock->Descriptor[1].CpuStart      = SmramHobDescriptorBlock->Descriptor[0].CpuStart + EFI_PAGE_SIZE;
diff --git a/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf b/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf
index 2bb1c0296f..21e6efa5e0 100644
--- a/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf
+++ b/OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf
@@ -56,10 +56,11 @@
 [LibraryClasses.X64]
   TdxLib
 
 [Guids]
   gEfiSmmSmramMemoryGuid
+  gEfiAcpiVariableGuid
 
 [Pcd]
   gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable
 
diff --git a/OvmfPkg/SmmAccess/SmmAccess2Dxe.c b/OvmfPkg/SmmAccess/SmmAccess2Dxe.c
index 4b9e6df37f..3371592de7 100644
--- a/OvmfPkg/SmmAccess/SmmAccess2Dxe.c
+++ b/OvmfPkg/SmmAccess/SmmAccess2Dxe.c
@@ -4,11 +4,11 @@
 
   Q35 TSEG is expected to have been verified and set up by the SmmAccessPei
   driver.
 
   Copyright (C) 2013, 2015, Red Hat, Inc.<BR>
-  Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2009 - 2024, Intel Corporation. All rights reserved.<BR>
 
   SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 
@@ -113,12 +113,10 @@ SmmAccess2DxeGetCapabilities (
   IN OUT UINTN                       *SmramMapSize,
   IN OUT EFI_SMRAM_DESCRIPTOR        *SmramMap
   )
 {
   return SmramAccessGetCapabilities (
-           This->LockState,
-           This->OpenState,
            SmramMapSize,
            SmramMap
            );
 }
 
diff --git a/OvmfPkg/SmmAccess/SmmAccess2Dxe.inf b/OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
index d86381d0fb..d9f01a13c4 100644
--- a/OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
+++ b/OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
@@ -3,10 +3,11 @@
 #
 # Q35 TSEG is expected to have been verified and set up by the SmmAccessPei
 # driver.
 #
 # Copyright (C) 2013, 2015, Red Hat, Inc.
+# Copyright (c) 2024 Intel Corporation.
 #
 # SPDX-License-Identifier: BSD-2-Clause-Patent
 #
 ##
 
@@ -39,17 +40,21 @@
   DebugLib
   PcdLib
   PciLib
   UefiBootServicesTableLib
   UefiDriverEntryPoint
+  HobLib
 
 [Protocols]
   gEfiSmmAccess2ProtocolGuid   ## PRODUCES
 
 [FeaturePcd]
   gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire
 
+[Guids]
+  gEfiSmmSmramMemoryGuid             # ALWAYS_CONSUMED
+
 [Pcd]
   gUefiOvmfPkgTokenSpaceGuid.PcdQ35SmramAtDefaultSmbase
   gUefiOvmfPkgTokenSpaceGuid.PcdQ35TsegMbytes
 
 [Depex]
diff --git a/OvmfPkg/SmmAccess/SmmAccessPei.c b/OvmfPkg/SmmAccess/SmmAccessPei.c
index 0e57b7804c..9459bcc989 100644
--- a/OvmfPkg/SmmAccess/SmmAccessPei.c
+++ b/OvmfPkg/SmmAccess/SmmAccessPei.c
@@ -9,21 +9,19 @@
 
   This PEIM runs from RAM, so we can write to variables with static storage
   duration.
 
   Copyright (C) 2013, 2015, Red Hat, Inc.<BR>
-  Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2010 - 2024, Intel Corporation. All rights reserved.<BR>
 
   SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 
-#include <Guid/AcpiS3Context.h>
 #include <Library/BaseLib.h>
 #include <Library/BaseMemoryLib.h>
 #include <Library/DebugLib.h>
-#include <Library/HobLib.h>
 #include <Library/IoLib.h>
 #include <Library/PcdLib.h>
 #include <Library/PciLib.h>
 #include <Library/PeiServicesLib.h>
 #include <Ppi/SmmAccess.h>
@@ -62,14 +60,10 @@ SmmAccessPeiOpen (
   IN EFI_PEI_SERVICES    **PeiServices,
   IN PEI_SMM_ACCESS_PPI  *This,
   IN UINTN               DescriptorIndex
   )
 {
-  if (DescriptorIndex >= DescIdxCount) {
-    return EFI_INVALID_PARAMETER;
-  }
-
   //
   // According to current practice, DescriptorIndex is not considered at all,
   // beyond validating it.
   //
   return SmramAccessOpen (&This->LockState, &This->OpenState);
@@ -100,14 +94,10 @@ SmmAccessPeiClose (
   IN EFI_PEI_SERVICES    **PeiServices,
   IN PEI_SMM_ACCESS_PPI  *This,
   IN UINTN               DescriptorIndex
   )
 {
-  if (DescriptorIndex >= DescIdxCount) {
-    return EFI_INVALID_PARAMETER;
-  }
-
   //
   // According to current practice, DescriptorIndex is not considered at all,
   // beyond validating it.
   //
   return SmramAccessClose (&This->LockState, &This->OpenState);
@@ -137,14 +127,10 @@ SmmAccessPeiLock (
   IN EFI_PEI_SERVICES    **PeiServices,
   IN PEI_SMM_ACCESS_PPI  *This,
   IN UINTN               DescriptorIndex
   )
 {
-  if (DescriptorIndex >= DescIdxCount) {
-    return EFI_INVALID_PARAMETER;
-  }
-
   //
   // According to current practice, DescriptorIndex is not considered at all,
   // beyond validating it.
   //
   return SmramAccessLock (&This->LockState, &This->OpenState);
@@ -176,12 +162,10 @@ SmmAccessPeiGetCapabilities (
   IN OUT UINTN                 *SmramMapSize,
   IN OUT EFI_SMRAM_DESCRIPTOR  *SmramMap
   )
 {
   return SmramAccessGetCapabilities (
-           This->LockState,
-           This->OpenState,
            SmramMapSize,
            SmramMap
            );
 }
 
@@ -238,18 +222,14 @@ EFIAPI
 SmmAccessPeiEntryPoint (
   IN       EFI_PEI_FILE_HANDLE  FileHandle,
   IN CONST EFI_PEI_SERVICES     **PeiServices
   )
 {
-  UINT16                HostBridgeDevId;
-  UINT8                 EsmramcVal;
-  UINT8                 RegMask8;
-  UINT32                TopOfLowRam, TopOfLowRamMb;
-  EFI_STATUS            Status;
-  UINTN                 SmramMapSize;
-  EFI_SMRAM_DESCRIPTOR  SmramMap[DescIdxCount];
-  VOID                  *GuidHob;
+  UINT16  HostBridgeDevId;
+  UINT8   EsmramcVal;
+  UINT8   RegMask8;
+  UINT32  TopOfLowRam, TopOfLowRamMb;
 
   //
   // This module should only be included if SMRAM support is required.
   //
   ASSERT (FeaturePcdGet (PcdSmmSmramRequire));
@@ -354,69 +334,11 @@ SmmAccessPeiEntryPoint (
     DRAMC_REGISTER_Q35 (MCH_SMRAM),
     (UINT8)((~(UINT32)MCH_SMRAM_D_LCK) & 0xff),
     MCH_SMRAM_G_SMRAME
     );
 
-  //
-  // Create the GUID HOB and point it to the first SMRAM range.
-  //
   GetStates (&mAccess.LockState, &mAccess.OpenState);
-  SmramMapSize = sizeof SmramMap;
-  Status       = SmramAccessGetCapabilities (
-                   mAccess.LockState,
-                   mAccess.OpenState,
-                   &SmramMapSize,
-                   SmramMap
-                   );
-  ASSERT_EFI_ERROR (Status);
-
-  DEBUG_CODE_BEGIN ();
-  {
-    UINTN  Count;
-    UINTN  Idx;
-
-    Count = SmramMapSize / sizeof SmramMap[0];
-    DEBUG ((
-      DEBUG_VERBOSE,
-      "%a: SMRAM map follows, %d entries\n",
-      __func__,
-      (INT32)Count
-      ));
-    DEBUG ((
-      DEBUG_VERBOSE,
-      "% 20a % 20a % 20a % 20a\n",
-      "PhysicalStart(0x)",
-      "PhysicalSize(0x)",
-      "CpuStart(0x)",
-      "RegionState(0x)"
-      ));
-    for (Idx = 0; Idx < Count; ++Idx) {
-      DEBUG ((
-        DEBUG_VERBOSE,
-        "% 20Lx % 20Lx % 20Lx % 20Lx\n",
-        SmramMap[Idx].PhysicalStart,
-        SmramMap[Idx].PhysicalSize,
-        SmramMap[Idx].CpuStart,
-        SmramMap[Idx].RegionState
-        ));
-    }
-  }
-  DEBUG_CODE_END ();
-
-  GuidHob = BuildGuidHob (
-              &gEfiAcpiVariableGuid,
-              sizeof SmramMap[DescIdxSmmS3ResumeState]
-              );
-  if (GuidHob == NULL) {
-    return EFI_OUT_OF_RESOURCES;
-  }
-
-  CopyMem (
-    GuidHob,
-    &SmramMap[DescIdxSmmS3ResumeState],
-    sizeof SmramMap[DescIdxSmmS3ResumeState]
-    );
 
   //
   // SmramAccessLock() depends on "mQ35SmramAtDefaultSmbase"; init the latter
   // just before exposing the former via PEI_SMM_ACCESS_PPI.Lock().
   //
diff --git a/OvmfPkg/SmmAccess/SmmAccessPei.inf b/OvmfPkg/SmmAccess/SmmAccessPei.inf
index 1698c4ce6c..98bbda20e3 100644
--- a/OvmfPkg/SmmAccess/SmmAccessPei.inf
+++ b/OvmfPkg/SmmAccess/SmmAccessPei.inf
@@ -5,10 +5,11 @@
 # - verify & configure the Q35 TSEG in the entry point,
 # - set aside the SMM_S3_RESUME_STATE object at the bottom of TSEG, and expose
 #   it via the gEfiAcpiVariableGuid GUIDed HOB.
 #
 # Copyright (C) 2013, 2015, Red Hat, Inc.
+# Copyright (c) 2024 Intel Corporation.
 #
 # SPDX-License-Identifier: BSD-2-Clause-Patent
 #
 ##
 
@@ -34,13 +35,10 @@
 [Packages]
   MdeModulePkg/MdeModulePkg.dec
   MdePkg/MdePkg.dec
   OvmfPkg/OvmfPkg.dec
 
-[Guids]
-  gEfiAcpiVariableGuid
-
 [LibraryClasses]
   BaseLib
   BaseMemoryLib
   DebugLib
   HobLib
@@ -55,10 +53,13 @@
 
 [Pcd]
   gUefiOvmfPkgTokenSpaceGuid.PcdQ35SmramAtDefaultSmbase
   gUefiOvmfPkgTokenSpaceGuid.PcdQ35TsegMbytes
 
+[Guids]
+  gEfiSmmSmramMemoryGuid             # ALWAYS_CONSUMED
+
 [Ppis]
   gPeiSmmAccessPpiGuid           ## PRODUCES
 
 [Depex]
   gEfiPeiMemoryDiscoveredPpiGuid
diff --git a/OvmfPkg/SmmAccess/SmramInternal.c b/OvmfPkg/SmmAccess/SmramInternal.c
index d391ddc9ae..312f67b304 100644
--- a/OvmfPkg/SmmAccess/SmramInternal.c
+++ b/OvmfPkg/SmmAccess/SmramInternal.c
@@ -1,20 +1,22 @@
 /** @file
 
   Functions and types shared by the SMM accessor PEI and DXE modules.
 
   Copyright (C) 2015, Red Hat, Inc.
+  Copyright (c) 2024 Intel Corporation.
 
   SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 
-#include <Guid/AcpiS3Context.h>
+#include <Guid/SmramMemoryReserve.h>
 #include <IndustryStandard/Q35MchIch9.h>
 #include <Library/DebugLib.h>
 #include <Library/PcdLib.h>
 #include <Library/PciLib.h>
+#include <Library/HobLib.h>
 
 #include "SmramInternal.h"
 
 //
 // The value of PcdQ35TsegMbytes is saved into this variable at module startup.
@@ -164,70 +166,45 @@ SmramAccessLock (
   return EFI_SUCCESS;
 }
 
 EFI_STATUS
 SmramAccessGetCapabilities (
-  IN BOOLEAN                   LockState,
-  IN BOOLEAN                   OpenState,
   IN OUT UINTN                 *SmramMapSize,
   IN OUT EFI_SMRAM_DESCRIPTOR  *SmramMap
   )
 {
-  UINTN   OriginalSize;
-  UINT32  TsegMemoryBaseMb, TsegMemoryBase;
-  UINT64  CommonRegionState;
-  UINT8   TsegSizeBits;
-
-  OriginalSize  = *SmramMapSize;
-  *SmramMapSize = DescIdxCount * sizeof *SmramMap;
-  if (OriginalSize < *SmramMapSize) {
-    return EFI_BUFFER_TOO_SMALL;
-  }
+  UINTN                           BufferSize;
+  EFI_HOB_GUID_TYPE               *GuidHob;
+  EFI_SMRAM_HOB_DESCRIPTOR_BLOCK  *DescriptorBlock;
+  UINTN                           Index;
 
   //
-  // Read the TSEG Memory Base register.
+  // Get Hob list
   //
-  TsegMemoryBaseMb = PciRead32 (DRAMC_REGISTER_Q35 (MCH_TSEGMB));
-  TsegMemoryBase   = (TsegMemoryBaseMb >> MCH_TSEGMB_MB_SHIFT) << 20;
+  GuidHob         = GetFirstGuidHob (&gEfiSmmSmramMemoryGuid);
+  DescriptorBlock = GET_GUID_HOB_DATA (GuidHob);
+  ASSERT (DescriptorBlock);
 
-  //
-  // Precompute the region state bits that will be set for all regions.
-  //
-  CommonRegionState = (OpenState ? EFI_SMRAM_OPEN : EFI_SMRAM_CLOSED) |
-                      (LockState ? EFI_SMRAM_LOCKED : 0) |
-                      EFI_CACHEABLE;
+  BufferSize = DescriptorBlock->NumberOfSmmReservedRegions * sizeof (EFI_SMRAM_DESCRIPTOR);
 
-  //
-  // The first region hosts an SMM_S3_RESUME_STATE object. It is located at the
-  // start of TSEG. We round up the size to whole pages, and we report it as
-  // EFI_ALLOCATED, so that the SMM_CORE stays away from it.
-  //
-  SmramMap[DescIdxSmmS3ResumeState].PhysicalStart = TsegMemoryBase;
-  SmramMap[DescIdxSmmS3ResumeState].CpuStart      = TsegMemoryBase;
-  SmramMap[DescIdxSmmS3ResumeState].PhysicalSize  =
-    EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (sizeof (SMM_S3_RESUME_STATE)));
-  SmramMap[DescIdxSmmS3ResumeState].RegionState =
-    CommonRegionState | EFI_ALLOCATED;
+  if (*SmramMapSize < BufferSize) {
+    *SmramMapSize = BufferSize;
+    return EFI_BUFFER_TOO_SMALL;
+  }
 
   //
-  // Get the TSEG size bits from the ESMRAMC register.
+  // Update SmramMapSize to real return SMRAM map size
   //
-  TsegSizeBits = PciRead8 (DRAMC_REGISTER_Q35 (MCH_ESMRAMC)) &
-                 MCH_ESMRAMC_TSEG_MASK;
+  *SmramMapSize = BufferSize;
 
   //
-  // The second region is the main one, following the first.
+  // Use the hob to publish SMRAM capabilities
   //
-  SmramMap[DescIdxMain].PhysicalStart =
-    SmramMap[DescIdxSmmS3ResumeState].PhysicalStart +
-    SmramMap[DescIdxSmmS3ResumeState].PhysicalSize;
-  SmramMap[DescIdxMain].CpuStart     = SmramMap[DescIdxMain].PhysicalStart;
-  SmramMap[DescIdxMain].PhysicalSize =
-    (TsegSizeBits == MCH_ESMRAMC_TSEG_8MB ? SIZE_8MB :
-     TsegSizeBits == MCH_ESMRAMC_TSEG_2MB ? SIZE_2MB :
-     TsegSizeBits == MCH_ESMRAMC_TSEG_1MB ? SIZE_1MB :
-     mQ35TsegMbytes * SIZE_1MB) -
-    SmramMap[DescIdxSmmS3ResumeState].PhysicalSize;
-  SmramMap[DescIdxMain].RegionState = CommonRegionState;
+  for (Index = 0; Index < DescriptorBlock->NumberOfSmmReservedRegions; Index++) {
+    SmramMap[Index].PhysicalStart = DescriptorBlock->Descriptor[Index].PhysicalStart;
+    SmramMap[Index].CpuStart      = DescriptorBlock->Descriptor[Index].CpuStart;
+    SmramMap[Index].PhysicalSize  = DescriptorBlock->Descriptor[Index].PhysicalSize;
+    SmramMap[Index].RegionState   = DescriptorBlock->Descriptor[Index].RegionState;
+  }
 
   return EFI_SUCCESS;
 }
diff --git a/OvmfPkg/SmmAccess/SmramInternal.h b/OvmfPkg/SmmAccess/SmramInternal.h
index da5b7bbca1..4dd1c6dc9b 100644
--- a/OvmfPkg/SmmAccess/SmramInternal.h
+++ b/OvmfPkg/SmmAccess/SmramInternal.h
@@ -1,32 +1,18 @@
 /** @file
 
   Functions and types shared by the SMM accessor PEI and DXE modules.
 
   Copyright (C) 2015, Red Hat, Inc.
+  Copyright (c) 2024 Intel Corporation.
 
   SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 
 #include <Pi/PiMultiPhase.h>
 
-//
-// We'll have two SMRAM ranges.
-//
-// The first is a tiny one that hosts an SMM_S3_RESUME_STATE object, to be
-// filled in by the CPU SMM driver during normal boot, for the PEI instance of
-// the LockBox library (which will rely on the object during S3 resume).
-//
-// The other SMRAM range is the main one, for the SMM core and the SMM drivers.
-//
-typedef enum {
-  DescIdxSmmS3ResumeState = 0,
-  DescIdxMain             = 1,
-  DescIdxCount            = 2
-} DESCRIPTOR_INDEX;
-
 //
 // The value of PcdQ35TsegMbytes is saved into this variable at module startup.
 //
 extern UINT16  mQ35TsegMbytes;
 
@@ -95,10 +81,8 @@ SmramAccessLock (
   IN OUT BOOLEAN  *OpenState
   );
 
 EFI_STATUS
 SmramAccessGetCapabilities (
-  IN BOOLEAN                   LockState,
-  IN BOOLEAN                   OpenState,
   IN OUT UINTN                 *SmramMapSize,
   IN OUT EFI_SMRAM_DESCRIPTOR  *SmramMap
   );
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117781): https://edk2.groups.io/g/devel/message/117781
Mute This Topic: https://groups.io/mt/105535811/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 19+ messages in thread

* [edk2-devel] [PATCH v2 07/10] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not
  2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
                   ` (5 preceding siblings ...)
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 06/10] OvmfPkg: Refine SmmAccess implementation Wu, Jiaxin
@ 2024-04-15 13:30 ` Wu, Jiaxin
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 08/10] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase Wu, Jiaxin
                   ` (3 subsequent siblings)
  10 siblings, 0 replies; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:30 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann, Ray Ni

Based on gSmmBaseHobGuid:
If gSmmBaseHobGuid found, means SmBase info has been relocated
and recorded in the SmBase array.
So, this patch check smbase relocation is done or not in
SmmCpuFeaturesInitializeProcessor().

With SmmRelocationLib, gSmmBaseHobGuid will be always created.
Here this patch just makes the function/logic correct. The SMM
Relocation logic can be totally cleaned from the
SmmCpuFeaturesLib. But it will happen in the future patch set,
this patch does not target to the cleanup work.

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Ray Ni <ray.ni@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
Reviewed-by: Ray Ni <ray.ni@intel.com>
---
 .../Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c  | 33 ++++++++++++++--------
 1 file changed, 22 insertions(+), 11 deletions(-)

diff --git a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
index 63822b126e..0a6f33c2b1 100644
--- a/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
+++ b/OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c
@@ -26,10 +26,16 @@
 //
 // EFER register LMA bit
 //
 #define LMA  BIT10
 
+//
+// Indicate SmBase for each Processors has been relocated or not. If TRUE,
+// means no need to do the relocation in SmmCpuFeaturesInitializeProcessor().
+//
+BOOLEAN  mSmmCpuFeaturesSmmRelocated;
+
 /**
   The constructor function
 
   @param[in]  ImageHandle  The firmware allocated handle for the EFI image.
   @param[in]  SystemTable  A pointer to the EFI System Table.
@@ -44,13 +50,13 @@ SmmCpuFeaturesLibConstructor (
   IN EFI_SYSTEM_TABLE  *SystemTable
   )
 {
   //
   // If gSmmBaseHobGuid found, means SmBase info has been relocated and recorded
-  // in the SmBase array. ASSERT it's not supported in OVMF.
+  // in the SmBase array.
   //
-  ASSERT (GetFirstGuidHob (&gSmmBaseHobGuid) == NULL);
+  mSmmCpuFeaturesSmmRelocated = (BOOLEAN)(GetFirstGuidHob (&gSmmBaseHobGuid) != NULL);
 
   //
   // No need to program SMRRs on our virtual platform.
   //
   return EFI_SUCCESS;
@@ -90,20 +96,25 @@ SmmCpuFeaturesInitializeProcessor (
   )
 {
   AMD_SMRAM_SAVE_STATE_MAP  *CpuState;
 
   //
-  // Configure SMBASE.
+  // No need to configure SMBASE if SmBase relocation has been done.
   //
-  CpuState = (AMD_SMRAM_SAVE_STATE_MAP *)(UINTN)(
-                                                 SMM_DEFAULT_SMBASE +
-                                                 SMRAM_SAVE_STATE_MAP_OFFSET
-                                                 );
-  if ((CpuState->x86.SMMRevId & 0xFFFF) == 0) {
-    CpuState->x86.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex];
-  } else {
-    CpuState->x64.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex];
+  if (!mSmmCpuFeaturesSmmRelocated) {
+    //
+    // Configure SMBASE.
+    //
+    CpuState = (AMD_SMRAM_SAVE_STATE_MAP *)(UINTN)(
+                                                   SMM_DEFAULT_SMBASE +
+                                                   SMRAM_SAVE_STATE_MAP_OFFSET
+                                                   );
+    if ((CpuState->x86.SMMRevId & 0xFFFF) == 0) {
+      CpuState->x86.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex];
+    } else {
+      CpuState->x64.SMBASE = (UINT32)CpuHotPlugData->SmBase[CpuIndex];
+    }
   }
 
   //
   // No need to program SMRRs on our virtual platform.
   //
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117782): https://edk2.groups.io/g/devel/message/117782
Mute This Topic: https://groups.io/mt/105535813/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 19+ messages in thread

* [edk2-devel] [PATCH v2 08/10] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase
  2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
                   ` (6 preceding siblings ...)
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 07/10] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not Wu, Jiaxin
@ 2024-04-15 13:30 ` Wu, Jiaxin
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 09/10] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib Wu, Jiaxin
                   ` (2 subsequent siblings)
  10 siblings, 0 replies; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:30 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann, Ray Ni

This patch is to consume SmmRelocationInit for SmBase
Relocation.

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Ray Ni <ray.ni@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 OvmfPkg/PlatformPei/Platform.c      |  3 ++
 OvmfPkg/PlatformPei/Platform.h      |  5 +++
 OvmfPkg/PlatformPei/PlatformPei.inf |  5 ++-
 OvmfPkg/PlatformPei/SmmRelocation.c | 80 +++++++++++++++++++++++++++++++++++++
 4 files changed, 92 insertions(+), 1 deletion(-)
 create mode 100644 OvmfPkg/PlatformPei/SmmRelocation.c

diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c
index f5dc41c3a8..df35726ff6 100644
--- a/OvmfPkg/PlatformPei/Platform.c
+++ b/OvmfPkg/PlatformPei/Platform.c
@@ -365,8 +365,11 @@ InitializePlatform (
     MiscInitialization (PlatformInfoHob);
   }
 
   IntelTdxInitialize ();
   InstallFeatureControlCallback (PlatformInfoHob);
+  if (PlatformInfoHob->SmmSmramRequire) {
+    RelocateSmBase ();
+  }
 
   return EFI_SUCCESS;
 }
diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h
index 1cf44844a7..0a59547cfc 100644
--- a/OvmfPkg/PlatformPei/Platform.h
+++ b/OvmfPkg/PlatformPei/Platform.h
@@ -76,10 +76,15 @@ InstallFeatureControlCallback (
 VOID
 InstallClearCacheCallback (
   VOID
   );
 
+VOID
+RelocateSmBase (
+  VOID
+  );
+
 VOID
 AmdSevInitialize (
   IN EFI_HOB_PLATFORM_INFO  *PlatformInfoHob
   );
 
diff --git a/OvmfPkg/PlatformPei/PlatformPei.inf b/OvmfPkg/PlatformPei/PlatformPei.inf
index ad52be3065..d7a4fd5ffe 100644
--- a/OvmfPkg/PlatformPei/PlatformPei.inf
+++ b/OvmfPkg/PlatformPei/PlatformPei.inf
@@ -1,10 +1,10 @@
 ## @file
 #  Platform PEI driver
 #
 #  This module provides platform specific function to detect boot mode.
-#  Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.<BR>
+#  Copyright (c) 2006 - 2024, Intel Corporation. All rights reserved.<BR>
 #
 #  SPDX-License-Identifier: BSD-2-Clause-Patent
 #
 ##
 
@@ -30,10 +30,11 @@
   MemDetect.c
   MemTypeInfo.c
   Platform.c
   Platform.h
   IntelTdx.c
+  SmmRelocation.c
 
 [Packages]
   EmbeddedPkg/EmbeddedPkg.dec
   MdePkg/MdePkg.dec
   MdeModulePkg/MdeModulePkg.dec
@@ -63,10 +64,11 @@
   MtrrLib
   MemEncryptSevLib
   PcdLib
   CcExitLib
   PlatformInitLib
+  SmmRelocationLib
 
 [Pcd]
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvSize
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase
@@ -137,9 +139,10 @@
 
 [Ppis]
   gEfiPeiMasterBootModePpiGuid
   gEfiPeiMpServicesPpiGuid
   gEfiPeiReadOnlyVariable2PpiGuid
+  gEdkiiPeiMpServices2PpiGuid
 
 [Depex]
   TRUE
 
diff --git a/OvmfPkg/PlatformPei/SmmRelocation.c b/OvmfPkg/PlatformPei/SmmRelocation.c
new file mode 100644
index 0000000000..1151fc9220
--- /dev/null
+++ b/OvmfPkg/PlatformPei/SmmRelocation.c
@@ -0,0 +1,80 @@
+/**@file
+  Install a callback to do smm relocation.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <Library/DebugLib.h>
+#include <Library/PeiServicesLib.h>
+#include <Library/SmmRelocationLib.h>
+#include <Ppi/MpServices2.h>
+#include "Platform.h"
+
+/**
+  Notification function called when EDKII_PEI_MP_SERVICES2_PPI becomes available.
+
+  @param[in] PeiServices      Indirect reference to the PEI Services Table.
+  @param[in] NotifyDescriptor Address of the notification descriptor data
+                              structure.
+  @param[in] Ppi              Address of the PPI that was installed.
+
+  @return  Status of the notification. The status code returned from this
+           function is ignored.
+**/
+STATIC
+EFI_STATUS
+EFIAPI
+OnMpServices2Available (
+  IN EFI_PEI_SERVICES           **PeiServices,
+  IN EFI_PEI_NOTIFY_DESCRIPTOR  *NotifyDescriptor,
+  IN VOID                       *Ppi
+  )
+{
+  EDKII_PEI_MP_SERVICES2_PPI  *MpServices2;
+  EFI_STATUS                  Status;
+
+  DEBUG ((DEBUG_INFO, "%a: %a\n", gEfiCallerBaseName, __func__));
+
+  MpServices2 = Ppi;
+
+  //
+  // Smm Relocation Initialize.
+  //
+  Status = SmmRelocationInit (MpServices2);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_WARN, "OnMpServices2Available: Not able to execute Smm Relocation Init.  Status: %r\n", Status));
+  }
+
+  return EFI_SUCCESS;
+}
+
+//
+// Notification object for registering the callback, for when
+// EDKII_PEI_MP_SERVICES2_PPI becomes available.
+//
+STATIC CONST EFI_PEI_NOTIFY_DESCRIPTOR  mMpServices2Notify = {
+  EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK |   // Flags
+  EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST,
+  &gEdkiiPeiMpServices2PpiGuid,              // Guid
+  OnMpServices2Available                     // Notify
+};
+
+VOID
+RelocateSmBase (
+  VOID
+  )
+{
+  EFI_STATUS  Status;
+
+  Status = PeiServicesNotifyPpi (&mMpServices2Notify);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "%a: failed to set up MP Services2 callback: %r\n",
+      __func__,
+      Status
+      ));
+  }
+}
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117783): https://edk2.groups.io/g/devel/message/117783
Mute This Topic: https://groups.io/mt/105535814/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 19+ messages in thread

* [edk2-devel] [PATCH v2 09/10] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib
  2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
                   ` (7 preceding siblings ...)
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 08/10] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase Wu, Jiaxin
@ 2024-04-15 13:30 ` Wu, Jiaxin
  2024-04-15 15:26   ` Guo Dong
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 10/10] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic Wu, Jiaxin
  2024-04-16  7:31 ` [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Gerd Hoffmann
  10 siblings, 1 reply; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:30 UTC (permalink / raw)
  To: devel; +Cc: Guo Dong, Sean Rhodes, James Lu, Gua Guo, Ray Ni

This patch just includes SmmRelocationLib in UefiPayloadPkg.

Cc: Guo Dong <guo.dong@intel.com>
Cc: Sean Rhodes <sean@starlabs.systems>
Cc: James Lu <james.lu@intel.com>
Cc: Gua Guo <gua.guo@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
Reviewed-by: Gua Guo <gua.guo@intel.com>
---
 UefiPayloadPkg/UefiPayloadPkg.dsc | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc
index 433fb51a56..328b7fd4fe 100644
--- a/UefiPayloadPkg/UefiPayloadPkg.dsc
+++ b/UefiPayloadPkg/UefiPayloadPkg.dsc
@@ -313,10 +313,12 @@
   VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf
   VariableFlashInfoLib|MdeModulePkg/Library/BaseVariableFlashInfoLib/BaseVariableFlashInfoLib.inf
   CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf
   ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
   FdtLib|MdePkg/Library/BaseFdtLib/BaseFdtLib.inf
+  SmmRelocationLib|UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
+
 [LibraryClasses.common]
 !if $(BOOTSPLASH_IMAGE)
   SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf
   BmpSupportLib|MdeModulePkg/Library/BaseBmpSupportLib/BaseBmpSupportLib.inf
 !endif
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117784): https://edk2.groups.io/g/devel/message/117784
Mute This Topic: https://groups.io/mt/105535815/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 19+ messages in thread

* [edk2-devel] [PATCH v2 10/10] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic
  2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
                   ` (8 preceding siblings ...)
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 09/10] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib Wu, Jiaxin
@ 2024-04-15 13:30 ` Wu, Jiaxin
  2024-04-16  7:31 ` [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Gerd Hoffmann
  10 siblings, 0 replies; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:30 UTC (permalink / raw)
  To: devel; +Cc: Ray Ni, Zeng Star, Gerd Hoffmann, Rahul Kumar

This patch is to remove legacy SmBase relocation in
PiSmmCpuDxeSmm Driver. The responsibility for SmBase
relocation has been transferred to the SmmRelocationInit
interface, which now handles the following tasks:
1. Relocates the SmBase for each processor.
2. Generates the gSmmBaseHobGuid HOB.

As a result of this change, the PiSmmCpuDxeSmm driver's
role in SMM environment setup is simplified to:
1. Utilize the gSmmBaseHobGuid to determine the SmBase.
2. Perform the ExecuteFirstSmiInit() to do early SMM
initialization.

Cc: Ray Ni <ray.ni@intel.com>
Cc: Zeng Star <star.zeng@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c            |  21 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c   |  42 ----
 UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm  |  96 --------
 UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c        |  10 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c   | 331 +++------------------------
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h   | 103 +--------
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf |   4 -
 UefiCpuPkg/PiSmmCpuDxeSmm/SmmMpPerf.h        |   2 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c   |  69 ------
 UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c    |  69 ------
 UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm   | 146 ------------
 11 files changed, 39 insertions(+), 854 deletions(-)
 delete mode 100644 UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c
 delete mode 100644 UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm
 delete mode 100644 UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c
 delete mode 100644 UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm

diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c b/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c
index b14c289a27..d67fb49890 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c
@@ -639,27 +639,14 @@ InitializeCpuProcedure (
     //
     InitializeCpuBeforeRebase (IsBsp);
   }
 
   if (IsBsp) {
-    DEBUG ((DEBUG_INFO, "SmmRestoreCpu: mSmmRelocated is %d\n", mSmmRelocated));
-
     //
-    // Check whether Smm Relocation is done or not.
-    // If not, will do the SmmBases Relocation here!!!
+    // Issue SMI IPI (All Excluding  Self SMM IPI + BSP SMM IPI) to execute first SMI init.
     //
-    if (!mSmmRelocated) {
-      //
-      // Restore SMBASE for BSP and all APs
-      //
-      SmmRelocateBases ();
-    } else {
-      //
-      // Issue SMI IPI (All Excluding  Self SMM IPI + BSP SMM IPI) to execute first SMI init.
-      //
-      ExecuteFirstSmiInit ();
-    }
+    ExecuteFirstSmiInit ();
   }
 
   //
   // Skip initialization if mAcpiCpuData is not valid
   //
@@ -978,13 +965,13 @@ InitSmmS3ResumeState (
     SmmS3ResumeState->SmmS3StackBase = (EFI_PHYSICAL_ADDRESS)(UINTN)AllocatePages (EFI_SIZE_TO_PAGES ((UINTN)SmmS3ResumeState->SmmS3StackSize));
     if (SmmS3ResumeState->SmmS3StackBase == 0) {
       SmmS3ResumeState->SmmS3StackSize = 0;
     }
 
-    SmmS3ResumeState->SmmS3Cr0 = mSmmCr0;
+    SmmS3ResumeState->SmmS3Cr0 = (UINT32)AsmReadCr0 ();
     SmmS3ResumeState->SmmS3Cr3 = Cr3;
-    SmmS3ResumeState->SmmS3Cr4 = mSmmCr4;
+    SmmS3ResumeState->SmmS3Cr4 = (UINT32)AsmReadCr4 ();
 
     if (sizeof (UINTN) == sizeof (UINT64)) {
       SmmS3ResumeState->Signature = SMM_S3_RESUME_SMM_64;
     }
 
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c b/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c
deleted file mode 100644
index a9fcc89dda..0000000000
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c
+++ /dev/null
@@ -1,42 +0,0 @@
-/** @file
-Semaphore mechanism to indicate to the BSP that an AP has exited SMM
-after SMBASE relocation.
-
-Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>
-SPDX-License-Identifier: BSD-2-Clause-Patent
-
-**/
-
-#include "PiSmmCpuDxeSmm.h"
-
-UINTN             mSmmRelocationOriginalAddress;
-volatile BOOLEAN  *mRebasedFlag;
-
-/**
-  Hook return address of SMM Save State so that semaphore code
-  can be executed immediately after AP exits SMM to indicate to
-  the BSP that an AP has exited SMM after SMBASE relocation.
-
-  @param[in] CpuIndex     The processor index.
-  @param[in] RebasedFlag  A pointer to a flag that is set to TRUE
-                          immediately after AP exits SMM.
-
-**/
-VOID
-SemaphoreHook (
-  IN UINTN             CpuIndex,
-  IN volatile BOOLEAN  *RebasedFlag
-  )
-{
-  SMRAM_SAVE_STATE_MAP  *CpuState;
-
-  mRebasedFlag = RebasedFlag;
-
-  CpuState                      = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
-  mSmmRelocationOriginalAddress = (UINTN)HookReturnFromSmm (
-                                           CpuIndex,
-                                           CpuState,
-                                           (UINT64)(UINTN)&SmmRelocationSemaphoreComplete,
-                                           (UINT64)(UINTN)&SmmRelocationSemaphoreComplete
-                                           );
-}
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm b/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm
deleted file mode 100644
index b5e77a1a5b..0000000000
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm
+++ /dev/null
@@ -1,96 +0,0 @@
-;------------------------------------------------------------------------------ ;
-; Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR>
-; SPDX-License-Identifier: BSD-2-Clause-Patent
-;
-; Module Name:
-;
-;   SmmInit.nasm
-;
-; Abstract:
-;
-;   Functions for relocating SMBASE's for all processors
-;
-;-------------------------------------------------------------------------------
-
-%include "StuffRsbNasm.inc"
-
-extern ASM_PFX(SmmInitHandler)
-extern ASM_PFX(mRebasedFlag)
-extern ASM_PFX(mSmmRelocationOriginalAddress)
-
-global ASM_PFX(gPatchSmmCr3)
-global ASM_PFX(gPatchSmmCr4)
-global ASM_PFX(gPatchSmmCr0)
-global ASM_PFX(gPatchSmmInitStack)
-global ASM_PFX(gcSmiInitGdtr)
-global ASM_PFX(gcSmmInitSize)
-global ASM_PFX(gcSmmInitTemplate)
-
-%define PROTECT_MODE_CS 0x8
-%define PROTECT_MODE_DS 0x20
-
-    SECTION .text
-
-ASM_PFX(gcSmiInitGdtr):
-            DW      0
-            DQ      0
-
-global ASM_PFX(SmmStartup)
-
-BITS 16
-ASM_PFX(SmmStartup):
-    mov     eax, 0x80000001             ; read capability
-    cpuid
-    mov     ebx, edx                    ; rdmsr will change edx. keep it in ebx.
-    and     ebx, BIT20                  ; extract NX capability bit
-    shr     ebx, 9                      ; shift bit to IA32_EFER.NXE[BIT11] position
-    mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr3):
-    mov     cr3, eax
-o32 lgdt    [cs:ebp + (ASM_PFX(gcSmiInitGdtr) - ASM_PFX(SmmStartup))]
-    mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr4):
-    mov     cr4, eax
-    mov     ecx, 0xc0000080             ; IA32_EFER MSR
-    rdmsr
-    or      eax, ebx                    ; set NXE bit if NX is available
-    wrmsr
-    mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr0):
-    mov     di, PROTECT_MODE_DS
-    mov     cr0, eax
-    jmp     PROTECT_MODE_CS : dword @32bit
-
-BITS 32
-@32bit:
-    mov     ds, edi
-    mov     es, edi
-    mov     fs, edi
-    mov     gs, edi
-    mov     ss, edi
-    mov     esp, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmInitStack):
-    call    ASM_PFX(SmmInitHandler)
-    StuffRsb32
-    rsm
-
-BITS 16
-ASM_PFX(gcSmmInitTemplate):
-    mov ebp, ASM_PFX(SmmStartup)
-    sub ebp, 0x30000
-    jmp ebp
-
-ASM_PFX(gcSmmInitSize): DW $ - ASM_PFX(gcSmmInitTemplate)
-
-BITS 32
-global ASM_PFX(SmmRelocationSemaphoreComplete)
-ASM_PFX(SmmRelocationSemaphoreComplete):
-    push    eax
-    mov     eax, [ASM_PFX(mRebasedFlag)]
-    mov     byte [eax], 1
-    pop     eax
-    jmp     [ASM_PFX(mSmmRelocationOriginalAddress)]
-
-global ASM_PFX(PiSmmCpuSmmInitFixupAddress)
-ASM_PFX(PiSmmCpuSmmInitFixupAddress):
-    ret
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c
index 081f0c1501..10baf3ceb9 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c
@@ -1511,26 +1511,24 @@ SmiRendezvous (
   UINTN       Index;
   UINTN       Cr2;
 
   ASSERT (CpuIndex < mMaxNumberOfCpus);
 
-  if (mSmmRelocated) {
-    ASSERT (mSmmInitialized != NULL);
-  }
+  ASSERT (mSmmInitialized != NULL);
 
   //
   // Save Cr2 because Page Fault exception in SMM may override its value,
   // when using on-demand paging for above 4G memory.
   //
   Cr2 = 0;
   SaveCr2 (&Cr2);
 
-  if (mSmmRelocated && !mSmmInitialized[CpuIndex]) {
+  if (!mSmmInitialized[CpuIndex]) {
     //
-    // Perform SmmInitHandler for CpuIndex
+    // Perform InitializeSmm for CpuIndex
     //
-    SmmInitHandler ();
+    InitializeSmm ();
 
     //
     // Restore Cr2
     //
     RestoreCr2 (Cr2);
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c
index 499f979d34..03043f200a 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c
@@ -54,15 +54,10 @@ CPU_HOT_PLUG_DATA  mCpuHotPlugData = {
 //
 // Global pointer used to access mSmmCpuPrivateData from outside and inside SMM
 //
 SMM_CPU_PRIVATE_DATA  *gSmmCpuPrivate = &mSmmCpuPrivateData;
 
-//
-// SMM Relocation variables
-//
-volatile BOOLEAN  *mRebased;
-
 ///
 /// Handle for the SMM CPU Protocol
 ///
 EFI_HANDLE  mSmmCpuHandle = NULL;
 
@@ -83,11 +78,10 @@ EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL  mSmmMemoryAttribute = {
   EdkiiSmmClearMemoryAttributes
 };
 
 EFI_CPU_INTERRUPT_HANDLER  mExternalVectorTable[EXCEPTION_VECTOR_NUMBER];
 
-BOOLEAN           mSmmRelocated    = FALSE;
 volatile BOOLEAN  *mSmmInitialized = NULL;
 UINT32            mBspApicId       = 0;
 
 //
 // SMM stack information
@@ -133,16 +127,10 @@ SPIN_LOCK  *mConfigSmmCodeAccessCheckLock = NULL;
 EFI_SMRAM_DESCRIPTOR  *mSmmCpuSmramRanges;
 UINTN                 mSmmCpuSmramRangeCount;
 
 UINT8  mPhysicalAddressBits;
 
-//
-// Control register contents saved for SMM S3 resume state initialization.
-//
-UINT32  mSmmCr0;
-UINT32  mSmmCr4;
-
 /**
   Initialize IDT to setup exception handlers for SMM.
 
 **/
 VOID
@@ -335,37 +323,32 @@ SmmWriteSaveState (
 
   return Status;
 }
 
 /**
-  C function for SMI handler. To change all processor's SMMBase Register.
+  Initialize SMM environment.
 
 **/
 VOID
-EFIAPI
-SmmInitHandler (
+InitializeSmm (
   VOID
   )
 {
   UINT32   ApicId;
   UINTN    Index;
   BOOLEAN  IsBsp;
 
-  //
-  // Update SMM IDT entries' code segment and load IDT
-  //
-  AsmWriteIdtr (&gcSmiIdtr);
   ApicId = GetApicId ();
 
   IsBsp = (BOOLEAN)(mBspApicId == ApicId);
 
   ASSERT (mNumberOfCpus <= mMaxNumberOfCpus);
 
   for (Index = 0; Index < mNumberOfCpus; Index++) {
     if (ApicId == (UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId) {
       PERF_CODE (
-        MpPerfBegin (Index, SMM_MP_PERF_PROCEDURE_ID (SmmInitHandler));
+        MpPerfBegin (Index, SMM_MP_PERF_PROCEDURE_ID (InitializeSmm));
         );
       //
       // Initialize SMM specific features on the currently executing CPU
       //
       SmmCpuFeaturesInitializeProcessor (
@@ -386,19 +369,12 @@ SmmInitHandler (
         // Initialize private data during S3 resume
         //
         InitializeMpSyncData ();
       }
 
-      if (!mSmmRelocated) {
-        //
-        // Hook return after RSM to set SMM re-based flag
-        //
-        SemaphoreHook (Index, &mRebased[Index]);
-      }
-
       PERF_CODE (
-        MpPerfEnd (Index, SMM_MP_PERF_PROCEDURE_ID (SmmInitHandler));
+        MpPerfEnd (Index, SMM_MP_PERF_PROCEDURE_ID (InitializeSmm));
         );
 
       return;
     }
   }
@@ -454,111 +430,10 @@ ExecuteFirstSmiInit (
   }
 
   PERF_FUNCTION_END ();
 }
 
-/**
-  Relocate SmmBases for each processor.
-
-  Execute on first boot and all S3 resumes
-
-**/
-VOID
-EFIAPI
-SmmRelocateBases (
-  VOID
-  )
-{
-  UINT8                 BakBuf[BACK_BUF_SIZE];
-  SMRAM_SAVE_STATE_MAP  BakBuf2;
-  SMRAM_SAVE_STATE_MAP  *CpuStatePtr;
-  UINT8                 *U8Ptr;
-  UINTN                 Index;
-  UINTN                 BspIndex;
-
-  PERF_FUNCTION_BEGIN ();
-
-  //
-  // Make sure the reserved size is large enough for procedure SmmInitTemplate.
-  //
-  ASSERT (sizeof (BakBuf) >= gcSmmInitSize);
-
-  //
-  // Patch ASM code template with current CR0, CR3, and CR4 values
-  //
-  mSmmCr0 = (UINT32)AsmReadCr0 ();
-  PatchInstructionX86 (gPatchSmmCr0, mSmmCr0, 4);
-  PatchInstructionX86 (gPatchSmmCr3, AsmReadCr3 (), 4);
-  mSmmCr4 = (UINT32)AsmReadCr4 ();
-  PatchInstructionX86 (gPatchSmmCr4, mSmmCr4 & (~CR4_CET_ENABLE), 4);
-
-  //
-  // Patch GDTR for SMM base relocation
-  //
-  gcSmiInitGdtr.Base  = gcSmiGdtr.Base;
-  gcSmiInitGdtr.Limit = gcSmiGdtr.Limit;
-
-  U8Ptr       = (UINT8 *)(UINTN)(SMM_DEFAULT_SMBASE + SMM_HANDLER_OFFSET);
-  CpuStatePtr = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
-
-  //
-  // Backup original contents at address 0x38000
-  //
-  CopyMem (BakBuf, U8Ptr, sizeof (BakBuf));
-  CopyMem (&BakBuf2, CpuStatePtr, sizeof (BakBuf2));
-
-  //
-  // Load image for relocation
-  //
-  CopyMem (U8Ptr, gcSmmInitTemplate, gcSmmInitSize);
-
-  //
-  // Retrieve the local APIC ID of current processor
-  //
-  mBspApicId = GetApicId ();
-
-  //
-  // Relocate SM bases for all APs
-  // This is APs' 1st SMI - rebase will be done here, and APs' default SMI handler will be overridden by gcSmmInitTemplate
-  //
-  BspIndex = (UINTN)-1;
-  for (Index = 0; Index < mNumberOfCpus; Index++) {
-    mRebased[Index] = FALSE;
-    if (mBspApicId != (UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId) {
-      SendSmiIpi ((UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId);
-      //
-      // Wait for this AP to finish its 1st SMI
-      //
-      while (!mRebased[Index]) {
-      }
-    } else {
-      //
-      // BSP will be Relocated later
-      //
-      BspIndex = Index;
-    }
-  }
-
-  //
-  // Relocate BSP's SMM base
-  //
-  ASSERT (BspIndex != (UINTN)-1);
-  SendSmiIpi (mBspApicId);
-  //
-  // Wait for the BSP to finish its 1st SMI
-  //
-  while (!mRebased[BspIndex]) {
-  }
-
-  //
-  // Restore contents at address 0x38000
-  //
-  CopyMem (CpuStatePtr, &BakBuf2, sizeof (BakBuf2));
-  CopyMem (U8Ptr, BakBuf, sizeof (BakBuf));
-  PERF_FUNCTION_END ();
-}
-
 /**
   SMM Ready To Lock event notification handler.
 
   The CPU S3 data is copied to SMRAM for security and mSmmReadyToLock is set to
   perform additional lock actions that must be performed from SMM on the next SMI.
@@ -881,12 +756,10 @@ PiCpuSmmEntry (
   IN EFI_SYSTEM_TABLE  *SystemTable
   )
 {
   EFI_STATUS  Status;
   UINTN       Index;
-  VOID        *Buffer;
-  UINTN       BufferPages;
   UINTN       TileCodeSize;
   UINTN       TileDataSize;
   UINTN       TileSize;
   UINT8       *Stacks;
   VOID        *Registration;
@@ -901,11 +774,10 @@ PiCpuSmmEntry (
   PERF_FUNCTION_BEGIN ();
 
   //
   // Initialize address fixup
   //
-  PiSmmCpuSmmInitFixupAddress ();
   PiSmmCpuSmiEntryFixupAddress ();
 
   //
   // Initialize Debug Agent to support source level debug in SMM code
   //
@@ -1113,65 +985,34 @@ PiCpuSmmEntry (
   // context must be reduced.
   //
   ASSERT (TileSize <= (SMRAM_SAVE_STATE_MAP_OFFSET + sizeof (SMRAM_SAVE_STATE_MAP) - SMM_HANDLER_OFFSET));
 
   //
-  // Retrive the allocated SmmBase from gSmmBaseHobGuid. If found,
+  // Retrieve the allocated SmmBase from gSmmBaseHobGuid. If found,
   // means the SmBase relocation has been done.
   //
   mCpuHotPlugData.SmBase = NULL;
   Status                 = GetSmBase (mMaxNumberOfCpus, &mCpuHotPlugData.SmBase);
-  if (Status == EFI_OUT_OF_RESOURCES) {
-    ASSERT (Status != EFI_OUT_OF_RESOURCES);
+  ASSERT (!EFI_ERROR (Status));
+  if (EFI_ERROR (Status)) {
     CpuDeadLoop ();
   }
 
-  if (!EFI_ERROR (Status)) {
-    ASSERT (mCpuHotPlugData.SmBase != NULL);
-    //
-    // Check whether the Required TileSize is enough.
-    //
-    if (TileSize > SIZE_8KB) {
-      DEBUG ((DEBUG_ERROR, "The Range of Smbase in SMRAM is not enough -- Required TileSize = 0x%08x, Actual TileSize = 0x%08x\n", TileSize, SIZE_8KB));
-      FreePool (mCpuHotPlugData.SmBase);
-      FreePool (gSmmCpuPrivate->ProcessorInfo);
-      CpuDeadLoop ();
-      return RETURN_BUFFER_TOO_SMALL;
-    }
-
-    mSmmRelocated = TRUE;
-  } else {
-    ASSERT (Status == EFI_NOT_FOUND);
-    ASSERT (mCpuHotPlugData.SmBase == NULL);
-    //
-    // When the HOB doesn't exist, allocate new SMBASE itself.
-    //
-    DEBUG ((DEBUG_INFO, "PiCpuSmmEntry: gSmmBaseHobGuid not found!\n"));
-
-    mCpuHotPlugData.SmBase = (UINTN *)AllocatePool (sizeof (UINTN) * mMaxNumberOfCpus);
-    if (mCpuHotPlugData.SmBase == NULL) {
-      ASSERT (mCpuHotPlugData.SmBase != NULL);
-      CpuDeadLoop ();
-    }
-
-    //
-    // very old processors (i486 + pentium) need 32k not 4k alignment, exclude them.
-    //
-    ASSERT (FamilyId >= 6);
-    //
-    // Allocate buffer for all of the tiles.
-    //
-    BufferPages = EFI_SIZE_TO_PAGES (SIZE_32KB + TileSize * (mMaxNumberOfCpus - 1));
-    Buffer      = AllocateAlignedCodePages (BufferPages, SIZE_4KB);
-    if (Buffer == NULL) {
-      DEBUG ((DEBUG_ERROR, "Failed to allocate %Lu pages.\n", (UINT64)BufferPages));
-      CpuDeadLoop ();
-      return EFI_OUT_OF_RESOURCES;
-    }
+  //
+  // ASSERT SmBase has been relocated.
+  //
+  ASSERT (mCpuHotPlugData.SmBase != NULL);
 
-    ASSERT (Buffer != NULL);
-    DEBUG ((DEBUG_INFO, "New Allcoated SMRAM SaveState Buffer (0x%08x, 0x%08x)\n", Buffer, EFI_PAGES_TO_SIZE (BufferPages)));
+  //
+  // Check whether the Required TileSize is enough.
+  //
+  if (TileSize > SIZE_8KB) {
+    DEBUG ((DEBUG_ERROR, "The Range of Smbase in SMRAM is not enough -- Required TileSize = 0x%08x, Actual TileSize = 0x%08x\n", TileSize, SIZE_8KB));
+    FreePool (mCpuHotPlugData.SmBase);
+    FreePool (gSmmCpuPrivate->ProcessorInfo);
+    CpuDeadLoop ();
+    return RETURN_BUFFER_TOO_SMALL;
   }
 
   //
   // Allocate buffer for pointers to array in  SMM_CPU_PRIVATE_DATA.
   //
@@ -1198,14 +1039,10 @@ PiCpuSmmEntry (
   // Retrieve APIC ID of each enabled processor from the MP Services protocol.
   // Also compute the SMBASE address, CPU Save State address, and CPU Save state
   // size for each CPU in the platform
   //
   for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
-    if (!mSmmRelocated) {
-      mCpuHotPlugData.SmBase[Index] = (UINTN)Buffer + Index * TileSize - SMM_HANDLER_OFFSET;
-    }
-
     gSmmCpuPrivate->CpuSaveStateSize[Index] = sizeof (SMRAM_SAVE_STATE_MAP);
     gSmmCpuPrivate->CpuSaveState[Index]     = (VOID *)(mCpuHotPlugData.SmBase[Index] + SMRAM_SAVE_STATE_MAP_OFFSET);
     gSmmCpuPrivate->Operation[Index]        = SmmCpuNone;
 
     if (Index < mNumberOfCpus) {
@@ -1297,45 +1134,15 @@ PiCpuSmmEntry (
   DEBUG ((DEBUG_INFO, "PcdCpuSmmStackGuard      - 0x%x\n", FeaturePcdGet (PcdCpuSmmStackGuard)));
   if ((PcdGet32 (PcdControlFlowEnforcementPropertyMask) != 0) && mCetSupported) {
     DEBUG ((DEBUG_INFO, "mSmmShadowStackSize      - 0x%x\n", mSmmShadowStackSize));
   }
 
-  //
-  // Set SMI stack for SMM base relocation
-  //
-  PatchInstructionX86 (
-    gPatchSmmInitStack,
-    (UINTN)(Stacks + mSmmStackSize - sizeof (UINTN)),
-    sizeof (UINTN)
-    );
-
   //
   // Initialize IDT
   //
   InitializeSmmIdt ();
 
-  //
-  // Check whether Smm Relocation is done or not.
-  // If not, will do the SmmBases Relocation here!!!
-  //
-  if (!mSmmRelocated) {
-    //
-    // Relocate SMM Base addresses to the ones allocated from SMRAM
-    //
-    mRebased = (BOOLEAN *)AllocateZeroPool (sizeof (BOOLEAN) * mMaxNumberOfCpus);
-    ASSERT (mRebased != NULL);
-    SmmRelocateBases ();
-
-    //
-    // Call hook for BSP to perform extra actions in normal mode after all
-    // SMM base addresses have been relocated on all CPUs
-    //
-    SmmCpuFeaturesSmmRelocationComplete ();
-  }
-
-  DEBUG ((DEBUG_INFO, "mXdSupported - 0x%x\n", mXdSupported));
-
   //
   // SMM Time initialization
   //
   InitializeSmmTimer ();
 
@@ -1368,19 +1175,19 @@ PiCpuSmmEntry (
   //
   // For relocated SMBASE, some MSRs & CSRs are still required to be configured in SMM Mode for SMM Initialization.
   // Those MSRs & CSRs must be configured before normal SMI sources happen.
   // So, here is to issue SMI IPI (All Excluding  Self SMM IPI + BSP SMM IPI) to execute first SMI init.
   //
-  if (mSmmRelocated) {
-    ExecuteFirstSmiInit ();
+  ExecuteFirstSmiInit ();
 
-    //
-    // Call hook for BSP to perform extra actions in normal mode after all
-    // SMM base addresses have been relocated on all CPUs
-    //
-    SmmCpuFeaturesSmmRelocationComplete ();
-  }
+  //
+  // Call hook for BSP to perform extra actions in normal mode after all
+  // SMM base addresses have been relocated on all CPUs
+  //
+  SmmCpuFeaturesSmmRelocationComplete ();
+
+  DEBUG ((DEBUG_INFO, "mXdSupported - 0x%x\n", mXdSupported));
 
   //
   // Fill in SMM Reserved Regions
   //
   gSmmCpuPrivate->SmmReservedSmramRegion[0].SmramReservedStart = 0;
@@ -1767,92 +1574,10 @@ AllocateCodePages (
   }
 
   return (VOID *)(UINTN)Memory;
 }
 
-/**
-  Allocate aligned pages for code.
-
-  @param[in]  Pages                 Number of pages to be allocated.
-  @param[in]  Alignment             The requested alignment of the allocation.
-                                    Must be a power of two.
-                                    If Alignment is zero, then byte alignment is used.
-
-  @return Allocated memory.
-**/
-VOID *
-AllocateAlignedCodePages (
-  IN UINTN  Pages,
-  IN UINTN  Alignment
-  )
-{
-  EFI_STATUS            Status;
-  EFI_PHYSICAL_ADDRESS  Memory;
-  UINTN                 AlignedMemory;
-  UINTN                 AlignmentMask;
-  UINTN                 UnalignedPages;
-  UINTN                 RealPages;
-
-  //
-  // Alignment must be a power of two or zero.
-  //
-  ASSERT ((Alignment & (Alignment - 1)) == 0);
-
-  if (Pages == 0) {
-    return NULL;
-  }
-
-  if (Alignment > EFI_PAGE_SIZE) {
-    //
-    // Calculate the total number of pages since alignment is larger than page size.
-    //
-    AlignmentMask = Alignment - 1;
-    RealPages     = Pages + EFI_SIZE_TO_PAGES (Alignment);
-    //
-    // Make sure that Pages plus EFI_SIZE_TO_PAGES (Alignment) does not overflow.
-    //
-    ASSERT (RealPages > Pages);
-
-    Status = gSmst->SmmAllocatePages (AllocateAnyPages, EfiRuntimeServicesCode, RealPages, &Memory);
-    if (EFI_ERROR (Status)) {
-      return NULL;
-    }
-
-    AlignedMemory  = ((UINTN)Memory + AlignmentMask) & ~AlignmentMask;
-    UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN)Memory);
-    if (UnalignedPages > 0) {
-      //
-      // Free first unaligned page(s).
-      //
-      Status = gSmst->SmmFreePages (Memory, UnalignedPages);
-      ASSERT_EFI_ERROR (Status);
-    }
-
-    Memory         = AlignedMemory + EFI_PAGES_TO_SIZE (Pages);
-    UnalignedPages = RealPages - Pages - UnalignedPages;
-    if (UnalignedPages > 0) {
-      //
-      // Free last unaligned page(s).
-      //
-      Status = gSmst->SmmFreePages (Memory, UnalignedPages);
-      ASSERT_EFI_ERROR (Status);
-    }
-  } else {
-    //
-    // Do not over-allocate pages in this case.
-    //
-    Status = gSmst->SmmAllocatePages (AllocateAnyPages, EfiRuntimeServicesCode, Pages, &Memory);
-    if (EFI_ERROR (Status)) {
-      return NULL;
-    }
-
-    AlignedMemory = (UINTN)Memory;
-  }
-
-  return (VOID *)AlignedMemory;
-}
-
 /**
   Perform the remaining tasks.
 
 **/
 VOID
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h
index 7f244ea803..f42910ddf1 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h
@@ -186,18 +186,10 @@ typedef struct {
 // Code select value
 //
 #define PROTECT_MODE_CODE_SEGMENT  0x08
 #define LONG_MODE_CODE_SEGMENT     0x38
 
-//
-// The size 0x20 must be bigger than
-// the size of template code of SmmInit. Currently,
-// the size of SmmInit requires the 0x16 Bytes buffer
-// at least.
-//
-#define BACK_BUF_SIZE  0x20
-
 #define EXCEPTION_VECTOR_NUMBER  0x20
 
 #define INVALID_APIC_ID  0xFFFFFFFFFFFFFFFFULL
 
 //
@@ -355,16 +347,15 @@ SmmWriteSaveState (
   IN UINTN                        CpuIndex,
   IN CONST VOID                   *Buffer
   );
 
 /**
-  C function for SMI handler. To change all processor's SMMBase Register.
+  Initialize SMM environment.
 
 **/
 VOID
-EFIAPI
-SmmInitHandler (
+InitializeSmm (
   VOID
   );
 
 /**
   Issue SMI IPI (All Excluding Self SMM IPI + BSP SMM IPI) to execute first SMI init.
@@ -373,22 +364,13 @@ SmmInitHandler (
 VOID
 ExecuteFirstSmiInit (
   VOID
   );
 
-extern BOOLEAN            mSmmRelocated;
 extern volatile  BOOLEAN  *mSmmInitialized;
 extern UINT32             mBspApicId;
 
-extern CONST UINT8        gcSmmInitTemplate[];
-extern CONST UINT16       gcSmmInitSize;
-X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr0;
-extern UINT32             mSmmCr0;
-X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr3;
-extern UINT32             mSmmCr4;
-X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr4;
-X86_ASSEMBLY_PATCH_LABEL  gPatchSmmInitStack;
 X86_ASSEMBLY_PATCH_LABEL  mPatchCetSupported;
 extern BOOLEAN            mCetSupported;
 
 /**
   Semaphore operation for all processor relocate SMMBase.
@@ -473,11 +455,10 @@ extern UINT64                        gPhyMask;
 extern SMM_DISPATCHER_MP_SYNC_DATA   *mSmmMpSyncData;
 extern UINTN                         mSmmStackArrayBase;
 extern UINTN                         mSmmStackArrayEnd;
 extern UINTN                         mSmmStackSize;
 extern EFI_SMM_CPU_SERVICE_PROTOCOL  mSmmCpuService;
-extern IA32_DESCRIPTOR               gcSmiInitGdtr;
 extern SMM_CPU_SEMAPHORES            mSmmCpuSemaphores;
 extern UINTN                         mSemaphoreSize;
 extern SPIN_LOCK                     *mPFLock;
 extern SPIN_LOCK                     *mConfigSmmCodeAccessCheckLock;
 extern EFI_SMRAM_DESCRIPTOR          *mSmmCpuSmramRanges;
@@ -791,22 +772,10 @@ VOID
 FindSmramInfo (
   OUT UINT32  *SmrrBase,
   OUT UINT32  *SmrrSize
   );
 
-/**
-  Relocate SmmBases for each processor.
-
-  Execute on first boot and all S3 resumes
-
-**/
-VOID
-EFIAPI
-SmmRelocateBases (
-  VOID
-  );
-
 /**
   Page Fault handler for SMM use.
 
   @param  InterruptType    Defines the type of interrupt or exception that
                            occurred on the processor.This parameter is processor architecture specific.
@@ -847,62 +816,19 @@ PerformPreTasks (
 VOID
 InitMsrSpinLockByIndex (
   IN UINT32  MsrIndex
   );
 
-/**
-  Hook return address of SMM Save State so that semaphore code
-  can be executed immediately after AP exits SMM to indicate to
-  the BSP that an AP has exited SMM after SMBASE relocation.
-
-  @param[in] CpuIndex     The processor index.
-  @param[in] RebasedFlag  A pointer to a flag that is set to TRUE
-                          immediately after AP exits SMM.
-
-**/
-VOID
-SemaphoreHook (
-  IN UINTN             CpuIndex,
-  IN volatile BOOLEAN  *RebasedFlag
-  );
-
 /**
 Configure SMM Code Access Check feature for all processors.
 SMM Feature Control MSR will be locked after configuration.
 **/
 VOID
 ConfigSmmCodeAccessCheck (
   VOID
   );
 
-/**
-  Hook the code executed immediately after an RSM instruction on the currently
-  executing CPU.  The mode of code executed immediately after RSM must be
-  detected, and the appropriate hook must be selected.  Always clear the auto
-  HALT restart flag if it is set.
-
-  @param[in] CpuIndex                 The processor index for the currently
-                                      executing CPU.
-  @param[in] CpuState                 Pointer to SMRAM Save State Map for the
-                                      currently executing CPU.
-  @param[in] NewInstructionPointer32  Instruction pointer to use if resuming to
-                                      32-bit mode from 64-bit SMM.
-  @param[in] NewInstructionPointer    Instruction pointer to use if resuming to
-                                      same mode as SMM.
-
-  @retval The value of the original instruction pointer before it was hooked.
-
-**/
-UINT64
-EFIAPI
-HookReturnFromSmm (
-  IN UINTN              CpuIndex,
-  SMRAM_SAVE_STATE_MAP  *CpuState,
-  UINT64                NewInstructionPointer32,
-  UINT64                NewInstructionPointer
-  );
-
 /**
   Get the size of the SMI Handler in bytes.
 
   @retval The size, in bytes, of the SMI Handler.
 
@@ -1103,26 +1029,10 @@ AllocatePageTableMemory (
 VOID *
 AllocateCodePages (
   IN UINTN  Pages
   );
 
-/**
-  Allocate aligned pages for code.
-
-  @param[in]  Pages                 Number of pages to be allocated.
-  @param[in]  Alignment             The requested alignment of the allocation.
-                                    Must be a power of two.
-                                    If Alignment is zero, then byte alignment is used.
-
-  @return Allocated memory.
-**/
-VOID *
-AllocateAlignedCodePages (
-  IN UINTN  Pages,
-  IN UINTN  Alignment
-  );
-
 //
 // S3 related global variable and function prototype.
 //
 
 extern BOOLEAN  mSmmS3Flag;
@@ -1300,19 +1210,10 @@ EdkiiSmmGetMemoryAttributes (
   IN  EFI_PHYSICAL_ADDRESS                 BaseAddress,
   IN  UINT64                               Length,
   IN  UINT64                               *Attributes
   );
 
-/**
-  This function fixes up the address of the global variable or function
-  referred in SmmInit assembly files to be the absolute address.
-**/
-VOID
-EFIAPI
-PiSmmCpuSmmInitFixupAddress (
-  );
-
 /**
   This function fixes up the address of the global variable or function
   referred in SmiEntry assembly files to be the absolute address.
 **/
 VOID
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf
index a018954ed7..1a230ad2d0 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf
@@ -45,28 +45,24 @@
   SmmMp.c
   SmmMpPerf.h
   SmmMpPerf.c
 
 [Sources.Ia32]
-  Ia32/Semaphore.c
   Ia32/PageTbl.c
   Ia32/SmmFuncsArch.c
   Ia32/SmmProfileArch.c
   Ia32/SmmProfileArch.h
-  Ia32/SmmInit.nasm
   Ia32/SmiEntry.nasm
   Ia32/SmiException.nasm
   Ia32/MpFuncs.nasm
   Ia32/Cet.nasm
 
 [Sources.X64]
-  X64/Semaphore.c
   X64/PageTbl.c
   X64/SmmFuncsArch.c
   X64/SmmProfileArch.c
   X64/SmmProfileArch.h
-  X64/SmmInit.nasm
   X64/SmiEntry.nasm
   X64/SmiException.nasm
   X64/MpFuncs.nasm
   X64/Cet.nasm
 
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmMpPerf.h b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmMpPerf.h
index 591b212c06..2e2ea3c76e 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmMpPerf.h
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmMpPerf.h
@@ -12,11 +12,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
 
 //
 // The list of all MP procedures that need to be perf-logged.
 //
 #define  SMM_MP_PERF_PROCEDURE_LIST(_) \
-  _(SmmInitHandler), \
+  _(InitializeSmm), \
   _(SmmRendezvousEntry), \
   _(PlatformValidSmi), \
   _(SmmRendezvousExit), \
   _(SmmMpProcedureMax) // Add new entries above this line
 
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c b/UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c
index 1e316ee0ac..b9a62aeeb0 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c
@@ -67,79 +67,10 @@ IA32_DESCRIPTOR  gSmiHandlerIdtr;
 ///
 /// The mode of the CPU at the time an SMI occurs
 ///
 UINT8  mSmmSaveStateRegisterLma;
 
-/**
-  Hook the code executed immediately after an RSM instruction on the currently
-  executing CPU.  The mode of code executed immediately after RSM must be
-  detected, and the appropriate hook must be selected.  Always clear the auto
-  HALT restart flag if it is set.
-
-  @param[in] CpuIndex                 The processor index for the currently
-                                      executing CPU.
-  @param[in] CpuState                 Pointer to SMRAM Save State Map for the
-                                      currently executing CPU.
-  @param[in] NewInstructionPointer32  Instruction pointer to use if resuming to
-                                      32-bit mode from 64-bit SMM.
-  @param[in] NewInstructionPointer    Instruction pointer to use if resuming to
-                                      same mode as SMM.
-
-  @retval The value of the original instruction pointer before it was hooked.
-
-**/
-UINT64
-EFIAPI
-HookReturnFromSmm (
-  IN UINTN              CpuIndex,
-  SMRAM_SAVE_STATE_MAP  *CpuState,
-  UINT64                NewInstructionPointer32,
-  UINT64                NewInstructionPointer
-  )
-{
-  UINT64  OriginalInstructionPointer;
-
-  OriginalInstructionPointer = SmmCpuFeaturesHookReturnFromSmm (
-                                 CpuIndex,
-                                 CpuState,
-                                 NewInstructionPointer32,
-                                 NewInstructionPointer
-                                 );
-  if (OriginalInstructionPointer != 0) {
-    return OriginalInstructionPointer;
-  }
-
-  if (mSmmSaveStateRegisterLma == EFI_SMM_SAVE_STATE_REGISTER_LMA_32BIT) {
-    OriginalInstructionPointer = (UINT64)CpuState->x86._EIP;
-    CpuState->x86._EIP         = (UINT32)NewInstructionPointer;
-    //
-    // Clear the auto HALT restart flag so the RSM instruction returns
-    // program control to the instruction following the HLT instruction.
-    //
-    if ((CpuState->x86.AutoHALTRestart & BIT0) != 0) {
-      CpuState->x86.AutoHALTRestart &= ~BIT0;
-    }
-  } else {
-    OriginalInstructionPointer = CpuState->x64._RIP;
-    if ((CpuState->x64.IA32_EFER & LMA) == 0) {
-      CpuState->x64._RIP = (UINT32)NewInstructionPointer32;
-    } else {
-      CpuState->x64._RIP = (UINT32)NewInstructionPointer;
-    }
-
-    //
-    // Clear the auto HALT restart flag so the RSM instruction returns
-    // program control to the instruction following the HLT instruction.
-    //
-    if ((CpuState->x64.AutoHALTRestart & BIT0) != 0) {
-      CpuState->x64.AutoHALTRestart &= ~BIT0;
-    }
-  }
-
-  return OriginalInstructionPointer;
-}
-
 /**
   Get the size of the SMI Handler in bytes.
 
   @retval The size, in bytes, of the SMI Handler.
 
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c
deleted file mode 100644
index dafbc3390e..0000000000
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c
+++ /dev/null
@@ -1,69 +0,0 @@
-/** @file
-Semaphore mechanism to indicate to the BSP that an AP has exited SMM
-after SMBASE relocation.
-
-Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>
-SPDX-License-Identifier: BSD-2-Clause-Patent
-
-**/
-
-#include "PiSmmCpuDxeSmm.h"
-
-X86_ASSEMBLY_PATCH_LABEL  gPatchSmmRelocationOriginalAddressPtr32;
-X86_ASSEMBLY_PATCH_LABEL  gPatchRebasedFlagAddr32;
-
-UINTN             mSmmRelocationOriginalAddress;
-volatile BOOLEAN  *mRebasedFlag;
-
-/**
-AP Semaphore operation in 32-bit mode while BSP runs in 64-bit mode.
-**/
-VOID
-SmmRelocationSemaphoreComplete32 (
-  VOID
-  );
-
-/**
-  Hook return address of SMM Save State so that semaphore code
-  can be executed immediately after AP exits SMM to indicate to
-  the BSP that an AP has exited SMM after SMBASE relocation.
-
-  @param[in] CpuIndex     The processor index.
-  @param[in] RebasedFlag  A pointer to a flag that is set to TRUE
-                          immediately after AP exits SMM.
-
-**/
-VOID
-SemaphoreHook (
-  IN UINTN             CpuIndex,
-  IN volatile BOOLEAN  *RebasedFlag
-  )
-{
-  SMRAM_SAVE_STATE_MAP  *CpuState;
-  UINTN                 TempValue;
-
-  mRebasedFlag = RebasedFlag;
-  PatchInstructionX86 (
-    gPatchRebasedFlagAddr32,
-    (UINT32)(UINTN)mRebasedFlag,
-    4
-    );
-
-  CpuState                      = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
-  mSmmRelocationOriginalAddress = HookReturnFromSmm (
-                                    CpuIndex,
-                                    CpuState,
-                                    (UINT64)(UINTN)&SmmRelocationSemaphoreComplete32,
-                                    (UINT64)(UINTN)&SmmRelocationSemaphoreComplete
-                                    );
-
-  //
-  // Use temp value to fix ICC compiler warning
-  //
-  TempValue = (UINTN)&mSmmRelocationOriginalAddress;
-  PatchInstructionX86 (
-    gPatchSmmRelocationOriginalAddressPtr32,
-    (UINT32)TempValue,
-    4
-    );
-}
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm
deleted file mode 100644
index 9cf3a6dcf9..0000000000
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm
+++ /dev/null
@@ -1,146 +0,0 @@
-;------------------------------------------------------------------------------ ;
-; Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR>
-; SPDX-License-Identifier: BSD-2-Clause-Patent
-;
-; Module Name:
-;
-;   SmmInit.nasm
-;
-; Abstract:
-;
-;   Functions for relocating SMBASE's for all processors
-;
-;-------------------------------------------------------------------------------
-
-%include "StuffRsbNasm.inc"
-
-extern ASM_PFX(SmmInitHandler)
-extern ASM_PFX(mRebasedFlag)
-extern ASM_PFX(mSmmRelocationOriginalAddress)
-
-global ASM_PFX(gPatchSmmCr3)
-global ASM_PFX(gPatchSmmCr4)
-global ASM_PFX(gPatchSmmCr0)
-global ASM_PFX(gPatchSmmInitStack)
-global ASM_PFX(gcSmiInitGdtr)
-global ASM_PFX(gcSmmInitSize)
-global ASM_PFX(gcSmmInitTemplate)
-global ASM_PFX(gPatchRebasedFlagAddr32)
-global ASM_PFX(gPatchSmmRelocationOriginalAddressPtr32)
-
-%define LONG_MODE_CS 0x38
-
-    DEFAULT REL
-    SECTION .text
-
-ASM_PFX(gcSmiInitGdtr):
-            DW      0
-            DQ      0
-
-global ASM_PFX(SmmStartup)
-
-BITS 16
-ASM_PFX(SmmStartup):
-    mov     eax, 0x80000001             ; read capability
-    cpuid
-    mov     ebx, edx                    ; rdmsr will change edx. keep it in ebx.
-    mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr3):
-    mov     cr3, eax
-o32 lgdt    [cs:ebp + (ASM_PFX(gcSmiInitGdtr) - ASM_PFX(SmmStartup))]
-    mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr4):
-    or      ah,  2                      ; enable XMM registers access
-    mov     cr4, eax
-    mov     ecx, 0xc0000080             ; IA32_EFER MSR
-    rdmsr
-    or      ah, BIT0                    ; set LME bit
-    test    ebx, BIT20                  ; check NXE capability
-    jz      .1
-    or      ah, BIT3                    ; set NXE bit
-.1:
-    wrmsr
-    mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr0):
-    mov     cr0, eax                    ; enable protected mode & paging
-    jmp     LONG_MODE_CS : dword 0      ; offset will be patched to @LongMode
-@PatchLongModeOffset:
-
-BITS 64
-@LongMode:                              ; long-mode starts here
-    mov     rsp, strict qword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmInitStack):
-    and     sp, 0xfff0                  ; make sure RSP is 16-byte aligned
-    ;
-    ; According to X64 calling convention, XMM0~5 are volatile, we need to save
-    ; them before calling C-function.
-    ;
-    sub     rsp, 0x60
-    movdqa  [rsp], xmm0
-    movdqa  [rsp + 0x10], xmm1
-    movdqa  [rsp + 0x20], xmm2
-    movdqa  [rsp + 0x30], xmm3
-    movdqa  [rsp + 0x40], xmm4
-    movdqa  [rsp + 0x50], xmm5
-
-    add     rsp, -0x20
-    call    ASM_PFX(SmmInitHandler)
-    add     rsp, 0x20
-
-    ;
-    ; Restore XMM0~5 after calling C-function.
-    ;
-    movdqa  xmm0, [rsp]
-    movdqa  xmm1, [rsp + 0x10]
-    movdqa  xmm2, [rsp + 0x20]
-    movdqa  xmm3, [rsp + 0x30]
-    movdqa  xmm4, [rsp + 0x40]
-    movdqa  xmm5, [rsp + 0x50]
-
-    StuffRsb64
-    rsm
-
-BITS 16
-ASM_PFX(gcSmmInitTemplate):
-    mov ebp, [cs:@L1 - ASM_PFX(gcSmmInitTemplate) + 0x8000]
-    sub ebp, 0x30000
-    jmp ebp
-@L1:
-    DQ     0; ASM_PFX(SmmStartup)
-
-ASM_PFX(gcSmmInitSize): DW $ - ASM_PFX(gcSmmInitTemplate)
-
-BITS 64
-global ASM_PFX(SmmRelocationSemaphoreComplete)
-ASM_PFX(SmmRelocationSemaphoreComplete):
-    push    rax
-    mov     rax, [ASM_PFX(mRebasedFlag)]
-    mov     byte [rax], 1
-    pop     rax
-    jmp     [ASM_PFX(mSmmRelocationOriginalAddress)]
-
-;
-; Semaphore code running in 32-bit mode
-;
-BITS 32
-global ASM_PFX(SmmRelocationSemaphoreComplete32)
-ASM_PFX(SmmRelocationSemaphoreComplete32):
-    push    eax
-    mov     eax, strict dword 0                ; source operand will be patched
-ASM_PFX(gPatchRebasedFlagAddr32):
-    mov     byte [eax], 1
-    pop     eax
-    jmp     dword [dword 0]                    ; destination will be patched
-ASM_PFX(gPatchSmmRelocationOriginalAddressPtr32):
-
-BITS 64
-global ASM_PFX(PiSmmCpuSmmInitFixupAddress)
-ASM_PFX(PiSmmCpuSmmInitFixupAddress):
-    lea    rax, [@LongMode]
-    lea    rcx, [@PatchLongModeOffset - 6]
-    mov    dword [rcx], eax
-
-    lea    rax, [ASM_PFX(SmmStartup)]
-    lea    rcx, [@L1]
-    mov    qword [rcx], rax
-    ret
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117785): https://edk2.groups.io/g/devel/message/117785
Mute This Topic: https://groups.io/mt/105535817/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 19+ messages in thread

* Re: [edk2-devel] [PATCH v2 09/10] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 09/10] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib Wu, Jiaxin
@ 2024-04-15 15:26   ` Guo Dong
  0 siblings, 0 replies; 19+ messages in thread
From: Guo Dong @ 2024-04-15 15:26 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Rhodes, Sean, Lu, James, Guo, Gua, Ni, Ray


Reviewed-by: Guo Dong <guo.dong@intel.com>

-----Original Message-----
From: Wu, Jiaxin <jiaxin.wu@intel.com> 
Sent: Monday, April 15, 2024 6:30 AM
To: devel@edk2.groups.io
Cc: Dong, Guo <guo.dong@intel.com>; Rhodes, Sean <sean@starlabs.systems>; Lu, James <james.lu@intel.com>; Guo, Gua <gua.guo@intel.com>; Ni, Ray <ray.ni@intel.com>
Subject: [PATCH v2 09/10] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib

This patch just includes SmmRelocationLib in UefiPayloadPkg.

Cc: Guo Dong <guo.dong@intel.com>
Cc: Sean Rhodes <sean@starlabs.systems>
Cc: James Lu <james.lu@intel.com>
Cc: Gua Guo <gua.guo@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
Reviewed-by: Gua Guo <gua.guo@intel.com>
---
 UefiPayloadPkg/UefiPayloadPkg.dsc | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc
index 433fb51a56..328b7fd4fe 100644
--- a/UefiPayloadPkg/UefiPayloadPkg.dsc
+++ b/UefiPayloadPkg/UefiPayloadPkg.dsc
@@ -313,10 +313,12 @@
   VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf
   VariableFlashInfoLib|MdeModulePkg/Library/BaseVariableFlashInfoLib/BaseVariableFlashInfoLib.inf
   CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf
   ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
   FdtLib|MdePkg/Library/BaseFdtLib/BaseFdtLib.inf
+  SmmRelocationLib|UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
+
 [LibraryClasses.common]
 !if $(BOOTSPLASH_IMAGE)
   SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf
   BmpSupportLib|MdeModulePkg/Library/BaseBmpSupportLib/BaseBmpSupportLib.inf
 !endif
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117792): https://edk2.groups.io/g/devel/message/117792
Mute This Topic: https://groups.io/mt/105535815/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 19+ messages in thread

* Re: [edk2-devel] [PATCH v2 01/10] UefiCpuPkg: Add SmmRelocationLib class
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 01/10] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
@ 2024-04-16  1:50   ` Ni, Ray
  0 siblings, 0 replies; 19+ messages in thread
From: Ni, Ray @ 2024-04-16  1:50 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

[-- Attachment #1: Type: text/plain, Size: 4038 bytes --]

Reviewed-by: Ray Ni <ray.ni@intel.com>

Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Monday, April 15, 2024 21:30
To: devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Ni, Ray <ray.ni@intel.com>; Zeng, Star <star.zeng@intel.com>; Gerd Hoffmann <kraxel@redhat.com>; Kumar, Rahul R <rahul.r.kumar@intel.com>
Subject: [PATCH v2 01/10] UefiCpuPkg: Add SmmRelocationLib class

Intel plans to separate the smbase relocation logic from
PiSmmCpuDxeSmm driver, and the related behavior will be
moved to the new interface defined by the SmmRelocationLib
class.

The SmmRelocationLib class provides the SmmRelocationInit()
interface for platform to do the smbase relocation, which
shall provide below 2 functionalities:
1. Relocate smbases for each processor.
2. Create the gSmmBaseHobGuid HOB.

With SmmRelocationLib, PiSmmCpuDxeSmm driver (which runs at
a later phase) shall:
1. Consume the gSmmBaseHobGuid HOB for the relocated smbases
for each Processor.
2. Execute the early SMM Init.

This patch just provides the SmmRelocationLib class.

Cc: Ray Ni <ray.ni@intel.com>
Cc: Zeng Star <star.zeng@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 UefiCpuPkg/Include/Library/SmmRelocationLib.h | 42 +++++++++++++++++++++++++++
 UefiCpuPkg/UefiCpuPkg.dec                     |  3 ++
 2 files changed, 45 insertions(+)
 create mode 100644 UefiCpuPkg/Include/Library/SmmRelocationLib.h

diff --git a/UefiCpuPkg/Include/Library/SmmRelocationLib.h b/UefiCpuPkg/Include/Library/SmmRelocationLib.h
new file mode 100644
index 0000000000..999a5b46d1
--- /dev/null
+++ b/UefiCpuPkg/Include/Library/SmmRelocationLib.h
@@ -0,0 +1,42 @@
+/** @file
+  Header file for SMM Relocation Library.
+
+  The SmmRelocationLib class provides the SmmRelocationInit()
+  interface for platform to do the smbase relocation, which
+  shall provide below 2 functionalities:
+  1. Relocate SmBases for each processor.
+  2. Create the SmBase HOB (gSmmBaseHobGuid).
+
+  With SmmRelocationLib, PiSmmCpuDxeSmm driver (which runs at a later phase)
+  shall:
+  1. Consume the gSmmBaseHobGuid for the relocated smbase for each Processor.
+  2. Execute early SMM init.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef SMM_RELOCATION_LIB_H_
+#define SMM_RELOCATION_LIB_H_
+
+#include <Ppi/MpServices2.h>
+
+/**
+  CPU SmmBase Relocation Init.
+
+  This function is to relocate CPU SmmBase.
+
+  @param[in] MpServices2        Pointer to this instance of the MpServices.
+
+  @retval EFI_SUCCESS           CPU SmmBase Relocated successfully.
+  @retval Others                CPU SmmBase Relocation failed.
+
+**/
+EFI_STATUS
+EFIAPI
+SmmRelocationInit (
+  IN EDKII_PEI_MP_SERVICES2_PPI  *MpServices2
+  );
+
+#endif
diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec
index 571b59b36f..1d7890f19e 100644
--- a/UefiCpuPkg/UefiCpuPkg.dec
+++ b/UefiCpuPkg/UefiCpuPkg.dec
@@ -65,10 +65,13 @@
   MmSaveStateLib|Include/Library/MmSaveStateLib.h

   ## @libraryclass   Provides functions for SMM CPU Sync Operation.
   SmmCpuSyncLib|Include/Library/SmmCpuSyncLib.h

+  ## @libraryclass   Provides functions for SMM Relocation Operation.
+  SmmRelocationLib|Include/Library/SmmRelocationLib.h
+
 [LibraryClasses.RISCV64]
   ##  @libraryclass  Provides functions to manage MMU features on RISCV64 CPUs.
   ##
   RiscVMmuLib|Include/Library/BaseRiscVMmuLib.h

--
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117815): https://edk2.groups.io/g/devel/message/117815
Mute This Topic: https://groups.io/mt/105535805/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



[-- Attachment #2: Type: text/html, Size: 6723 bytes --]

^ permalink raw reply related	[flat|nested] 19+ messages in thread

* Re: [edk2-devel] [PATCH v2 02/10] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 02/10] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance Wu, Jiaxin
@ 2024-04-16  3:19   ` Ni, Ray
  2024-04-16 12:58     ` Wu, Jiaxin
  0 siblings, 1 reply; 19+ messages in thread
From: Ni, Ray @ 2024-04-16  3:19 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

[-- Attachment #1: Type: text/plain, Size: 10997 bytes --]

Comments below starting with [Ray.xx]

Thanks,
Ray


 /**
@@ -30,11 +30,12 @@ SemaphoreHook (
 {
   SMRAM_SAVE_STATE_MAP  *CpuState;

   mRebasedFlag = RebasedFlag;

-  CpuState                      = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+  CpuState = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);

[Ray.1] This change is unnecessary.

+;-------------------------------------------------------------------------------
+
+%include "StuffRsbNasm.inc"
+
+global  ASM_PFX(gcSmmInitIdtr)
+global  ASM_PFX(gcSmmInitGdtr)
+
+extern ASM_PFX(SmmInitHandler)
+extern ASM_PFX(mRebasedFlag)
+extern ASM_PFX(mSmmRelocationOriginalAddress)
+
+global ASM_PFX(gPatchSmmCr3)
+global ASM_PFX(gPatchSmmCr4)
+global ASM_PFX(gPatchSmmCr0)
+global ASM_PFX(gPatchSmmInitStack)
+global ASM_PFX(gcSmmInitSize)
+global ASM_PFX(gcSmmInitTemplate)


[Ray.2] Can you create another patch after this patch to rename the global variables/functions to avoid using the same as PiSmmCpuDxeSmm driver?



+
+**/
+
+#ifndef INTERNAL_SMM_RELOCATION_LIB_H_
+#define INTERNAL_SMM_RELOCATION_LIB_H_
+
+#include <PiPei.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/CpuExceptionHandlerLib.h>
+#include <Library/DebugLib.h>
+#include <Library/HobLib.h>
+#include <Library/LocalApicLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/PcdLib.h>
+#include <Library/PeimEntryPoint.h>
+#include <Library/PeiServicesLib.h>
+#include <Library/SmmRelocationLib.h>
+#include <Guid/SmramMemoryReserve.h>
+#include <Guid/SmmBaseHob.h>
+#include <Register/Intel/Cpuid.h>
+#include <Register/Intel/SmramSaveStateMap.h>
+#include <Protocol/MmCpu.h>

[Ray.3] Can you double confirm if all above headers are needed?

+
+extern UINT64  *mSmBaseForAllCpus;
+
+extern IA32_DESCRIPTOR  gcSmmInitGdtr;
+extern IA32_DESCRIPTOR  gcSmmInitIdtr;
+extern CONST UINT16     gcSmmInitSize;
+extern CONST UINT8      gcSmmInitTemplate[];
+
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr0;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr3;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr4;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmInitStack;

[Ray.4] Can you evaluate what extra changes are required if allowing the lib runs in flash area? Basically all global variables cannot be modified at runtime.


+**/
+EFI_STATUS
+SplitSmramHobForSmmRelocation (
+  IN     UINT64                SmmRelocationSize,
+  IN OUT EFI_PHYSICAL_ADDRESS  *SmmRelocationStart
+  )
+{
+  EFI_HOB_GUID_TYPE               *GuidHob;
+  EFI_SMRAM_HOB_DESCRIPTOR_BLOCK  *DescriptorBlock;
+  EFI_SMRAM_HOB_DESCRIPTOR_BLOCK  *NewDescriptorBlock;
+  UINTN                           BufferSize;

[Ray.5] How about Block, NewBlock, NewBlockSize? It's simpler and easy to understand.

+  UINTN                           SmramRanges;
[Ray.6] No need SmramRanges.

+
+  NewDescriptorBlock = NULL;
[Ray.7] No need of this line.

+
+  //
+  // Retrieve the GUID HOB data that contains the set of SMRAM descriptors
+  //
+  GuidHob = GetFirstGuidHob (&gEfiSmmSmramMemoryGuid);
+  if (GuidHob == NULL) {
+    return EFI_NOT_FOUND;
+  }
+
+  DescriptorBlock = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)GET_GUID_HOB_DATA (GuidHob);
+
+  //
+  // Allocate one extra EFI_SMRAM_DESCRIPTOR to describe SMRAM memory that contains a pointer
+  // to the Smm relocated memory.
[Ray.8] "pointer" is a bit confusing.
"Allocate one extra EFI_SMRAM_DESCRIPTOR to describe smram carved out for all SMBASE."

+  //
+  SmramRanges = DescriptorBlock->NumberOfSmmReservedRegions;
+  BufferSize  = sizeof (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK) + (SmramRanges * sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  NewDescriptorBlock = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)BuildGuidHob (
+                                                           &gEfiSmmSmramMemoryGuid,
+                                                           BufferSize
+                                                           );
+  ASSERT (NewDescriptorBlock != NULL);
+  if (NewDescriptorBlock == NULL) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  //
+  // Copy old EFI_SMRAM_HOB_DESCRIPTOR_BLOCK to new allocated region
+  //
+  CopyMem ((VOID *)NewDescriptorBlock, DescriptorBlock, BufferSize - sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  //
+  // Increase the number of SMRAM descriptors by 1 to make room for the ALLOCATED descriptor of size EFI_PAGE_SIZE
+  //
+  NewDescriptorBlock->NumberOfSmmReservedRegions = (UINT32)(SmramRanges + 1);
[Ray.9] NewBlock->NumberOfSmmReservedRegions++;


+
+  ASSERT (SmramRanges >= 1);
+  //
+  // Copy last entry to the end - we assume TSEG is last entry.
+  //
+  CopyMem (&NewDescriptorBlock->Descriptor[SmramRanges], &NewDescriptorBlock->Descriptor[SmramRanges - 1], sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  //
+  // Update the entry in the array with a size of SmmRelocationSize and put into the ALLOCATED state
+  //
+  NewDescriptorBlock->Descriptor[SmramRanges - 1].PhysicalSize = SmmRelocationSize;
+  NewDescriptorBlock->Descriptor[SmramRanges - 1].RegionState |= EFI_ALLOCATED;
+
+  //
+  // Return the start address of Smm relocated memory in SMRAM.
+  //
+  if (SmmRelocationStart != NULL) {
[Ray.10] It's a local function and we know SmmRelocationStart is never NULL. No need the if-check.

+EFI_STATUS
+CreateSmmBaseHob (
+  IN UINT64  *SmBaseForAllCpus
+  )
+{
+  UINTN              Index;
+  SMM_BASE_HOB_DATA  *SmmBaseHobData;
+  UINT32             CpuCount;
+  UINT32             NumberOfProcessorsInHob;
+  UINT32             MaxCapOfProcessorsInHob;
+  UINT32             HobCount;
+
+  SmmBaseHobData          = NULL;
+  CpuCount                = 0;
+  NumberOfProcessorsInHob = 0;
+  MaxCapOfProcessorsInHob = 0;
+  HobCount                = 0;
+
+  //
+  // Count the HOB instance maximum capacity of CPU (MaxCapOfProcessorsInHob) since the max HobLength is 0xFFF8.
+  //
+  MaxCapOfProcessorsInHob = (0xFFF8 - sizeof (EFI_HOB_GUID_TYPE) - sizeof (SMM_BASE_HOB_DATA)) / sizeof (UINT64) + 1;
+  DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - MaxCapOfProcessorsInHob: %03x\n", MaxCapOfProcessorsInHob));
[Ray.11] "%03x" is confusing. Log readers cannot know "10" means 10 or 16. How about "%d"?

+
+  //
+  // Create Guided SMM Base HOB Instances.
+  //
+  while (CpuCount != mMaxNumberOfCpus) {
+    NumberOfProcessorsInHob = MIN ((UINT32)mMaxNumberOfCpus - CpuCount, MaxCapOfProcessorsInHob);
+
+    SmmBaseHobData = BuildGuidHob (
+                       &gSmmBaseHobGuid,
+                       sizeof (SMM_BASE_HOB_DATA) + sizeof (UINT64) * NumberOfProcessorsInHob
+                       );
+    if (SmmBaseHobData == NULL) {
+      return EFI_OUT_OF_RESOURCES;
+    }
+
+    SmmBaseHobData->ProcessorIndex     = CpuCount;
+    SmmBaseHobData->NumberOfProcessors = NumberOfProcessorsInHob;
+
+    DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->ProcessorIndex: %03x\n", HobCount, SmmBaseHobData->ProcessorIndex));
+    DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->NumberOfProcessors: %03x\n", HobCount, SmmBaseHobData->NumberOfProcessors));
+    for (Index = 0; Index < SmmBaseHobData->NumberOfProcessors; Index++) {
+      //
+      // Calculate the new SMBASE address
+      //
+      SmmBaseHobData->SmBase[Index] = SmBaseForAllCpus[Index + CpuCount];
[Ray.12] Please re-organize the code so that SmBaseForAllCpus array is not needed. What we need is only the Cpu0SmBase and TileSize.

+      DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->SmBase[%03x]: %08x\n", HobCount, Index, SmmBaseHobData->SmBase[Index]));
[Ray.13] Same comments as above. Please use "0x" prefix if you prints hex otherwise the log is hard to understand.

+
+  //
+  // Patch ASM code template with current CR0, CR3, and CR4 values
+  //
+  PatchInstructionX86 (gPatchSmmCr0, AsmReadCr0 (), 4);
+  PatchInstructionX86 (gPatchSmmCr3, AsmReadCr3 (), 4);
+  PatchInstructionX86 (gPatchSmmCr4, AsmReadCr4 () & (~CR4_CET_ENABLE), 4);
[Ray.14] Similar question: Please try to remove the assumption that the lib runs in physical memory.


+
+  //
+  // Patch SMI stack for SMM base relocation
+  // Note: No need allocate stack for all CPUs since the relocation
+  // occurs serially for each CPU
+  //
+  SmmStackSize = EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (PcdGet32 (PcdCpuSmmStackSize)));
[Ray.15] PcdCpuSmmStackSize is configured by platform as only platform knows what kind of SMI handlers will run in SMM env.
But in this case, all code is provided by this lib and stack size should be fixed, maybe simply 1 page is enough.

+  //
+  // Get the number of processors
+  //
+  Status = MpServices2->GetNumberOfProcessors (
+                          MpServices2,
+                          &mNumberOfCpus,
+                          &NumberOfEnabledCpus
+                          );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  if (FeaturePcdGet (PcdCpuHotPlugSupport)) {
+    mMaxNumberOfCpus = PcdGet32 (PcdCpuMaxLogicalProcessorNumber);
+  } else {
+    mMaxNumberOfCpus = mNumberOfCpus;
+  }
+
+  //
+  // Retrieve the Processor Info for all CPUs
+  //
+  mProcessorInfo = (EFI_PROCESSOR_INFORMATION *)AllocatePool (sizeof (EFI_PROCESSOR_INFORMATION) * mMaxNumberOfCpus);
[Ray.16] mProcessorInfo is needed when programming the new SMBASE. Then can you just put the new SMBASE for every CPU in the stack top, or just patch the value in the code region?
You can do that in a new patch.

+  //
+  // Initialize the SmBase for all CPUs
+  //
+  Status = InitSmBaseForAllCpus (&mSmBaseForAllCpus);
[Ray.17] mSmBaseForAllCpus global variable is not needed. We only need Cpu0Smbase and TileSize and the two can be local variables and passed to further routines through parameters.

+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
@@ -0,0 +1,139 @@
+/** @file
+  Config SMRAM Save State for SmmBases Relocation.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#include "InternalSmmRelocationLib.h"
+#include <Library/CpuLib.h>
+
+/**
+  Determine the mode of the CPU at the time an SMI occurs
+
+  @retval EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT   32 bit.
+  @retval EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT   64 bit.
+
+**/
+UINT8
+CheckMmSaveStateRegisterLma (
[Ray.18] GetMmSaveStateRegisterLma(). I recommend to never use "check" in function name.



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117838): https://edk2.groups.io/g/devel/message/117838
Mute This Topic: https://groups.io/mt/105535806/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



[-- Attachment #2: Type: text/html, Size: 27210 bytes --]

^ permalink raw reply	[flat|nested] 19+ messages in thread

* Re: [edk2-devel] [PATCH v2 03/10] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 03/10] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD Wu, Jiaxin
@ 2024-04-16  3:27   ` Ni, Ray
  0 siblings, 0 replies; 19+ messages in thread
From: Ni, Ray @ 2024-04-16  3:27 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Abdul Lateef Attar, Abner Chang, Tom Lendacky, Zeng, Star,
	Gerd Hoffmann, Kumar, Rahul R

[-- Attachment #1: Type: text/plain, Size: 10664 bytes --]

Acked-by: Ray Ni <ray.ni@intel.com>

Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Monday, April 15, 2024 21:30
To: devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Abdul Lateef Attar <AbdulLateef.Attar@amd.com>; Abner Chang <abner.chang@amd.com>; Tom Lendacky <thomas.lendacky@amd.com>; Ni, Ray <ray.ni@intel.com>; Zeng, Star <star.zeng@intel.com>; Gerd Hoffmann <kraxel@redhat.com>; Kumar, Rahul R <rahul.r.kumar@intel.com>
Subject: [PATCH v2 03/10] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD

Due to the definition difference of SMRAM Save State,
SmmBase config in SMRAM Save State for AMD is also different.

This patch provides the AmdSmmRelocationLib library instance
to handle the SMRAM Save State difference.

Cc: Abdul Lateef Attar <AbdulLateef.Attar@amd.com>
Cc: Abner Chang <abner.chang@amd.com>
Cc: Tom Lendacky <thomas.lendacky@amd.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Zeng Star <star.zeng@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 ...mmRelocationLib.inf => AmdSmmRelocationLib.inf} |  5 +-
 ...SaveStateConfig.c => AmdSmramSaveStateConfig.c} | 93 ++++++++++------------
 UefiCpuPkg/UefiCpuPkg.dsc                          |  1 +
 3 files changed, 46 insertions(+), 53 deletions(-)
 copy UefiCpuPkg/Library/SmmRelocationLib/{SmmRelocationLib.inf => AmdSmmRelocationLib.inf} (89%)
 copy UefiCpuPkg/Library/SmmRelocationLib/{SmramSaveStateConfig.c => AmdSmramSaveStateConfig.c} (50%)

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
similarity index 89%
copy from UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
copy to UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
index 6581fa2dad..710cd1948b 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
+++ b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
@@ -13,18 +13,18 @@
 ##

 [Defines]
   INF_VERSION                    = 0x00010005
   BASE_NAME                      = SmmRelocationLib
-  FILE_GUID                      = 853E97B3-790C-4EA3-945C-8F622FC47FE8
+  FILE_GUID                      = 65C74DCD-0D09-494A-8BFF-A64226EB8054
   MODULE_TYPE                    = PEIM
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = SmmRelocationLib

 [Sources]
   InternalSmmRelocationLib.h
-  SmramSaveStateConfig.c
+  AmdSmramSaveStateConfig.c
   SmmRelocationLib.c

 [Sources.Ia32]
   Ia32/Semaphore.c
   Ia32/SmmInit.nasm
@@ -40,11 +40,10 @@

 [LibraryClasses]
   BaseLib
   BaseMemoryLib
   CpuExceptionHandlerLib
-  CpuLib
   DebugLib
   HobLib
   LocalApicLib
   MemoryAllocationLib
   PcdLib
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
similarity index 50%
copy from UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
copy to UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
index fb69b2b5c5..95a1ce8d46 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
@@ -1,14 +1,17 @@
 /** @file
   Config SMRAM Save State for SmmBases Relocation.

+  Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.<BR>
   Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
   SPDX-License-Identifier: BSD-2-Clause-Patent

 **/
 #include "InternalSmmRelocationLib.h"
-#include <Library/CpuLib.h>
+#include <Register/Amd/SmramSaveStateMap.h>
+
+#define EFER_ADDRESS  0XC0000080ul

 /**
   Determine the mode of the CPU at the time an SMI occurs

   @retval EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT   32 bit.
@@ -18,44 +21,18 @@
 UINT8
 CheckMmSaveStateRegisterLma (
   VOID
   )
 {
-  CPUID_VERSION_INFO_EAX      RegEax;
-  CPUID_EXTENDED_CPU_SIG_EDX  RegEdx;
-  UINTN                       FamilyId;
-  UINTN                       ModelId;
-  UINT32                      Eax;
-  UINT8                       SmmSaveStateRegisterLma;
-
-  //
-  // Determine the mode of the CPU at the time an SMI occurs
-  //   Intel(R) 64 and IA-32 Architectures Software Developer's Manual
-  //   Volume 3C, Section 34.4.1.1
-  //
-  RegEax.Uint32 = GetCpuFamilyModel ();
-  FamilyId      = RegEax.Bits.FamilyId;
-  ModelId       = RegEax.Bits.Model;
-  if ((FamilyId == 0x06) || (FamilyId == 0x0f)) {
-    ModelId = ModelId | RegEax.Bits.ExtendedModelId << 4;
-  }
+  UINT8   SmmSaveStateRegisterLma;
+  UINT32  LMAValue;

-  RegEdx.Uint32 = 0;
-  AsmCpuid (CPUID_EXTENDED_FUNCTION, &Eax, NULL, NULL, NULL);
-  if (Eax >= CPUID_EXTENDED_CPU_SIG) {
-    AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &(RegEdx.Uint32));
-  }
-
-  SmmSaveStateRegisterLma = EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT;
-  if (RegEdx.Bits.LM) {
-    SmmSaveStateRegisterLma = EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT;
-  }
+  SmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_32BIT;

-  if (FamilyId == 0x06) {
-    if ((ModelId == 0x17) || (ModelId == 0x0f) || (ModelId == 0x1c)) {
-      SmmSaveStateRegisterLma = EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT;
-    }
+  LMAValue = (UINT32)AsmReadMsr64 (EFER_ADDRESS) & LMA;
+  if (LMAValue) {
+    SmmSaveStateRegisterLma = EFI_SMM_SAVE_STATE_REGISTER_LMA_64BIT;
   }

   return SmmSaveStateRegisterLma;
 }

@@ -73,18 +50,32 @@ EFIAPI
 ConfigureSmBase (
   IN     UINTN                 CpuIndex,
   IN OUT SMRAM_SAVE_STATE_MAP  *CpuState
   )
 {
-  CpuState->x86.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
+  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;
+
+  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
+
+  AmdCpuState->x64.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
 }

 /**
-  Hook the code executed immediately after an RSM instruction on the currently
-  executing CPU.  The mode of code executed immediately after RSM must be
-  detected, and the appropriate hook must be selected.  Always clear the auto
-  HALT restart flag if it is set.
+  This function updates the SMRAM save state on the currently executing CPU
+  to resume execution at a specific address after an RSM instruction.  This
+  function must evaluate the SMRAM save state to determine the execution mode
+  the RSM instruction resumes and update the resume execution address with
+  either NewInstructionPointer32 or NewInstructionPoint.  The auto HALT restart
+  flag in the SMRAM save state must always be cleared.  This function returns
+  the value of the instruction pointer from the SMRAM save state that was
+  replaced.  If this function returns 0, then the SMRAM save state was not
+  modified.
+
+  This function is called during the very first SMI on each CPU after
+  SmmCpuFeaturesInitializeProcessor() to set a flag in normal execution mode
+  to signal that the SMBASE of each CPU has been updated before the default
+  SMBASE address is used for the first SMI to the next CPU.

   @param[in]     CpuIndex                 The processor index for the currently
                                           executing CPU.
   @param[in,out] CpuState                 Pointer to SMRAM Save State Map for the
                                           currently executing CPU.
@@ -103,37 +94,39 @@ HookReturnFromSmm (
   IN OUT SMRAM_SAVE_STATE_MAP  *CpuState,
   IN     UINT64                NewInstructionPointer32,
   IN     UINT64                NewInstructionPointer
   )
 {
-  UINT64  OriginalInstructionPointer;
+  UINT64                    OriginalInstructionPointer;
+  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;

-  if (CheckMmSaveStateRegisterLma () == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
-    OriginalInstructionPointer = (UINT64)CpuState->x86._EIP;
-    CpuState->x86._EIP         = (UINT32)NewInstructionPointer;
+  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;

+  if (CheckMmSaveStateRegisterLma () == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
+    OriginalInstructionPointer = (UINT64)AmdCpuState->x86._EIP;
+    AmdCpuState->x86._EIP      = (UINT32)NewInstructionPointer;
     //
     // Clear the auto HALT restart flag so the RSM instruction returns
     // program control to the instruction following the HLT instruction.
     //
-    if ((CpuState->x86.AutoHALTRestart & BIT0) != 0) {
-      CpuState->x86.AutoHALTRestart &= ~BIT0;
+    if ((AmdCpuState->x86.AutoHALTRestart & BIT0) != 0) {
+      AmdCpuState->x86.AutoHALTRestart &= ~BIT0;
     }
   } else {
-    OriginalInstructionPointer = CpuState->x64._RIP;
-    if ((CpuState->x64.IA32_EFER & LMA) == 0) {
-      CpuState->x64._RIP = (UINT32)NewInstructionPointer32;
+    OriginalInstructionPointer = AmdCpuState->x64._RIP;
+    if ((AmdCpuState->x64.EFER & LMA) == 0) {
+      AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer32;
     } else {
-      CpuState->x64._RIP = (UINT32)NewInstructionPointer;
+      AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer;
     }

     //
     // Clear the auto HALT restart flag so the RSM instruction returns
     // program control to the instruction following the HLT instruction.
     //
-    if ((CpuState->x64.AutoHALTRestart & BIT0) != 0) {
-      CpuState->x64.AutoHALTRestart &= ~BIT0;
+    if ((AmdCpuState->x64.AutoHALTRestart & BIT0) != 0) {
+      AmdCpuState->x64.AutoHALTRestart &= ~BIT0;
     }
   }

   return OriginalInstructionPointer;
 }
diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc
index dd2ad398c0..0c5fdcffde 100644
--- a/UefiCpuPkg/UefiCpuPkg.dsc
+++ b/UefiCpuPkg/UefiCpuPkg.dsc
@@ -195,10 +195,11 @@
   }
   UefiCpuPkg/Library/MmSaveStateLib/AmdMmSaveStateLib.inf
   UefiCpuPkg/Library/MmSaveStateLib/IntelMmSaveStateLib.inf
   UefiCpuPkg/Library/SmmCpuFeaturesLib/AmdSmmCpuFeaturesLib.inf
   UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
+  UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf

 [Components.X64]
   UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf

 [Components.RISCV64]
--
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117840): https://edk2.groups.io/g/devel/message/117840
Mute This Topic: https://groups.io/mt/105535807/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



[-- Attachment #2: Type: text/html, Size: 17859 bytes --]

^ permalink raw reply related	[flat|nested] 19+ messages in thread

* Re: [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib
  2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
                   ` (9 preceding siblings ...)
  2024-04-15 13:30 ` [edk2-devel] [PATCH v2 10/10] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic Wu, Jiaxin
@ 2024-04-16  7:31 ` Gerd Hoffmann
  2024-04-16 10:08   ` Wu, Jiaxin
  10 siblings, 1 reply; 19+ messages in thread
From: Gerd Hoffmann @ 2024-04-16  7:31 UTC (permalink / raw)
  To: devel, jiaxin.wu
  Cc: Ray Ni, Zeng Star, Rahul Kumar, Guo Dong, Sean Rhodes, James Lu,
	Gua Guo, Ard Biesheuvel, Jiewen Yao, Abdul Lateef Attar,
	Abner Chang, Tom Lendacky

On Mon, Apr 15, 2024 at 09:30:11PM +0800, Wu, Jiaxin wrote:
> Intel plans to separate the smbase relocation logic from
> PiSmmCpuDxeSmm driver, and the related behavior will be
> moved to the new interface defined by the SmmRelocationLib
> class.
> 
> The SmmRelocationLib class provides the SmmRelocationInit()
> interface for platform to do the smbase relocation, which
> shall provide below 2 functionalities:
> 1. Relocate smbases for each processor.
> 2. Create the gSmmBaseHobGuid HOB.
> 
> With SmmRelocationLib, PiSmmCpuDxeSmm driver (which runs at
> a later phase) can be simplfied as below for SMM init:
> 1. Consume the gSmmBaseHobGuid HOB for the relocated smbases
> for each Processor.
> 2. Execute the early SMM Init.

How this was tested?
I can't even build this (without -D SMM_REQUIRE=TRUE).

/home/kraxel/projects/edk2/OvmfPkg/OvmfPkgX64.dsc(...): error 4000: Instance of library class [SmmRelocationLib] is not found
	in [/home/kraxel/projects/edk2/OvmfPkg/PlatformPei/PlatformPei.inf] [X64]
	consumed by module [/home/kraxel/projects/edk2/OvmfPkg/PlatformPei/PlatformPei.inf]

I doubt it passes CI.

take care,
  Gerd



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117852): https://edk2.groups.io/g/devel/message/117852
Mute This Topic: https://groups.io/mt/105535804/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 19+ messages in thread

* Re: [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib
  2024-04-16  7:31 ` [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Gerd Hoffmann
@ 2024-04-16 10:08   ` Wu, Jiaxin
  0 siblings, 0 replies; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-16 10:08 UTC (permalink / raw)
  To: Gerd Hoffmann, devel@edk2.groups.io
  Cc: Ni, Ray, Zeng, Star, Kumar, Rahul R, Dong, Guo, Rhodes, Sean,
	Lu, James, Guo, Gua, Ard Biesheuvel, Yao, Jiewen,
	Abdul Lateef Attar, Abner Chang, Tom Lendacky

Yes, because I moved the SmmRelocationLib within the condition of SMM_REQUIRE == TRUE in the version 2 patch. It should be always included since the PlatformPei need consume it.

I will fix it in the next version patch. It won't impact the code review & test with SMM_REQUIRE == TRUE build.

Thanks,
Jiaxin 


> -----Original Message-----
> From: Gerd Hoffmann <kraxel@redhat.com>
> Sent: Tuesday, April 16, 2024 3:31 PM
> To: devel@edk2.groups.io; Wu, Jiaxin <jiaxin.wu@intel.com>
> Cc: Ni, Ray <ray.ni@intel.com>; Zeng, Star <star.zeng@intel.com>; Kumar,
> Rahul R <rahul.r.kumar@intel.com>; Dong, Guo <guo.dong@intel.com>;
> Rhodes, Sean <sean@starlabs.systems>; Lu, James <james.lu@intel.com>;
> Guo, Gua <gua.guo@intel.com>; Ard Biesheuvel
> <ardb+tianocore@kernel.org>; Yao, Jiewen <jiewen.yao@intel.com>; Abdul
> Lateef Attar <AbdulLateef.Attar@amd.com>; Abner Chang
> <abner.chang@amd.com>; Tom Lendacky <thomas.lendacky@amd.com>
> Subject: Re: [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib
> 
> On Mon, Apr 15, 2024 at 09:30:11PM +0800, Wu, Jiaxin wrote:
> > Intel plans to separate the smbase relocation logic from
> > PiSmmCpuDxeSmm driver, and the related behavior will be
> > moved to the new interface defined by the SmmRelocationLib
> > class.
> >
> > The SmmRelocationLib class provides the SmmRelocationInit()
> > interface for platform to do the smbase relocation, which
> > shall provide below 2 functionalities:
> > 1. Relocate smbases for each processor.
> > 2. Create the gSmmBaseHobGuid HOB.
> >
> > With SmmRelocationLib, PiSmmCpuDxeSmm driver (which runs at
> > a later phase) can be simplfied as below for SMM init:
> > 1. Consume the gSmmBaseHobGuid HOB for the relocated smbases
> > for each Processor.
> > 2. Execute the early SMM Init.
> 
> How this was tested?
> I can't even build this (without -D SMM_REQUIRE=TRUE).
> 
> /home/kraxel/projects/edk2/OvmfPkg/OvmfPkgX64.dsc(...): error 4000:
> Instance of library class [SmmRelocationLib] is not found
> 	in
> [/home/kraxel/projects/edk2/OvmfPkg/PlatformPei/PlatformPei.inf] [X64]
> 	consumed by module
> [/home/kraxel/projects/edk2/OvmfPkg/PlatformPei/PlatformPei.inf]
> 
> I doubt it passes CI.
> 
> take care,
>   Gerd



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117873): https://edk2.groups.io/g/devel/message/117873
Mute This Topic: https://groups.io/mt/105535804/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 19+ messages in thread

* Re: [edk2-devel] [PATCH v2 02/10] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance
  2024-04-16  3:19   ` Ni, Ray
@ 2024-04-16 12:58     ` Wu, Jiaxin
  2024-04-17  5:24       ` Ni, Ray
  0 siblings, 1 reply; 19+ messages in thread
From: Wu, Jiaxin @ 2024-04-16 12:58 UTC (permalink / raw)
  To: Ni, Ray, devel@edk2.groups.io; +Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R


[-- Attachment #1.1: Type: text/plain, Size: 13385 bytes --]



 /**
@@ -30,11 +30,12 @@ SemaphoreHook (
 {
   SMRAM_SAVE_STATE_MAP  *CpuState;

   mRebasedFlag = RebasedFlag;

-  CpuState                      = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+  CpuState = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);

[Ray.1] This change is unnecessary.
[Jiaxin.1] it's not only move the code to the new lib, but also do some adaptation. For example here: the code style change to PASS the CI.
If no this change, can't pass the CI check.

+;-------------------------------------------------------------------------------
+
+%include "StuffRsbNasm.inc"
+
+global  ASM_PFX(gcSmmInitIdtr)
+global  ASM_PFX(gcSmmInitGdtr)
+
+extern ASM_PFX(SmmInitHandler)
+extern ASM_PFX(mRebasedFlag)
+extern ASM_PFX(mSmmRelocationOriginalAddress)
+
+global ASM_PFX(gPatchSmmCr3)
+global ASM_PFX(gPatchSmmCr4)
+global ASM_PFX(gPatchSmmCr0)
+global ASM_PFX(gPatchSmmInitStack)
+global ASM_PFX(gcSmmInitSize)
+global ASM_PFX(gcSmmInitTemplate)


[Ray.2] Can you create another patch after this patch to rename the global variables/functions to avoid using the same as PiSmmCpuDxeSmm driver?

[Jiaxin.2] I just rename below 2, all others are same as original and all has been moved to this lib, no definition in the smm cpu driver anymore, see below diff:

gcSmiIdtr -> gcSmmInitIdtr
gcSmiInitGdtr -> gcSmmInitGdtr

[cid:image001.png@01DA9037.9567A690]


+
+**/
+
+#ifndef INTERNAL_SMM_RELOCATION_LIB_H_
+#define INTERNAL_SMM_RELOCATION_LIB_H_
+
+#include <PiPei.h>
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/CpuExceptionHandlerLib.h>
+#include <Library/DebugLib.h>
+#include <Library/HobLib.h>
+#include <Library/LocalApicLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/PcdLib.h>
+#include <Library/PeimEntryPoint.h>
+#include <Library/PeiServicesLib.h>
+#include <Library/SmmRelocationLib.h>
+#include <Guid/SmramMemoryReserve.h>
+#include <Guid/SmmBaseHob.h>
+#include <Register/Intel/Cpuid.h>
+#include <Register/Intel/SmramSaveStateMap.h>
+#include <Protocol/MmCpu.h>

[Ray.3] Can you double confirm if all above headers are needed?
[Jiaxin.3] Except below 2, all others are needed (at least checked in OVMF).
#include <PiPei.h>
#include <Library/BaseLib.h>

+
+extern UINT64  *mSmBaseForAllCpus;
+
+extern IA32_DESCRIPTOR  gcSmmInitGdtr;
+extern IA32_DESCRIPTOR  gcSmmInitIdtr;
+extern CONST UINT16     gcSmmInitSize;
+extern CONST UINT8      gcSmmInitTemplate[];
+
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr0;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr3;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmCr4;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmInitStack;

[Ray.4] Can you evaluate what extra changes are required if allowing the lib runs in flash area? Basically all global variables cannot be modified at runtime.
[Jiaxin.4] The Lib needs to depend on the MP service PPI, it shall be called during post-mem phase, global variables can't be used?

+**/
+EFI_STATUS
+SplitSmramHobForSmmRelocation (
+  IN     UINT64                SmmRelocationSize,
+  IN OUT EFI_PHYSICAL_ADDRESS  *SmmRelocationStart
+  )
+{
+  EFI_HOB_GUID_TYPE               *GuidHob;
+  EFI_SMRAM_HOB_DESCRIPTOR_BLOCK  *DescriptorBlock;
+  EFI_SMRAM_HOB_DESCRIPTOR_BLOCK  *NewDescriptorBlock;
+  UINTN                           BufferSize;

[Ray.5] How about Block, NewBlock, NewBlockSize? It's simpler and easy to understand.
[Jiaxin.5] Agree. I will change in the next version patches.

+  UINTN                           SmramRanges;
[Ray.6] No need SmramRanges.
[Jiaxin.6] replace it with DescriptorBlock ->NumberOfSmmReservedRegions directly?


+
+  NewDescriptorBlock = NULL;
[Ray.7] No need of this line.
[Jiaxin.7] Agree.


+
+  //
+  // Retrieve the GUID HOB data that contains the set of SMRAM descriptors
+  //
+  GuidHob = GetFirstGuidHob (&gEfiSmmSmramMemoryGuid);
+  if (GuidHob == NULL) {
+    return EFI_NOT_FOUND;
+  }
+
+  DescriptorBlock = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)GET_GUID_HOB_DATA (GuidHob);
+
+  //
+  // Allocate one extra EFI_SMRAM_DESCRIPTOR to describe SMRAM memory that contains a pointer
+  // to the Smm relocated memory.
[Ray.8] "pointer" is a bit confusing.
"Allocate one extra EFI_SMRAM_DESCRIPTOR to describe smram carved out for all SMBASE."
[Jiaxin.8] Agree.

+  //
+  SmramRanges = DescriptorBlock->NumberOfSmmReservedRegions;
+  BufferSize  = sizeof (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK) + (SmramRanges * sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  NewDescriptorBlock = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)BuildGuidHob (
+                                                           &gEfiSmmSmramMemoryGuid,
+                                                           BufferSize
+                                                           );
+  ASSERT (NewDescriptorBlock != NULL);
+  if (NewDescriptorBlock == NULL) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  //
+  // Copy old EFI_SMRAM_HOB_DESCRIPTOR_BLOCK to new allocated region
+  //
+  CopyMem ((VOID *)NewDescriptorBlock, DescriptorBlock, BufferSize - sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  //
+  // Increase the number of SMRAM descriptors by 1 to make room for the ALLOCATED descriptor of size EFI_PAGE_SIZE
+  //
+  NewDescriptorBlock->NumberOfSmmReservedRegions = (UINT32)(SmramRanges + 1);
[Ray.9] NewBlock->NumberOfSmmReservedRegions++;
[Jiaxin.9] Agree since we copied the DescriptorBlock to NewDescriptorBlock first. But I still think original is more easy to understand.

+
+  ASSERT (SmramRanges >= 1);
+  //
+  // Copy last entry to the end - we assume TSEG is last entry.
+  //
+  CopyMem (&NewDescriptorBlock->Descriptor[SmramRanges], &NewDescriptorBlock->Descriptor[SmramRanges - 1], sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  //
+  // Update the entry in the array with a size of SmmRelocationSize and put into the ALLOCATED state
+  //
+  NewDescriptorBlock->Descriptor[SmramRanges - 1].PhysicalSize = SmmRelocationSize;
+  NewDescriptorBlock->Descriptor[SmramRanges - 1].RegionState |= EFI_ALLOCATED;
+
+  //
+  // Return the start address of Smm relocated memory in SMRAM.
+  //
+  if (SmmRelocationStart != NULL) {
[Ray.10] It's a local function and we know SmmRelocationStart is never NULL. No need the if-check.
[Jiaxin.10] Agree

+EFI_STATUS
+CreateSmmBaseHob (
+  IN UINT64  *SmBaseForAllCpus
+  )
+{
+  UINTN              Index;
+  SMM_BASE_HOB_DATA  *SmmBaseHobData;
+  UINT32             CpuCount;
+  UINT32             NumberOfProcessorsInHob;
+  UINT32             MaxCapOfProcessorsInHob;
+  UINT32             HobCount;
+
+  SmmBaseHobData          = NULL;
+  CpuCount                = 0;
+  NumberOfProcessorsInHob = 0;
+  MaxCapOfProcessorsInHob = 0;
+  HobCount                = 0;
+
+  //
+  // Count the HOB instance maximum capacity of CPU (MaxCapOfProcessorsInHob) since the max HobLength is 0xFFF8.
+  //
+  MaxCapOfProcessorsInHob = (0xFFF8 - sizeof (EFI_HOB_GUID_TYPE) - sizeof (SMM_BASE_HOB_DATA)) / sizeof (UINT64) + 1;
+  DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - MaxCapOfProcessorsInHob: %03x\n", MaxCapOfProcessorsInHob));
[Ray.11] "%03x" is confusing. Log readers cannot know "10" means 10 or 16. How about "%d"?
[Jiaxin.11] Agree.

+
+  //
+  // Create Guided SMM Base HOB Instances.
+  //
+  while (CpuCount != mMaxNumberOfCpus) {
+    NumberOfProcessorsInHob = MIN ((UINT32)mMaxNumberOfCpus - CpuCount, MaxCapOfProcessorsInHob);
+
+    SmmBaseHobData = BuildGuidHob (
+                       &gSmmBaseHobGuid,
+                       sizeof (SMM_BASE_HOB_DATA) + sizeof (UINT64) * NumberOfProcessorsInHob
+                       );
+    if (SmmBaseHobData == NULL) {
+      return EFI_OUT_OF_RESOURCES;
+    }
+
+    SmmBaseHobData->ProcessorIndex     = CpuCount;
+    SmmBaseHobData->NumberOfProcessors = NumberOfProcessorsInHob;
+
+    DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->ProcessorIndex: %03x\n", HobCount, SmmBaseHobData->ProcessorIndex));
+    DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->NumberOfProcessors: %03x\n", HobCount, SmmBaseHobData->NumberOfProcessors));
+    for (Index = 0; Index < SmmBaseHobData->NumberOfProcessors; Index++) {
+      //
+      // Calculate the new SMBASE address
+      //
+      SmmBaseHobData->SmBase[Index] = SmBaseForAllCpus[Index + CpuCount];
[Ray.12] Please re-organize the code so that SmBaseForAllCpus array is not needed. What we need is only the Cpu0SmBase and TileSize.
[Jiaxin.12] do you mean calculate the value here? --> (UINTN)(Cpu0SmBase)+ Index * TileSize - SMM_HANDLER_OFFSET ?
I init the smbase value in the function of InitSmBaseForAllCpus(), the value will be used in both ConfigureSmBase & CreateSmmBaseHob.
How about the ConfigureSmBase function during SmmRelocateBases()? What's reason you think SmBaseForAllCpus is not good?


+      DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->SmBase[%03x]: %08x\n", HobCount, Index, SmmBaseHobData->SmBase[Index]));
[Ray.13] Same comments as above. Please use "0x" prefix if you prints hex otherwise the log is hard to understand.
[Jiaxin.13] i will align with above to %d, and change the %08x to 0x%08x.

+
+  //
+  // Patch ASM code template with current CR0, CR3, and CR4 values
+  //
+  PatchInstructionX86 (gPatchSmmCr0, AsmReadCr0 (), 4);
+  PatchInstructionX86 (gPatchSmmCr3, AsmReadCr3 (), 4);
+  PatchInstructionX86 (gPatchSmmCr4, AsmReadCr4 () & (~CR4_CET_ENABLE), 4);
[Ray.14] Similar question: Please try to remove the assumption that the lib runs in physical memory.
[Jiaxin.14] same as [Jiaxin.4]


+
+  //
+  // Patch SMI stack for SMM base relocation
+  // Note: No need allocate stack for all CPUs since the relocation
+  // occurs serially for each CPU
+  //
+  SmmStackSize = EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (PcdGet32 (PcdCpuSmmStackSize)));
[Ray.15] PcdCpuSmmStackSize is configured by platform as only platform knows what kind of SMI handlers will run in SMM env.
But in this case, all code is provided by this lib and stack size should be fixed, maybe simply 1 page is enough.
[Jiaxin.15] agree, do you prefer this change as another patch or I just update the hard code value directly in this patch?

+  //
+  // Get the number of processors
+  //
+  Status = MpServices2->GetNumberOfProcessors (
+                          MpServices2,
+                          &mNumberOfCpus,
+                          &NumberOfEnabledCpus
+                          );
+  if (EFI_ERROR (Status)) {
+    return Status;
+  }
+
+  if (FeaturePcdGet (PcdCpuHotPlugSupport)) {
+    mMaxNumberOfCpus = PcdGet32 (PcdCpuMaxLogicalProcessorNumber);
+  } else {
+    mMaxNumberOfCpus = mNumberOfCpus;
+  }
+
+  //
+  // Retrieve the Processor Info for all CPUs
+  //
+  mProcessorInfo = (EFI_PROCESSOR_INFORMATION *)AllocatePool (sizeof (EFI_PROCESSOR_INFORMATION) * mMaxNumberOfCpus);
[Ray.16] mProcessorInfo is needed when programming the new SMBASE. Then can you just put the new SMBASE for every CPU in the stack top, or just patch the value in the code region?
You can do that in a new patch.
[Jiaxin.16] why need such behavior? I only allocate one stack for all cpus with existing design. The reason see below as I explained:

  //
  // Patch SMI stack for SMM base relocation
  // Note: No need allocate stack for all CPUs since the relocation
  // occurs serially for each CPU
  //
  SmmStackSize = EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (PcdGet32 (PcdCpuSmmStackSize)));
  SmmStacks    = (UINT8 *)AllocatePages (EFI_SIZE_TO_PAGES (SmmStackSize));
  if (SmmStacks == NULL) {
    Status = EFI_OUT_OF_RESOURCES;
    goto ON_EXIT;
  }


+  //
+  // Initialize the SmBase for all CPUs
+  //
+  Status = InitSmBaseForAllCpus (&mSmBaseForAllCpus);
[Ray.17] mSmBaseForAllCpus global variable is not needed. We only need Cpu0Smbase and TileSize and the two can be local variables and passed to further routines through parameters.
[Jiaxin.17] let me remove the mSmBaseForAllCpus global variable. But I still think it's not good to calculate value in different 2 places again and again (ConfigureSmBase & CreateSmmBaseHob).

+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
@@ -0,0 +1,139 @@
+/** @file
+  Config SMRAM Save State for SmmBases Relocation.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#include "InternalSmmRelocationLib.h"
+#include <Library/CpuLib.h>
+
+/**
+  Determine the mode of the CPU at the time an SMI occurs
+
+  @retval EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT   32 bit.
+  @retval EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT   64 bit.
+
+**/
+UINT8
+CheckMmSaveStateRegisterLma (
[Ray.18] GetMmSaveStateRegisterLma(). I recommend to never use "check" in function name.
[Jiaxin] agree.



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117880): https://edk2.groups.io/g/devel/message/117880
Mute This Topic: https://groups.io/mt/105535806/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



[-- Attachment #1.2: Type: text/html, Size: 31904 bytes --]

[-- Attachment #2: image001.png --]
[-- Type: image/png, Size: 87383 bytes --]

^ permalink raw reply	[flat|nested] 19+ messages in thread

* Re: [edk2-devel] [PATCH v2 02/10] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance
  2024-04-16 12:58     ` Wu, Jiaxin
@ 2024-04-17  5:24       ` Ni, Ray
  0 siblings, 0 replies; 19+ messages in thread
From: Ni, Ray @ 2024-04-17  5:24 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

[-- Attachment #1: Type: text/plain, Size: 5691 bytes --]

Comments below starting with [Ray]

Thanks,
Ray

________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Tuesday, April 16, 2024 20:58
To: Ni, Ray <ray.ni@intel.com>; devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Zeng, Star <star.zeng@intel.com>; Gerd Hoffmann <kraxel@redhat.com>; Kumar, Rahul R <rahul.r.kumar@intel.com>
Subject: RE: [PATCH v2 02/10] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance



 /**
@@ -30,11 +30,12 @@ SemaphoreHook (
 {
   SMRAM_SAVE_STATE_MAP  *CpuState;

   mRebasedFlag = RebasedFlag;

-  CpuState                      = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+  CpuState = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);



[Ray.1] This change is unnecessary.

[Jiaxin.1] it’s not only move the code to the new lib, but also do some adaptation. For example here: the code style change to PASS the CI.

If no this change, can’t pass the CI check.

[Ray] Original code should also pass uncrustify checker. I guess you added one blank line above so the alignment of "=" is not required.




[Ray.4] Can you evaluate what extra changes are required if allowing the lib runs in flash area? Basically all global variables cannot be modified at runtime.

[Jiaxin.4] The Lib needs to depend on the MP service PPI, it shall be called during post-mem phase, global variables can’t be used?

[Ray] A PEIM could run in flash in post-mem phase. If you pass the values across routines through parameters, most of the global variables can be avoided.


+  UINTN                           SmramRanges;

[Ray.6] No need SmramRanges.

[Jiaxin.6] replace it with DescriptorBlock ->NumberOfSmmReservedRegions directly?

[Ray] yes.


+  //
+  // Increase the number of SMRAM descriptors by 1 to make room for the ALLOCATED descriptor of size EFI_PAGE_SIZE
+  //
+  NewDescriptorBlock->NumberOfSmmReservedRegions = (UINT32)(SmramRanges + 1);

[Ray.9] NewBlock->NumberOfSmmReservedRegions++;

[Jiaxin.9] Agree since we copied the DescriptorBlock to NewDescriptorBlock first. But I still think original is more easy to understand.

[Ray] As long as you remove local variable SmramRanges, I am fine.



+
+    DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->ProcessorIndex: %03x\n", HobCount, SmmBaseHobData->ProcessorIndex));
+    DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->NumberOfProcessors: %03x\n", HobCount, SmmBaseHobData->NumberOfProcessors));
+    for (Index = 0; Index < SmmBaseHobData->NumberOfProcessors; Index++) {
+      //
+      // Calculate the new SMBASE address
+      //
+      SmmBaseHobData->SmBase[Index] = SmBaseForAllCpus[Index + CpuCount];

[Ray.12] Please re-organize the code so that SmBaseForAllCpus array is not needed. What we need is only the Cpu0SmBase and TileSize.

[Jiaxin.12] do you mean calculate the value here? --> (UINTN)(Cpu0SmBase)+ Index * TileSize - SMM_HANDLER_OFFSET ?

I init the smbase value in the function of InitSmBaseForAllCpus(), the value will be used in both ConfigureSmBase & CreateSmmBaseHob.

How about the ConfigureSmBase function during SmmRelocateBases()? What’s reason you think SmBaseForAllCpus is not good?

[Ray] I just want to avoid unnecessary memory allocation.




+
+  //
+  // Patch SMI stack for SMM base relocation
+  // Note: No need allocate stack for all CPUs since the relocation
+  // occurs serially for each CPU
+  //
+  SmmStackSize = EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (PcdGet32 (PcdCpuSmmStackSize)));

[Ray.15] PcdCpuSmmStackSize is configured by platform as only platform knows what kind of SMI handlers will run in SMM env.

But in this case, all code is provided by this lib and stack size should be fixed, maybe simply 1 page is enough.

[Jiaxin.15] agree, do you prefer this change as another patch or I just update the hard code value directly in this patch?

[Ray] If the code is inherited from PiSmmCpuDxeSmm driver, you can do that change in another patch.

+  //
+  // Retrieve the Processor Info for all CPUs
+  //
+  mProcessorInfo = (EFI_PROCESSOR_INFORMATION *)AllocatePool (sizeof (EFI_PROCESSOR_INFORMATION) * mMaxNumberOfCpus);

[Ray.16] mProcessorInfo is needed when programming the new SMBASE. Then can you just put the new SMBASE for every CPU in the stack top, or just patch the value in the code region?

You can do that in a new patch.

[Jiaxin.16] why need such behavior? I only allocate one stack for all cpus with existing design. The reason see below as I explained:

[Ray] My purpose is to avoid global variables.



+  //
+  // Initialize the SmBase for all CPUs
+  //
+  Status = InitSmBaseForAllCpus (&mSmBaseForAllCpus);

[Ray.17] mSmBaseForAllCpus global variable is not needed. We only need Cpu0Smbase and TileSize and the two can be local variables and passed to further routines through parameters.

[Jiaxin.17] let me remove the mSmBaseForAllCpus global variable. But I still think it’s not good to calculate value in different 2 places again and again (ConfigureSmBase & CreateSmmBaseHob).

[Ray] I agree with you regarding not calculating values in more than 1 place. Please think about how to avoid that.





-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117893): https://edk2.groups.io/g/devel/message/117893
Mute This Topic: https://groups.io/mt/105535806/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



[-- Attachment #2: Type: text/html, Size: 16138 bytes --]

^ permalink raw reply	[flat|nested] 19+ messages in thread

end of thread, other threads:[~2024-04-17  5:24 UTC | newest]

Thread overview: 19+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2024-04-15 13:30 [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Wu, Jiaxin
2024-04-15 13:30 ` [edk2-devel] [PATCH v2 01/10] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
2024-04-16  1:50   ` Ni, Ray
2024-04-15 13:30 ` [edk2-devel] [PATCH v2 02/10] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance Wu, Jiaxin
2024-04-16  3:19   ` Ni, Ray
2024-04-16 12:58     ` Wu, Jiaxin
2024-04-17  5:24       ` Ni, Ray
2024-04-15 13:30 ` [edk2-devel] [PATCH v2 03/10] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD Wu, Jiaxin
2024-04-16  3:27   ` Ni, Ray
2024-04-15 13:30 ` [edk2-devel] [PATCH v2 04/10] OvmfPkg/SmmRelocationLib: Add library instance for OVMF Wu, Jiaxin
2024-04-15 13:30 ` [edk2-devel] [PATCH v2 05/10] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid Wu, Jiaxin
2024-04-15 13:30 ` [edk2-devel] [PATCH v2 06/10] OvmfPkg: Refine SmmAccess implementation Wu, Jiaxin
2024-04-15 13:30 ` [edk2-devel] [PATCH v2 07/10] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not Wu, Jiaxin
2024-04-15 13:30 ` [edk2-devel] [PATCH v2 08/10] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase Wu, Jiaxin
2024-04-15 13:30 ` [edk2-devel] [PATCH v2 09/10] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib Wu, Jiaxin
2024-04-15 15:26   ` Guo Dong
2024-04-15 13:30 ` [edk2-devel] [PATCH v2 10/10] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic Wu, Jiaxin
2024-04-16  7:31 ` [edk2-devel] [PATCH v2 00/10] Add SmmRelocationLib Gerd Hoffmann
2024-04-16 10:08   ` Wu, Jiaxin

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox