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

PR: https://github.com/tianocore/edk2/pull/5546

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

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

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

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

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

 OvmfPkg/AmdSev/AmdSevX64.dsc                       |   1 +
 OvmfPkg/CloudHv/CloudHvX64.dsc                     |   1 +
 OvmfPkg/Library/PlatformInitLib/MemDetect.c        | 104 ++--
 .../Library/PlatformInitLib/PlatformInitLib.inf    |   6 +-
 .../Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.c  |  33 +-
 .../Library/SmmRelocationLib}/Ia32/Semaphore.c     |  13 +-
 .../Library/SmmRelocationLib}/Ia32/SmmInit.nasm    |  83 +++-
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 127 +++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 549 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  60 +++
 .../SmmRelocationLib/SmramSaveStateConfig.c        | 100 ++++
 .../Library/SmmRelocationLib}/X64/Semaphore.c      |  13 +-
 .../Library/SmmRelocationLib}/X64/SmmInit.nasm     |  85 +++-
 OvmfPkg/Microvm/MicrovmX64.dsc                     |   1 +
 OvmfPkg/OvmfPkgIa32.dsc                            |   1 +
 OvmfPkg/OvmfPkgIa32X64.dsc                         |   1 +
 OvmfPkg/OvmfPkgX64.dsc                             |   1 +
 OvmfPkg/PlatformPei/Platform.c                     |   3 +
 OvmfPkg/PlatformPei/Platform.h                     |   5 +
 OvmfPkg/PlatformPei/PlatformPei.inf                |   5 +-
 OvmfPkg/PlatformPei/SmmRelocation.c                |  80 +++
 OvmfPkg/SmmAccess/SmmAccess2Dxe.c                  |   4 +-
 OvmfPkg/SmmAccess/SmmAccess2Dxe.inf                |   5 +
 OvmfPkg/SmmAccess/SmmAccessPei.c                   |  88 +---
 OvmfPkg/SmmAccess/SmmAccessPei.inf                 |   7 +-
 OvmfPkg/SmmAccess/SmramInternal.c                  |  73 +--
 OvmfPkg/SmmAccess/SmramInternal.h                  |  18 +-
 UefiCpuPkg/Include/Library/SmmRelocationLib.h      |  42 ++
 .../SmmRelocationLib/AmdSmmRelocationLib.inf       |  60 +++
 .../SmmRelocationLib/AmdSmramSaveStateConfig.c     | 125 +++++
 .../SmmRelocationLib}/Ia32/Semaphore.c             |  13 +-
 .../SmmRelocationLib}/Ia32/SmmInit.nasm            |  83 +++-
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 127 +++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 549 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  61 +++
 .../SmmRelocationLib/SmramSaveStateConfig.c        | 136 +++++
 .../SmmRelocationLib}/X64/Semaphore.c              |  13 +-
 .../SmmRelocationLib}/X64/SmmInit.nasm             |  85 +++-
 UefiCpuPkg/PiSmmCpuDxeSmm/CpuS3.c                  |  21 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c              |  10 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.c         | 331 ++-----------
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h         | 103 +---
 UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf       |   4 -
 UefiCpuPkg/PiSmmCpuDxeSmm/SmmMpPerf.h              |   2 +-
 UefiCpuPkg/PiSmmCpuDxeSmm/SmramSaveState.c         |  69 ---
 UefiCpuPkg/UefiCpuPkg.dec                          |   3 +
 UefiCpuPkg/UefiCpuPkg.dsc                          |   2 +
 UefiPayloadPkg/UefiPayloadPkg.dsc                  |   2 +
 48 files changed, 2514 insertions(+), 794 deletions(-)
 copy {UefiCpuPkg/PiSmmCpuDxeSmm => OvmfPkg/Library/SmmRelocationLib}/Ia32/Semaphore.c (71%)
 copy {UefiCpuPkg/PiSmmCpuDxeSmm => OvmfPkg/Library/SmmRelocationLib}/Ia32/SmmInit.nasm (47%)
 create mode 100644 OvmfPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
 create mode 100644 OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.c
 create mode 100644 OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 create mode 100644 OvmfPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
 copy {UefiCpuPkg/PiSmmCpuDxeSmm => OvmfPkg/Library/SmmRelocationLib}/X64/Semaphore.c (78%)
 copy {UefiCpuPkg/PiSmmCpuDxeSmm => OvmfPkg/Library/SmmRelocationLib}/X64/SmmInit.nasm (59%)
 create mode 100644 OvmfPkg/PlatformPei/SmmRelocation.c
 create mode 100644 UefiCpuPkg/Include/Library/SmmRelocationLib.h
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/AmdSmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
 rename UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/Ia32/Semaphore.c (71%)
 rename UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/Ia32/SmmInit.nasm (47%)
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
 rename UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/X64/Semaphore.c (78%)
 rename UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/X64/SmmInit.nasm (59%)

-- 
2.16.2.windows.1



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



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

