public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib
@ 2024-04-10 13:57 Wu, Jiaxin
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 01/13] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
                   ` (14 more replies)
  0 siblings, 15 replies; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 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

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>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>

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

 OvmfPkg/AmdSev/AmdSevX64.dsc                       |   1 +
 OvmfPkg/CloudHv/CloudHvX64.dsc                     |   1 +
 OvmfPkg/Library/PlatformInitLib/MemDetect.c        | 104 ++--
 .../Library/PlatformInitLib/PlatformInitLib.inf    |   6 +-
 .../Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c  |  33 +-
 OvmfPkg/Microvm/MicrovmX64.dsc                     |   1 +
 OvmfPkg/OvmfPkgIa32.dsc                            |   1 +
 OvmfPkg/OvmfPkgIa32X64.dsc                         |   1 +
 OvmfPkg/OvmfPkgX64.dsc                             |   1 +
 OvmfPkg/PlatformPei/Platform.c                     |   1 +
 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     | 109 ++++
 .../SmmRelocationLib}/Ia32/Semaphore.c             |  13 +-
 .../Library/SmmRelocationLib/Ia32/SmmInit.nasm     | 157 +++++
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 141 +++++
 .../SmmRelocationLib/OvmfSmmRelocationLib.inf      |  61 ++
 .../SmmRelocationLib/OvmfSmramSaveStateConfig.c    | 107 ++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 659 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  61 ++
 .../SmmRelocationLib/SmramSaveStateConfig.c        |  91 +++
 .../SmmRelocationLib}/X64/Semaphore.c              |  13 +-
 .../SmmRelocationLib}/X64/SmmInit.nasm             |  93 ++-
 UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c                  |  21 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm        |  96 ---
 UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c              |   6 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c         | 322 +---------
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h         |  98 ---
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf       |   4 -
 UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c         |  69 ---
 UefiCpuPkg/UefiCpuPkg.dec                          |   3 +
 UefiCpuPkg/UefiCpuPkg.dsc                          |   3 +
 UefiPayloadPkg/UefiPayloadPkg.dsc                  |   2 +
 42 files changed, 1850 insertions(+), 817 deletions(-)
 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/OvmfSmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/OvmfSmramSaveStateConfig.c
 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 (57%)
 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 (#117588): https://edk2.groups.io/g/devel/message/117588
Mute This Topic: https://groups.io/mt/105441987/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* [edk2-devel] [PATCH v1 01/13] UefiCpuPkg: Add SmmRelocationLib class
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance Wu, Jiaxin
                   ` (13 subsequent siblings)
  14 siblings, 0 replies; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 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..13043641a2