* [edk2-devel] [PATCH v3 01/13] UefiCpuPkg: Add SmmRelocationLib class
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance Wu, Jiaxin
                   ` (11 subsequent siblings)
  12 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 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>
Reviewed-by: Ray Ni <ray.ni@intel.com>
---
 UefiCpuPkg/Include/Library/SmmRelocationLib.h | 42 +++++++++++++++++++++++++++
 UefiCpuPkg/UefiCpuPkg.dec                     |  3 ++
 2 files changed, 45 insertions(+)
 create mode 100644 UefiCpuPkg/Include/Library/SmmRelocationLib.h

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

* [edk2-devel] [PATCH v3 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 01/13] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  7:32   ` Ni, Ray
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 03/13] UefiCpuPkg/SmmRelocationLib: Rename global variables Wu, Jiaxin
                   ` (10 subsequent siblings)
  12 siblings, 1 reply; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 UTC (permalink / raw)
  To: devel; +Cc: Ray Ni, Zeng Star, Gerd Hoffmann, Rahul Kumar

This patch just separates the smbase relocation logic from
PiSmmCpuDxeSmm driver, and moves to the SmmRelocationInit
interface. It maintains the original implementation of most
functions and leaves the definitions of global variables
intact. Further refinements to the code are planned for
subsequent patches.

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

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

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

Cc: Ray Ni <ray.ni@intel.com>
Cc: Zeng Star <star.zeng@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 .../SmmRelocationLib}/Ia32/Semaphore.c             |  10 +-
 .../SmmRelocationLib}/Ia32/SmmInit.nasm            |  67 ++-
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 132 +++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 600 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  61 +++
 .../SmmRelocationLib/SmramSaveStateConfig.c        | 139 +++++
 .../SmmRelocationLib}/X64/Semaphore.c              |  10 +-
 .../SmmRelocationLib}/X64/SmmInit.nasm             |  69 ++-
 UefiCpuPkg/UefiCpuPkg.dsc                          |   1 +
 9 files changed, 1066 insertions(+), 23 deletions(-)
 copy UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/Ia32/Semaphore.c (79%)
 copy UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/Ia32/SmmInit.nasm (53%)
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
 copy UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/X64/Semaphore.c (84%)
 copy UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/X64/SmmInit.nasm (64%)

diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
similarity index 79%
copy from UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c
copy to UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
index a9fcc89dda..ba329d6ba2 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
@@ -1,15 +1,15 @@
 /** @file
-Semaphore mechanism to indicate to the BSP that an AP has exited SMM
-after SMBASE relocation.
+  Semaphore mechanism to indicate to the BSP that an AP has exited SMM
+  after SMBASE relocation.
 
-Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>
-SPDX-License-Identifier: BSD-2-Clause-Patent
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 
-#include "PiSmmCpuDxeSmm.h"
+#include "InternalSmmRelocationLib.h"
 
 UINTN             mSmmRelocationOriginalAddress;
 volatile BOOLEAN  *mRebasedFlag;
 
 /**
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
similarity index 53%
copy from UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm
copy to UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
index b5e77a1a5b..3d845e9e16 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
@@ -1,7 +1,7 @@
 ;------------------------------------------------------------------------------ ;
-; Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR>
+; Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
 ; SPDX-License-Identifier: BSD-2-Clause-Patent
 ;
 ; Module Name:
 ;
 ;   SmmInit.nasm
@@ -27,15 +27,70 @@ global ASM_PFX(gcSmmInitSize)
 global ASM_PFX(gcSmmInitTemplate)
 
 %define PROTECT_MODE_CS 0x8
 %define PROTECT_MODE_DS 0x20
 
-    SECTION .text
+    SECTION .data
 
-ASM_PFX(gcSmiInitGdtr):
+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
-            DQ      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(gcSmiInitGdtr):
+    DW      GDT_SIZE - 1
+    DD      NullSeg
+
+
+    SECTION .text
 
 global ASM_PFX(SmmStartup)
 
 BITS 16
 ASM_PFX(SmmStartup):
@@ -89,8 +144,8 @@ ASM_PFX(SmmRelocationSemaphoreComplete):
     mov     eax, [ASM_PFX(mRebasedFlag)]
     mov     byte [eax], 1
     pop     eax
     jmp     [ASM_PFX(mSmmRelocationOriginalAddress)]
 
-global ASM_PFX(PiSmmCpuSmmInitFixupAddress)
-ASM_PFX(PiSmmCpuSmmInitFixupAddress):
+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..a9d3f271a9
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
@@ -0,0 +1,132 @@
+/** @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 <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 IA32_DESCRIPTOR  gcSmiInitGdtr;
+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]     SmBase             The SmBase on the currently executing CPU.
+
+**/
+VOID
+EFIAPI
+ConfigureSmBase (
+  IN UINT64  SmBase
+  );
+
+/**
+  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..13e62b662d
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
@@ -0,0 +1,600 @@
+/** @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;
+
+//
+// Record all Processors Info
+//
+EFI_PROCESSOR_INFORMATION  *mProcessorInfo = NULL;
+
+//
+// IDT used during SMM Init
+//
+IA32_DESCRIPTOR  gcSmiIdtr;
+
+//
+// Smbase for all CPUs
+//
+UINT64  *mSmBase = NULL;
+
+//
+// SmBase Rebased flag for all CPUs
+//
+volatile BOOLEAN  *mRebased;
+
+/**
+  This function will create SmBase for all CPUs.
+
+  @param[in] SmBase    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  *SmBase
+  )
+{
+  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: %d\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: %d\n", HobCount, SmmBaseHobData->ProcessorIndex));
+    DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->NumberOfProcessors: %d\n", HobCount, SmmBaseHobData->NumberOfProcessors));
+    for (Index = 0; Index < SmmBaseHobData->NumberOfProcessors; Index++) {
+      //
+      // Calculate the new SMBASE address
+      //
+      SmmBaseHobData->SmBase[Index] = SmBase[Index + CpuCount];
+      DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->SmBase[%d]: 0x%08x\n", HobCount, Index, SmmBaseHobData->SmBase[Index]));
+    }
+
+    CpuCount += NumberOfProcessorsInHob;
+    HobCount++;
+    SmmBaseHobData = NULL;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  C function for SMI handler. To change all processor's SMMBase Register.
+
+**/
+VOID
+EFIAPI
+SmmInitHandler (
+  VOID
+  )
+{
+  UINT32  ApicId;
+  UINTN   Index;
+
+  //
+  // Update SMM IDT entries' code segment and load IDT
+  //
+  AsmWriteIdtr (&gcSmiIdtr);
+  ApicId = GetApicId ();
+
+  for (Index = 0; Index < mNumberOfCpus; Index++) {
+    if (ApicId == (UINT32)mProcessorInfo[Index].ProcessorId) {
+      //
+      // Configure SmBase.
+      //
+      ConfigureSmBase (mSmBase[Index]);
+
+      //
+      // 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);
+}
+
+/**
+  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));
+}
+
+/**
+  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);
+}
+
+/**
+  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  *Block;
+  EFI_SMRAM_HOB_DESCRIPTOR_BLOCK  *NewBlock;
+  UINTN                           NewBlockSize;
+
+  ASSERT (SmmRelocationStart != NULL);
+
+  //
+  // Retrieve the GUID HOB data that contains the set of SMRAM descriptors
+  //
+  GuidHob = GetFirstGuidHob (&gEfiSmmSmramMemoryGuid);
+  if (GuidHob == NULL) {
+    return EFI_NOT_FOUND;
+  }
+
+  Block = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)GET_GUID_HOB_DATA (GuidHob);
+
+  //
+  // Allocate one extra EFI_SMRAM_DESCRIPTOR to describe smram carved out for all SMBASE
+  //
+  NewBlockSize = sizeof (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK) + (Block->NumberOfSmmReservedRegions * sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  NewBlock = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)BuildGuidHob (
+                                                 &gEfiSmmSmramMemoryGuid,
+                                                 NewBlockSize
+                                                 );
+  ASSERT (NewBlock != NULL);
+  if (NewBlock == NULL) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  //
+  // Copy old EFI_SMRAM_HOB_DESCRIPTOR_BLOCK to new allocated region
+  //
+  CopyMem ((VOID *)NewBlock, Block, NewBlockSize - sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  //
+  // Increase the number of SMRAM descriptors by 1 to make room for the ALLOCATED descriptor of size EFI_PAGE_SIZE
+  //
+  NewBlock->NumberOfSmmReservedRegions = (UINT32)(Block->NumberOfSmmReservedRegions + 1);
+
+  ASSERT (Block->NumberOfSmmReservedRegions >= 1);
+  //
+  // Copy last entry to the end - we assume TSEG is last entry.
+  //
+  CopyMem (&NewBlock->Descriptor[Block->NumberOfSmmReservedRegions], &NewBlock->Descriptor[Block->NumberOfSmmReservedRegions - 1], sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  //
+  // Update the entry in the array with a size of SmmRelocationSize and put into the ALLOCATED state
+  //
+  NewBlock->Descriptor[Block->NumberOfSmmReservedRegions - 1].PhysicalSize = SmmRelocationSize;
+  NewBlock->Descriptor[Block->NumberOfSmmReservedRegions - 1].RegionState |= EFI_ALLOCATED;
+
+  //
+  // Return the start address of Smm relocated memory in SMRAM.
+  //
+  *SmmRelocationStart = NewBlock->Descriptor[Block->NumberOfSmmReservedRegions - 1].CpuStart;
+
+  //
+  // Reduce the size of the last SMRAM descriptor by SmmRelocationSize
+  //
+  NewBlock->Descriptor[Block->NumberOfSmmReservedRegions].PhysicalStart += SmmRelocationSize;
+  NewBlock->Descriptor[Block->NumberOfSmmReservedRegions].CpuStart      += SmmRelocationSize;
+  NewBlock->Descriptor[Block->NumberOfSmmReservedRegions].PhysicalSize  -= SmmRelocationSize;
+
+  //
+  // Last step, we can scrub old one
+  //
+  ZeroMem (&GuidHob->Name, sizeof (GuidHob->Name));
+
+  return EFI_SUCCESS;
+}
+
+/**
+  This function will initialize SmBase for all CPUs.
+
+  @param[in,out] SmBase    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  **SmBase
+  )
+{
+  EFI_STATUS            Status;
+  UINTN                 TileSize;
+  UINT64                SmmRelocationSize;
+  EFI_PHYSICAL_ADDRESS  SmmRelocationStart;
+  UINTN                 Index;
+
+  SmmRelocationStart = 0;
+
+  ASSERT (SmBase != 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 SmBase
+  //
+  *SmBase = (UINT64 *)AllocatePages (EFI_SIZE_TO_PAGES (sizeof (UINT64) * mMaxNumberOfCpus));
+  if (*SmBase == NULL) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
+    //
+    // Return each SmBase in SmBase
+    //
+    (*SmBase)[Index] = (UINTN)(SmmRelocationStart)+ Index * TileSize - SMM_HANDLER_OFFSET;
+    DEBUG ((DEBUG_INFO, "InitSmBaseForAllCpus - SmBase For CPU[%d]: 0x%08x\n", Index, (*SmBase)[Index]));
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  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;
+  }
+
+  //
+  // Get the number of processors
+  //
+  Status = MpServices2->GetNumberOfProcessors (
+                          MpServices2,
+                          &mNumberOfCpus,
+                          &NumberOfEnabledCpus
+                          );
+  if (EFI_ERROR (Status)) {
+    goto ON_EXIT;
+  }
+
+  if (FeaturePcdGet (PcdCpuHotPlugSupport)) {
+    mMaxNumberOfCpus = PcdGet32 (PcdCpuMaxLogicalProcessorNumber);
+  } else {
+    mMaxNumberOfCpus = mNumberOfCpus;
+  }
+
+  ASSERT (mNumberOfCpus <= mMaxNumberOfCpus);
+
+  //
+  // 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 (&mSmBase);
+  if (EFI_ERROR (Status)) {
+    goto ON_EXIT;
+  }
+
+  //
+  // Fix up the address of the global variable or function referred in
+  // SmmInit assembly files to be the absolute address
+  //
+  SmmInitFixupAddress ();
+
+  //
+  // Patch SMI stack for SMM base relocation
+  // Note: No need allocate stack for all CPUs since the relocation
+  // occurs serially for each CPU
+  //
+  SmmStackSize = EFI_PAGE_SIZE;
+  SmmStacks    = (UINT8 *)AllocatePages (EFI_SIZE_TO_PAGES (SmmStackSize));
+  if (SmmStacks == NULL) {
+    Status = EFI_OUT_OF_RESOURCES;
+    goto ON_EXIT;
+  }
+
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit - SmmStackSize: 0x%08x\n", SmmStackSize));
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit - SmmStacks: 0x%08x\n", SmmStacks));
+
+  PatchInstructionX86 (
+    gPatchSmmInitStack,
+    (UINTN)(SmmStacks + SmmStackSize - sizeof (UINTN)),
+    sizeof (UINTN)
+    );
+
+  //
+  // Initialize the SMM IDT for SMM base relocation
+  //
+  InitSmmIdt ();
+
+  //
+  // 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 (mSmBase);
+
+ON_EXIT:
+  if (SmmStacks != NULL) {
+    FreePages (SmmStacks, EFI_SIZE_TO_PAGES (SmmStackSize));
+  }
+
+  if (mSmBase != NULL) {
+    FreePages (mSmBase, 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..45fdaf35bc
--- /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
+  CpuLib
+  DebugLib
+  HobLib
+  LocalApicLib
+  MemoryAllocationLib
+  PcdLib
+  PeiServicesLib
+
+[Guids]
+  gSmmBaseHobGuid                               ## HOB ALWAYS_PRODUCED
+  gEfiSmmSmramMemoryGuid                        ## CONSUMES
+
+[Pcd]
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber
+
+[FeaturePcd]
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugSupport                        ## CONSUMES
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
new file mode 100644
index 0000000000..d3a0bb9b89
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
@@ -0,0 +1,139 @@
+/** @file
+  Config SMRAM Save State for SmmBases Relocation.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#include "InternalSmmRelocationLib.h"
+#include <Library/CpuLib.h>
+
+/**
+  Get 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
+GetMmSaveStateRegisterLma (
+  VOID
+  )
+{
+  CPUID_VERSION_INFO_EAX      RegEax;
+  CPUID_EXTENDED_CPU_SIG_EDX  RegEdx;
+  UINTN                       FamilyId;
+  UINTN                       ModelId;
+  UINT32                      Eax;
+  UINT8                       SmmSaveStateRegisterLma;
+
+  //
+  // Determine the mode of the CPU at the time an SMI occurs
+  //   Intel(R) 64 and IA-32 Architectures Software Developer's Manual
+  //   Volume 3C, Section 34.4.1.1
+  //
+  RegEax.Uint32 = GetCpuFamilyModel ();
+  FamilyId      = RegEax.Bits.FamilyId;
+  ModelId       = RegEax.Bits.Model;
+  if ((FamilyId == 0x06) || (FamilyId == 0x0f)) {
+    ModelId = ModelId | RegEax.Bits.ExtendedModelId << 4;
+  }
+
+  RegEdx.Uint32 = 0;
+  AsmCpuid (CPUID_EXTENDED_FUNCTION, &Eax, NULL, NULL, NULL);
+  if (Eax >= CPUID_EXTENDED_CPU_SIG) {
+    AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &(RegEdx.Uint32));
+  }
+
+  SmmSaveStateRegisterLma = (UINT8)EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT;
+  if (RegEdx.Bits.LM) {
+    SmmSaveStateRegisterLma = (UINT8)EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT;
+  }
+
+  if (FamilyId == 0x06) {
+    if ((ModelId == 0x17) || (ModelId == 0x0f) || (ModelId == 0x1c)) {
+      SmmSaveStateRegisterLma = (UINT8)EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT;
+    }
+  }
+
+  return SmmSaveStateRegisterLma;
+}
+
+/**
+  This function configures the SmBase on the currently executing CPU.
+
+  @param[in]     SmBase             The SmBase on the currently executing CPU.
+
+**/
+VOID
+EFIAPI
+ConfigureSmBase (
+  IN UINT64  SmBase
+  )
+{
+  SMRAM_SAVE_STATE_MAP  *CpuState;
+
+  CpuState = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+
+  CpuState->x86.SMBASE = (UINT32)SmBase;
+}
+
+/**
+  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 (GetMmSaveStateRegisterLma () == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
+    OriginalInstructionPointer = (UINT64)CpuState->x86._EIP;
+    CpuState->x86._EIP         = (UINT32)NewInstructionPointer;
+
+    //
+    // Clear the auto HALT restart flag so the RSM instruction returns
+    // program control to the instruction following the HLT instruction.
+    //
+    if ((CpuState->x86.AutoHALTRestart & BIT0) != 0) {
+      CpuState->x86.AutoHALTRestart &= ~BIT0;
+    }
+  } else {
+    OriginalInstructionPointer = CpuState->x64._RIP;
+    if ((CpuState->x64.IA32_EFER & LMA) == 0) {
+      CpuState->x64._RIP = (UINT32)NewInstructionPointer32;
+    } else {
+      CpuState->x64._RIP = (UINT32)NewInstructionPointer;
+    }
+
+    //
+    // Clear the auto HALT restart flag so the RSM instruction returns
+    // program control to the instruction following the HLT instruction.
+    //
+    if ((CpuState->x64.AutoHALTRestart & BIT0) != 0) {
+      CpuState->x64.AutoHALTRestart &= ~BIT0;
+    }
+  }
+
+  return OriginalInstructionPointer;
+}
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
similarity index 84%
copy from UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c
copy to UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
index dafbc3390e..53f3084363 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
@@ -1,15 +1,15 @@
 /** @file
-Semaphore mechanism to indicate to the BSP that an AP has exited SMM
-after SMBASE relocation.
+  Semaphore mechanism to indicate to the BSP that an AP has exited SMM
+  after SMBASE relocation.
 
-Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>
-SPDX-License-Identifier: BSD-2-Clause-Patent
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 
-#include "PiSmmCpuDxeSmm.h"
+#include "InternalSmmRelocationLib.h"
 
 X86_ASSEMBLY_PATCH_LABEL  gPatchSmmRelocationOriginalAddressPtr32;
 X86_ASSEMBLY_PATCH_LABEL  gPatchRebasedFlagAddr32;
 
 UINTN             mSmmRelocationOriginalAddress;
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
similarity index 64%
copy from UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm
copy to UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
index 9cf3a6dcf9..c790ad7ad8 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
@@ -1,7 +1,7 @@
 ;------------------------------------------------------------------------------ ;
-; Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR>
+; Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
 ; SPDX-License-Identifier: BSD-2-Clause-Patent
 ;
 ; Module Name:
 ;
 ;   SmmInit.nasm
@@ -28,16 +28,71 @@ global ASM_PFX(gcSmmInitTemplate)
 global ASM_PFX(gPatchRebasedFlagAddr32)
 global ASM_PFX(gPatchSmmRelocationOriginalAddressPtr32)
 
 %define LONG_MODE_CS 0x38
 
-    DEFAULT REL
-    SECTION .text
+    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(gcSmiInitGdtr):
-            DW      0
-            DQ      0
+    DW      GDT_SIZE - 1
+    DQ      NullSeg
+
+
+    DEFAULT REL
+    SECTION .text
 
 global ASM_PFX(SmmStartup)
 
 BITS 16
 ASM_PFX(SmmStartup):
@@ -132,12 +187,12 @@ ASM_PFX(gPatchRebasedFlagAddr32):
     pop     eax
     jmp     dword [dword 0]                    ; destination will be patched
 ASM_PFX(gPatchSmmRelocationOriginalAddressPtr32):
 
 BITS 64
-global ASM_PFX(PiSmmCpuSmmInitFixupAddress)
-ASM_PFX(PiSmmCpuSmmInitFixupAddress):
+global ASM_PFX(SmmInitFixupAddress)
+ASM_PFX(SmmInitFixupAddress):
     lea    rax, [@LongMode]
     lea    rcx, [@PatchLongModeOffset - 6]
     mov    dword [rcx], eax
 
     lea    rax, [ASM_PFX(SmmStartup)]
diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc
index 9426641eb2..8f67587e91 100644
--- a/UefiCpuPkg/UefiCpuPkg.dsc
+++ b/UefiCpuPkg/UefiCpuPkg.dsc
@@ -199,10 +199,11 @@
       UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf
   }
   UefiCpuPkg/Library/MmSaveStateLib/AmdMmSaveStateLib.inf
   UefiCpuPkg/Library/MmSaveStateLib/IntelMmSaveStateLib.inf
   UefiCpuPkg/Library/SmmCpuFeaturesLib/AmdSmmCpuFeaturesLib.inf
+  UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 
 [Components.X64]
   UefiCpuPkg/Library/CpuExceptionHandlerLib/UnitTest/DxeCpuExceptionHandlerLibUnitTest.inf
 
 [Components.RISCV64]
-- 
2.16.2.windows.1



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

* [edk2-devel] [PATCH v3 03/13] UefiCpuPkg/SmmRelocationLib: Rename global variables
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 01/13] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  7:33   ` Ni, Ray
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 04/13] UefiCpuPkg/SmmRelocationLib: Avoid unnecessary memory allocation Wu, Jiaxin
                   ` (9 subsequent siblings)
  12 siblings, 1 reply; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 UTC (permalink / raw)
  To: devel; +Cc: Ray Ni, Zeng Star, Gerd Hoffmann, Rahul Kumar

This patch aims to rename global variables for clearer
association with Smm Init, ensuring their names are
distinct from those used in the PiSmmCpuDxeSmm Driver.

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/SmmInit.nasm     | 18 +++++++--------
 .../SmmRelocationLib/InternalSmmRelocationLib.h    |  8 +++----
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 26 +++++++++++-----------
 .../Library/SmmRelocationLib/X64/SmmInit.nasm      | 18 +++++++--------
 4 files changed, 35 insertions(+), 35 deletions(-)

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
index 3d845e9e16..8916cb7d06 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
@@ -16,15 +16,15 @@
 
 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(gPatchSmmInitCr3)
+global ASM_PFX(gPatchSmmInitCr4)
+global ASM_PFX(gPatchSmmInitCr0)
 global ASM_PFX(gPatchSmmInitStack)
-global ASM_PFX(gcSmiInitGdtr)
+global ASM_PFX(gcSmmInitGdtr)
 global ASM_PFX(gcSmmInitSize)
 global ASM_PFX(gcSmmInitTemplate)
 
 %define PROTECT_MODE_CS 0x8
 %define PROTECT_MODE_DS 0x20
@@ -81,11 +81,11 @@ CodeSeg64:
             DB      0x9b
             DB      0xaf                ; LimitHigh
             DB      0                   ; BaseHigh
 GDT_SIZE equ $ - NullSeg
 
-ASM_PFX(gcSmiInitGdtr):
+ASM_PFX(gcSmmInitGdtr):
     DW      GDT_SIZE - 1
     DD      NullSeg
 
 
     SECTION .text
@@ -98,22 +98,22 @@ ASM_PFX(SmmStartup):
     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):
+ASM_PFX(gPatchSmmInitCr3):
     mov     cr3, eax
-o32 lgdt    [cs:ebp + (ASM_PFX(gcSmiInitGdtr) - ASM_PFX(SmmStartup))]
+o32 lgdt    [cs:ebp + (ASM_PFX(gcSmmInitGdtr) - ASM_PFX(SmmStartup))]
     mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr4):
+ASM_PFX(gPatchSmmInitCr4):
     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):
+ASM_PFX(gPatchSmmInitCr0):
     mov     di, PROTECT_MODE_DS
     mov     cr0, eax
     jmp     PROTECT_MODE_CS : dword @32bit
 
 BITS 32
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
index a9d3f271a9..ede61b956f 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
+++ b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
@@ -30,17 +30,17 @@
 #include <Guid/SmmBaseHob.h>
 #include <Register/Intel/Cpuid.h>
 #include <Register/Intel/SmramSaveStateMap.h>
 #include <Protocol/MmCpu.h>
 
-extern IA32_DESCRIPTOR  gcSmiInitGdtr;
+extern IA32_DESCRIPTOR  gcSmmInitGdtr;
 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  gPatchSmmInitCr0;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmInitCr3;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmInitCr4;
 X86_ASSEMBLY_PATCH_LABEL  gPatchSmmInitStack;
 
 //
 // The size 0x20 must be bigger than
 // the size of template code of SmmInit. Currently,
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
index 13e62b662d..ca98f06a05 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
@@ -22,11 +22,11 @@ UINTN  mNumberOfCpus    = 1;
 EFI_PROCESSOR_INFORMATION  *mProcessorInfo = NULL;
 
 //
 // IDT used during SMM Init
 //
-IA32_DESCRIPTOR  gcSmiIdtr;
+IA32_DESCRIPTOR  gcSmmInitIdtr;
 
 //
 // Smbase for all CPUs
 //
 UINT64  *mSmBase = NULL;
@@ -118,11 +118,11 @@ SmmInitHandler (
   UINTN   Index;
 
   //
   // Update SMM IDT entries' code segment and load IDT
   //
-  AsmWriteIdtr (&gcSmiIdtr);
+  AsmWriteIdtr (&gcSmmInitIdtr);
   ApicId = GetApicId ();
 
   for (Index = 0; Index < mNumberOfCpus; Index++) {
     if (ApicId == (UINT32)mProcessorInfo[Index].ProcessorId) {
       //
@@ -167,13 +167,13 @@ SmmRelocateBases (
   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);
+  PatchInstructionX86 (gPatchSmmInitCr0, AsmReadCr0 (), 4);
+  PatchInstructionX86 (gPatchSmmInitCr3, AsmReadCr3 (), 4);
+  PatchInstructionX86 (gPatchSmmInitCr4, 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);
 
   //
@@ -249,19 +249,19 @@ InitSmmIdt (
 
   //
   // 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;
+  gcSmmInitIdtr.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);
+  gcSmmInitIdtr.Base = (UINTN)AllocateZeroPool (gcSmmInitIdtr.Limit + 1 + sizeof (UINTN));
+  ASSERT (gcSmmInitIdtr.Base != 0);
+  gcSmmInitIdtr.Base += sizeof (UINTN);
 
   //
   // Disable Interrupt, save InterruptState and save PEI IDT table
   //
   InterruptState = SaveAndDisableInterrupts ();
@@ -270,21 +270,21 @@ InitSmmIdt (
   //
   // 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;
+  PeiServices                                       = (CONST EFI_PEI_SERVICES **)(*(UINTN *)(PeiIdtr.Base - sizeof (UINTN)));
+  (*(UINTN *)(gcSmmInitIdtr.Base - sizeof (UINTN))) = (UINTN)PeiServices;
 
   //
   // Load SMM temporary IDT table
   //
-  AsmWriteIdtr (&gcSmiIdtr);
+  AsmWriteIdtr (&gcSmmInitIdtr);
 
   //
   // Setup SMM default exception handlers, SMM IDT table
-  // will be updated and saved in gcSmiIdtr
+  // will be updated and saved in gcSmmInitIdtr
   //
   Status = InitializeCpuExceptionHandlers (NULL);
   ASSERT_EFI_ERROR (Status);
 
   //
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
index c790ad7ad8..8288b723c4 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
@@ -16,15 +16,15 @@
 
 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(gPatchSmmInitCr3)
+global ASM_PFX(gPatchSmmInitCr4)
+global ASM_PFX(gPatchSmmInitCr0)
 global ASM_PFX(gPatchSmmInitStack)
-global ASM_PFX(gcSmiInitGdtr)
+global ASM_PFX(gcSmmInitGdtr)
 global ASM_PFX(gcSmmInitSize)
 global ASM_PFX(gcSmmInitTemplate)
 global ASM_PFX(gPatchRebasedFlagAddr32)
 global ASM_PFX(gPatchSmmRelocationOriginalAddressPtr32)
 
@@ -82,11 +82,11 @@ CodeSeg64:
             DB      0x9b
             DB      0xaf                ; LimitHigh
             DB      0                   ; BaseHigh
 GDT_SIZE equ $ -   NullSeg
 
-ASM_PFX(gcSmiInitGdtr):
+ASM_PFX(gcSmmInitGdtr):
     DW      GDT_SIZE - 1
     DQ      NullSeg
 
 
     DEFAULT REL
@@ -98,15 +98,15 @@ 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):
+ASM_PFX(gPatchSmmInitCr3):
     mov     cr3, eax
-o32 lgdt    [cs:ebp + (ASM_PFX(gcSmiInitGdtr) - ASM_PFX(SmmStartup))]
+o32 lgdt    [cs:ebp + (ASM_PFX(gcSmmInitGdtr) - ASM_PFX(SmmStartup))]
     mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr4):
+ASM_PFX(gPatchSmmInitCr4):
     or      ah,  2                      ; enable XMM registers access
     mov     cr4, eax
     mov     ecx, 0xc0000080             ; IA32_EFER MSR
     rdmsr
     or      ah, BIT0                    ; set LME bit
@@ -114,11 +114,11 @@ ASM_PFX(gPatchSmmCr4):
     jz      .1
     or      ah, BIT3                    ; set NXE bit
 .1:
     wrmsr
     mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr0):
+ASM_PFX(gPatchSmmInitCr0):
     mov     cr0, eax                    ; enable protected mode & paging
     jmp     LONG_MODE_CS : dword 0      ; offset will be patched to @LongMode
 @PatchLongModeOffset:
 
 BITS 64
-- 
2.16.2.windows.1



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

* [edk2-devel] [PATCH v3 04/13] UefiCpuPkg/SmmRelocationLib: Avoid unnecessary memory allocation
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (2 preceding siblings ...)
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 03/13] UefiCpuPkg/SmmRelocationLib: Rename global variables Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  7:40   ` Ni, Ray
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 05/13] UefiCpuPkg/SmmRelocationLib: Remove unnecessary global variable Wu, Jiaxin
                   ` (8 subsequent siblings)
  12 siblings, 1 reply; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 UTC (permalink / raw)
  To: devel; +Cc: Ray Ni, Zeng Star, Gerd Hoffmann, Rahul Kumar

Since SMM relocation is performed serially for each CPU, there is
no need to allocate buffers for all CPUs to store the SmBase
address in mSmBase and the Rebased flag in mRebased. A defined
global variable is sufficient.

This patch focuses on the mSmBase and mRebased global variables
to prevent unnecessary memory allocation for these variables.

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/SmmRelocationLib.c    | 201 +++++++++------------
 1 file changed, 90 insertions(+), 111 deletions(-)

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
index ca98f06a05..3694a07cbb 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
@@ -25,31 +25,57 @@ EFI_PROCESSOR_INFORMATION  *mProcessorInfo = NULL;
 // IDT used during SMM Init
 //
 IA32_DESCRIPTOR  gcSmmInitIdtr;
 
 //
-// Smbase for all CPUs
+// Smbase for current CPU
 //
-UINT64  *mSmBase = NULL;
+UINT64  mSmBase;
 
 //
-// SmBase Rebased flag for all CPUs
+// SmBase Rebased flag for current CPU
 //
-volatile BOOLEAN  *mRebased;
+volatile BOOLEAN  mRebased;
+
+/**
+  This function will get the SmBase for CpuIndex.
+
+  @param[in]   CpuIndex            The processor index.
+  @param[in]   SmmRelocationStart  The start address of Smm relocated memory in SMRAM.
+  @param[in]   TileSize            The total size required for a CPU save state, any
+                                   additional CPU-specific context and the size of code
+                                   for the SMI entry point.
+
+  @retval The value of SmBase for CpuIndex.
+
+**/
+UINTN
+GetSmBase (
+  IN UINTN                 CpuIndex,
+  IN EFI_PHYSICAL_ADDRESS  SmmRelocationStart,
+  IN UINTN                 TileSize
+  )
+{
+  return (UINTN)(SmmRelocationStart) + CpuIndex * TileSize - SMM_HANDLER_OFFSET;
+}
 
 /**
   This function will create SmBase for all CPUs.
 
-  @param[in] SmBase    Pointer to SmBase for all CPUs.
+  @param[in]   SmmRelocationStart  The start address of Smm relocated memory in SMRAM.
+  @param[in]   TileSize            The total size required for a CPU save state, any
+                                   additional CPU-specific context and the size of code
+                                   for the SMI entry point.
 
   @retval EFI_SUCCESS           Create SmBase for all CPUs successfully.
   @retval Others                Failed to create SmBase for all CPUs.
 
 **/
 EFI_STATUS
 CreateSmmBaseHob (
-  IN UINT64  *SmBase
+  IN EFI_PHYSICAL_ADDRESS  SmmRelocationStart,
+  IN UINTN                 TileSize
   )
 {
   UINTN              Index;
   SMM_BASE_HOB_DATA  *SmmBaseHobData;
   UINT32             CpuCount;
@@ -90,11 +116,11 @@ CreateSmmBaseHob (
     DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->NumberOfProcessors: %d\n", HobCount, SmmBaseHobData->NumberOfProcessors));
     for (Index = 0; Index < SmmBaseHobData->NumberOfProcessors; Index++) {
       //
       // Calculate the new SMBASE address
       //
-      SmmBaseHobData->SmBase[Index] = SmBase[Index + CpuCount];
+      SmmBaseHobData->SmBase[Index] = GetSmBase (Index + CpuCount, SmmRelocationStart, TileSize);
       DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->SmBase[%d]: 0x%08x\n", HobCount, Index, SmmBaseHobData->SmBase[Index]));
     }
 
     CpuCount += NumberOfProcessorsInHob;
     HobCount++;
@@ -126,18 +152,18 @@ SmmInitHandler (
   for (Index = 0; Index < mNumberOfCpus; Index++) {
     if (ApicId == (UINT32)mProcessorInfo[Index].ProcessorId) {
       //
       // Configure SmBase.
       //
-      ConfigureSmBase (mSmBase[Index]);
+      ConfigureSmBase (mSmBase);
 
       //
       // 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]);
+      SemaphoreHook (Index, &mRebased);
       return;
     }
   }
 
   ASSERT (FALSE);
@@ -145,14 +171,22 @@ SmmInitHandler (
 
 /**
   Relocate SmmBases for each processor.
   Execute on first boot and all S3 resumes
 
+  @param[in]   MpServices2         Pointer to this instance of the MpServices.
+  @param[in]   SmmRelocationStart  The start address of Smm relocated memory in SMRAM.
+  @param[in]   TileSize            The total size required for a CPU save state, any
+                                   additional CPU-specific context and the size of code
+                                   for the SMI entry point.
+
 **/
 VOID
 SmmRelocateBases (
-  VOID
+  IN EDKII_PEI_MP_SERVICES2_PPI  *MpServices2,
+  IN EFI_PHYSICAL_ADDRESS        SmmRelocationStart,
+  IN UINTN                       TileSize
   )
 {
   UINT8                 BakBuf[BACK_BUF_SIZE];
   SMRAM_SAVE_STATE_MAP  BakBuf2;
   SMRAM_SAVE_STATE_MAP  *CpuStatePtr;
@@ -196,17 +230,18 @@ SmmRelocateBases (
   // 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) {
+      mRebased = FALSE;
+      mSmBase  = GetSmBase (Index, SmmRelocationStart, TileSize);
       SendSmiIpi ((UINT32)mProcessorInfo[Index].ProcessorId);
       //
       // Wait for this AP to finish its 1st SMI
       //
-      while (!mRebased[Index]) {
+      while (!mRebased) {
       }
     } else {
       //
       // BSP will be Relocated later
       //
@@ -216,16 +251,18 @@ SmmRelocateBases (
 
   //
   // Relocate BSP's SMM base
   //
   ASSERT (BspIndex != (UINTN)-1);
+  mRebased = FALSE;
+  mSmBase  = GetSmBase (BspIndex, SmmRelocationStart, TileSize);
   SendSmiIpi (BspApicId);
 
   //
   // Wait for the BSP to finish its 1st SMI
   //
-  while (!mRebased[BspIndex]) {
+  while (!mRebased) {
   }
 
   //
   // Restore contents at address 0x38000
   //
@@ -382,87 +419,10 @@ SplitSmramHobForSmmRelocation (
   ZeroMem (&GuidHob->Name, sizeof (GuidHob->Name));
 
   return EFI_SUCCESS;
 }
 
-/**
-  This function will initialize SmBase for all CPUs.
-
-  @param[in,out] SmBase    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  **SmBase
-  )
-{
-  EFI_STATUS            Status;
-  UINTN                 TileSize;
-  UINT64                SmmRelocationSize;
-  EFI_PHYSICAL_ADDRESS  SmmRelocationStart;
-  UINTN                 Index;
-
-  SmmRelocationStart = 0;
-
-  ASSERT (SmBase != 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 SmBase
-  //
-  *SmBase = (UINT64 *)AllocatePages (EFI_SIZE_TO_PAGES (sizeof (UINT64) * mMaxNumberOfCpus));
-  if (*SmBase == NULL) {
-    return EFI_OUT_OF_RESOURCES;
-  }
-
-  for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
-    //
-    // Return each SmBase in SmBase
-    //
-    (*SmBase)[Index] = (UINTN)(SmmRelocationStart)+ Index * TileSize - SMM_HANDLER_OFFSET;
-    DEBUG ((DEBUG_INFO, "InitSmBaseForAllCpus - SmBase For CPU[%d]: 0x%08x\n", Index, (*SmBase)[Index]));
-  }
-
-  return EFI_SUCCESS;
-}
-
 /**
   CPU SmmBase Relocation Init.
 
   This function is to relocate CPU SmmBase.
 
@@ -476,17 +436,21 @@ EFI_STATUS
 EFIAPI
 SmmRelocationInit (
   IN EDKII_PEI_MP_SERVICES2_PPI  *MpServices2
   )
 {
-  EFI_STATUS  Status;
-  UINTN       NumberOfEnabledCpus;
-  UINTN       SmmStackSize;
-  UINT8       *SmmStacks;
-  UINTN       Index;
+  EFI_STATUS            Status;
+  UINTN                 NumberOfEnabledCpus;
+  UINTN                 TileSize;
+  UINT64                SmmRelocationSize;
+  EFI_PHYSICAL_ADDRESS  SmmRelocationStart;
+  UINTN                 SmmStackSize;
+  UINT8                 *SmmStacks;
+  UINTN                 Index;
 
-  SmmStacks = NULL;
+  SmmRelocationStart = 0;
+  SmmStacks          = NULL;
 
   DEBUG ((DEBUG_INFO, "SmmRelocationInit Start \n"));
   if (MpServices2 == NULL) {
     return EFI_INVALID_PARAMETER;
   }
@@ -528,17 +492,43 @@ SmmRelocationInit (
       }
     }
   }
 
   //
-  // Initialize the SmBase for all CPUs
+  // Calculate SmmRelocationSize for all of the tiles.
   //
-  Status = InitSmBaseForAllCpus (&mSmBase);
+  // 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)) {
     goto ON_EXIT;
   }
 
+  ASSERT (SmmRelocationStart != 0);
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit - SmmRelocationSize: 0x%08x\n", SmmRelocationSize));
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit - SmmRelocationStart: 0x%08x\n", SmmRelocationStart));
+
   //
   // Fix up the address of the global variable or function referred in
   // SmmInit assembly files to be the absolute address
   //
   SmmInitFixupAddress ();
@@ -569,32 +559,21 @@ SmmRelocationInit (
   //
   InitSmmIdt ();
 
   //
   // 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 ();
+  SmmRelocateBases (MpServices2, SmmRelocationStart, TileSize);
 
   //
   // Create the SmBase HOB for all CPUs
   //
-  Status = CreateSmmBaseHob (mSmBase);
+  Status = CreateSmmBaseHob (SmmRelocationStart, TileSize);
 
 ON_EXIT:
   if (SmmStacks != NULL) {
     FreePages (SmmStacks, EFI_SIZE_TO_PAGES (SmmStackSize));
   }
 
-  if (mSmBase != NULL) {
-    FreePages (mSmBase, EFI_SIZE_TO_PAGES (sizeof (UINT64) * mMaxNumberOfCpus));
-  }
-
   DEBUG ((DEBUG_INFO, "SmmRelocationInit Done\n"));
   return Status;
 }
-- 
2.16.2.windows.1



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

* [edk2-devel] [PATCH v3 05/13] UefiCpuPkg/SmmRelocationLib: Remove unnecessary global variable
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (3 preceding siblings ...)
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 04/13] UefiCpuPkg/SmmRelocationLib: Avoid unnecessary memory allocation Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  7:48   ` Ni, Ray
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 06/13] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD Wu, Jiaxin
                   ` (7 subsequent siblings)
  12 siblings, 1 reply; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 UTC (permalink / raw)
  To: devel; +Cc: Ray Ni, Zeng Star, Gerd Hoffmann, Rahul Kumar

This patch aims on mProcessorInfo global variable, which can be
defined as local variable in SmmRelocateBases(). With this patch,
no need to allocate the memory for all CPUs to store the
Processor Info.

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      |  3 -
 .../SmmRelocationLib/InternalSmmRelocationLib.h    |  5 --
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 78 +++++++---------------
 .../SmmRelocationLib/SmramSaveStateConfig.c        |  3 -
 .../Library/SmmRelocationLib/X64/Semaphore.c       |  3 -
 5 files changed, 24 insertions(+), 68 deletions(-)

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
index ba329d6ba2..5d9eea3de9 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
@@ -15,28 +15,25 @@ 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/InternalSmmRelocationLib.h b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
index ede61b956f..d1387f2dfb 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
+++ b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
@@ -81,12 +81,10 @@ SmmRelocationSemaphoreComplete (
   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
@@ -96,29 +94,26 @@ SmmRelocationSemaphoreComplete (
 
 **/
 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
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
index 3694a07cbb..7e65bbf929 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
@@ -14,15 +14,10 @@
 #include "InternalSmmRelocationLib.h"
 
 UINTN  mMaxNumberOfCpus = 1;
 UINTN  mNumberOfCpus    = 1;
 
-//
-// Record all Processors Info
-//
-EFI_PROCESSOR_INFORMATION  *mProcessorInfo = NULL;
-
 //
 // IDT used during SMM Init
 //
 IA32_DESCRIPTOR  gcSmmInitIdtr;
 
@@ -138,37 +133,26 @@ VOID
 EFIAPI
 SmmInitHandler (
   VOID
   )
 {
-  UINT32  ApicId;
-  UINTN   Index;
-
   //
   // Update SMM IDT entries' code segment and load IDT
   //
   AsmWriteIdtr (&gcSmmInitIdtr);
-  ApicId = GetApicId ();
-
-  for (Index = 0; Index < mNumberOfCpus; Index++) {
-    if (ApicId == (UINT32)mProcessorInfo[Index].ProcessorId) {
-      //
-      // Configure SmBase.
-      //
-      ConfigureSmBase (mSmBase);
 
-      //
-      // 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);
-      return;
-    }
-  }
+  //
+  // Configure SmBase.
+  //
+  ConfigureSmBase (mSmBase);
 
-  ASSERT (FALSE);
+  //
+  // 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 (&mRebased);
 }
 
 /**
   Relocate SmmBases for each processor.
   Execute on first boot and all S3 resumes
@@ -185,17 +169,19 @@ SmmRelocateBases (
   IN EDKII_PEI_MP_SERVICES2_PPI  *MpServices2,
   IN EFI_PHYSICAL_ADDRESS        SmmRelocationStart,
   IN UINTN                       TileSize
   )
 {
-  UINT8                 BakBuf[BACK_BUF_SIZE];
-  SMRAM_SAVE_STATE_MAP  BakBuf2;
-  SMRAM_SAVE_STATE_MAP  *CpuStatePtr;
-  UINT8                 *U8Ptr;
-  UINTN                 Index;
-  UINTN                 BspIndex;
-  UINT32                BspApicId;
+  EFI_STATUS                 Status;
+  UINT8                      BakBuf[BACK_BUF_SIZE];
+  SMRAM_SAVE_STATE_MAP       BakBuf2;
+  SMRAM_SAVE_STATE_MAP       *CpuStatePtr;
+  UINT8                      *U8Ptr;
+  UINTN                      Index;
+  UINTN                      BspIndex;
+  UINT32                     BspApicId;
+  EFI_PROCESSOR_INFORMATION  ProcessorInfo;
 
   //
   // Make sure the reserved size is large enough for procedure SmmInitTemplate.
   //
   ASSERT (sizeof (BakBuf) >= gcSmmInitSize);
@@ -230,14 +216,17 @@ SmmRelocateBases (
   // 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++) {
-    if (BspApicId != (UINT32)mProcessorInfo[Index].ProcessorId) {
+    Status = MpServices2->GetProcessorInfo (MpServices2, Index | CPU_V2_EXTENDED_TOPOLOGY, &ProcessorInfo);
+    ASSERT_EFI_ERROR (Status);
+
+    if (BspApicId != (UINT32)ProcessorInfo.ProcessorId) {
       mRebased = FALSE;
       mSmBase  = GetSmBase (Index, SmmRelocationStart, TileSize);
-      SendSmiIpi ((UINT32)mProcessorInfo[Index].ProcessorId);
+      SendSmiIpi ((UINT32)ProcessorInfo.ProcessorId);
       //
       // Wait for this AP to finish its 1st SMI
       //
       while (!mRebased) {
       }
@@ -443,11 +432,10 @@ SmmRelocationInit (
   UINTN                 TileSize;
   UINT64                SmmRelocationSize;
   EFI_PHYSICAL_ADDRESS  SmmRelocationStart;
   UINTN                 SmmStackSize;
   UINT8                 *SmmStacks;
-  UINTN                 Index;
 
   SmmRelocationStart = 0;
   SmmStacks          = NULL;
 
   DEBUG ((DEBUG_INFO, "SmmRelocationInit Start \n"));
@@ -473,28 +461,10 @@ SmmRelocationInit (
     mMaxNumberOfCpus = mNumberOfCpus;
   }
 
   ASSERT (mNumberOfCpus <= mMaxNumberOfCpus);
 
-  //
-  // 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;
-      }
-    }
-  }
-
   //
   // 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
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
index d3a0bb9b89..76d798aba5 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
@@ -82,12 +82,10 @@ ConfigureSmBase (
   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
@@ -97,11 +95,10 @@ ConfigureSmBase (
 
 **/
 UINT64
 EFIAPI
 HookReturnFromSmm (
-  IN     UINTN                 CpuIndex,
   IN OUT SMRAM_SAVE_STATE_MAP  *CpuState,
   IN     UINT64                NewInstructionPointer32,
   IN     UINT64                NewInstructionPointer
   )
 {
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
index 53f3084363..cd6778e3fc 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
@@ -26,18 +26,16 @@ SmmRelocationSemaphoreComplete32 (
 /**
   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;
@@ -49,11 +47,10 @@ SemaphoreHook (
     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
                                     );
 
-- 
2.16.2.windows.1



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

* [edk2-devel] [PATCH v3 06/13] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (4 preceding siblings ...)
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 05/13] UefiCpuPkg/SmmRelocationLib: Remove unnecessary global variable Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 07/13] OvmfPkg/SmmRelocationLib: Add library instance for OVMF Wu, Jiaxin
                   ` (6 subsequent siblings)
  12 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 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>
Acked-by: Ray Ni <ray.ni@intel.com>
---
 ...mmRelocationLib.inf => AmdSmmRelocationLib.inf} |  5 +-
 ...SaveStateConfig.c => AmdSmramSaveStateConfig.c} | 91 ++++++++++------------
 UefiCpuPkg/UefiCpuPkg.dsc                          |  1 +
 3 files changed, 43 insertions(+), 54 deletions(-)
 copy UefiCpuPkg/Library/SmmRelocationLib/{SmmRelocationLib.inf => AmdSmmRelocationLib.inf} (89%)
 copy UefiCpuPkg/Library/SmmRelocationLib/{SmramSaveStateConfig.c => AmdSmramSaveStateConfig.c} (47%)

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



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

* [edk2-devel] [PATCH v3 07/13] OvmfPkg/SmmRelocationLib: Add library instance for OVMF
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (5 preceding siblings ...)
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 06/13] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid Wu, Jiaxin
                   ` (5 subsequent siblings)
  12 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 UTC (permalink / raw)
  To: devel
  Cc: Ray Ni, Zeng Star, Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann,
	Rahul Kumar

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

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

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

AMD:
 AmdCpuState->x64.SMBASE = mSmBaseForAllCpus[CpuIndex];

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

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

diff --git a/OvmfPkg/AmdSev/AmdSevX64.dsc b/OvmfPkg/AmdSev/AmdSevX64.dsc
index a7540bb636..8eb6f4f24f 100644
--- a/OvmfPkg/AmdSev/AmdSevX64.dsc
+++ b/OvmfPkg/AmdSev/AmdSevX64.dsc
@@ -108,10 +108,11 @@
 ################################################################################
 
 !include MdePkg/MdeLibs.dsc.inc
 
 [LibraryClasses]
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
   PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
   TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.inf
   ResetSystemLib|OvmfPkg/Library/ResetSystemLib/BaseResetSystemLib.inf
   PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
   BaseMemoryLib|MdePkg/Library/BaseMemoryLibRepStr/BaseMemoryLibRepStr.inf
diff --git a/OvmfPkg/CloudHv/CloudHvX64.dsc b/OvmfPkg/CloudHv/CloudHvX64.dsc
index b1911d6ab4..4996885301 100644
--- a/OvmfPkg/CloudHv/CloudHvX64.dsc
+++ b/OvmfPkg/CloudHv/CloudHvX64.dsc
@@ -124,10 +124,11 @@
 ################################################################################
 
 !include MdePkg/MdeLibs.dsc.inc
 
 [LibraryClasses]
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
   PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
   TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.inf
   ResetSystemLib|OvmfPkg/Library/ResetSystemLib/BaseResetSystemLib.inf
   PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
   BaseMemoryLib|MdePkg/Library/BaseMemoryLibRepStr/BaseMemoryLibRepStr.inf
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c b/OvmfPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
copy to OvmfPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm b/OvmfPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
copy to OvmfPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h b/OvmfPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
copy to OvmfPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c b/OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.c
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
copy to OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.c
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf b/OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
similarity index 90%
copy from UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
copy to OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
index 45fdaf35bc..3ea6a1a0bc 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
+++ b/OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
@@ -13,11 +13,11 @@
 ##
 
 [Defines]
   INF_VERSION                    = 0x00010005
   BASE_NAME                      = SmmRelocationLib
-  FILE_GUID                      = 853E97B3-790C-4EA3-945C-8F622FC47FE8
+  FILE_GUID                      = 51834F51-CCE0-4743-B553-935D0C8A53FF
   MODULE_TYPE                    = PEIM
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = SmmRelocationLib
 
 [Sources]
@@ -40,11 +40,10 @@
 
 [LibraryClasses]
   BaseLib
   BaseMemoryLib
   CpuExceptionHandlerLib
-  CpuLib
   DebugLib
   HobLib
   LocalApicLib
   MemoryAllocationLib
   PcdLib
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c b/OvmfPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
similarity index 60%
copy from UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
copy to OvmfPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
index 068ae60887..146e6d54d9 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/AmdSmramSaveStateConfig.c
+++ b/OvmfPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
@@ -1,43 +1,15 @@
 /** @file
   Config SMRAM Save State for SmmBases Relocation.
 
-  Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.<BR>
   Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
   SPDX-License-Identifier: BSD-2-Clause-Patent
 
 **/
 #include "InternalSmmRelocationLib.h"
 #include <Register/Amd/SmramSaveStateMap.h>
 
-#define EFER_ADDRESS  0XC0000080ul
-
-/**
-  Get 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
-GetMmSaveStateRegisterLma (
-  VOID
-  )
-{
-  UINT8   SmmSaveStateRegisterLma;
-  UINT32  LMAValue;
-
-  SmmSaveStateRegisterLma = (UINT8)EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT;
-
-  LMAValue = (UINT32)AsmReadMsr64 (EFER_ADDRESS) & LMA;
-  if (LMAValue) {
-    SmmSaveStateRegisterLma = (UINT8)EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT;
-  }
-
-  return SmmSaveStateRegisterLma;
-}
-
 /**
   This function configures the SmBase on the currently executing CPU.
 
   @param[in]     SmBase             The SmBase on the currently executing CPU.
 
@@ -46,15 +18,19 @@ VOID
 EFIAPI
 ConfigureSmBase (
   IN UINT64  SmBase
   )
 {
-  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;
+  AMD_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
 
-  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+  CpuSaveState = (AMD_SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
 
-  AmdCpuState->x64.SMBASE = (UINT32)SmBase;
+  if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
+    CpuSaveState->x86.SMBASE = (UINT32)SmBase;
+  } else {
+    CpuSaveState->x64.SMBASE = (UINT32)SmBase;
+  }
 }
 
 /**
   This function updates the SMRAM save state on the currently executing CPU
   to resume execution at a specific address after an RSM instruction.  This
@@ -88,38 +64,37 @@ HookReturnFromSmm (
   IN     UINT64                NewInstructionPointer32,
   IN     UINT64                NewInstructionPointer
   )
 {
   UINT64                    OriginalInstructionPointer;
-  AMD_SMRAM_SAVE_STATE_MAP  *AmdCpuState;
-
-  AmdCpuState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
+  AMD_SMRAM_SAVE_STATE_MAP  *CpuSaveState;
 
-  if (GetMmSaveStateRegisterLma () == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
-    OriginalInstructionPointer = (UINT64)AmdCpuState->x86._EIP;
-    AmdCpuState->x86._EIP      = (UINT32)NewInstructionPointer;
+  CpuSaveState = (AMD_SMRAM_SAVE_STATE_MAP *)CpuState;
+  if ((CpuSaveState->x86.SMMRevId & 0xFFFF) == 0) {
+    OriginalInstructionPointer = (UINT64)CpuSaveState->x86._EIP;
+    CpuSaveState->x86._EIP     = (UINT32)NewInstructionPointer;
     //
     // Clear the auto HALT restart flag so the RSM instruction returns
     // program control to the instruction following the HLT instruction.
     //
-    if ((AmdCpuState->x86.AutoHALTRestart & BIT0) != 0) {
-      AmdCpuState->x86.AutoHALTRestart &= ~BIT0;
+    if ((CpuSaveState->x86.AutoHALTRestart & BIT0) != 0) {
+      CpuSaveState->x86.AutoHALTRestart &= ~BIT0;
     }
   } else {
-    OriginalInstructionPointer = AmdCpuState->x64._RIP;
-    if ((AmdCpuState->x64.EFER & LMA) == 0) {
-      AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer32;
+    OriginalInstructionPointer = CpuSaveState->x64._RIP;
+    if ((CpuSaveState->x64.EFER & LMA) == 0) {
+      CpuSaveState->x64._RIP = (UINT32)NewInstructionPointer32;
     } else {
-      AmdCpuState->x64._RIP = (UINT32)NewInstructionPointer;
+      CpuSaveState->x64._RIP = (UINT32)NewInstructionPointer;
     }
 
     //
     // Clear the auto HALT restart flag so the RSM instruction returns
     // program control to the instruction following the HLT instruction.
     //
-    if ((AmdCpuState->x64.AutoHALTRestart & BIT0) != 0) {
-      AmdCpuState->x64.AutoHALTRestart &= ~BIT0;
+    if ((CpuSaveState->x64.AutoHALTRestart & BIT0) != 0) {
+      CpuSaveState->x64.AutoHALTRestart &= ~BIT0;
     }
   }
 
   return OriginalInstructionPointer;
 }
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c b/OvmfPkg/Library/SmmRelocationLib/X64/Semaphore.c
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
copy to OvmfPkg/Library/SmmRelocationLib/X64/Semaphore.c
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm b/OvmfPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
similarity index 100%
copy from UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
copy to OvmfPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
diff --git a/OvmfPkg/Microvm/MicrovmX64.dsc b/OvmfPkg/Microvm/MicrovmX64.dsc
index 1f2f8b5bb6..69de4dd3f1 100644
--- a/OvmfPkg/Microvm/MicrovmX64.dsc
+++ b/OvmfPkg/Microvm/MicrovmX64.dsc
@@ -127,10 +127,11 @@
 ################################################################################
 
 !include MdePkg/MdeLibs.dsc.inc
 
 [LibraryClasses]
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
   PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
   TimerLib|MdePkg/Library/SecPeiDxeTimerLibCpu/SecPeiDxeTimerLibCpu.inf
   ResetSystemLib|OvmfPkg/Library/ResetSystemLib/BaseResetSystemLibMicrovm.inf
   PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
   BaseMemoryLib|MdePkg/Library/BaseMemoryLibRepStr/BaseMemoryLibRepStr.inf
diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc
index 15fadc2fdc..78a5aefb6d 100644
--- a/OvmfPkg/OvmfPkgIa32.dsc
+++ b/OvmfPkg/OvmfPkgIa32.dsc
@@ -127,10 +127,11 @@
 ################################################################################
 
 !include MdePkg/MdeLibs.dsc.inc
 
 [LibraryClasses]
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
   PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
   TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.inf
   ResetSystemLib|OvmfPkg/Library/ResetSystemLib/BaseResetSystemLib.inf
   PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
   BaseMemoryLib|MdePkg/Library/BaseMemoryLibRepStr/BaseMemoryLibRepStr.inf
diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc
index 6e55b50a96..8258129baf 100644
--- a/OvmfPkg/OvmfPkgIa32X64.dsc
+++ b/OvmfPkg/OvmfPkgIa32X64.dsc
@@ -132,10 +132,11 @@
 ################################################################################
 
 !include MdePkg/MdeLibs.dsc.inc
 
 [LibraryClasses]
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
   PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
   TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.inf
   ResetSystemLib|OvmfPkg/Library/ResetSystemLib/BaseResetSystemLib.inf
   PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
   BaseMemoryLib|MdePkg/Library/BaseMemoryLibRepStr/BaseMemoryLibRepStr.inf
diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc
index f2edd3bbc0..240fc18081 100644
--- a/OvmfPkg/OvmfPkgX64.dsc
+++ b/OvmfPkg/OvmfPkgX64.dsc
@@ -145,10 +145,11 @@
 ################################################################################
 
 !include MdePkg/MdeLibs.dsc.inc
 
 [LibraryClasses]
+  SmmRelocationLib|OvmfPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
   PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
   TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.inf
   ResetSystemLib|OvmfPkg/Library/ResetSystemLib/BaseResetSystemLib.inf
   PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
   BaseMemoryLib|MdePkg/Library/BaseMemoryLibRepStr/BaseMemoryLibRepStr.inf
-- 
2.16.2.windows.1



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

* [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (6 preceding siblings ...)
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 07/13] OvmfPkg/SmmRelocationLib: Add library instance for OVMF Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-23  9:25   ` Gerd Hoffmann
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 09/13] OvmfPkg: Refine SmmAccess implementation Wu, Jiaxin
                   ` (4 subsequent siblings)
  12 siblings, 1 reply; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann, Ray Ni

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

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

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

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



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

* [edk2-devel] [PATCH v3 09/13] OvmfPkg: Refine SmmAccess implementation
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (7 preceding siblings ...)
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 10/13] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not Wu, Jiaxin
                   ` (3 subsequent siblings)
  12 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann, Ray Ni

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

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

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



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