--- /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) 2023, 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 (#117589): https://edk2.groups.io/g/devel/message/117589
Mute This Topic: https://groups.io/mt/105441988/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 01/13] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-11  3:18   ` Ni, Ray
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF Wu, Jiaxin
                   ` (12 subsequent siblings)
  14 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 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.

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>
---
 .../Library/SmmRelocationLib/Ia32/Semaphore.c      |  43 ++
 .../Library/SmmRelocationLib/Ia32/SmmInit.nasm     | 157 +++++
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 141 +++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 659 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  61 ++
 .../SmmRelocationLib/SmramSaveStateConfig.c        |  91 +++
 .../Library/SmmRelocationLib/X64/Semaphore.c       |  70 +++
 .../Library/SmmRelocationLib/X64/SmmInit.nasm      | 207 +++++++
 8 files changed, 1429 insertions(+)
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
 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
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
new file mode 100644
index 0000000000..ace3221cfc
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
@@ -0,0 +1,43 @@
+/** @file
+  Semaphore mechanism to indicate to the BSP that an AP has exited SMM
+  after SMBASE relocation.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "InternalSmmRelocationLib.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/Library/SmmRelocationLib/Ia32/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
new file mode 100644
index 0000000000..cb8b030693
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
@@ -0,0 +1,157 @@
+;------------------------------------------------------------------------------ ;
+; 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(gcSmiIdtr)
+global  ASM_PFX(gcSmiGdtr)
+
+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(gcSmiGdtr):
+    DW      GDT_SIZE - 1
+    DD      NullSeg
+
+ASM_PFX(gcSmiIdtr):
+    DW      0
+    DD      0
+
+
+    SECTION .text
+
+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(gcSmiGdtr) - 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(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..c8647fbfe7
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
@@ -0,0 +1,141 @@
+/** @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 UINT8   mSmmSaveStateRegisterLma;
+
+extern IA32_DESCRIPTOR  gcSmiGdtr;
+extern IA32_DESCRIPTOR  gcSmiIdtr;
+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..38bad24e7a
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
@@ -0,0 +1,659 @@
+/** @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;
+
+//
+// The mode of the CPU at the time an SMI occurs
+//
+UINT8  mSmmSaveStateRegisterLma;
+
+//
+// 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 (&gcSmiIdtr);
+  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.
+  //
+  gcSmiIdtr.Limit = (sizeof (IA32_IDT_GATE_DESCRIPTOR) * 32) - 1;
+
+  //
+  // Allocate for IDT.
+  // sizeof (UINTN) is for the PEI Services Table pointer.
+  //
+  gcSmiIdtr.Base = (UINTN)AllocateZeroPool (gcSmiIdtr.Limit + 1 + sizeof (UINTN));
+  ASSERT (gcSmiIdtr.Base != 0);
+  gcSmiIdtr.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 *)(gcSmiIdtr.Base - sizeof (UINTN))) = (UINTN)PeiServices;
+
+  //
+  // Load SMM temporary IDT table
+  //
+  AsmWriteIdtr (&gcSmiIdtr);
+
+  //
+  // Setup SMM default exception handlers, SMM IDT table
+  // will be updated and saved in gcSmiIdtr
+  //
+  Status = InitializeCpuExceptionHandlers (NULL);
+  ASSERT_EFI_ERROR (Status);
+
+  //
+  // Restore PEI IDT table and CPU InterruptState
+  //
+  AsmWriteIdtr ((IA32_DESCRIPTOR *)&PeiIdtr);
+  SetInterruptState (InterruptState);
+}
+
+/**
+  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
+CheckSmmCpuMode (
+  VOID
+  )
+{
+  UINT32  RegEax;
+  UINT32  RegEdx;
+  UINTN   FamilyId;
+  UINTN   ModelId;
+  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
+  //
+  AsmCpuid (CPUID_VERSION_INFO, &RegEax, NULL, NULL, NULL);
+  FamilyId = (RegEax >> 8) & 0xf;
+  ModelId  = (RegEax >> 4) & 0xf;
+  if ((FamilyId == 0x06) || (FamilyId == 0x0f)) {
+    ModelId = ModelId | ((RegEax >> 12) & 0xf0);
+  }
+
+  RegEdx = 0;
+  AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL);
+  if (RegEax >= CPUID_EXTENDED_CPU_SIG) {
+    AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &RegEdx);
+  }
+
+  SmmSaveStateRegisterLma = EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT;
+  if ((RegEdx & BIT29) != 0) {
+    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;
+}
+
+/**
+  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 ();
+
+  //
+  // Check the mode of the CPU at the time an SMI occurs
+  //
+  mSmmSaveStateRegisterLma = CheckSmmCpuMode ();
+
+  //
+  // 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..2ac16ab5d1
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
@@ -0,0 +1,61 @@
+## @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
+  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..3982158979
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
@@ -0,0 +1,91 @@
+/** @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"
+
+/**
+  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
+  )
+{
+  if (mSmmSaveStateRegisterLma == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
+    CpuState->x86.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
+  } else {
+    CpuState->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.
+
+  @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 (mSmmSaveStateRegisterLma == 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/Library/SmmRelocationLib/X64/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
new file mode 100644
index 0000000000..54d3462ef8
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
@@ -0,0 +1,70 @@
+/** @file
+  Semaphore mechanism to indicate to the BSP that an AP has exited SMM
+  after SMBASE relocation.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "InternalSmmRelocationLib.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/Library/SmmRelocationLib/X64/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
new file mode 100644
index 0000000000..ce4311fffd
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
@@ -0,0 +1,207 @@
+;------------------------------------------------------------------------------ ;
+; 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(gcSmiIdtr)
+global  ASM_PFX(gcSmiGdtr)
+
+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)
+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(gcSmiGdtr):
+    DW      GDT_SIZE - 1
+    DQ      NullSeg
+
+ASM_PFX(gcSmiIdtr):
+    DW      0
+    DQ      0
+
+
+    DEFAULT REL
+    SECTION .text
+
+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(gcSmiGdtr) - 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(SmmInitFixupAddress)
+ASM_PFX(SmmInitFixupAddress):
+    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 (#117590): https://edk2.groups.io/g/devel/message/117590
Mute This Topic: https://groups.io/mt/105441989/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 01/13] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-11  3:19   ` Ni, Ray
  2024-04-11  7:11   ` Gerd Hoffmann
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 04/13] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD Wu, Jiaxin
                   ` (11 subsequent siblings)
  14 siblings, 2 replies; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 UTC (permalink / raw)
  To: devel
  Cc: Ray Ni, Zeng Star, Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann,
	Rahul Kumar

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

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

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>
---
 .../SmmRelocationLib/OvmfSmmRelocationLib.inf      |  61 ++++++++++++
 .../SmmRelocationLib/OvmfSmramSaveStateConfig.c    | 107 +++++++++++++++++++++
 2 files changed, 168 insertions(+)
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/OvmfSmramSaveStateConfig.c

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf b/UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
new file mode 100644
index 0000000000..eba1129ac2
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
@@ -0,0 +1,61 @@
+## @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                      = 51834F51-CCE0-4743-B553-935D0C8A53FF
+  MODULE_TYPE                    = PEIM
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = SmmRelocationLib
+
+[Sources]
+  InternalSmmRelocationLib.h
+  OvmfSmramSaveStateConfig.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
+  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/OvmfSmramSaveStateConfig.c b/UefiCpuPkg/Library/SmmRelocationLib/OvmfSmramSaveStateConfig.c
new file mode 100644
index 0000000000..505b1d694a
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/OvmfSmramSaveStateConfig.c
@@ -0,0 +1,107 @@
+/** @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 <Register/Amd/SmramSaveStateMap.h>
+
+/**
+  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
+  )
+{
+  AMD_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
+
+  CpuSaveState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
+
+  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
+  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.
+  @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;
+  AMD_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
+
+  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 ((CpuSaveState->x86.AutoHALTRestart & BIT0) != 0) {
+      CpuSaveState->x86.AutoHALTRestart &= ~BIT0;
+    }
+  } else {
+    OriginalInstructionPointer = CpuSaveState->x64._RIP;
+    if ((CpuSaveState->x64.EFER & LMA) == 0) {
+      CpuSaveState->x64._RIP = (UINT32)NewInstructionPointer32;
+    } else {
+      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 ((CpuSaveState->x64.AutoHALTRestart & BIT0) != 0) {
+      CpuSaveState->x64.AutoHALTRestart &= ~BIT0;
+    }
+  }
+
+  return OriginalInstructionPointer;
+}
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117591): https://edk2.groups.io/g/devel/message/117591
Mute This Topic: https://groups.io/mt/105441992/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 04/13] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (2 preceding siblings ...)
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-16 10:20   ` Abdul Lateef Attar via groups.io
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 05/13] UefiCpuPkg/UefiCpuPkg.dsc: Include SmmRelocationLib in UefiCpuPkg Wu, Jiaxin
                   ` (10 subsequent siblings)
  14 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 UTC (permalink / raw)
  To: devel
  Cc: Abdul Lateef Attar, Abner Chang, 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: 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/AmdSmmRelocationLib.inf       |  61 ++++++++++++
 .../SmmRelocationLib/AmdSmramSaveStateConfig.c     | 109 +++++++++++++++++++++
 2 files changed, 170 insertions(+)
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
new file mode 100644
index 0000000000..710cd1948b
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
@@ -0,0 +1,61 @@
+## @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                      = 65C74DCD-0D09-494A-8BFF-A64226EB8054
+  MODULE_TYPE                    = PEIM
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = SmmRelocationLib
+
+[Sources]
+  InternalSmmRelocationLib.h
+  AmdSmramSaveStateConfig.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
+  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/AmdSmramSaveStateConfig.c b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
new file mode 100644
index 0000000000..fbcf347f9b
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
@@ -0,0 +1,109 @@
+/** @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>
+
+/**
+  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
+  )
+{
+  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;
+
+  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
+
+  if (mSmmSaveStateRegisterLma == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
+    AmdCpuState->x86.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
+  } else {
+    AmdCpuState->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
+  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.
+  @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;
+  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;
+
+  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
+
+  if (mSmmSaveStateRegisterLma == 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 ((AmdCpuState->x86.AutoHALTRestart & BIT0) != 0) {
+      AmdCpuState->x86.AutoHALTRestart &= ~BIT0;
+    }
+  } else {
+    OriginalInstructionPointer = AmdCpuState->x64._RIP;
+    if ((AmdCpuState->x64.EFER & LMA) == 0) {
+      AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer32;
+    } else {
+      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 ((AmdCpuState->x64.AutoHALTRestart & BIT0) != 0) {
+      AmdCpuState->x64.AutoHALTRestart &= ~BIT0;
+    }
+  }
+
+  return OriginalInstructionPointer;
+}
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117592): https://edk2.groups.io/g/devel/message/117592
Mute This Topic: https://groups.io/mt/105441993/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 05/13] UefiCpuPkg/UefiCpuPkg.dsc: Include SmmRelocationLib in UefiCpuPkg
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (3 preceding siblings ...)
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 04/13] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-11  3:21   ` Ni, Ray
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 06/13] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib Wu, Jiaxin
                   ` (9 subsequent siblings)
  14 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 UTC (permalink / raw)
  To: devel; +Cc: Ray Ni, Zeng Star, Gerd Hoffmann, Rahul Kumar

This patch just includes SmmRelocationLib in UefiCpuPkg.

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/UefiCpuPkg.dsc | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc
index 10b33594e5..631a850c78 100644
--- a/UefiCpuPkg/UefiCpuPkg.dsc
+++ b/UefiCpuPkg/UefiCpuPkg.dsc
@@ -194,10 +194,13 @@
       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
+  UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.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 (#117593): https://edk2.groups.io/g/devel/message/117593
Mute This Topic: https://groups.io/mt/105441994/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 06/13] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (4 preceding siblings ...)
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 05/13] UefiCpuPkg/UefiCpuPkg.dsc: Include SmmRelocationLib in UefiCpuPkg Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-10 13:59   ` Guo, Gua
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 07/13] OvmfPkg: Include SmmRelocationLib in OvmfPkg Wu, Jiaxin
                   ` (8 subsequent siblings)
  14 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 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>
---
 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 (#117594): https://edk2.groups.io/g/devel/message/117594
Mute This Topic: https://groups.io/mt/105441995/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 07/13] OvmfPkg: Include SmmRelocationLib in OvmfPkg
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (5 preceding siblings ...)
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 06/13] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid Wu, Jiaxin
                   ` (7 subsequent siblings)
  14 siblings, 0 replies; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann, Ray Ni

This patch just includes SmmRelocationLib in OvmfPkg.

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/AmdSev/AmdSevX64.dsc   | 1 +
 OvmfPkg/CloudHv/CloudHvX64.dsc | 1 +
 OvmfPkg/Microvm/MicrovmX64.dsc | 1 +
 OvmfPkg/OvmfPkgIa32.dsc        | 1 +
 OvmfPkg/OvmfPkgIa32X64.dsc     | 1 +
 OvmfPkg/OvmfPkgX64.dsc         | 1 +
 6 files changed, 6 insertions(+)

diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc
index 60e916b4fd..e171f4e89f 100644
--- a/OvmfPkg/AmdSev/AmdSevX64.dsc
+++ b/OvmfPkg/AmdSev/AmdSevX64.dsc
@@ -146,10 +146,11 @@
   OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
   SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
   MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
   MicrocodeLib|UefiCpuPkg/Library/MicrocodeLib/MicrocodeLib.inf
   CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf
+  SmmRelocationLib|UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
   UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
   UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
   UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
   UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
   UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc
index b522fa1059..5d7ec9bbfa 100644
--- a/OvmfPkg/CloudHv/CloudHvX64.dsc
+++ b/OvmfPkg/CloudHv/CloudHvX64.dsc
@@ -163,10 +163,11 @@
   OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
   SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
   MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
   MicrocodeLib|UefiCpuPkg/Library/MicrocodeLib/MicrocodeLib.inf
   CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf
+  SmmRelocationLib|UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
   UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
   UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
   UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
   UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
   UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc
index 2c6bb83beb..a8b12a49a3 100644
--- a/OvmfPkg/Microvm/MicrovmX64.dsc
+++ b/OvmfPkg/Microvm/MicrovmX64.dsc
@@ -166,10 +166,11 @@
   OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
   SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
   MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
   MicrocodeLib|UefiCpuPkg/Library/MicrocodeLib/MicrocodeLib.inf
   CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf
+  SmmRelocationLib|UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
   UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
   UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
   UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
   UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
   UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
index 713f08764b..03c35a1a72 100644
--- a/OvmfPkg/OvmfPkgIa32.dsc
+++ b/OvmfPkg/OvmfPkgIa32.dsc
@@ -166,10 +166,11 @@
   OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
   SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
   MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
   MicrocodeLib|UefiCpuPkg/Library/MicrocodeLib/MicrocodeLib.inf
   CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf
+  SmmRelocationLib|UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
   UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
   UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
   UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
   UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
   UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index 90b15dc270..90a0c08d6d 100644
--- a/OvmfPkg/OvmfPkgIa32X64.dsc
+++ b/OvmfPkg/OvmfPkgIa32X64.dsc
@@ -171,10 +171,11 @@
   OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
   SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
   MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
   MicrocodeLib|UefiCpuPkg/Library/MicrocodeLib/MicrocodeLib.inf
   CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf
+  SmmRelocationLib|UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
   UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
   UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
   UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
   UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
   UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index 56c920168d..b3ee245022 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -183,10 +183,11 @@
   OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
   SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
   MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
   MicrocodeLib|UefiCpuPkg/Library/MicrocodeLib/MicrocodeLib.inf
   CpuPageTableLib|UefiCpuPkg/Library/CpuPageTableLib/CpuPageTableLib.inf
+  SmmRelocationLib|UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
   UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
   UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
   UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
   UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
   UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117595): https://edk2.groups.io/g/devel/message/117595
Mute This Topic: https://groups.io/mt/105441996/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (6 preceding siblings ...)
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 07/13] OvmfPkg: Include SmmRelocationLib in OvmfPkg Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-11  3:27   ` Ni, Ray
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 09/13] OvmfPkg/SmmAccess: Consume gEfiSmmSmramMemoryGuid Wu, Jiaxin
                   ` (6 subsequent siblings)
  14 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann, Ray Ni

SmmRelocationLib instance will reserve the memory from
gEfiSmmSmramMemoryGuid for the smbase relocation.

So, system must produce the gEfiSmmSmramMemoryGuid.

This patch is for the OVMF to produce the
gEfiSmmSmramMemoryGuid HOB.

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 (#117596): https://edk2.groups.io/g/devel/message/117596
Mute This Topic: https://groups.io/mt/105441999/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 09/13] OvmfPkg/SmmAccess: Consume gEfiSmmSmramMemoryGuid
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (7 preceding siblings ...)
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-11  8:21   ` Ni, Ray
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 10/13] OvmfPkg/PlatformInitLib: Create gEfiAcpiVariableGuid Wu, Jiaxin
                   ` (5 subsequent siblings)
  14 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 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.
The gEfiAcpiVariableGuid HOB will be created in 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/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 +-------
 6 files changed, 41 insertions(+), 154 deletions(-)

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 (#117597): https://edk2.groups.io/g/devel/message/117597
Mute This Topic: https://groups.io/mt/105442001/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 10/13] OvmfPkg/PlatformInitLib: Create gEfiAcpiVariableGuid
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (8 preceding siblings ...)
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 09/13] OvmfPkg/SmmAccess: Consume gEfiSmmSmramMemoryGuid Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-11  8:20   ` Ni, Ray
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 11/13] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not Wu, Jiaxin
                   ` (4 subsequent siblings)
  14 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann, Ray Ni

This patch is for OVMF to create the gEfiAcpiVariableGuid
since it has been removed from the SmmAccess driver.

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 +++++++++
 OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf | 1 +
 2 files changed, 10 insertions(+)

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
 
-- 
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117598): https://edk2.groups.io/g/devel/message/117598
Mute This Topic: https://groups.io/mt/105442002/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 11/13] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (9 preceding siblings ...)
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 10/13] OvmfPkg/PlatformInitLib: Create gEfiAcpiVariableGuid Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-11  8:22   ` Ni, Ray
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 12/13] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase Wu, Jiaxin
                   ` (3 subsequent siblings)
  14 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 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>
---
 .../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 (#117599): https://edk2.groups.io/g/devel/message/117599
Mute This Topic: https://groups.io/mt/105442004/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 12/13] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (10 preceding siblings ...)
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 11/13] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-11  8:25   ` Ni, Ray
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic Wu, Jiaxin
                   ` (2 subsequent siblings)
  14 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 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      |  1 +
 OvmfPkg/PlatformPei/Platform.h      |  5 +++
 OvmfPkg/PlatformPei/PlatformPei.inf |  5 ++-
 OvmfPkg/PlatformPei/SmmRelocation.c | 80 +++++++++++++++++++++++++++++++++++++
 4 files changed, 90 insertions(+), 1 deletion(-)
 create mode 100644 OvmfPkg/PlatformPei/SmmRelocation.c

diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c
index f5dc41c3a8..47ccf9e2b9 100644
--- a/OvmfPkg/PlatformPei/Platform.c
+++ b/OvmfPkg/PlatformPei/Platform.c
@@ -365,8 +365,9 @@ InitializePlatform (
     MiscInitialization (PlatformInfoHob);
   }
 
   IntelTdxInitialize ();
   InstallFeatureControlCallback (PlatformInfoHob);
+  InstallSmmRelocationCallback ();
 
   return EFI_SUCCESS;
 }
diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h
index 1cf44844a7..e2057623b7 100644
--- a/OvmfPkg/PlatformPei/Platform.h
+++ b/OvmfPkg/PlatformPei/Platform.h
@@ -76,10 +76,15 @@ InstallFeatureControlCallback (
 VOID
 InstallClearCacheCallback (
   VOID
   );
 
+VOID
+InstallSmmRelocationCallback (
+  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..63db7101b5
--- /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
+InstallSmmRelocationCallback (
+  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 (#117600): https://edk2.groups.io/g/devel/message/117600
Mute This Topic: https://groups.io/mt/105442006/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] 37+ messages in thread

* [edk2-devel] [PATCH v1 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (11 preceding siblings ...)
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 12/13] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase Wu, Jiaxin
@ 2024-04-10 13:57 ` Wu, Jiaxin
  2024-04-10 14:01 ` [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Yao, Jiewen
  2024-04-11  3:14 ` Ni, Ray
  14 siblings, 0 replies; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 13:57 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, and the SmBase relocation
behavior will be in the SmmRelocationInit interface:
1. Relocate smbases for each processor.
2. Create the gSmmBaseHobGuid HOB.

Then, PiSmmCpuDxeSmm driver can be simplified to:
1. Consume the gSmmBaseHobGuid for the smbase.
2. ExecuteFirstSmiInit for 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>
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        |   6 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c   | 322 ++-------------------------
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h   |  98 --------
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf |   4 -
 UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c   |  69 ------
 UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c    |  69 ------
 UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm   | 146 ------------
 10 files changed, 30 insertions(+), 843 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..4180a25432 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c
@@ -1511,22 +1511,20 @@ 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
     //
     SmmInitHandler ();
 
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c
index 499f979d34..bdf524e33d 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
@@ -348,14 +336,10 @@ SmmInitHandler (
 {
   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);
@@ -386,17 +370,10 @@ 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));
         );
 
       return;
@@ -454,111 +431,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 +757,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 +775,10 @@ PiCpuSmmEntry (
   PERF_FUNCTION_BEGIN ();
 
   //
   // Initialize address fixup
   //
-  PiSmmCpuSmmInitFixupAddress ();
   PiSmmCpuSmiEntryFixupAddress ();
 
   //
   // Initialize Debug Agent to support source level debug in SMM code
   //
@@ -1113,65 +986,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 +1040,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 +1135,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 +1176,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 +1575,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..097a8c1b25 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
 
 //
@@ -373,22 +365,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 +456,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 +773,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 +817,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 +1030,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 +1211,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/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 (#117601): https://edk2.groups.io/g/devel/message/117601
Mute This Topic: https://groups.io/mt/105442009/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] 37+ messages in thread

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

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

Reviewed-by: Gua Guo <gua.guo@intel.com>
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Wednesday, April 10, 2024 9:57:17 PM
To: devel@edk2.groups.io <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 v1 06/13] 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>
---
 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 (#117602): https://edk2.groups.io/g/devel/message/117602
Mute This Topic: https://groups.io/mt/105441995/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: 3357 bytes --]

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

* Re: [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (12 preceding siblings ...)
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic Wu, Jiaxin
@ 2024-04-10 14:01 ` Yao, Jiewen
  2024-04-10 15:15   ` Wu, Jiaxin
  2024-04-11  3:14 ` Ni, Ray
  14 siblings, 1 reply; 37+ messages in thread
From: Yao, Jiewen @ 2024-04-10 14:01 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Ni, Ray, Zeng, Star, Gerd Hoffmann, Kumar, Rahul R, Dong, Guo,
	Rhodes, Sean, Lu, James, Guo, Gua, Ard Biesheuvel

Hello
Would you please describe what test has been done for OvmfPkg?
For example, have you validated OVMF with SMM enabled?


> -----Original Message-----
> From: Wu, Jiaxin <jiaxin.wu@intel.com>
> Sent: Wednesday, April 10, 2024 9:57 PM
> To: 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>;
> 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>
> Subject: [PATCH v1 00/13] Add SmmRelocationLib
> 
> 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>
> Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
> 
> Jiaxin Wu (13):
>   UefiCpuPkg: Add SmmRelocationLib class
>   UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance
>   UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
>   UefiCpuPkg/SmmRelocationLib: Add library instance for AMD
>   UefiCpuPkg/UefiCpuPkg.dsc: Include SmmRelocationLib in UefiCpuPkg
>   UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib
>   OvmfPkg: Include SmmRelocationLib in OvmfPkg
>   OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
>   OvmfPkg/SmmAccess: Consume gEfiSmmSmramMemoryGuid
>   OvmfPkg/PlatformInitLib: Create gEfiAcpiVariableGuid
>   OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not
>   OvmfPkg/PlatformPei: Relocate SmBases in PEI phase
>   UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic
> 
>  OvmfPkg/AmdSev/AmdSevX64.dsc                       |   1 +
>  OvmfPkg/CloudHv/CloudHvX64.dsc                     |   1 +
>  OvmfPkg/Library/PlatformInitLib/MemDetect.c        | 104 ++--
>  .../Library/PlatformInitLib/PlatformInitLib.inf    |   6 +-
>  .../Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c  |  33 +-
>  OvmfPkg/Microvm/MicrovmX64.dsc                     |   1 +
>  OvmfPkg/OvmfPkgIa32.dsc                            |   1 +
>  OvmfPkg/OvmfPkgIa32X64.dsc                         |   1 +
>  OvmfPkg/OvmfPkgX64.dsc                             |   1 +
>  OvmfPkg/PlatformPei/Platform.c                     |   1 +
>  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     | 109 ++++
>  .../SmmRelocationLib}/Ia32/Semaphore.c             |  13 +-
>  .../Library/SmmRelocationLib/Ia32/SmmInit.nasm     | 157 +++++
>  .../SmmRelocationLib/InternalSmmRelocationLib.h    | 141 +++++
>  .../SmmRelocationLib/OvmfSmmRelocationLib.inf      |  61 ++
>  .../SmmRelocationLib/OvmfSmramSaveStateConfig.c    | 107 ++++
>  .../Library/SmmRelocationLib/SmmRelocationLib.c    | 659
> +++++++++++++++++++++
>  .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  61 ++
>  .../SmmRelocationLib/SmramSaveStateConfig.c        |  91 +++
>  .../SmmRelocationLib}/X64/Semaphore.c              |  13 +-
>  .../SmmRelocationLib}/X64/SmmInit.nasm             |  93 ++-
>  UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c                  |  21 +-
>  UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm        |  96 ---
>  UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c              |   6 +-
>  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c         | 322 +---------
>  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h         |  98 ---
>  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf       |   4 -
>  UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c         |  69 ---
>  UefiCpuPkg/UefiCpuPkg.dec                          |   3 +
>  UefiCpuPkg/UefiCpuPkg.dsc                          |   3 +
>  UefiPayloadPkg/UefiPayloadPkg.dsc                  |   2 +
>  42 files changed, 1850 insertions(+), 817 deletions(-)
>  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/OvmfSmmRelocationLib.inf
>  create mode 100644
> UefiCpuPkg/Library/SmmRelocationLib/OvmfSmramSaveStateConfig.c
>  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 (57%)
>  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 (#117603): https://edk2.groups.io/g/devel/message/117603
Mute This Topic: https://groups.io/mt/105441987/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* Re: [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib
  2024-04-10 14:01 ` [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Yao, Jiewen
@ 2024-04-10 15:15   ` Wu, Jiaxin
  0 siblings, 0 replies; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-10 15:15 UTC (permalink / raw)
  To: Yao, Jiewen, devel@edk2.groups.io
  Cc: Ni, Ray, Zeng, Star, Gerd Hoffmann, Kumar, Rahul R, Dong, Guo,
	Rhodes, Sean, Lu, James, Guo, Gua, Ard Biesheuvel

Sure, Jiewen, Yes, I have tested on OVMF:

1) Checked the OVMF can normal boot with SMM enabled. 
2) Checked the multiple processor support on OVMF with -smp 4 command.
3) Test the OVMF can response soft SMI, the smbase has been rebased before smm cpu driver dispatch.
4) Pass SMM test on intel QSP platform.

Thanks,
Jiaxin


> -----Original Message-----
> From: Yao, Jiewen <jiewen.yao@intel.com>
> Sent: Wednesday, April 10, 2024 10:02 PM
> To: Wu, Jiaxin <jiaxin.wu@intel.com>; 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>;
> 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>
> Subject: RE: [PATCH v1 00/13] Add SmmRelocationLib
> 
> Hello
> Would you please describe what test has been done for OvmfPkg?
> For example, have you validated OVMF with SMM enabled?
> 
> 
> > -----Original Message-----
> > From: Wu, Jiaxin <jiaxin.wu@intel.com>
> > Sent: Wednesday, April 10, 2024 9:57 PM
> > To: 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>;
> > 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>
> > Subject: [PATCH v1 00/13] Add SmmRelocationLib
> >
> > 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>
> > Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
> >
> > Jiaxin Wu (13):
> >   UefiCpuPkg: Add SmmRelocationLib class
> >   UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance
> >   UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
> >   UefiCpuPkg/SmmRelocationLib: Add library instance for AMD
> >   UefiCpuPkg/UefiCpuPkg.dsc: Include SmmRelocationLib in UefiCpuPkg
> >   UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib
> >   OvmfPkg: Include SmmRelocationLib in OvmfPkg
> >   OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
> >   OvmfPkg/SmmAccess: Consume gEfiSmmSmramMemoryGuid
> >   OvmfPkg/PlatformInitLib: Create gEfiAcpiVariableGuid
> >   OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not
> >   OvmfPkg/PlatformPei: Relocate SmBases in PEI phase
> >   UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic
> >
> >  OvmfPkg/AmdSev/AmdSevX64.dsc                       |   1 +
> >  OvmfPkg/CloudHv/CloudHvX64.dsc                     |   1 +
> >  OvmfPkg/Library/PlatformInitLib/MemDetect.c        | 104 ++--
> >  .../Library/PlatformInitLib/PlatformInitLib.inf    |   6 +-
> >  .../Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c  |  33 +-
> >  OvmfPkg/Microvm/MicrovmX64.dsc                     |   1 +
> >  OvmfPkg/OvmfPkgIa32.dsc                            |   1 +
> >  OvmfPkg/OvmfPkgIa32X64.dsc                         |   1 +
> >  OvmfPkg/OvmfPkgX64.dsc                             |   1 +
> >  OvmfPkg/PlatformPei/Platform.c                     |   1 +
> >  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     | 109 ++++
> >  .../SmmRelocationLib}/Ia32/Semaphore.c             |  13 +-
> >  .../Library/SmmRelocationLib/Ia32/SmmInit.nasm     | 157 +++++
> >  .../SmmRelocationLib/InternalSmmRelocationLib.h    | 141 +++++
> >  .../SmmRelocationLib/OvmfSmmRelocationLib.inf      |  61 ++
> >  .../SmmRelocationLib/OvmfSmramSaveStateConfig.c    | 107 ++++
> >  .../Library/SmmRelocationLib/SmmRelocationLib.c    | 659
> > +++++++++++++++++++++
> >  .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  61 ++
> >  .../SmmRelocationLib/SmramSaveStateConfig.c        |  91 +++
> >  .../SmmRelocationLib}/X64/Semaphore.c              |  13 +-
> >  .../SmmRelocationLib}/X64/SmmInit.nasm             |  93 ++-
> >  UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c                  |  21 +-
> >  UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm        |  96 ---
> >  UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c              |   6 +-
> >  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c         | 322 +---------
> >  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h         |  98 ---
> >  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf       |   4 -
> >  UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c         |  69 ---
> >  UefiCpuPkg/UefiCpuPkg.dec                          |   3 +
> >  UefiCpuPkg/UefiCpuPkg.dsc                          |   3 +
> >  UefiPayloadPkg/UefiPayloadPkg.dsc                  |   2 +
> >  42 files changed, 1850 insertions(+), 817 deletions(-)
> >  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/OvmfSmmRelocationLib.inf
> >  create mode 100644
> > UefiCpuPkg/Library/SmmRelocationLib/OvmfSmramSaveStateConfig.c
> >  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 (57%)
> >  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 (#117604): https://edk2.groups.io/g/devel/message/117604
Mute This Topic: https://groups.io/mt/105441987/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



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

* Re: [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib
  2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (13 preceding siblings ...)
  2024-04-10 14:01 ` [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Yao, Jiewen
@ 2024-04-11  3:14 ` Ni, Ray
  2024-04-11  4:31   ` Wu, Jiaxin
  14 siblings, 1 reply; 37+ messages in thread
From: Ni, Ray @ 2024-04-11  3:14 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R, Dong, Guo,
	Rhodes, Sean, Lu, James, Guo, Gua, Ard Biesheuvel, Yao, Jiewen

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

Jiaxin, can you kindly share a PR in GitHub so that it will be easier to review?

Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Wednesday, April 10, 2024 21:57
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>; 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>
Subject: [PATCH v1 00/13] Add SmmRelocationLib

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>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>

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

 OvmfPkg/AmdSev/AmdSevX64.dsc                       |   1 +
 OvmfPkg/CloudHv/CloudHvX64.dsc                     |   1 +
 OvmfPkg/Library/PlatformInitLib/MemDetect.c        | 104 ++--
 .../Library/PlatformInitLib/PlatformInitLib.inf    |   6 +-
 .../Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c  |  33 +-
 OvmfPkg/Microvm/MicrovmX64.dsc                     |   1 +
 OvmfPkg/OvmfPkgIa32.dsc                            |   1 +
 OvmfPkg/OvmfPkgIa32X64.dsc                         |   1 +
 OvmfPkg/OvmfPkgX64.dsc                             |   1 +
 OvmfPkg/PlatformPei/Platform.c                     |   1 +
 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     | 109 ++++
 .../SmmRelocationLib}/Ia32/Semaphore.c             |  13 +-
 .../Library/SmmRelocationLib/Ia32/SmmInit.nasm     | 157 +++++
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 141 +++++
 .../SmmRelocationLib/OvmfSmmRelocationLib.inf      |  61 ++
 .../SmmRelocationLib/OvmfSmramSaveStateConfig.c    | 107 ++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 659 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  61 ++
 .../SmmRelocationLib/SmramSaveStateConfig.c        |  91 +++
 .../SmmRelocationLib}/X64/Semaphore.c              |  13 +-
 .../SmmRelocationLib}/X64/SmmInit.nasm             |  93 ++-
 UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c                  |  21 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm        |  96 ---
 UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c              |   6 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c         | 322 +---------
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h         |  98 ---
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf       |   4 -
 UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c         |  69 ---
 UefiCpuPkg/UefiCpuPkg.dec                          |   3 +
 UefiCpuPkg/UefiCpuPkg.dsc                          |   3 +
 UefiPayloadPkg/UefiPayloadPkg.dsc                  |   2 +
 42 files changed, 1850 insertions(+), 817 deletions(-)
 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/OvmfSmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/OvmfSmramSaveStateConfig.c
 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 (57%)
 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 (#117609): https://edk2.groups.io/g/devel/message/117609
Mute This Topic: https://groups.io/mt/105441987/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: 12361 bytes --]

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

* Re: [edk2-devel] [PATCH v1 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance Wu, Jiaxin
@ 2024-04-11  3:18   ` Ni, Ray
  0 siblings, 0 replies; 37+ messages in thread
From: Ni, Ray @ 2024-04-11  3:18 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

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

Not sure if "--find-copies-harder" helps to detect that the new files are copies of existing files.
Can you try in next version if some comments request a new version of patch?

Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Wednesday, April 10, 2024 21:57
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 v1 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance

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.

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>
---
 .../Library/SmmRelocationLib/Ia32/Semaphore.c      |  43 ++
 .../Library/SmmRelocationLib/Ia32/SmmInit.nasm     | 157 +++++
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 141 +++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 659 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  61 ++
 .../SmmRelocationLib/SmramSaveStateConfig.c        |  91 +++
 .../Library/SmmRelocationLib/X64/Semaphore.c       |  70 +++
 .../Library/SmmRelocationLib/X64/SmmInit.nasm      | 207 +++++++
 8 files changed, 1429 insertions(+)
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
 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
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
new file mode 100644
index 0000000000..ace3221cfc
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
@@ -0,0 +1,43 @@
+/** @file
+  Semaphore mechanism to indicate to the BSP that an AP has exited SMM
+  after SMBASE relocation.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "InternalSmmRelocationLib.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/Library/SmmRelocationLib/Ia32/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
new file mode 100644
index 0000000000..cb8b030693
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
@@ -0,0 +1,157 @@
+;------------------------------------------------------------------------------ ;
+; 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(gcSmiIdtr)
+global  ASM_PFX(gcSmiGdtr)
+
+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(gcSmiGdtr):
+    DW      GDT_SIZE - 1
+    DD      NullSeg
+
+ASM_PFX(gcSmiIdtr):
+    DW      0
+    DD      0
+
+
+    SECTION .text
+
+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(gcSmiGdtr) - 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(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..c8647fbfe7
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
@@ -0,0 +1,141 @@
+/** @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 UINT8   mSmmSaveStateRegisterLma;
+
+extern IA32_DESCRIPTOR  gcSmiGdtr;
+extern IA32_DESCRIPTOR  gcSmiIdtr;
+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..38bad24e7a
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
@@ -0,0 +1,659 @@
+/** @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;
+
+//
+// The mode of the CPU at the time an SMI occurs
+//
+UINT8  mSmmSaveStateRegisterLma;
+
+//
+// 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 (&gcSmiIdtr);
+  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.
+  //
+  gcSmiIdtr.Limit = (sizeof (IA32_IDT_GATE_DESCRIPTOR) * 32) - 1;
+
+  //
+  // Allocate for IDT.
+  // sizeof (UINTN) is for the PEI Services Table pointer.
+  //
+  gcSmiIdtr.Base = (UINTN)AllocateZeroPool (gcSmiIdtr.Limit + 1 + sizeof (UINTN));
+  ASSERT (gcSmiIdtr.Base != 0);
+  gcSmiIdtr.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 *)(gcSmiIdtr.Base - sizeof (UINTN))) = (UINTN)PeiServices;
+
+  //
+  // Load SMM temporary IDT table
+  //
+  AsmWriteIdtr (&gcSmiIdtr);
+
+  //
+  // Setup SMM default exception handlers, SMM IDT table
+  // will be updated and saved in gcSmiIdtr
+  //
+  Status = InitializeCpuExceptionHandlers (NULL);
+  ASSERT_EFI_ERROR (Status);
+
+  //
+  // Restore PEI IDT table and CPU InterruptState
+  //
+  AsmWriteIdtr ((IA32_DESCRIPTOR *)&PeiIdtr);
+  SetInterruptState (InterruptState);
+}
+
+/**
+  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
+CheckSmmCpuMode (
+  VOID
+  )
+{
+  UINT32  RegEax;
+  UINT32  RegEdx;
+  UINTN   FamilyId;
+  UINTN   ModelId;
+  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
+  //
+  AsmCpuid (CPUID_VERSION_INFO, &RegEax, NULL, NULL, NULL);
+  FamilyId = (RegEax >> 8) & 0xf;
+  ModelId  = (RegEax >> 4) & 0xf;
+  if ((FamilyId == 0x06) || (FamilyId == 0x0f)) {
+    ModelId = ModelId | ((RegEax >> 12) & 0xf0);
+  }
+
+  RegEdx = 0;
+  AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL);
+  if (RegEax >= CPUID_EXTENDED_CPU_SIG) {
+    AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &RegEdx);
+  }
+
+  SmmSaveStateRegisterLma = EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT;
+  if ((RegEdx & BIT29) != 0) {
+    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;
+}
+
+/**
+  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 ();
+
+  //
+  // Check the mode of the CPU at the time an SMI occurs
+  //
+  mSmmSaveStateRegisterLma = CheckSmmCpuMode ();
+
+  //
+  // 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..2ac16ab5d1
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
@@ -0,0 +1,61 @@
+## @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
+  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..3982158979
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
@@ -0,0 +1,91 @@
+/** @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"
+
+/**
+  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
+  )
+{
+  if (mSmmSaveStateRegisterLma == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
+    CpuState->x86.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
+  } else {
+    CpuState->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.
+
+  @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 (mSmmSaveStateRegisterLma == 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/Library/SmmRelocationLib/X64/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
new file mode 100644
index 0000000000..54d3462ef8
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
@@ -0,0 +1,70 @@
+/** @file
+  Semaphore mechanism to indicate to the BSP that an AP has exited SMM
+  after SMBASE relocation.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "InternalSmmRelocationLib.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/Library/SmmRelocationLib/X64/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
new file mode 100644
index 0000000000..ce4311fffd
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
@@ -0,0 +1,207 @@
+;------------------------------------------------------------------------------ ;
+; 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(gcSmiIdtr)
+global  ASM_PFX(gcSmiGdtr)
+
+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)
+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(gcSmiGdtr):
+    DW      GDT_SIZE - 1
+    DQ      NullSeg
+
+ASM_PFX(gcSmiIdtr):
+    DW      0
+    DQ      0
+
+
+    DEFAULT REL
+    SECTION .text
+
+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(gcSmiGdtr) - 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(SmmInitFixupAddress)
+ASM_PFX(SmmInitFixupAddress):
+    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 (#117610): https://edk2.groups.io/g/devel/message/117610
Mute This Topic: https://groups.io/mt/105441989/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: 92966 bytes --]

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

* Re: [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF Wu, Jiaxin
@ 2024-04-11  3:19   ` Ni, Ray
  2024-04-11  7:11   ` Gerd Hoffmann
  1 sibling, 0 replies; 37+ messages in thread
From: Ni, Ray @ 2024-04-11  3:19 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Ard Biesheuvel, Yao, Jiewen, Gerd Hoffmann,
	Kumar, Rahul R

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

No. Please do not create a OVMF specific lib instance in UefiCpuPkg.


Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Wednesday, April 10, 2024 21:57
To: devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Ni, Ray <ray.ni@intel.com>; Zeng, Star <star.zeng@intel.com>; Ard Biesheuvel <ardb+tianocore@kernel.org>; Yao, Jiewen <jiewen.yao@intel.com>; Gerd Hoffmann <kraxel@redhat.com>; Kumar, Rahul R <rahul.r.kumar@intel.com>
Subject: [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF

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

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

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>
---
 .../SmmRelocationLib/OvmfSmmRelocationLib.inf      |  61 ++++++++++++
 .../SmmRelocationLib/OvmfSmramSaveStateConfig.c    | 107 +++++++++++++++++++++
 2 files changed, 168 insertions(+)
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/OvmfSmramSaveStateConfig.c

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf b/UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
new file mode 100644
index 0000000000..eba1129ac2
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.inf
@@ -0,0 +1,61 @@
+## @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                      = 51834F51-CCE0-4743-B553-935D0C8A53FF
+  MODULE_TYPE                    = PEIM
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = SmmRelocationLib
+
+[Sources]
+  InternalSmmRelocationLib.h
+  OvmfSmramSaveStateConfig.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
+  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/OvmfSmramSaveStateConfig.c b/UefiCpuPkg/Library/SmmRelocationLib/OvmfSmramSaveStateConfig.c
new file mode 100644
index 0000000000..505b1d694a
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/OvmfSmramSaveStateConfig.c
@@ -0,0 +1,107 @@
+/** @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 <Register/Amd/SmramSaveStateMap.h>
+
+/**
+  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
+  )
+{
+  AMD_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
+
+  CpuSaveState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
+
+  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
+  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.
+  @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;
+  AMD_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
+
+  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 ((CpuSaveState->x86.AutoHALTRestart & BIT0) != 0) {
+      CpuSaveState->x86.AutoHALTRestart &= ~BIT0;
+    }
+  } else {
+    OriginalInstructionPointer = CpuSaveState->x64._RIP;
+    if ((CpuSaveState->x64.EFER & LMA) == 0) {
+      CpuSaveState->x64._RIP = (UINT32)NewInstructionPointer32;
+    } else {
+      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 ((CpuSaveState->x64.AutoHALTRestart & BIT0) != 0) {
+      CpuSaveState->x64.AutoHALTRestart &= ~BIT0;
+    }
+  }
+
+  return OriginalInstructionPointer;
+}
--
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117611): https://edk2.groups.io/g/devel/message/117611
Mute This Topic: https://groups.io/mt/105441992/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: 15264 bytes --]

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

* Re: [edk2-devel] [PATCH v1 05/13] UefiCpuPkg/UefiCpuPkg.dsc: Include SmmRelocationLib in UefiCpuPkg
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 05/13] UefiCpuPkg/UefiCpuPkg.dsc: Include SmmRelocationLib in UefiCpuPkg Wu, Jiaxin
@ 2024-04-11  3:21   ` Ni, Ray
  0 siblings, 0 replies; 37+ messages in thread
From: Ni, Ray @ 2024-04-11  3:21 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

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

Please change the DSC in the earlier patch that adds the lib instance and avoid this patch.


Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Wednesday, April 10, 2024 21:57
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 v1 05/13] UefiCpuPkg/UefiCpuPkg.dsc: Include SmmRelocationLib in UefiCpuPkg

This patch just includes SmmRelocationLib in UefiCpuPkg.

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/UefiCpuPkg.dsc | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc
index 10b33594e5..631a850c78 100644
--- a/UefiCpuPkg/UefiCpuPkg.dsc
+++ b/UefiCpuPkg/UefiCpuPkg.dsc
@@ -194,10 +194,13 @@
       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
+  UefiCpuPkg/Library/SmmRelocationLib/OvmfSmmRelocationLib.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 (#117612): https://edk2.groups.io/g/devel/message/117612
Mute This Topic: https://groups.io/mt/105441994/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: 4270 bytes --]

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

* Re: [edk2-devel] [PATCH v1 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid Wu, Jiaxin
@ 2024-04-11  3:27   ` Ni, Ray
  0 siblings, 0 replies; 37+ messages in thread
From: Ni, Ray @ 2024-04-11  3:27 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Ard Biesheuvel, Yao, Jiewen, Gerd Hoffmann

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

I think the commit message can have more details to help OVMF developers understand the needs of this patch.
E.g.:
  Before using SmmRelocationLib, the PiSmmCpuDxeSmm driver allocates the SMRAM to be used for SMI handler + 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 when the Smst->AllocatePages() service is not available. So, the allocation is done by
  splitting the SMRAM out of the SMRAM regions reported from Guid HOB (gEfiSmmSMramMemoryGuid).
  However, OVMF platform does not produce the GUID HOB. This patch produces the HOB......

Thanks,
Ray

________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Wednesday, April 10, 2024 21:57
To: devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>; Yao, Jiewen <jiewen.yao@intel.com>; Gerd Hoffmann <kraxel@redhat.com>; Ni, Ray <ray.ni@intel.com>
Subject: [PATCH v1 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid

SmmRelocationLib instance will reserve the memory from
gEfiSmmSmramMemoryGuid for the smbase relocation.

So, system must produce the gEfiSmmSmramMemoryGuid.

This patch is for the OVMF to produce the
gEfiSmmSmramMemoryGuid HOB.

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 (#117613): https://edk2.groups.io/g/devel/message/117613
Mute This Topic: https://groups.io/mt/105441999/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: 15261 bytes --]

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

* Re: [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib
  2024-04-11  3:14 ` Ni, Ray
@ 2024-04-11  4:31   ` Wu, Jiaxin
  0 siblings, 0 replies; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-11  4:31 UTC (permalink / raw)
  To: Ni, Ray, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R, Dong, Guo,
	Rhodes, Sean, Lu, James, Guo, Gua, Ard Biesheuvel, Yao, Jiewen

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

Share the PR here: https://github.com/tianocore/edk2/pull/5546

From: Ni, Ray <ray.ni@intel.com>
Sent: Thursday, April 11, 2024 11:15 AM
To: Wu, Jiaxin <jiaxin.wu@intel.com>; devel@edk2.groups.io
Cc: Zeng, Star <star.zeng@intel.com>; Gerd Hoffmann <kraxel@redhat.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>
Subject: Re: [PATCH v1 00/13] Add SmmRelocationLib

Jiaxin, can you kindly share a PR in GitHub so that it will be easier to review?

Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com<mailto:jiaxin.wu@intel.com>>
Sent: Wednesday, April 10, 2024 21:57
To: devel@edk2.groups.io<mailto:devel@edk2.groups.io> <devel@edk2.groups.io<mailto:devel@edk2.groups.io>>
Cc: Ni, Ray <ray.ni@intel.com<mailto:ray.ni@intel.com>>; Zeng, Star <star.zeng@intel.com<mailto:star.zeng@intel.com>>; Gerd Hoffmann <kraxel@redhat.com<mailto:kraxel@redhat.com>>; Kumar, Rahul R <rahul.r.kumar@intel.com<mailto:rahul.r.kumar@intel.com>>; Dong, Guo <guo.dong@intel.com<mailto:guo.dong@intel.com>>; Rhodes, Sean <sean@starlabs.systems<mailto:sean@starlabs.systems>>; Lu, James <james.lu@intel.com<mailto:james.lu@intel.com>>; Guo, Gua <gua.guo@intel.com<mailto:gua.guo@intel.com>>; Ard Biesheuvel <ardb+tianocore@kernel.org<mailto:ardb+tianocore@kernel.org>>; Yao, Jiewen <jiewen.yao@intel.com<mailto:jiewen.yao@intel.com>>
Subject: [PATCH v1 00/13] Add SmmRelocationLib

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<mailto:ray.ni@intel.com>>
Cc: Zeng Star <star.zeng@intel.com<mailto:star.zeng@intel.com>>
Cc: Gerd Hoffmann <kraxel@redhat.com<mailto:kraxel@redhat.com>>
Cc: Rahul Kumar <rahul1.kumar@intel.com<mailto:rahul1.kumar@intel.com>>
Cc: Guo Dong <guo.dong@intel.com<mailto:guo.dong@intel.com>>
Cc: Sean Rhodes <sean@starlabs.systems<mailto:sean@starlabs.systems>>
Cc: James Lu <james.lu@intel.com<mailto:james.lu@intel.com>>
Cc: Gua Guo <gua.guo@intel.com<mailto:gua.guo@intel.com>>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org<mailto:ardb+tianocore@kernel.org>>
Cc: Jiewen Yao <jiewen.yao@intel.com<mailto:jiewen.yao@intel.com>>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com<mailto:jiaxin.wu@intel.com>>

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

 OvmfPkg/AmdSev/AmdSevX64.dsc                       |   1 +
 OvmfPkg/CloudHv/CloudHvX64.dsc                     |   1 +
 OvmfPkg/Library/PlatformInitLib/MemDetect.c        | 104 ++--
 .../Library/PlatformInitLib/PlatformInitLib.inf    |   6 +-
 .../Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c  |  33 +-
 OvmfPkg/Microvm/MicrovmX64.dsc                     |   1 +
 OvmfPkg/OvmfPkgIa32.dsc                            |   1 +
 OvmfPkg/OvmfPkgIa32X64.dsc                         |   1 +
 OvmfPkg/OvmfPkgX64.dsc                             |   1 +
 OvmfPkg/PlatformPei/Platform.c                     |   1 +
 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     | 109 ++++
 .../SmmRelocationLib}/Ia32/Semaphore.c             |  13 +-
 .../Library/SmmRelocationLib/Ia32/SmmInit.nasm     | 157 +++++
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 141 +++++
 .../SmmRelocationLib/OvmfSmmRelocationLib.inf      |  61 ++
 .../SmmRelocationLib/OvmfSmramSaveStateConfig.c    | 107 ++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 659 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  61 ++
 .../SmmRelocationLib/SmramSaveStateConfig.c        |  91 +++
 .../SmmRelocationLib}/X64/Semaphore.c              |  13 +-
 .../SmmRelocationLib}/X64/SmmInit.nasm             |  93 ++-
 UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c                  |  21 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm        |  96 ---
 UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c              |   6 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c         | 322 +---------
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h         |  98 ---
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf       |   4 -
 UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c         |  69 ---
 UefiCpuPkg/UefiCpuPkg.dec                          |   3 +
 UefiCpuPkg/UefiCpuPkg.dsc                          |   3 +
 UefiPayloadPkg/UefiPayloadPkg.dsc                  |   2 +
 42 files changed, 1850 insertions(+), 817 deletions(-)
 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/OvmfSmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/OvmfSmramSaveStateConfig.c
 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 (57%)
 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 (#117614): https://edk2.groups.io/g/devel/message/117614
Mute This Topic: https://groups.io/mt/105441987/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: 16010 bytes --]

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

* Re: [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF Wu, Jiaxin
  2024-04-11  3:19   ` Ni, Ray
@ 2024-04-11  7:11   ` Gerd Hoffmann
  2024-04-15 13:04     ` Wu, Jiaxin
  1 sibling, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2024-04-11  7:11 UTC (permalink / raw)
  To: Jiaxin Wu
  Cc: devel, Ray Ni, Zeng Star, Ard Biesheuvel, Jiewen Yao, Rahul Kumar

On Wed, Apr 10, 2024 at 09:57:14PM +0800, Jiaxin Wu wrote:
> Due to the definition difference of SMRAM Save State,
> SmmBase config in SMRAM Save State for OVMF is also different.
> 
> This patch provides the OvmfSmmRelocationLib library instance
> to handle the SMRAM Save State difference.

Why ovmf needs its own version?  Patch #4 adds an AMD version, and given
that KVM uses the AMD smram layout that library should work for OVMF
too, no?

take care,
  Gerd



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



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

* Re: [edk2-devel] [PATCH v1 10/13] OvmfPkg/PlatformInitLib: Create gEfiAcpiVariableGuid
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 10/13] OvmfPkg/PlatformInitLib: Create gEfiAcpiVariableGuid Wu, Jiaxin
@ 2024-04-11  8:20   ` Ni, Ray
  0 siblings, 0 replies; 37+ messages in thread
From: Ni, Ray @ 2024-04-11  8:20 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Ard Biesheuvel, Yao, Jiewen, Gerd Hoffmann

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

Which patch removes this HOB creation from SmmAccess driver?

Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Wednesday, April 10, 2024 21:57
To: devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>; Yao, Jiewen <jiewen.yao@intel.com>; Gerd Hoffmann <kraxel@redhat.com>; Ni, Ray <ray.ni@intel.com>
Subject: [PATCH v1 10/13] OvmfPkg/PlatformInitLib: Create gEfiAcpiVariableGuid

This patch is for OVMF to create the gEfiAcpiVariableGuid
since it has been removed from the SmmAccess driver.

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 +++++++++
 OvmfPkg/Library/PlatformInitLib/PlatformInitLib.inf | 1 +
 2 files changed, 10 insertions(+)

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

--
2.16.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117621): https://edk2.groups.io/g/devel/message/117621
Mute This Topic: https://groups.io/mt/105442002/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: 7527 bytes --]

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

* Re: [edk2-devel] [PATCH v1 09/13] OvmfPkg/SmmAccess: Consume gEfiSmmSmramMemoryGuid
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 09/13] OvmfPkg/SmmAccess: Consume gEfiSmmSmramMemoryGuid Wu, Jiaxin
@ 2024-04-11  8:21   ` Ni, Ray
  0 siblings, 0 replies; 37+ messages in thread
From: Ni, Ray @ 2024-04-11  8:21 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Ard Biesheuvel, Yao, Jiewen, Gerd Hoffmann

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

Do you think it makes sense to combine this with #10? Otherwise, with this patch the OVMF is broken.

Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Wednesday, April 10, 2024 21:57
To: devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>; Yao, Jiewen <jiewen.yao@intel.com>; Gerd Hoffmann <kraxel@redhat.com>; Ni, Ray <ray.ni@intel.com>
Subject: [PATCH v1 09/13] OvmfPkg/SmmAccess: Consume gEfiSmmSmramMemoryGuid

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.
The gEfiAcpiVariableGuid HOB will be created in 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/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 +-------
 6 files changed, 41 insertions(+), 154 deletions(-)

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 (#117623): https://edk2.groups.io/g/devel/message/117623
Mute This Topic: https://groups.io/mt/105442001/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: 27312 bytes --]

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

* Re: [edk2-devel] [PATCH v1 11/13] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 11/13] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not Wu, Jiaxin
@ 2024-04-11  8:22   ` Ni, Ray
  0 siblings, 0 replies; 37+ messages in thread
From: Ni, Ray @ 2024-04-11  8:22 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Ard Biesheuvel, Yao, Jiewen, Gerd Hoffmann

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

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

Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Wednesday, April 10, 2024 21:57
To: devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>; Yao, Jiewen <jiewen.yao@intel.com>; Gerd Hoffmann <kraxel@redhat.com>; Ni, Ray <ray.ni@intel.com>
Subject: [PATCH v1 11/13] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not

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>
---
 .../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 (#117624): https://edk2.groups.io/g/devel/message/117624
Mute This Topic: https://groups.io/mt/105442004/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: 8552 bytes --]

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

* Re: [edk2-devel] [PATCH v1 12/13] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 12/13] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase Wu, Jiaxin
@ 2024-04-11  8:25   ` Ni, Ray
  0 siblings, 0 replies; 37+ messages in thread
From: Ni, Ray @ 2024-04-11  8:25 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Ard Biesheuvel, Yao, Jiewen, Gerd Hoffmann

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

+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
+InstallSmmRelocationCallback (
[Ray.1] This function name is confusing. It's like installing a callback when smm relocation happens. How about "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 (#117625): https://edk2.groups.io/g/devel/message/117625
Mute This Topic: https://groups.io/mt/105442006/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: 3172 bytes --]

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

* Re: [edk2-devel] [PATCH v1 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic
@ 2024-04-11 10:35 Ni, Ray
  0 siblings, 0 replies; 37+ messages in thread
From: Ni, Ray @ 2024-04-11 10:35 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

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

@@ -348,14 +336,10 @@ SmmInitHandler (

[Ray.1] Can you rename this function to a different name? Originally it was really a handler to initialize SMM env called from SmmInit.nasm. But today it's purely to initialize the SMM env.
How about "InitializeSmm"? And "EFIAPI" is not needed as it's not called from ASEMBLY anymore.

 {
   UINT32   ApicId;
   UINTN    Index;
   BOOLEAN  IsBsp;

-  //
-  // Update SMM IDT entries' code segment and load IDT
-  //
-  AsmWriteIdtr (&gcSmiIdtr);

[Ray.2]
OK.
The IDTR update is needed when it's called from SmmInit.nasm as IDTR is not updated there.
But it's not needed when it's called from SmmEntry.nasm as IDTR is updated there.


Other changes look good to me.

________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Wednesday, April 10, 2024 21:57
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 v1 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic

This patch is to remove legacy SmBase relocation in
PiSmmCpuDxeSmm Driver, and the SmBase relocation
behavior will be in the SmmRelocationInit interface:
1. Relocate smbases for each processor.
2. Create the gSmmBaseHobGuid HOB.

Then, PiSmmCpuDxeSmm driver can be simplified to:
1. Consume the gSmmBaseHobGuid for the smbase.
2. ExecuteFirstSmiInit for 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>
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        |   6 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c   | 322 ++-------------------------
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h   |  98 --------
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf |   4 -
 UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c   |  69 ------
 UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c    |  69 ------
 UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm   | 146 ------------
 10 files changed, 30 insertions(+), 843 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..4180a25432 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c
+++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c
@@ -1511,22 +1511,20 @@ 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
     //
     SmmInitHandler ();

diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c
index 499f979d34..bdf524e33d 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
@@ -348,14 +336,10 @@ SmmInitHandler (
 {
   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);
@@ -386,17 +370,10 @@ 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));
         );

       return;
@@ -454,111 +431,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 +757,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 +775,10 @@ PiCpuSmmEntry (
   PERF_FUNCTION_BEGIN ();

   //
   // Initialize address fixup
   //
-  PiSmmCpuSmmInitFixupAddress ();
   PiSmmCpuSmiEntryFixupAddress ();

   //
   // Initialize Debug Agent to support source level debug in SMM code
   //
@@ -1113,65 +986,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 +1040,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 +1135,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 +1176,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 +1575,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..097a8c1b25 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

 //
@@ -373,22 +365,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 +456,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 +773,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 +817,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 +1030,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 +1211,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/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 (#117631): https://edk2.groups.io/g/devel/message/117631
Mute This Topic: https://groups.io/mt/105442009/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: 78623 bytes --]

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

* Re: [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-11  7:11   ` Gerd Hoffmann
@ 2024-04-15 13:04     ` Wu, Jiaxin
  2024-04-16  7:35       ` Gerd Hoffmann
  0 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-15 13:04 UTC (permalink / raw)
  To: Gerd Hoffmann, thomas.lendacky@amd.com
  Cc: devel@edk2.groups.io, Ni, Ray, Zeng, Star, Ard Biesheuvel,
	Yao, Jiewen, Kumar, Rahul R

Hi Gred,

Because:
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 = (UINT32)mSmBaseForAllCpus[CpuIndex];

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

This series patch won't change the existing implementation code logic, so, we need override one version for OVMF.

+AMD feature owner 

Thanks,
Jiaxin 


> -----Original Message-----
> From: Gerd Hoffmann <kraxel@redhat.com>
> Sent: Thursday, April 11, 2024 3:11 PM
> To: Wu, Jiaxin <jiaxin.wu@intel.com>
> Cc: devel@edk2.groups.io; Ni, Ray <ray.ni@intel.com>; Zeng, Star
> <star.zeng@intel.com>; Ard Biesheuvel <ardb+tianocore@kernel.org>; Yao,
> Jiewen <jiewen.yao@intel.com>; Kumar, Rahul R <rahul.r.kumar@intel.com>
> Subject: Re: [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library
> instance for OVMF
> 
> On Wed, Apr 10, 2024 at 09:57:14PM +0800, Jiaxin Wu wrote:
> > Due to the definition difference of SMRAM Save State,
> > SmmBase config in SMRAM Save State for OVMF is also different.
> >
> > This patch provides the OvmfSmmRelocationLib library instance
> > to handle the SMRAM Save State difference.
> 
> Why ovmf needs its own version?  Patch #4 adds an AMD version, and given
> that KVM uses the AMD smram layout that library should work for OVMF
> too, no?
> 
> take care,
>   Gerd



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



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

* Re: [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-15 13:04     ` Wu, Jiaxin
@ 2024-04-16  7:35       ` Gerd Hoffmann
  2024-04-16 10:12         ` Wu, Jiaxin
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2024-04-16  7:35 UTC (permalink / raw)
  To: Wu, Jiaxin
  Cc: thomas.lendacky@amd.com, devel@edk2.groups.io, Ni, Ray,
	Zeng, Star, Ard Biesheuvel, Yao, Jiewen, Kumar, Rahul R

On Mon, Apr 15, 2024 at 01:04:58PM +0000, Wu, Jiaxin wrote:
> Hi Gred,
> 
> Because:
> 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 = (UINT32)mSmBaseForAllCpus[CpuIndex];
> 
> AMD:   
>  if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
>     CpuSaveState->x86.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
>   } else {
>     CpuSaveState->x64.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
>   }
> 
> This series patch won't change the existing implementation code logic, so, we need override one version for OVMF.

The real question is why do these differences exist and are they
actually needed.

I'd expect the CPU mode check return identical results.

The SmBase configuration for OVMF looks suspicious to me.  I'm wondering
whenever the OVMF code actually works in Ia32 builds ...

take care,
  Gerd



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



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

* Re: [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-16  7:35       ` Gerd Hoffmann
@ 2024-04-16 10:12         ` Wu, Jiaxin
  2024-04-16 10:30           ` Gerd Hoffmann
  0 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-16 10:12 UTC (permalink / raw)
  To: Gerd Hoffmann
  Cc: thomas.lendacky@amd.com, devel@edk2.groups.io, Ni, Ray,
	Zeng, Star, Ard Biesheuvel, Yao, Jiewen, Kumar, Rahul R

> 
> On Mon, Apr 15, 2024 at 01:04:58PM +0000, Wu, Jiaxin wrote:
> > Hi Gred,
> >
> > Because:
> > 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 = (UINT32)mSmBaseForAllCpus[CpuIndex];
> >
> > AMD:
> >  if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
> >     CpuSaveState->x86.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
> >   } else {
> >     CpuSaveState->x64.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
> >   }
> >
> > This series patch won't change the existing implementation code logic, so, we
> need override one version for OVMF.
> 
> The real question is why do these differences exist and are they
> actually needed.
> 
> I'd expect the CPU mode check return identical results.

I don't the background why AMD and OVMF has such difference. Maybe OVFM doesn't not support the MSR "EFER_ADDRESS".

> 
> The SmBase configuration for OVMF looks suspicious to me.  I'm wondering
> whenever the OVMF code actually works in Ia32 builds ...
> 

Yes, I will fix it in the next version. Currently, please build it with SMM_REQUIRE == TRUE. In the next version, I will make sure all pass the check.

> take care,
>   Gerd



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



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

* Re: [edk2-devel] [PATCH v1 04/13] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD
  2024-04-10 13:57 ` [edk2-devel] [PATCH v1 04/13] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD Wu, Jiaxin
@ 2024-04-16 10:20   ` Abdul Lateef Attar via groups.io
  0 siblings, 0 replies; 37+ messages in thread
From: Abdul Lateef Attar via groups.io @ 2024-04-16 10:20 UTC (permalink / raw)
  To: Jiaxin Wu, devel
  Cc: Abner Chang, Ray Ni, Zeng Star, Gerd Hoffmann, Rahul Kumar

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

Reviewed-by: Abdul Lateef Attar <AbdulLateef.Attar@amd.com>

On 10-04-2024 19:27, Jiaxin Wu wrote:
> Caution: This message originated from an External Source. Use proper caution when opening attachments, clicking links, or responding.
>
>
> 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: 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/AmdSmmRelocationLib.inf       |  61 ++++++++++++
>   .../SmmRelocationLib/AmdSmramSaveStateConfig.c     | 109 +++++++++++++++++++++
>   2 files changed, 170 insertions(+)
>   create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
>   create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
>
> diff --git a/UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
> new file mode 100644
> index 0000000000..710cd1948b
> --- /dev/null
> +++ b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
> @@ -0,0 +1,61 @@
> +## @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                      = 65C74DCD-0D09-494A-8BFF-A64226EB8054
> +  MODULE_TYPE                    = PEIM
> +  VERSION_STRING                 = 1.0
> +  LIBRARY_CLASS                  = SmmRelocationLib
> +
> +[Sources]
> +  InternalSmmRelocationLib.h
> +  AmdSmramSaveStateConfig.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
> +  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/AmdSmramSaveStateConfig.c b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
> new file mode 100644
> index 0000000000..fbcf347f9b
> --- /dev/null
> +++ b/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
> @@ -0,0 +1,109 @@
> +/** @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>
> +
> +/**
> +  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
> +  )
> +{
> +  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;
> +
> +  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
> +
> +  if (mSmmSaveStateRegisterLma == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
> +    AmdCpuState->x86.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
> +  } else {
> +    AmdCpuState->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
> +  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.
> +  @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;
> +  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;
> +
> +  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
> +
> +  if (mSmmSaveStateRegisterLma == 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 ((AmdCpuState->x86.AutoHALTRestart & BIT0) != 0) {
> +      AmdCpuState->x86.AutoHALTRestart &= ~BIT0;
> +    }
> +  } else {
> +    OriginalInstructionPointer = AmdCpuState->x64._RIP;
> +    if ((AmdCpuState->x64.EFER & LMA) == 0) {
> +      AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer32;
> +    } else {
> +      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 ((AmdCpuState->x64.AutoHALTRestart & BIT0) != 0) {
> +      AmdCpuState->x64.AutoHALTRestart &= ~BIT0;
> +    }
> +  }
> +
> +  return OriginalInstructionPointer;
> +}
> --
> 2.16.2.windows.1
>


-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#117876): https://edk2.groups.io/g/devel/message/117876
Mute This Topic: https://groups.io/mt/105441993/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: 9688 bytes --]

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

* Re: [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-16 10:12         ` Wu, Jiaxin
@ 2024-04-16 10:30           ` Gerd Hoffmann
  2024-04-16 11:34             ` Wu, Jiaxin
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2024-04-16 10:30 UTC (permalink / raw)
  To: Wu, Jiaxin
  Cc: thomas.lendacky@amd.com, devel@edk2.groups.io, Ni, Ray,
	Zeng, Star, Ard Biesheuvel, Yao, Jiewen, Kumar, Rahul R

  Hi,

> > > 2) Existing SmBase configuration is different between the AMD & OVMF.
> > > OVMF:
> > >  AmdCpuState->x64.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
> > >
> > > AMD:
> > >  if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
> > >     CpuSaveState->x86.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
> > >   } else {
> > >     CpuSaveState->x64.SMBASE = (UINT32)mSmBaseForAllCpus[CpuIndex];
> > >   }

> I don't the background why AMD and OVMF has such difference. Maybe OVFM doesn't not support the MSR "EFER_ADDRESS".

It surely does, it's a rather essential MSR for x64 CPUs.

> > The SmBase configuration for OVMF looks suspicious to me.  I'm wondering
> > whenever the OVMF code actually works in Ia32 builds ...

Tested OvmfPkg/OvmfPkgIa32.dsc with SMM_REQUIRE == TRUE (master branch).
Doesn't boot.  The difference above (where the OVMF code does not
consider the 32bit case) could very well explain why 32bit support is
broken.  Switching to the AMD code might actually fix that.

Is the SmmRelocationLib approach supposed to work with mixed mode
firmware where PEI is running in ia32 mode and dxe/smm is running
in x64 mode (i.e. OvmfPkg/OvmfPkgIa32X64.dsc)?

take care,
  Gerd



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



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

* Re: [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-16 10:30           ` Gerd Hoffmann
@ 2024-04-16 11:34             ` Wu, Jiaxin
  2024-04-17  7:04               ` Gerd Hoffmann
  0 siblings, 1 reply; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-16 11:34 UTC (permalink / raw)
  To: Gerd Hoffmann
  Cc: thomas.lendacky@amd.com, devel@edk2.groups.io, Ni, Ray,
	Zeng, Star, Ard Biesheuvel, Yao, Jiewen, Kumar, Rahul R

Hi Gerd,

> > I don't the background why AMD and OVMF has such difference. Maybe
> OVFM doesn't not support the MSR "EFER_ADDRESS".
> 
> It surely does, it's a rather essential MSR for x64 CPUs.
> 
> > > The SmBase configuration for OVMF looks suspicious to me.  I'm
> wondering
> > > whenever the OVMF code actually works in Ia32 builds ...
> 
> Tested OvmfPkg/OvmfPkgIa32.dsc with SMM_REQUIRE == TRUE (master
> branch).
> Doesn't boot.  The difference above (where the OVMF code does not
> consider the 32bit case) could very well explain why 32bit support is
> broken.  Switching to the AMD code might actually fix that.
> 
> Is the SmmRelocationLib approach supposed to work with mixed mode
> firmware where PEI is running in ia32 mode and dxe/smm is running
> in x64 mode (i.e. OvmfPkg/OvmfPkgIa32X64.dsc)?
> 

Yes, I passed the test on the both OvmfPkgIa32X64 & OvmfPkgX64 for SMM support.

It does has the problem on OvmfPkgIa32 for smm support (same as master). I did quick check, it's not only the CpuSaveState->x86 or CpuSaveState->x64 structure issue, but also has some problem to handler the smi hook return. We can handle this problem in another topic. 

Thanks,
Jiaxin

 



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



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

* Re: [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-16 11:34             ` Wu, Jiaxin
@ 2024-04-17  7:04               ` Gerd Hoffmann
  2024-04-17  7:45                 ` Wu, Jiaxin
  0 siblings, 1 reply; 37+ messages in thread
From: Gerd Hoffmann @ 2024-04-17  7:04 UTC (permalink / raw)
  To: Wu, Jiaxin
  Cc: thomas.lendacky@amd.com, devel@edk2.groups.io, Ni, Ray,
	Zeng, Star, Ard Biesheuvel, Yao, Jiewen, Kumar, Rahul R

On Tue, Apr 16, 2024 at 11:34:00AM +0000, Wu, Jiaxin wrote:
> Hi Gerd,
> 
> > Is the SmmRelocationLib approach supposed to work with mixed mode
> > firmware where PEI is running in ia32 mode and dxe/smm is running
> > in x64 mode (i.e. OvmfPkg/OvmfPkgIa32X64.dsc)?
> 
> Yes, I passed the test on the both OvmfPkgIa32X64 & OvmfPkgX64 for SMM support.

The OVMF library I assume?
Did you try the AMD library too?

> It does has the problem on OvmfPkgIa32 for smm support (same as
> master). I did quick check, it's not only the CpuSaveState->x86 or
> CpuSaveState->x64 structure issue, but also has some problem to
> handler the smi hook return. We can handle this problem in another
> topic.

Yes, fixing ia32 can be done separately.

take care,
  Gerd



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



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

* Re: [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-17  7:04               ` Gerd Hoffmann
@ 2024-04-17  7:45                 ` Wu, Jiaxin
  0 siblings, 0 replies; 37+ messages in thread
From: Wu, Jiaxin @ 2024-04-17  7:45 UTC (permalink / raw)
  To: Gerd Hoffmann
  Cc: thomas.lendacky@amd.com, devel@edk2.groups.io, Ni, Ray,
	Zeng, Star, Ard Biesheuvel, Yao, Jiewen, Kumar, Rahul R

I'm using the OVMF library, haven't try the AMD library:).

> -----Original Message-----
> From: Gerd Hoffmann <kraxel@redhat.com>
> Sent: Wednesday, April 17, 2024 3:04 PM
> To: Wu, Jiaxin <jiaxin.wu@intel.com>
> Cc: thomas.lendacky@amd.com; devel@edk2.groups.io; Ni, Ray
> <ray.ni@intel.com>; Zeng, Star <star.zeng@intel.com>; Ard Biesheuvel
> <ardb+tianocore@kernel.org>; Yao, Jiewen <jiewen.yao@intel.com>; Kumar,
> Rahul R <rahul.r.kumar@intel.com>
> Subject: Re: [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library
> instance for OVMF
> 
> On Tue, Apr 16, 2024 at 11:34:00AM +0000, Wu, Jiaxin wrote:
> > Hi Gerd,
> >
> > > Is the SmmRelocationLib approach supposed to work with mixed mode
> > > firmware where PEI is running in ia32 mode and dxe/smm is running
> > > in x64 mode (i.e. OvmfPkg/OvmfPkgIa32X64.dsc)?
> >
> > Yes, I passed the test on the both OvmfPkgIa32X64 & OvmfPkgX64 for SMM
> support.
> 
> The OVMF library I assume?
> Did you try the AMD library too?
> 
> > It does has the problem on OvmfPkgIa32 for smm support (same as
> > master). I did quick check, it's not only the CpuSaveState->x86 or
> > CpuSaveState->x64 structure issue, but also has some problem to
> > handler the smi hook return. We can handle this problem in another
> > topic.
> 
> Yes, fixing ia32 can be done separately.
> 
> take care,
>   Gerd



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



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

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

Thread overview: 37+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2024-04-10 13:57 [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Wu, Jiaxin
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 01/13] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance Wu, Jiaxin
2024-04-11  3:18   ` Ni, Ray
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 03/13] UefiCpuPkg/SmmRelocationLib: Add library instance for OVMF Wu, Jiaxin
2024-04-11  3:19   ` Ni, Ray
2024-04-11  7:11   ` Gerd Hoffmann
2024-04-15 13:04     ` Wu, Jiaxin
2024-04-16  7:35       ` Gerd Hoffmann
2024-04-16 10:12         ` Wu, Jiaxin
2024-04-16 10:30           ` Gerd Hoffmann
2024-04-16 11:34             ` Wu, Jiaxin
2024-04-17  7:04               ` Gerd Hoffmann
2024-04-17  7:45                 ` Wu, Jiaxin
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 04/13] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD Wu, Jiaxin
2024-04-16 10:20   ` Abdul Lateef Attar via groups.io
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 05/13] UefiCpuPkg/UefiCpuPkg.dsc: Include SmmRelocationLib in UefiCpuPkg Wu, Jiaxin
2024-04-11  3:21   ` Ni, Ray
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 06/13] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib Wu, Jiaxin
2024-04-10 13:59   ` Guo, Gua
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 07/13] OvmfPkg: Include SmmRelocationLib in OvmfPkg Wu, Jiaxin
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid Wu, Jiaxin
2024-04-11  3:27   ` Ni, Ray
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 09/13] OvmfPkg/SmmAccess: Consume gEfiSmmSmramMemoryGuid Wu, Jiaxin
2024-04-11  8:21   ` Ni, Ray
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 10/13] OvmfPkg/PlatformInitLib: Create gEfiAcpiVariableGuid Wu, Jiaxin
2024-04-11  8:20   ` Ni, Ray
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 11/13] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not Wu, Jiaxin
2024-04-11  8:22   ` Ni, Ray
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 12/13] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase Wu, Jiaxin
2024-04-11  8:25   ` Ni, Ray
2024-04-10 13:57 ` [edk2-devel] [PATCH v1 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic Wu, Jiaxin
2024-04-10 14:01 ` [edk2-devel] [PATCH v1 00/13] Add SmmRelocationLib Yao, Jiewen
2024-04-10 15:15   ` Wu, Jiaxin
2024-04-11  3:14 ` Ni, Ray
2024-04-11  4:31   ` Wu, Jiaxin
  -- strict thread matches above, loose matches on Subject: below --
2024-04-11 10:35 [edk2-devel] [PATCH v1 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic Ni, Ray

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