* [edk2-devel] [PATCH v3 10/13] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (8 preceding siblings ...)
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 09/13] OvmfPkg: Refine SmmAccess implementation Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 11/13] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase Wu, Jiaxin
                   ` (2 subsequent siblings)
  12 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann, Ray Ni

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

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

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

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



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

* [edk2-devel] [PATCH v3 11/13] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (9 preceding siblings ...)
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 10/13] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 12/13] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib Wu, Jiaxin
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic Wu, Jiaxin
  12 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Jiewen Yao, Gerd Hoffmann, Ray Ni

This patch is to consume SmmRelocationInit for SmBase
Relocation.

Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Ray Ni <ray.ni@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 OvmfPkg/PlatformPei/Platform.c                     |  3 +
 OvmfPkg/PlatformPei/Platform.h                     |  5 ++
 OvmfPkg/PlatformPei/PlatformPei.inf                |  5 +-
 .../ClearCache.c => PlatformPei/SmmRelocation.c}   | 79 ++++++----------------
 4 files changed, 34 insertions(+), 58 deletions(-)
 copy OvmfPkg/{Bhyve/PlatformPei/ClearCache.c => PlatformPei/SmmRelocation.c} (32%)

diff --git a/OvmfPkg/PlatformPei/Platform.c b/OvmfPkg/PlatformPei/Platform.c
index f5dc41c3a8..df35726ff6 100644
--- a/OvmfPkg/PlatformPei/Platform.c
+++ b/OvmfPkg/PlatformPei/Platform.c
@@ -365,8 +365,11 @@ InitializePlatform (
     MiscInitialization (PlatformInfoHob);
   }
 
   IntelTdxInitialize ();
   InstallFeatureControlCallback (PlatformInfoHob);
+  if (PlatformInfoHob->SmmSmramRequire) {
+    RelocateSmBase ();
+  }
 
   return EFI_SUCCESS;
 }
diff --git a/OvmfPkg/PlatformPei/Platform.h b/OvmfPkg/PlatformPei/Platform.h
index 1cf44844a7..0a59547cfc 100644
--- a/OvmfPkg/PlatformPei/Platform.h
+++ b/OvmfPkg/PlatformPei/Platform.h
@@ -76,10 +76,15 @@ InstallFeatureControlCallback (
 VOID
 InstallClearCacheCallback (
   VOID
   );
 
+VOID
+RelocateSmBase (
+  VOID
+  );
+
 VOID
 AmdSevInitialize (
   IN EFI_HOB_PLATFORM_INFO  *PlatformInfoHob
   );
 
diff --git a/OvmfPkg/PlatformPei/PlatformPei.inf b/OvmfPkg/PlatformPei/PlatformPei.inf
index 20b1b98292..e036018eab 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
@@ -64,10 +65,11 @@
   MtrrLib
   MemEncryptSevLib
   PcdLib
   CcExitLib
   PlatformInitLib
+  SmmRelocationLib
 
 [Pcd]
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvSize
   gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase
@@ -140,9 +142,10 @@
 
 [Ppis]
   gEfiPeiMasterBootModePpiGuid
   gEfiPeiMpServicesPpiGuid
   gEfiPeiReadOnlyVariable2PpiGuid
+  gEdkiiPeiMpServices2PpiGuid
 
 [Depex]
   TRUE
 
diff --git a/OvmfPkg/Bhyve/PlatformPei/ClearCache.c b/OvmfPkg/PlatformPei/SmmRelocation.c
similarity index 32%
copy from OvmfPkg/Bhyve/PlatformPei/ClearCache.c
copy to OvmfPkg/PlatformPei/SmmRelocation.c
index 9e59f31df7..1151fc9220 100644
--- a/OvmfPkg/Bhyve/PlatformPei/ClearCache.c
+++ b/OvmfPkg/PlatformPei/SmmRelocation.c
@@ -1,45 +1,21 @@
 /**@file
-  Install a callback to clear cache on all processors.
-  This is for conformance with the TCG "Platform Reset Attack Mitigation
-  Specification". Because clearing the CPU caches at boot doesn't impact
-  performance significantly, do it unconditionally, for simplicity's
-  sake.
+  Install a callback to do smm relocation.
 
-  Copyright (C) 2018, Red Hat, Inc.
+  Copyright (c) 2024, Intel Corporation. All rights reserved.
 
   SPDX-License-Identifier: BSD-2-Clause-Patent
 **/
 
-#include <Library/CacheMaintenanceLib.h>
 #include <Library/DebugLib.h>
 #include <Library/PeiServicesLib.h>
-#include <Ppi/MpServices.h>
-
+#include <Library/SmmRelocationLib.h>
+#include <Ppi/MpServices2.h>
 #include "Platform.h"
 
 /**
-  Invalidate data & instruction caches.
-  All APs execute this function in parallel. The BSP executes the function
-  separately.
-
-  @param[in,out] WorkSpace  Pointer to the input/output argument workspace
-                            shared by all processors.
-**/
-STATIC
-VOID
-EFIAPI
-ClearCache (
-  IN OUT VOID  *WorkSpace
-  )
-{
-  WriteBackInvalidateDataCache ();
-  InvalidateInstructionCache ();
-}
-
-/**
-  Notification function called when EFI_PEI_MP_SERVICES_PPI becomes available.
+  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.
@@ -48,68 +24,57 @@ ClearCache (
            function is ignored.
 **/
 STATIC
 EFI_STATUS
 EFIAPI
-ClearCacheOnMpServicesAvailable (
+OnMpServices2Available (
   IN EFI_PEI_SERVICES           **PeiServices,
   IN EFI_PEI_NOTIFY_DESCRIPTOR  *NotifyDescriptor,
   IN VOID                       *Ppi
   )
 {
-  EFI_PEI_MP_SERVICES_PPI  *MpServices;
-  EFI_STATUS               Status;
+  EDKII_PEI_MP_SERVICES2_PPI  *MpServices2;
+  EFI_STATUS                  Status;
 
   DEBUG ((DEBUG_INFO, "%a: %a\n", gEfiCallerBaseName, __func__));
 
+  MpServices2 = Ppi;
+
   //
-  // Clear cache on all the APs in parallel.
+  // Smm Relocation Initialize.
   //
-  MpServices = Ppi;
-  Status     = MpServices->StartupAllAPs (
-                             (CONST EFI_PEI_SERVICES **)PeiServices,
-                             MpServices,
-                             ClearCache,      // Procedure
-                             FALSE,           // SingleThread
-                             0,               // TimeoutInMicroSeconds: inf.
-                             NULL             // ProcedureArgument
-                             );
-  if (EFI_ERROR (Status) && (Status != EFI_NOT_STARTED)) {
-    DEBUG ((DEBUG_ERROR, "%a: StartupAllAps(): %r\n", __func__, Status));
-    return Status;
+  Status = SmmRelocationInit (MpServices2);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_WARN, "OnMpServices2Available: Not able to execute Smm Relocation Init.  Status: %r\n", Status));
   }
 
-  //
-  // Now clear cache on the BSP too.
-  //
-  ClearCache (NULL);
   return EFI_SUCCESS;
 }
 
 //
 // Notification object for registering the callback, for when
-// EFI_PEI_MP_SERVICES_PPI becomes available.
+// EDKII_PEI_MP_SERVICES2_PPI becomes available.
 //
-STATIC CONST EFI_PEI_NOTIFY_DESCRIPTOR  mMpServicesNotify = {
-  EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | // Flags
+STATIC CONST EFI_PEI_NOTIFY_DESCRIPTOR  mMpServices2Notify = {
+  EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK |   // Flags
   EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST,
-  &gEfiPeiMpServicesPpiGuid,               // Guid
-  ClearCacheOnMpServicesAvailable          // Notify
+  &gEdkiiPeiMpServices2PpiGuid,              // Guid
+  OnMpServices2Available                     // Notify
 };
 
 VOID
-InstallClearCacheCallback (
+RelocateSmBase (
   VOID
   )
 {
   EFI_STATUS  Status;
 
-  Status = PeiServicesNotifyPpi (&mMpServicesNotify);
+  Status = PeiServicesNotifyPpi (&mMpServices2Notify);
   if (EFI_ERROR (Status)) {
     DEBUG ((
       DEBUG_ERROR,
-      "%a: failed to set up MP Services callback: %r\n",
+      "%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 (#117955): https://edk2.groups.io/g/devel/message/117955
Mute This Topic: https://groups.io/mt/105593581/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] 31+ messages in thread

* [edk2-devel] [PATCH v3 12/13] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (10 preceding siblings ...)
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 11/13] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic Wu, Jiaxin
  12 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 UTC (permalink / raw)
  To: devel; +Cc: Guo Dong, Sean Rhodes, James Lu, Gua Guo, Ray Ni

This patch just includes SmmRelocationLib in UefiPayloadPkg.

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

diff --git a/UefiPayloadPkg/UefiPayloadPkg.dsc b/UefiPayloadPkg/UefiPayloadPkg.dsc
index e1b9d5ecf1..2860a659f6 100644
--- a/UefiPayloadPkg/UefiPayloadPkg.dsc
+++ b/UefiPayloadPkg/UefiPayloadPkg.dsc
@@ -314,10 +314,12 @@
   VariableFlashInfoLib|MdeModulePkg/Library/BaseVariableFlashInfoLib/BaseVariableFlashInfoLib.inf
   CcExitLib|UefiCpuPkg/Library/CcExitLibNull/CcExitLibNull.inf
   AmdSvsmLib|UefiCpuPkg/Library/AmdSvsmLibNull/AmdSvsmLibNull.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 (#117957): https://edk2.groups.io/g/devel/message/117957
Mute This Topic: https://groups.io/mt/105593583/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] 31+ messages in thread

* [edk2-devel] [PATCH v3 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic
  2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
                   ` (11 preceding siblings ...)
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 12/13] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib Wu, Jiaxin
@ 2024-04-18  6:55 ` Wu, Jiaxin
  2024-04-18  8:15   ` Ni, Ray
  12 siblings, 1 reply; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  6:55 UTC (permalink / raw)
  To: devel; +Cc: Ray Ni, Zeng Star, Gerd Hoffmann, Rahul Kumar

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

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

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

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



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

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

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

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

Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Thursday, April 18, 2024 14:55
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 v3 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance

This patch just separates the smbase relocation logic from
PiSmmCpuDxeSmm driver, and moves to the SmmRelocationInit
interface. It maintains the original implementation of most
functions and leaves the definitions of global variables
intact. Further refinements to the code are planned for
subsequent patches.

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

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

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

Cc: Ray Ni <ray.ni@intel.com>
Cc: Zeng Star <star.zeng@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Signed-off-by: Jiaxin Wu <jiaxin.wu@intel.com>
---
 .../SmmRelocationLib}/Ia32/Semaphore.c             |  10 +-
 .../SmmRelocationLib}/Ia32/SmmInit.nasm            |  67 ++-
 .../SmmRelocationLib/InternalSmmRelocationLib.h    | 132 +++++
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 600 +++++++++++++++++++++
 .../Library/SmmRelocationLib/SmmRelocationLib.inf  |  61 +++
 .../SmmRelocationLib/SmramSaveStateConfig.c        | 139 +++++
 .../SmmRelocationLib}/X64/Semaphore.c              |  10 +-
 .../SmmRelocationLib}/X64/SmmInit.nasm             |  69 ++-
 UefiCpuPkg/UefiCpuPkg.dsc                          |   1 +
 9 files changed, 1066 insertions(+), 23 deletions(-)
 copy UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/Ia32/Semaphore.c (79%)
 copy UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/Ia32/SmmInit.nasm (53%)
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf
 create mode 100644 UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
 copy UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/X64/Semaphore.c (84%)
 copy UefiCpuPkg/{PiSmmCpuDxeSmm => Library/SmmRelocationLib}/X64/SmmInit.nasm (64%)

diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
similarity index 79%
copy from UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c
copy to UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
index a9fcc89dda..ba329d6ba2 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/Semaphore.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/Semaphore.c
@@ -1,15 +1,15 @@
 /** @file
-Semaphore mechanism to indicate to the BSP that an AP has exited SMM
-after SMBASE relocation.
+  Semaphore mechanism to indicate to the BSP that an AP has exited SMM
+  after SMBASE relocation.

-Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>
-SPDX-License-Identifier: BSD-2-Clause-Patent
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent

 **/

-#include "PiSmmCpuDxeSmm.h"
+#include "InternalSmmRelocationLib.h"

 UINTN             mSmmRelocationOriginalAddress;
 volatile BOOLEAN  *mRebasedFlag;

 /**
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
similarity index 53%
copy from UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm
copy to UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
index b5e77a1a5b..3d845e9e16 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/SmmInit.nasm
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
@@ -1,7 +1,7 @@
 ;------------------------------------------------------------------------------ ;
-; Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR>
+; Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
 ; SPDX-License-Identifier: BSD-2-Clause-Patent
 ;
 ; Module Name:
 ;
 ;   SmmInit.nasm
@@ -27,15 +27,70 @@ global ASM_PFX(gcSmmInitSize)
 global ASM_PFX(gcSmmInitTemplate)

 %define PROTECT_MODE_CS 0x8
 %define PROTECT_MODE_DS 0x20

-    SECTION .text
+    SECTION .data

-ASM_PFX(gcSmiInitGdtr):
+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
-            DQ      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(gcSmiInitGdtr):
+    DW      GDT_SIZE - 1
+    DD      NullSeg
+
+
+    SECTION .text

 global ASM_PFX(SmmStartup)

 BITS 16
 ASM_PFX(SmmStartup):
@@ -89,8 +144,8 @@ ASM_PFX(SmmRelocationSemaphoreComplete):
     mov     eax, [ASM_PFX(mRebasedFlag)]
     mov     byte [eax], 1
     pop     eax
     jmp     [ASM_PFX(mSmmRelocationOriginalAddress)]

-global ASM_PFX(PiSmmCpuSmmInitFixupAddress)
-ASM_PFX(PiSmmCpuSmmInitFixupAddress):
+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..a9d3f271a9
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
@@ -0,0 +1,132 @@
+/** @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 <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 IA32_DESCRIPTOR  gcSmiInitGdtr;
+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]     SmBase             The SmBase on the currently executing CPU.
+
+**/
+VOID
+EFIAPI
+ConfigureSmBase (
+  IN UINT64  SmBase
+  );
+
+/**
+  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..13e62b662d
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
@@ -0,0 +1,600 @@
+/** @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;
+
+//
+// Record all Processors Info
+//
+EFI_PROCESSOR_INFORMATION  *mProcessorInfo = NULL;
+
+//
+// IDT used during SMM Init
+//
+IA32_DESCRIPTOR  gcSmiIdtr;
+
+//
+// Smbase for all CPUs
+//
+UINT64  *mSmBase = NULL;
+
+//
+// SmBase Rebased flag for all CPUs
+//
+volatile BOOLEAN  *mRebased;
+
+/**
+  This function will create SmBase for all CPUs.
+
+  @param[in] SmBase    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  *SmBase
+  )
+{
+  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: %d\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: %d\n", HobCount, SmmBaseHobData->ProcessorIndex));
+    DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->NumberOfProcessors: %d\n", HobCount, SmmBaseHobData->NumberOfProcessors));
+    for (Index = 0; Index < SmmBaseHobData->NumberOfProcessors; Index++) {
+      //
+      // Calculate the new SMBASE address
+      //
+      SmmBaseHobData->SmBase[Index] = SmBase[Index + CpuCount];
+      DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->SmBase[%d]: 0x%08x\n", HobCount, Index, SmmBaseHobData->SmBase[Index]));
+    }
+
+    CpuCount += NumberOfProcessorsInHob;
+    HobCount++;
+    SmmBaseHobData = NULL;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  C function for SMI handler. To change all processor's SMMBase Register.
+
+**/
+VOID
+EFIAPI
+SmmInitHandler (
+  VOID
+  )
+{
+  UINT32  ApicId;
+  UINTN   Index;
+
+  //
+  // Update SMM IDT entries' code segment and load IDT
+  //
+  AsmWriteIdtr (&gcSmiIdtr);
+  ApicId = GetApicId ();
+
+  for (Index = 0; Index < mNumberOfCpus; Index++) {
+    if (ApicId == (UINT32)mProcessorInfo[Index].ProcessorId) {
+      //
+      // Configure SmBase.
+      //
+      ConfigureSmBase (mSmBase[Index]);
+
+      //
+      // 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);
+}
+
+/**
+  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));
+}
+
+/**
+  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);
+}
+
+/**
+  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  *Block;
+  EFI_SMRAM_HOB_DESCRIPTOR_BLOCK  *NewBlock;
+  UINTN                           NewBlockSize;
+
+  ASSERT (SmmRelocationStart != NULL);
+
+  //
+  // Retrieve the GUID HOB data that contains the set of SMRAM descriptors
+  //
+  GuidHob = GetFirstGuidHob (&gEfiSmmSmramMemoryGuid);
+  if (GuidHob == NULL) {
+    return EFI_NOT_FOUND;
+  }
+
+  Block = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)GET_GUID_HOB_DATA (GuidHob);
+
+  //
+  // Allocate one extra EFI_SMRAM_DESCRIPTOR to describe smram carved out for all SMBASE
+  //
+  NewBlockSize = sizeof (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK) + (Block->NumberOfSmmReservedRegions * sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  NewBlock = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)BuildGuidHob (
+                                                 &gEfiSmmSmramMemoryGuid,
+                                                 NewBlockSize
+                                                 );
+  ASSERT (NewBlock != NULL);
+  if (NewBlock == NULL) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  //
+  // Copy old EFI_SMRAM_HOB_DESCRIPTOR_BLOCK to new allocated region
+  //
+  CopyMem ((VOID *)NewBlock, Block, NewBlockSize - sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  //
+  // Increase the number of SMRAM descriptors by 1 to make room for the ALLOCATED descriptor of size EFI_PAGE_SIZE
+  //
+  NewBlock->NumberOfSmmReservedRegions = (UINT32)(Block->NumberOfSmmReservedRegions + 1);
+
+  ASSERT (Block->NumberOfSmmReservedRegions >= 1);
+  //
+  // Copy last entry to the end - we assume TSEG is last entry.
+  //
+  CopyMem (&NewBlock->Descriptor[Block->NumberOfSmmReservedRegions], &NewBlock->Descriptor[Block->NumberOfSmmReservedRegions - 1], sizeof (EFI_SMRAM_DESCRIPTOR));
+
+  //
+  // Update the entry in the array with a size of SmmRelocationSize and put into the ALLOCATED state
+  //
+  NewBlock->Descriptor[Block->NumberOfSmmReservedRegions - 1].PhysicalSize = SmmRelocationSize;
+  NewBlock->Descriptor[Block->NumberOfSmmReservedRegions - 1].RegionState |= EFI_ALLOCATED;
+
+  //
+  // Return the start address of Smm relocated memory in SMRAM.
+  //
+  *SmmRelocationStart = NewBlock->Descriptor[Block->NumberOfSmmReservedRegions - 1].CpuStart;
+
+  //
+  // Reduce the size of the last SMRAM descriptor by SmmRelocationSize
+  //
+  NewBlock->Descriptor[Block->NumberOfSmmReservedRegions].PhysicalStart += SmmRelocationSize;
+  NewBlock->Descriptor[Block->NumberOfSmmReservedRegions].CpuStart      += SmmRelocationSize;
+  NewBlock->Descriptor[Block->NumberOfSmmReservedRegions].PhysicalSize  -= SmmRelocationSize;
+
+  //
+  // Last step, we can scrub old one
+  //
+  ZeroMem (&GuidHob->Name, sizeof (GuidHob->Name));
+
+  return EFI_SUCCESS;
+}
+
+/**
+  This function will initialize SmBase for all CPUs.
+
+  @param[in,out] SmBase    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  **SmBase
+  )
+{
+  EFI_STATUS            Status;
+  UINTN                 TileSize;
+  UINT64                SmmRelocationSize;
+  EFI_PHYSICAL_ADDRESS  SmmRelocationStart;
+  UINTN                 Index;
+
+  SmmRelocationStart = 0;
+
+  ASSERT (SmBase != 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 SmBase
+  //
+  *SmBase = (UINT64 *)AllocatePages (EFI_SIZE_TO_PAGES (sizeof (UINT64) * mMaxNumberOfCpus));
+  if (*SmBase == NULL) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
+    //
+    // Return each SmBase in SmBase
+    //
+    (*SmBase)[Index] = (UINTN)(SmmRelocationStart)+ Index * TileSize - SMM_HANDLER_OFFSET;
+    DEBUG ((DEBUG_INFO, "InitSmBaseForAllCpus - SmBase For CPU[%d]: 0x%08x\n", Index, (*SmBase)[Index]));
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  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;
+  }
+
+  //
+  // Get the number of processors
+  //
+  Status = MpServices2->GetNumberOfProcessors (
+                          MpServices2,
+                          &mNumberOfCpus,
+                          &NumberOfEnabledCpus
+                          );
+  if (EFI_ERROR (Status)) {
+    goto ON_EXIT;
+  }
+
+  if (FeaturePcdGet (PcdCpuHotPlugSupport)) {
+    mMaxNumberOfCpus = PcdGet32 (PcdCpuMaxLogicalProcessorNumber);
+  } else {
+    mMaxNumberOfCpus = mNumberOfCpus;
+  }
+
+  ASSERT (mNumberOfCpus <= mMaxNumberOfCpus);
+
+  //
+  // 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 (&mSmBase);
+  if (EFI_ERROR (Status)) {
+    goto ON_EXIT;
+  }
+
+  //
+  // Fix up the address of the global variable or function referred in
+  // SmmInit assembly files to be the absolute address
+  //
+  SmmInitFixupAddress ();
+
+  //
+  // Patch SMI stack for SMM base relocation
+  // Note: No need allocate stack for all CPUs since the relocation
+  // occurs serially for each CPU
+  //
+  SmmStackSize = EFI_PAGE_SIZE;
+  SmmStacks    = (UINT8 *)AllocatePages (EFI_SIZE_TO_PAGES (SmmStackSize));
+  if (SmmStacks == NULL) {
+    Status = EFI_OUT_OF_RESOURCES;
+    goto ON_EXIT;
+  }
+
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit - SmmStackSize: 0x%08x\n", SmmStackSize));
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit - SmmStacks: 0x%08x\n", SmmStacks));
+
+  PatchInstructionX86 (
+    gPatchSmmInitStack,
+    (UINTN)(SmmStacks + SmmStackSize - sizeof (UINTN)),
+    sizeof (UINTN)
+    );
+
+  //
+  // Initialize the SMM IDT for SMM base relocation
+  //
+  InitSmmIdt ();
+
+  //
+  // 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 (mSmBase);
+
+ON_EXIT:
+  if (SmmStacks != NULL) {
+    FreePages (SmmStacks, EFI_SIZE_TO_PAGES (SmmStackSize));
+  }
+
+  if (mSmBase != NULL) {
+    FreePages (mSmBase, 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..45fdaf35bc
--- /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
+  CpuLib
+  DebugLib
+  HobLib
+  LocalApicLib
+  MemoryAllocationLib
+  PcdLib
+  PeiServicesLib
+
+[Guids]
+  gSmmBaseHobGuid                               ## HOB ALWAYS_PRODUCED
+  gEfiSmmSmramMemoryGuid                        ## CONSUMES
+
+[Pcd]
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber
+
+[FeaturePcd]
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugSupport                        ## CONSUMES
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
new file mode 100644
index 0000000000..d3a0bb9b89
--- /dev/null
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmramSaveStateConfig.c
@@ -0,0 +1,139 @@
+/** @file
+  Config SMRAM Save State for SmmBases Relocation.
+
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#include "InternalSmmRelocationLib.h"
+#include <Library/CpuLib.h>
+
+/**
+  Get 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
+GetMmSaveStateRegisterLma (
+  VOID
+  )
+{
+  CPUID_VERSION_INFO_EAX      RegEax;
+  CPUID_EXTENDED_CPU_SIG_EDX  RegEdx;
+  UINTN                       FamilyId;
+  UINTN                       ModelId;
+  UINT32                      Eax;
+  UINT8                       SmmSaveStateRegisterLma;
+
+  //
+  // Determine the mode of the CPU at the time an SMI occurs
+  //   Intel(R) 64 and IA-32 Architectures Software Developer's Manual
+  //   Volume 3C, Section 34.4.1.1
+  //
+  RegEax.Uint32 = GetCpuFamilyModel ();
+  FamilyId      = RegEax.Bits.FamilyId;
+  ModelId       = RegEax.Bits.Model;
+  if ((FamilyId == 0x06) || (FamilyId == 0x0f)) {
+    ModelId = ModelId | RegEax.Bits.ExtendedModelId << 4;
+  }
+
+  RegEdx.Uint32 = 0;
+  AsmCpuid (CPUID_EXTENDED_FUNCTION, &Eax, NULL, NULL, NULL);
+  if (Eax >= CPUID_EXTENDED_CPU_SIG) {
+    AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &(RegEdx.Uint32));
+  }
+
+  SmmSaveStateRegisterLma = (UINT8)EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT;
+  if (RegEdx.Bits.LM) {
+    SmmSaveStateRegisterLma = (UINT8)EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT;
+  }
+
+  if (FamilyId == 0x06) {
+    if ((ModelId == 0x17) || (ModelId == 0x0f) || (ModelId == 0x1c)) {
+      SmmSaveStateRegisterLma = (UINT8)EFI_MM_SAVE_STATE_REGISTER_LMA_64BIT;
+    }
+  }
+
+  return SmmSaveStateRegisterLma;
+}
+
+/**
+  This function configures the SmBase on the currently executing CPU.
+
+  @param[in]     SmBase             The SmBase on the currently executing CPU.
+
+**/
+VOID
+EFIAPI
+ConfigureSmBase (
+  IN UINT64  SmBase
+  )
+{
+  SMRAM_SAVE_STATE_MAP  *CpuState;
+
+  CpuState = (SMRAM_SAVE_STATE_MAP *)(UINTN)(SMM_DEFAULT_SMBASE + SMRAM_SAVE_STATE_MAP_OFFSET);
+
+  CpuState->x86.SMBASE = (UINT32)SmBase;
+}
+
+/**
+  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 (GetMmSaveStateRegisterLma () == EFI_MM_SAVE_STATE_REGISTER_LMA_32BIT) {
+    OriginalInstructionPointer = (UINT64)CpuState->x86._EIP;
+    CpuState->x86._EIP         = (UINT32)NewInstructionPointer;
+
+    //
+    // Clear the auto HALT restart flag so the RSM instruction returns
+    // program control to the instruction following the HLT instruction.
+    //
+    if ((CpuState->x86.AutoHALTRestart & BIT0) != 0) {
+      CpuState->x86.AutoHALTRestart &= ~BIT0;
+    }
+  } else {
+    OriginalInstructionPointer = CpuState->x64._RIP;
+    if ((CpuState->x64.IA32_EFER & LMA) == 0) {
+      CpuState->x64._RIP = (UINT32)NewInstructionPointer32;
+    } else {
+      CpuState->x64._RIP = (UINT32)NewInstructionPointer;
+    }
+
+    //
+    // Clear the auto HALT restart flag so the RSM instruction returns
+    // program control to the instruction following the HLT instruction.
+    //
+    if ((CpuState->x64.AutoHALTRestart & BIT0) != 0) {
+      CpuState->x64.AutoHALTRestart &= ~BIT0;
+    }
+  }
+
+  return OriginalInstructionPointer;
+}
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
similarity index 84%
copy from UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c
copy to UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
index dafbc3390e..53f3084363 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/Semaphore.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
@@ -1,15 +1,15 @@
 /** @file
-Semaphore mechanism to indicate to the BSP that an AP has exited SMM
-after SMBASE relocation.
+  Semaphore mechanism to indicate to the BSP that an AP has exited SMM
+  after SMBASE relocation.

-Copyright (c) 2009 - 2015, Intel Corporation. All rights reserved.<BR>
-SPDX-License-Identifier: BSD-2-Clause-Patent
+  Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+  SPDX-License-Identifier: BSD-2-Clause-Patent

 **/

-#include "PiSmmCpuDxeSmm.h"
+#include "InternalSmmRelocationLib.h"

 X86_ASSEMBLY_PATCH_LABEL  gPatchSmmRelocationOriginalAddressPtr32;
 X86_ASSEMBLY_PATCH_LABEL  gPatchRebasedFlagAddr32;

 UINTN             mSmmRelocationOriginalAddress;
diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
similarity index 64%
copy from UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm
copy to UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
index 9cf3a6dcf9..c790ad7ad8 100644
--- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmmInit.nasm
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
@@ -1,7 +1,7 @@
 ;------------------------------------------------------------------------------ ;
-; Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR>
+; Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
 ; SPDX-License-Identifier: BSD-2-Clause-Patent
 ;
 ; Module Name:
 ;
 ;   SmmInit.nasm
@@ -28,16 +28,71 @@ global ASM_PFX(gcSmmInitTemplate)
 global ASM_PFX(gPatchRebasedFlagAddr32)
 global ASM_PFX(gPatchSmmRelocationOriginalAddressPtr32)

 %define LONG_MODE_CS 0x38

-    DEFAULT REL
-    SECTION .text
+    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(gcSmiInitGdtr):
-            DW      0
-            DQ      0
+    DW      GDT_SIZE - 1
+    DQ      NullSeg
+
+
+    DEFAULT REL
+    SECTION .text

 global ASM_PFX(SmmStartup)

 BITS 16
 ASM_PFX(SmmStartup):
@@ -132,12 +187,12 @@ ASM_PFX(gPatchRebasedFlagAddr32):
     pop     eax
     jmp     dword [dword 0]                    ; destination will be patched
 ASM_PFX(gPatchSmmRelocationOriginalAddressPtr32):

 BITS 64
-global ASM_PFX(PiSmmCpuSmmInitFixupAddress)
-ASM_PFX(PiSmmCpuSmmInitFixupAddress):
+global ASM_PFX(SmmInitFixupAddress)
+ASM_PFX(SmmInitFixupAddress):
     lea    rax, [@LongMode]
     lea    rcx, [@PatchLongModeOffset - 6]
     mov    dword [rcx], eax

     lea    rax, [ASM_PFX(SmmStartup)]
diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc
index 9426641eb2..8f67587e91 100644
--- a/UefiCpuPkg/UefiCpuPkg.dsc
+++ b/UefiCpuPkg/UefiCpuPkg.dsc
@@ -199,10 +199,11 @@
       UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf
   }
   UefiCpuPkg/Library/MmSaveStateLib/AmdMmSaveStateLib.inf
   UefiCpuPkg/Library/MmSaveStateLib/IntelMmSaveStateLib.inf
   UefiCpuPkg/Library/SmmCpuFeaturesLib/AmdSmmCpuFeaturesLib.inf
+  UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.inf

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

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



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

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

* Re: [edk2-devel] [PATCH v3 03/13] UefiCpuPkg/SmmRelocationLib: Rename global variables
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 03/13] UefiCpuPkg/SmmRelocationLib: Rename global variables Wu, Jiaxin
@ 2024-04-18  7:33   ` Ni, Ray
  0 siblings, 0 replies; 31+ messages in thread
From: Ni, Ray @ 2024-04-18  7:33 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

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

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

Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Thursday, April 18, 2024 14:55
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 v3 03/13] UefiCpuPkg/SmmRelocationLib: Rename global variables

This patch aims to rename global variables for clearer
association with Smm Init, ensuring their names are
distinct from those used in the PiSmmCpuDxeSmm Driver.

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/SmmInit.nasm     | 18 +++++++--------
 .../SmmRelocationLib/InternalSmmRelocationLib.h    |  8 +++----
 .../Library/SmmRelocationLib/SmmRelocationLib.c    | 26 +++++++++++-----------
 .../Library/SmmRelocationLib/X64/SmmInit.nasm      | 18 +++++++--------
 4 files changed, 35 insertions(+), 35 deletions(-)

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
index 3d845e9e16..8916cb7d06 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
+++ b/UefiCpuPkg/Library/SmmRelocationLib/Ia32/SmmInit.nasm
@@ -16,15 +16,15 @@

 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(gPatchSmmInitCr3)
+global ASM_PFX(gPatchSmmInitCr4)
+global ASM_PFX(gPatchSmmInitCr0)
 global ASM_PFX(gPatchSmmInitStack)
-global ASM_PFX(gcSmiInitGdtr)
+global ASM_PFX(gcSmmInitGdtr)
 global ASM_PFX(gcSmmInitSize)
 global ASM_PFX(gcSmmInitTemplate)

 %define PROTECT_MODE_CS 0x8
 %define PROTECT_MODE_DS 0x20
@@ -81,11 +81,11 @@ CodeSeg64:
             DB      0x9b
             DB      0xaf                ; LimitHigh
             DB      0                   ; BaseHigh
 GDT_SIZE equ $ - NullSeg

-ASM_PFX(gcSmiInitGdtr):
+ASM_PFX(gcSmmInitGdtr):
     DW      GDT_SIZE - 1
     DD      NullSeg


     SECTION .text
@@ -98,22 +98,22 @@ ASM_PFX(SmmStartup):
     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):
+ASM_PFX(gPatchSmmInitCr3):
     mov     cr3, eax
-o32 lgdt    [cs:ebp + (ASM_PFX(gcSmiInitGdtr) - ASM_PFX(SmmStartup))]
+o32 lgdt    [cs:ebp + (ASM_PFX(gcSmmInitGdtr) - ASM_PFX(SmmStartup))]
     mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr4):
+ASM_PFX(gPatchSmmInitCr4):
     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):
+ASM_PFX(gPatchSmmInitCr0):
     mov     di, PROTECT_MODE_DS
     mov     cr0, eax
     jmp     PROTECT_MODE_CS : dword @32bit

 BITS 32
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
index a9d3f271a9..ede61b956f 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
+++ b/UefiCpuPkg/Library/SmmRelocationLib/InternalSmmRelocationLib.h
@@ -30,17 +30,17 @@
 #include <Guid/SmmBaseHob.h>
 #include <Register/Intel/Cpuid.h>
 #include <Register/Intel/SmramSaveStateMap.h>
 #include <Protocol/MmCpu.h>

-extern IA32_DESCRIPTOR  gcSmiInitGdtr;
+extern IA32_DESCRIPTOR  gcSmmInitGdtr;
 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  gPatchSmmInitCr0;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmInitCr3;
+X86_ASSEMBLY_PATCH_LABEL  gPatchSmmInitCr4;
 X86_ASSEMBLY_PATCH_LABEL  gPatchSmmInitStack;

 //
 // The size 0x20 must be bigger than
 // the size of template code of SmmInit. Currently,
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
index 13e62b662d..ca98f06a05 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
@@ -22,11 +22,11 @@ UINTN  mNumberOfCpus    = 1;
 EFI_PROCESSOR_INFORMATION  *mProcessorInfo = NULL;

 //
 // IDT used during SMM Init
 //
-IA32_DESCRIPTOR  gcSmiIdtr;
+IA32_DESCRIPTOR  gcSmmInitIdtr;

 //
 // Smbase for all CPUs
 //
 UINT64  *mSmBase = NULL;
@@ -118,11 +118,11 @@ SmmInitHandler (
   UINTN   Index;

   //
   // Update SMM IDT entries' code segment and load IDT
   //
-  AsmWriteIdtr (&gcSmiIdtr);
+  AsmWriteIdtr (&gcSmmInitIdtr);
   ApicId = GetApicId ();

   for (Index = 0; Index < mNumberOfCpus; Index++) {
     if (ApicId == (UINT32)mProcessorInfo[Index].ProcessorId) {
       //
@@ -167,13 +167,13 @@ SmmRelocateBases (
   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);
+  PatchInstructionX86 (gPatchSmmInitCr0, AsmReadCr0 (), 4);
+  PatchInstructionX86 (gPatchSmmInitCr3, AsmReadCr3 (), 4);
+  PatchInstructionX86 (gPatchSmmInitCr4, 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);

   //
@@ -249,19 +249,19 @@ InitSmmIdt (

   //
   // 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;
+  gcSmmInitIdtr.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);
+  gcSmmInitIdtr.Base = (UINTN)AllocateZeroPool (gcSmmInitIdtr.Limit + 1 + sizeof (UINTN));
+  ASSERT (gcSmmInitIdtr.Base != 0);
+  gcSmmInitIdtr.Base += sizeof (UINTN);

   //
   // Disable Interrupt, save InterruptState and save PEI IDT table
   //
   InterruptState = SaveAndDisableInterrupts ();
@@ -270,21 +270,21 @@ InitSmmIdt (
   //
   // 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;
+  PeiServices                                       = (CONST EFI_PEI_SERVICES **)(*(UINTN *)(PeiIdtr.Base - sizeof (UINTN)));
+  (*(UINTN *)(gcSmmInitIdtr.Base - sizeof (UINTN))) = (UINTN)PeiServices;

   //
   // Load SMM temporary IDT table
   //
-  AsmWriteIdtr (&gcSmiIdtr);
+  AsmWriteIdtr (&gcSmmInitIdtr);

   //
   // Setup SMM default exception handlers, SMM IDT table
-  // will be updated and saved in gcSmiIdtr
+  // will be updated and saved in gcSmmInitIdtr
   //
   Status = InitializeCpuExceptionHandlers (NULL);
   ASSERT_EFI_ERROR (Status);

   //
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
index c790ad7ad8..8288b723c4 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/SmmInit.nasm
@@ -16,15 +16,15 @@

 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(gPatchSmmInitCr3)
+global ASM_PFX(gPatchSmmInitCr4)
+global ASM_PFX(gPatchSmmInitCr0)
 global ASM_PFX(gPatchSmmInitStack)
-global ASM_PFX(gcSmiInitGdtr)
+global ASM_PFX(gcSmmInitGdtr)
 global ASM_PFX(gcSmmInitSize)
 global ASM_PFX(gcSmmInitTemplate)
 global ASM_PFX(gPatchRebasedFlagAddr32)
 global ASM_PFX(gPatchSmmRelocationOriginalAddressPtr32)

@@ -82,11 +82,11 @@ CodeSeg64:
             DB      0x9b
             DB      0xaf                ; LimitHigh
             DB      0                   ; BaseHigh
 GDT_SIZE equ $ -   NullSeg

-ASM_PFX(gcSmiInitGdtr):
+ASM_PFX(gcSmmInitGdtr):
     DW      GDT_SIZE - 1
     DQ      NullSeg


     DEFAULT REL
@@ -98,15 +98,15 @@ 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):
+ASM_PFX(gPatchSmmInitCr3):
     mov     cr3, eax
-o32 lgdt    [cs:ebp + (ASM_PFX(gcSmiInitGdtr) - ASM_PFX(SmmStartup))]
+o32 lgdt    [cs:ebp + (ASM_PFX(gcSmmInitGdtr) - ASM_PFX(SmmStartup))]
     mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr4):
+ASM_PFX(gPatchSmmInitCr4):
     or      ah,  2                      ; enable XMM registers access
     mov     cr4, eax
     mov     ecx, 0xc0000080             ; IA32_EFER MSR
     rdmsr
     or      ah, BIT0                    ; set LME bit
@@ -114,11 +114,11 @@ ASM_PFX(gPatchSmmCr4):
     jz      .1
     or      ah, BIT3                    ; set NXE bit
 .1:
     wrmsr
     mov     eax, strict dword 0         ; source operand will be patched
-ASM_PFX(gPatchSmmCr0):
+ASM_PFX(gPatchSmmInitCr0):
     mov     cr0, eax                    ; enable protected mode & paging
     jmp     LONG_MODE_CS : dword 0      ; offset will be patched to @LongMode
 @PatchLongModeOffset:

 BITS 64
--
2.16.2.windows.1



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

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

* Re: [edk2-devel] [PATCH v3 04/13] UefiCpuPkg/SmmRelocationLib: Avoid unnecessary memory allocation
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 04/13] UefiCpuPkg/SmmRelocationLib: Avoid unnecessary memory allocation Wu, Jiaxin
@ 2024-04-18  7:40   ` Ni, Ray
  0 siblings, 0 replies; 31+ messages in thread
From: Ni, Ray @ 2024-04-18  7:40 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

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

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

Thanks,
Ray
________________________________
From: Wu, Jiaxin <jiaxin.wu@intel.com>
Sent: Thursday, April 18, 2024 14:55
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 v3 04/13] UefiCpuPkg/SmmRelocationLib: Avoid unnecessary memory allocation

Since SMM relocation is performed serially for each CPU, there is
no need to allocate buffers for all CPUs to store the SmBase
address in mSmBase and the Rebased flag in mRebased. A defined
global variable is sufficient.

This patch focuses on the mSmBase and mRebased global variables
to prevent unnecessary memory allocation for these variables.

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/SmmRelocationLib.c    | 201 +++++++++------------
 1 file changed, 90 insertions(+), 111 deletions(-)

diff --git a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
index ca98f06a05..3694a07cbb 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/SmmRelocationLib.c
@@ -25,31 +25,57 @@ EFI_PROCESSOR_INFORMATION  *mProcessorInfo = NULL;
 // IDT used during SMM Init
 //
 IA32_DESCRIPTOR  gcSmmInitIdtr;

 //
-// Smbase for all CPUs
+// Smbase for current CPU
 //
-UINT64  *mSmBase = NULL;
+UINT64  mSmBase;

 //
-// SmBase Rebased flag for all CPUs
+// SmBase Rebased flag for current CPU
 //
-volatile BOOLEAN  *mRebased;
+volatile BOOLEAN  mRebased;
+
+/**
+  This function will get the SmBase for CpuIndex.
+
+  @param[in]   CpuIndex            The processor index.
+  @param[in]   SmmRelocationStart  The start address of Smm relocated memory in SMRAM.
+  @param[in]   TileSize            The total size required for a CPU save state, any
+                                   additional CPU-specific context and the size of code
+                                   for the SMI entry point.
+
+  @retval The value of SmBase for CpuIndex.
+
+**/
+UINTN
+GetSmBase (
+  IN UINTN                 CpuIndex,
+  IN EFI_PHYSICAL_ADDRESS  SmmRelocationStart,
+  IN UINTN                 TileSize
+  )
+{
+  return (UINTN)(SmmRelocationStart) + CpuIndex * TileSize - SMM_HANDLER_OFFSET;
+}

 /**
   This function will create SmBase for all CPUs.

-  @param[in] SmBase    Pointer to SmBase for all CPUs.
+  @param[in]   SmmRelocationStart  The start address of Smm relocated memory in SMRAM.
+  @param[in]   TileSize            The total size required for a CPU save state, any
+                                   additional CPU-specific context and the size of code
+                                   for the SMI entry point.

   @retval EFI_SUCCESS           Create SmBase for all CPUs successfully.
   @retval Others                Failed to create SmBase for all CPUs.

 **/
 EFI_STATUS
 CreateSmmBaseHob (
-  IN UINT64  *SmBase
+  IN EFI_PHYSICAL_ADDRESS  SmmRelocationStart,
+  IN UINTN                 TileSize
   )
 {
   UINTN              Index;
   SMM_BASE_HOB_DATA  *SmmBaseHobData;
   UINT32             CpuCount;
@@ -90,11 +116,11 @@ CreateSmmBaseHob (
     DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->NumberOfProcessors: %d\n", HobCount, SmmBaseHobData->NumberOfProcessors));
     for (Index = 0; Index < SmmBaseHobData->NumberOfProcessors; Index++) {
       //
       // Calculate the new SMBASE address
       //
-      SmmBaseHobData->SmBase[Index] = SmBase[Index + CpuCount];
+      SmmBaseHobData->SmBase[Index] = GetSmBase (Index + CpuCount, SmmRelocationStart, TileSize);
       DEBUG ((DEBUG_INFO, "CreateSmmBaseHob - SmmBaseHobData[%d]->SmBase[%d]: 0x%08x\n", HobCount, Index, SmmBaseHobData->SmBase[Index]));
     }

     CpuCount += NumberOfProcessorsInHob;
     HobCount++;
@@ -126,18 +152,18 @@ SmmInitHandler (
   for (Index = 0; Index < mNumberOfCpus; Index++) {
     if (ApicId == (UINT32)mProcessorInfo[Index].ProcessorId) {
       //
       // Configure SmBase.
       //
-      ConfigureSmBase (mSmBase[Index]);
+      ConfigureSmBase (mSmBase);

       //
       // 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]);
+      SemaphoreHook (Index, &mRebased);
       return;
     }
   }

   ASSERT (FALSE);
@@ -145,14 +171,22 @@ SmmInitHandler (

 /**
   Relocate SmmBases for each processor.
   Execute on first boot and all S3 resumes

+  @param[in]   MpServices2         Pointer to this instance of the MpServices.
+  @param[in]   SmmRelocationStart  The start address of Smm relocated memory in SMRAM.
+  @param[in]   TileSize            The total size required for a CPU save state, any
+                                   additional CPU-specific context and the size of code
+                                   for the SMI entry point.
+
 **/
 VOID
 SmmRelocateBases (
-  VOID
+  IN EDKII_PEI_MP_SERVICES2_PPI  *MpServices2,
+  IN EFI_PHYSICAL_ADDRESS        SmmRelocationStart,
+  IN UINTN                       TileSize
   )
 {
   UINT8                 BakBuf[BACK_BUF_SIZE];
   SMRAM_SAVE_STATE_MAP  BakBuf2;
   SMRAM_SAVE_STATE_MAP  *CpuStatePtr;
@@ -196,17 +230,18 @@ SmmRelocateBases (
   // 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) {
+      mRebased = FALSE;
+      mSmBase  = GetSmBase (Index, SmmRelocationStart, TileSize);
       SendSmiIpi ((UINT32)mProcessorInfo[Index].ProcessorId);
       //
       // Wait for this AP to finish its 1st SMI
       //
-      while (!mRebased[Index]) {
+      while (!mRebased) {
       }
     } else {
       //
       // BSP will be Relocated later
       //
@@ -216,16 +251,18 @@ SmmRelocateBases (

   //
   // Relocate BSP's SMM base
   //
   ASSERT (BspIndex != (UINTN)-1);
+  mRebased = FALSE;
+  mSmBase  = GetSmBase (BspIndex, SmmRelocationStart, TileSize);
   SendSmiIpi (BspApicId);

   //
   // Wait for the BSP to finish its 1st SMI
   //
-  while (!mRebased[BspIndex]) {
+  while (!mRebased) {
   }

   //
   // Restore contents at address 0x38000
   //
@@ -382,87 +419,10 @@ SplitSmramHobForSmmRelocation (
   ZeroMem (&GuidHob->Name, sizeof (GuidHob->Name));

   return EFI_SUCCESS;
 }

-/**
-  This function will initialize SmBase for all CPUs.
-
-  @param[in,out] SmBase    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  **SmBase
-  )
-{
-  EFI_STATUS            Status;
-  UINTN                 TileSize;
-  UINT64                SmmRelocationSize;
-  EFI_PHYSICAL_ADDRESS  SmmRelocationStart;
-  UINTN                 Index;
-
-  SmmRelocationStart = 0;
-
-  ASSERT (SmBase != 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 SmBase
-  //
-  *SmBase = (UINT64 *)AllocatePages (EFI_SIZE_TO_PAGES (sizeof (UINT64) * mMaxNumberOfCpus));
-  if (*SmBase == NULL) {
-    return EFI_OUT_OF_RESOURCES;
-  }
-
-  for (Index = 0; Index < mMaxNumberOfCpus; Index++) {
-    //
-    // Return each SmBase in SmBase
-    //
-    (*SmBase)[Index] = (UINTN)(SmmRelocationStart)+ Index * TileSize - SMM_HANDLER_OFFSET;
-    DEBUG ((DEBUG_INFO, "InitSmBaseForAllCpus - SmBase For CPU[%d]: 0x%08x\n", Index, (*SmBase)[Index]));
-  }
-
-  return EFI_SUCCESS;
-}
-
 /**
   CPU SmmBase Relocation Init.

   This function is to relocate CPU SmmBase.

@@ -476,17 +436,21 @@ EFI_STATUS
 EFIAPI
 SmmRelocationInit (
   IN EDKII_PEI_MP_SERVICES2_PPI  *MpServices2
   )
 {
-  EFI_STATUS  Status;
-  UINTN       NumberOfEnabledCpus;
-  UINTN       SmmStackSize;
-  UINT8       *SmmStacks;
-  UINTN       Index;
+  EFI_STATUS            Status;
+  UINTN                 NumberOfEnabledCpus;
+  UINTN                 TileSize;
+  UINT64                SmmRelocationSize;
+  EFI_PHYSICAL_ADDRESS  SmmRelocationStart;
+  UINTN                 SmmStackSize;
+  UINT8                 *SmmStacks;
+  UINTN                 Index;

-  SmmStacks = NULL;
+  SmmRelocationStart = 0;
+  SmmStacks          = NULL;

   DEBUG ((DEBUG_INFO, "SmmRelocationInit Start \n"));
   if (MpServices2 == NULL) {
     return EFI_INVALID_PARAMETER;
   }
@@ -528,17 +492,43 @@ SmmRelocationInit (
       }
     }
   }

   //
-  // Initialize the SmBase for all CPUs
+  // Calculate SmmRelocationSize for all of the tiles.
   //
-  Status = InitSmBaseForAllCpus (&mSmBase);
+  // 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)) {
     goto ON_EXIT;
   }

+  ASSERT (SmmRelocationStart != 0);
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit - SmmRelocationSize: 0x%08x\n", SmmRelocationSize));
+  DEBUG ((DEBUG_INFO, "SmmRelocationInit - SmmRelocationStart: 0x%08x\n", SmmRelocationStart));
+
   //
   // Fix up the address of the global variable or function referred in
   // SmmInit assembly files to be the absolute address
   //
   SmmInitFixupAddress ();
@@ -569,32 +559,21 @@ SmmRelocationInit (
   //
   InitSmmIdt ();

   //
   // 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 ();
+  SmmRelocateBases (MpServices2, SmmRelocationStart, TileSize);

   //
   // Create the SmBase HOB for all CPUs
   //
-  Status = CreateSmmBaseHob (mSmBase);
+  Status = CreateSmmBaseHob (SmmRelocationStart, TileSize);

 ON_EXIT:
   if (SmmStacks != NULL) {
     FreePages (SmmStacks, EFI_SIZE_TO_PAGES (SmmStackSize));
   }

-  if (mSmBase != NULL) {
-    FreePages (mSmBase, EFI_SIZE_TO_PAGES (sizeof (UINT64) * mMaxNumberOfCpus));
-  }
-
   DEBUG ((DEBUG_INFO, "SmmRelocationInit Done\n"));
   return Status;
 }
--
2.16.2.windows.1



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

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

* Re: [edk2-devel] [PATCH v3 05/13] UefiCpuPkg/SmmRelocationLib: Remove unnecessary global variable
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 05/13] UefiCpuPkg/SmmRelocationLib: Remove unnecessary global variable Wu, Jiaxin
@ 2024-04-18  7:48   ` Ni, Ray
  2024-04-18  7:57     ` Wu, Jiaxin
  0 siblings, 1 reply; 31+ messages in thread
From: Ni, Ray @ 2024-04-18  7:48 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

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

 UINT64
 EFIAPI
 HookReturnFromSmm (
-  IN     UINTN                 CpuIndex,
   IN OUT SMRAM_SAVE_STATE_MAP  *CpuState,
   IN     UINT64                NewInstructionPointer32,
   IN     UINT64                NewInstructionPointer
   )
 {
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
index 53f3084363..cd6778e3fc 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
@@ -26,18 +26,16 @@ SmmRelocationSemaphoreComplete32 (
 /**
   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;
@@ -49,11 +47,10 @@ SemaphoreHook (
     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
                                     );


[Ray] Can you split the removal of CpuIndex parameter in a new patch? Others look good to me.

--
2.16.2.windows.1



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

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

* Re: [edk2-devel] [PATCH v3 05/13] UefiCpuPkg/SmmRelocationLib: Remove unnecessary global variable
  2024-04-18  7:48   ` Ni, Ray
@ 2024-04-18  7:57     ` Wu, Jiaxin
  0 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-18  7:57 UTC (permalink / raw)
  To: Ni, Ray, devel@edk2.groups.io; +Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

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

Sure, I will you split the removal of CpuIndex parameter in a new patch.

Thanks,
Jiaxin

From: Ni, Ray <ray.ni@intel.com>
Sent: Thursday, April 18, 2024 3:48 PM
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>
Subject: Re: [PATCH v3 05/13] UefiCpuPkg/SmmRelocationLib: Remove unnecessary global variable

 UINT64
 EFIAPI
 HookReturnFromSmm (
-  IN     UINTN                 CpuIndex,
   IN OUT SMRAM_SAVE_STATE_MAP  *CpuState,
   IN     UINT64                NewInstructionPointer32,
   IN     UINT64                NewInstructionPointer
   )
 {
diff --git a/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
index 53f3084363..cd6778e3fc 100644
--- a/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
+++ b/UefiCpuPkg/Library/SmmRelocationLib/X64/Semaphore.c
@@ -26,18 +26,16 @@ SmmRelocationSemaphoreComplete32 (
 /**
   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;
@@ -49,11 +47,10 @@ SemaphoreHook (
     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
                                     );


[Ray] Can you split the removal of CpuIndex parameter in a new patch? Others look good to me.

--
2.16.2.windows.1


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

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

* Re: [edk2-devel] [PATCH v3 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic Wu, Jiaxin
@ 2024-04-18  8:15   ` Ni, Ray
  2024-04-19  2:06     ` Wu, Jiaxin
  0 siblings, 1 reply; 31+ messages in thread
From: Ni, Ray @ 2024-04-18  8:15 UTC (permalink / raw)
  To: Wu, Jiaxin, devel@edk2.groups.io
  Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

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


+  //
+  // 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;
   }

[Ray] Can you move the "TileSize" check just below the original TileSize calculation logic? Others look good to me.


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

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

* Re: [edk2-devel] [PATCH v3 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic
  2024-04-18  8:15   ` Ni, Ray
@ 2024-04-19  2:06     ` Wu, Jiaxin
  0 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-19  2:06 UTC (permalink / raw)
  To: Ni, Ray, devel@edk2.groups.io; +Cc: Zeng, Star, Gerd Hoffmann, Kumar, Rahul R

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

Ok, thanks Ray, I will follow the change in next version.

From: Ni, Ray <ray.ni@intel.com>
Sent: Thursday, April 18, 2024 4:15 PM
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>
Subject: Re: [PATCH v3 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic


+  //
+  // 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;
   }

[Ray] Can you move the "TileSize" check just below the original TileSize calculation logic? Others look good to me.


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

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

* Re: [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-18  6:55 ` [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid Wu, Jiaxin
@ 2024-04-23  9:25   ` Gerd Hoffmann
  2024-04-23 12:18     ` Wu, Jiaxin
                       ` (2 more replies)
  0 siblings, 3 replies; 31+ messages in thread
From: Gerd Hoffmann @ 2024-04-23  9:25 UTC (permalink / raw)
  To: Jiaxin Wu; +Cc: devel, Ard Biesheuvel, Jiewen Yao, Ray Ni

  Hi,

> +    Hob.Raw = BuildGuidHob (
> +                &gEfiSmmSmramMemoryGuid,
> +                BufferSize
> +                );

> +    SmramHobDescriptorBlock                             = (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)(Hob.Raw);

> +    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;

> +    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;

This is not going to fly.

First, smram allocation doesn't work that way.  Have a look at
OvmfPkg/SmmAccess.  I guess that easily explains why this series
breaks S3 suspend.

Second, storing these descriptors in a HOB (which is PEI memory)
is questionable from a security point of view.

take care,
  Gerd



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



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

* Re: [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-23  9:25   ` Gerd Hoffmann
@ 2024-04-23 12:18     ` Wu, Jiaxin
  2024-04-24 12:35       ` Gerd Hoffmann
  2024-04-23 13:20     ` Wu, Jiaxin
  2024-04-23 15:59     ` Wu, Jiaxin
  2 siblings, 1 reply; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-23 12:18 UTC (permalink / raw)
  To: Gerd Hoffmann; +Cc: devel@edk2.groups.io, Ard Biesheuvel, Yao, Jiewen, Ni, Ray

> 
> > +    SmramHobDescriptorBlock                             =
> (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)(Hob.Raw);
> 
> > +    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;
> 
> > +    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;
> 
> This is not going to fly.
> 
> First, smram allocation doesn't work that way.  Have a look at
> OvmfPkg/SmmAccess.  I guess that easily explains why this series
> breaks S3 suspend.
> 

Oh? Could you explain a bit more for 1) how smram allocation works? 2) what's the possible reason break the S3? I haven't check yet. 

> Second, storing these descriptors in a HOB (which is PEI memory)
> is questionable from a security point of view.
> 

HOB is only to expose the SMRAM address and size, not the contents in smram, what's the security concern?


Thanks,
Jiaxin


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



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

* Re: [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-23  9:25   ` Gerd Hoffmann
  2024-04-23 12:18     ` Wu, Jiaxin
@ 2024-04-23 13:20     ` Wu, Jiaxin
  2024-04-23 15:59     ` Wu, Jiaxin
  2 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-23 13:20 UTC (permalink / raw)
  To: Gerd Hoffmann; +Cc: devel@edk2.groups.io, Ard Biesheuvel, Yao, Jiewen, Ni, Ray

More info:
I quick dump the SMRAM info with original SmmAccess implementation, it's same as I produced in the gEfiSmmSmramMemoryGuid HOB.

SmmAccess:
SmmAccessPeiEntryPoint: SMRAM map follows, 2 entries
SmmAccessPeiEntryPoint:             7F000000                 1000             7F000000                   1A    ---> for the S3 Resume in gEfiAcpiVariableGuid
SmmAccessPeiEntryPoint:             7F001000               FFF000             7F001000                    A

Smram map in the gEfiSmmSmramMemoryGuid:
PlatformQemuInitializeRam:             7F000000                 1000             7F000000                   1A    --> ---> for the S3 Resume in gEfiAcpiVariableGuid
PlatformQemuInitializeRam:             7F001000               FFF000             7F001000                    A


Thanks,
Jiaxin

> -----Original Message-----
> From: Wu, Jiaxin
> Sent: Tuesday, April 23, 2024 8:19 PM
> To: Gerd Hoffmann <kraxel@redhat.com>
> Cc: devel@edk2.groups.io; Ard Biesheuvel <ardb+tianocore@kernel.org>; Yao,
> Jiewen <jiewen.yao@intel.com>; Ni, Ray <ray.ni@intel.com>
> Subject: RE: [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create
> gEfiSmmSmramMemoryGuid
> 
> >
> > > +    SmramHobDescriptorBlock                             =
> > (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)(Hob.Raw);
> >
> > > +    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;
> >
> > > +    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;
> >
> > This is not going to fly.
> >
> > First, smram allocation doesn't work that way.  Have a look at
> > OvmfPkg/SmmAccess.  I guess that easily explains why this series
> > breaks S3 suspend.
> >
> 
> Oh? Could you explain a bit more for 1) how smram allocation works? 2)
> what's the possible reason break the S3? I haven't check yet.
> 
> > Second, storing these descriptors in a HOB (which is PEI memory)
> > is questionable from a security point of view.
> >
> 
> HOB is only to expose the SMRAM address and size, not the contents in
> smram, what's the security concern?
> 
> 
> Thanks,
> Jiaxin


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



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

* Re: [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-23  9:25   ` Gerd Hoffmann
  2024-04-23 12:18     ` Wu, Jiaxin
  2024-04-23 13:20     ` Wu, Jiaxin
@ 2024-04-23 15:59     ` Wu, Jiaxin
  2024-04-24 12:38       ` Gerd Hoffmann
  2 siblings, 1 reply; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-23 15:59 UTC (permalink / raw)
  To: Gerd Hoffmann; +Cc: devel@edk2.groups.io, Ard Biesheuvel, Yao, Jiewen, Ni, Ray

Hi Gerd,

There was the issue in my patch to change the smm access driver: SmmAccessPeiOpen(), I removed below code due to the comment in original code that indicate the DescriptorIndex is not considered at all:

  ...
  if (DescriptorIndex >= DescIdxCount) {
    return EFI_INVALID_PARAMETER;
  }
  //
  // According to current practice, *DescriptorIndex is not considered at all*,
  // beyond validating it.
  //
  ...

But it's important for smmlockboxpeilib to check the return status of SmmAccessPeiOpen (EFI_INVALID_PARAMETER) to continue the RestoreLockBox():
    for (Index = 0; !EFI_ERROR (Status); Index++) {
      Status = SmmAccess->Open ((EFI_PEI_SERVICES **)GetPeiServicesTablePointer (), SmmAccess, Index);
    }

So, it hangs at for() loop once I removed above code in the SmmAccessPeiOpen!!!

After that fix, I still found S3 doesn't work, I checked the master code without my patch. It also can't work for S3, which means S3 broken on latest master code. You can also double confirm the log that stop as below:

...
S3_BOOT_SCRIPT_LIB_TERMINATE_OPCODE
S3BootScriptDone - Success
Call AsmDisablePaging64() to return to S3 Resume in PEI Phase
Install PPI: 88C9D306-0900-4EB5-8260-3E2DBEDA1F89
Install PPI: 605EA650-C65C-42E1-BA80-91A52AB618C6
Notify: PPI Guid: 605EA650-C65C-42E1-BA80-91A52AB618C6, Peim notify entry point: 82B5B0
Signal EndOfS3Resume
Signal 96F5296D-05F7-4F3C-8467-E456890E0CB5 to SMM - Enter
Locate Smm Communicate Ppi failed (Not Found)!
Transfer to 16bit OS waking vector - 991F0 ----> hang here!!!

Thanks,
Jiaxin 

> -----Original Message-----
> From: Wu, Jiaxin
> Sent: Tuesday, April 23, 2024 9:20 PM
> To: Gerd Hoffmann <kraxel@redhat.com>
> Cc: devel@edk2.groups.io; Ard Biesheuvel <ardb+tianocore@kernel.org>; Yao,
> Jiewen <jiewen.yao@intel.com>; Ni, Ray <ray.ni@intel.com>
> Subject: RE: [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create
> gEfiSmmSmramMemoryGuid
> 
> More info:
> I quick dump the SMRAM info with original SmmAccess implementation, it's
> same as I produced in the gEfiSmmSmramMemoryGuid HOB.
> 
> SmmAccess:
> SmmAccessPeiEntryPoint: SMRAM map follows, 2 entries
> SmmAccessPeiEntryPoint:             7F000000                 1000             7F000000
> 1A    ---> for the S3 Resume in gEfiAcpiVariableGuid
> SmmAccessPeiEntryPoint:             7F001000               FFF000             7F001000
> A
> 
> Smram map in the gEfiSmmSmramMemoryGuid:
> PlatformQemuInitializeRam:             7F000000                 1000             7F000000
> 1A    --> ---> for the S3 Resume in gEfiAcpiVariableGuid
> PlatformQemuInitializeRam:             7F001000               FFF000             7F001000
> A
> 
> 
> Thanks,
> Jiaxin
> 
> > -----Original Message-----
> > From: Wu, Jiaxin
> > Sent: Tuesday, April 23, 2024 8:19 PM
> > To: Gerd Hoffmann <kraxel@redhat.com>
> > Cc: devel@edk2.groups.io; Ard Biesheuvel <ardb+tianocore@kernel.org>;
> Yao,
> > Jiewen <jiewen.yao@intel.com>; Ni, Ray <ray.ni@intel.com>
> > Subject: RE: [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create
> > gEfiSmmSmramMemoryGuid
> >
> > >
> > > > +    SmramHobDescriptorBlock                             =
> > > (EFI_SMRAM_HOB_DESCRIPTOR_BLOCK *)(Hob.Raw);
> > >
> > > > +    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;
> > >
> > > > +    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;
> > >
> > > This is not going to fly.
> > >
> > > First, smram allocation doesn't work that way.  Have a look at
> > > OvmfPkg/SmmAccess.  I guess that easily explains why this series
> > > breaks S3 suspend.
> > >
> >
> > Oh? Could you explain a bit more for 1) how smram allocation works? 2)
> > what's the possible reason break the S3? I haven't check yet.
> >
> > > Second, storing these descriptors in a HOB (which is PEI memory)
> > > is questionable from a security point of view.
> > >
> >
> > HOB is only to expose the SMRAM address and size, not the contents in
> > smram, what's the security concern?
> >
> >
> > Thanks,
> > Jiaxin


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



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

* Re: [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-23 12:18     ` Wu, Jiaxin
@ 2024-04-24 12:35       ` Gerd Hoffmann
  2024-04-25  1:54         ` Wu, Jiaxin
  0 siblings, 1 reply; 31+ messages in thread
From: Gerd Hoffmann @ 2024-04-24 12:35 UTC (permalink / raw)
  To: Wu, Jiaxin; +Cc: devel@edk2.groups.io, Ard Biesheuvel, Yao, Jiewen, Ni, Ray

  Hi,

> > First, smram allocation doesn't work that way.  Have a look at
> > OvmfPkg/SmmAccess.  I guess that easily explains why this series
> > breaks S3 suspend.
> 
> Oh? Could you explain a bit more for 1) how smram allocation works? 2) what's the possible reason break the S3? I haven't check yet. 

SmramInternal.c handles that.  It creates two regions, one is a page at
the start of SMRAM where S3 state is stored (and marked as allocated),
one is all the rest.

So, if you need some smram to initialize SMM in PEI I'd suggest to
either add a third region, or make the first region larger.

It's not clear to me why you put the logic upside down and introduce
that HOB in the first place.

> > Second, storing these descriptors in a HOB (which is PEI memory)
> > is questionable from a security point of view.
> 
> HOB is only to expose the SMRAM address and size, not the contents in smram, what's the security concern?

Storing anything SMM related outside SMRAM makes me nervous.
I'd strongly suggest to avoid that.

It might be that in this specific case it is not a problem.  But it
needs very careful review of the implications (which I have not done)
and you have to hope you don't miss a possible attack vector, such as
someone modifying the HOB and the firmware then storing SMM data + code
outside SMRAM.

take care,
  Gerd



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



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

* Re: [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-23 15:59     ` Wu, Jiaxin
@ 2024-04-24 12:38       ` Gerd Hoffmann
  2024-04-25  0:54         ` Wu, Jiaxin
  0 siblings, 1 reply; 31+ messages in thread
From: Gerd Hoffmann @ 2024-04-24 12:38 UTC (permalink / raw)
  To: Wu, Jiaxin; +Cc: devel@edk2.groups.io, Ard Biesheuvel, Yao, Jiewen, Ni, Ray

  Hi,

> Transfer to 16bit OS waking vector - 991F0 ----> hang here!!!

That is the last ovmf message of a successful S3 resume, after that the
OS should have back control.  Looks fine to me.

take care,
  Gerd



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



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

* Re: [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-24 12:38       ` Gerd Hoffmann
@ 2024-04-25  0:54         ` Wu, Jiaxin
  0 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-25  0:54 UTC (permalink / raw)
  To: Gerd Hoffmann; +Cc: devel@edk2.groups.io, Ard Biesheuvel, Yao, Jiewen, Ni, Ray

> 
> > Transfer to 16bit OS waking vector - 991F0 ----> hang here!!!
> 
> That is the last ovmf message of a successful S3 resume, after that the
> OS should have back control.  Looks fine to me.
> 

Great, got it.

Thanks,
Jiaxin



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



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

* Re: [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-24 12:35       ` Gerd Hoffmann
@ 2024-04-25  1:54         ` Wu, Jiaxin
  2024-04-25  7:20           ` Gerd Hoffmann
  0 siblings, 1 reply; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-25  1:54 UTC (permalink / raw)
  To: devel@edk2.groups.io, kraxel@redhat.com
  Cc: Ard Biesheuvel, Yao, Jiewen, Ni, Ray

> 
> SmramInternal.c handles that.  It creates two regions, one is a page at
> the start of SMRAM where S3 state is stored (and marked as allocated),
> one is all the rest.
> 

Yes, the same logic is moved to the OvmfPkg/Library/PlatformInitLib/MemDetect.c:

    //
    // Create first SMRAM descriptor, which contains data structures used in S3 resume.
    // One page is enough for the data structure
    //
    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 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;
    SmramHobDescriptorBlock->Descriptor[1].PhysicalSize  = TsegSize - EFI_PAGE_SIZE;
    SmramHobDescriptorBlock->Descriptor[1].RegionState   = EFI_SMRAM_CLOSED | EFI_CACHEABLE;


> So, if you need some smram to initialize SMM in PEI I'd suggest to
> either add a third region, or make the first region larger.
> 
> It's not clear to me why you put the logic upside down and introduce
> that HOB in the first place.
> 

Let me explain more why need this change:

1. The EFI_SMM_SMRAM_MEMORY_GUID HOB, as defined in the PI specification, is used to describe the SMRAM memory regions supported by the platform. This HOB should be produced during the memory detection phase to align with the PI spec.

2. In addition to the memory reserved for ACPI S3 resume, an increasing number of features require reserving SMRAM for specific purposes, such as SmmRelocation. Other advanced features in Intel platforms also necessitate this. The implementation of these features varies and is entirely dependent on the platform. This is why an increasing number of platforms are adopting the EFI_SMM_SMRAM_MEMORY_GUID HOB for SMRAM description.

3. It is crucial that the SMRAM information remains consistent when retrieved from the platform, whether through the SMM ACCESS PPI/Protocol or the EFI_SMM_SMRAM_MEMORY_GUID HOB. Inconsistencies can lead to unexpected issues, most commonly memory region conflicts.

4. The SMM ACCESS PPI/Protocol can be naturally implemented for general use. The common approach is to utilize the EFI_SMM_SMRAM_MEMORY_GUID HOB. For reference, see the existing implementation in the EDK2 repository at edk2/UefiPayloadPkg/SmmAccessDxe/SmmAccessDxe.inf and edk2-platforms/Silicon/Intel/IntelSiliconPkg/Feature/SmmAccess/Library/PeiSmmAccessLib/PeiSmmAccessLib.inf. 

For the reasons mentioned, we are moving the SMRAM memory regions to HOBs and allowing SMM access to consume these HOBs.

I will add the above info into commit message.

> 
> Storing anything SMM related outside SMRAM makes me nervous.
> I'd strongly suggest to avoid that.
> 
> It might be that in this specific case it is not a problem.  But it
> needs very careful review of the implications (which I have not done)
> and you have to hope you don't miss a possible attack vector, such as
> someone modifying the HOB and the firmware then storing SMM data + code
> outside SMRAM.
> 

Understand, but here is the case we can record the info in non-smram since PI spec exposes that, there is no difference the info retrieved from PPI/ non-smm Protocol or the non-smram.

Thanks,
Jiaxin






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



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

* Re: [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-25  1:54         ` Wu, Jiaxin
@ 2024-04-25  7:20           ` Gerd Hoffmann
  2024-04-25  7:41             ` Wu, Jiaxin
  0 siblings, 1 reply; 31+ messages in thread
From: Gerd Hoffmann @ 2024-04-25  7:20 UTC (permalink / raw)
  To: Wu, Jiaxin; +Cc: devel@edk2.groups.io, Ard Biesheuvel, Yao, Jiewen, Ni, Ray

  Hi,

> Let me explain more why need this change:
> 
> 1. The EFI_SMM_SMRAM_MEMORY_GUID HOB, as defined in the PI specification, is used to describe the SMRAM memory regions supported by the platform. This HOB should be produced during the memory detection phase to align with the PI spec.
> 
> 2. In addition to the memory reserved for ACPI S3 resume, an increasing number of features require reserving SMRAM for specific purposes, such as SmmRelocation. Other advanced features in Intel platforms also necessitate this. The implementation of these features varies and is entirely dependent on the platform. This is why an increasing number of platforms are adopting the EFI_SMM_SMRAM_MEMORY_GUID HOB for SMRAM description.
> 
> 3. It is crucial that the SMRAM information remains consistent when retrieved from the platform, whether through the SMM ACCESS PPI/Protocol or the EFI_SMM_SMRAM_MEMORY_GUID HOB. Inconsistencies can lead to unexpected issues, most commonly memory region conflicts.
> 
> 4. The SMM ACCESS PPI/Protocol can be naturally implemented for general use. The common approach is to utilize the EFI_SMM_SMRAM_MEMORY_GUID HOB. For reference, see the existing implementation in the EDK2 repository at edk2/UefiPayloadPkg/SmmAccessDxe/SmmAccessDxe.inf and edk2-platforms/Silicon/Intel/IntelSiliconPkg/Feature/SmmAccess/Library/PeiSmmAccessLib/PeiSmmAccessLib.inf. 
> 
> For the reasons mentioned, we are moving the SMRAM memory regions to HOBs and allowing SMM access to consume these HOBs.
> 
> I will add the above info into commit message.

Thanks.

Creating the EFI_SMM_SMRAM_MEMORY_GUID HOB should be moved to its own
function.  Also move over the comments from SmmAccess describing the
regions please.

Adding a reference to the PI spec section describing this would be good
too.

> > Storing anything SMM related outside SMRAM makes me nervous.
> > I'd strongly suggest to avoid that.
> > 
> > It might be that in this specific case it is not a problem.  But it
> > needs very careful review of the implications (which I have not done)
> > and you have to hope you don't miss a possible attack vector, such as
> > someone modifying the HOB and the firmware then storing SMM data + code
> > outside SMRAM.
> 
> Understand, but here is the case we can record the info in non-smram
> since PI spec exposes that, there is no difference the info retrieved
> from PPI/ non-smm Protocol or the non-smram.

Good point.

take care,
  Gerd



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



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

* Re: [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid
  2024-04-25  7:20           ` Gerd Hoffmann
@ 2024-04-25  7:41             ` Wu, Jiaxin
  0 siblings, 0 replies; 31+ messages in thread
From: Wu, Jiaxin @ 2024-04-25  7:41 UTC (permalink / raw)
  To: devel@edk2.groups.io, kraxel@redhat.com
  Cc: Ard Biesheuvel, Yao, Jiewen, Ni, Ray

> 
> Creating the EFI_SMM_SMRAM_MEMORY_GUID HOB should be moved to its
> own
> function.  Also move over the comments from SmmAccess describing the
> regions please.
> 
> Adding a reference to the PI spec section describing this would be good
> too.
> 

Got it, I will refine the patch to V4 based on your comments.

Thanks,
Jiaxin 


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



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

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

Thread overview: 31+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2024-04-18  6:55 [edk2-devel] [PATCH v3 00/13] Add SmmRelocationLib Wu, Jiaxin
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 01/13] UefiCpuPkg: Add SmmRelocationLib class Wu, Jiaxin
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 02/13] UefiCpuPkg/SmmRelocationLib: Add SmmRelocationLib library instance Wu, Jiaxin
2024-04-18  7:32   ` Ni, Ray
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 03/13] UefiCpuPkg/SmmRelocationLib: Rename global variables Wu, Jiaxin
2024-04-18  7:33   ` Ni, Ray
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 04/13] UefiCpuPkg/SmmRelocationLib: Avoid unnecessary memory allocation Wu, Jiaxin
2024-04-18  7:40   ` Ni, Ray
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 05/13] UefiCpuPkg/SmmRelocationLib: Remove unnecessary global variable Wu, Jiaxin
2024-04-18  7:48   ` Ni, Ray
2024-04-18  7:57     ` Wu, Jiaxin
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 06/13] UefiCpuPkg/SmmRelocationLib: Add library instance for AMD Wu, Jiaxin
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 07/13] OvmfPkg/SmmRelocationLib: Add library instance for OVMF Wu, Jiaxin
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 08/13] OvmfPkg/PlatformInitLib: Create gEfiSmmSmramMemoryGuid Wu, Jiaxin
2024-04-23  9:25   ` Gerd Hoffmann
2024-04-23 12:18     ` Wu, Jiaxin
2024-04-24 12:35       ` Gerd Hoffmann
2024-04-25  1:54         ` Wu, Jiaxin
2024-04-25  7:20           ` Gerd Hoffmann
2024-04-25  7:41             ` Wu, Jiaxin
2024-04-23 13:20     ` Wu, Jiaxin
2024-04-23 15:59     ` Wu, Jiaxin
2024-04-24 12:38       ` Gerd Hoffmann
2024-04-25  0:54         ` Wu, Jiaxin
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 09/13] OvmfPkg: Refine SmmAccess implementation Wu, Jiaxin
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 10/13] OvmfPkg/SmmCpuFeaturesLib: Check Smbase Relocation is done or not Wu, Jiaxin
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 11/13] OvmfPkg/PlatformPei: Relocate SmBases in PEI phase Wu, Jiaxin
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 12/13] UefiPayloadPkg/UefiPayloadPkg.dsc: Include SmmRelocationLib Wu, Jiaxin
2024-04-18  6:55 ` [edk2-devel] [PATCH v3 13/13] UefiCpuPkg/PiSmmCpuDxeSmm: Remove SmBases relocation logic Wu, Jiaxin
2024-04-18  8:15   ` Ni, Ray
2024-04-19  2:06     ` Wu, Jiaxin

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