[edk2-platforms][PATCH V2 1/1] Features/Intel/PlatformPayloadPkg: add platform payload FV


Guo Dong
 

From: Guo Dong <guo.dong@...>

UefiPayloadPkg in EDK2 repo was added SMM variable support for Intel
platform with SPI flash. But some of the modules for SMM variable are
Intel PCH specific (e.g. SPI library, SMM PCH module), so move these
modules into edk2-platforms repo.

A platform payload FV could be built from PlatformPayloadPkg which works
on Intel platforms (e.g.. ICX, APL, CML, CFL, KBL, TGL, ADL, etc.) with
SMM variable. This platform payload FV could be added into universal UEFI
payload built from EDK2 UefiPayloadPkg.

The steps to build a complete payload (use windows host as example):

set WORKSPACE=3Dc:\payload
set PACKAGES_PATH=3DC:\payload\edk2;C:\payload\edk2-platforms\Platform\Inte=
l;
C:\payload\edk2-platforms\Features\Intel;
edk2\edksetup.bat

python edk2\UefiPayloadPkg\UniversalPayloadBuild.py -t VS2019
-D SMM_SUPPORT=3DTRUE -DVARIABLE_SUPPORT=3DNONE

python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg.=
py
-t VS2019 -D SMM_VARIABLE=3DTRUE -s

The final UEFI payload generated at Build\UefiPayloadPkgX64\UniversalPayloa=
d.elf
if build success.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Ray Ni <ray.ni@...>
Cc: Sean Rhodes <sean@...>
Signed-off-by: Guo Dong <guo.dong@...>
Signed-off-by: Isaac Oram <isaac.w.oram@...>
---
Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc =
| 5 +++++
Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc =
| 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc =
| 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf =
| 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf =
| 7 ++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c =
| 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c =
| 1088 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h =
| 185 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c =
| 139 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf =
| 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h =
| 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h =
| 24 +++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h =
| 38 ++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h =
| 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h =
| 213 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc =
| 112 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf =
| 20 +++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf =
| 8 +++++++
Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c =
| 160 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.in=
f | 38 ++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c =
| 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++
Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf =
| 50 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c =
| 170 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h =
| 120 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h =
| 203 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c =
| 874 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf =
| 48 +++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c =
| 455 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h =
| 36 +++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf =
| 51 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec =
| 49 ++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc =
| 110 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf =
| 50 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py =
| 113 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Readme.md =
| 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++=
+++++++++++++++
35 files changed, 4887 insertions(+)

diff --git a/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc b/Fea=
tures/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
index 28530b8c67..17cc3224b7 100644
--- a/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
@@ -80,6 +80,11 @@
gUserAuthFeaturePkgTokenSpaceGuid.PcdUserAuthenticationFeatureEnable =
|TRUE=0D
gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable=
|TRUE=0D
=0D
+ #=0D
+ # Individual features=0D
+ #=0D
+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable =
|TRUE=0D
+=0D
#=0D
# PCD that are required to be set by the build target should be configured=
here for test purposes=0D
# These settings are only for the purposes of buildings, boards should fol=
low instructions in Readme files.=0D
diff --git a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc=
b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
index 2b36938df6..2a93ca1ec7 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
@@ -75,3 +75,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnab=
le =3D=3D TRUE=0D
!include VirtualKeyboardFeaturePkg/Include/VirtualKeyboardFeature.dsc=0D
!endif=0D
+=0D
+#=0D
+# Individual features=0D
+#=0D
+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable =3D=
=3D TRUE=0D
+ !include PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc=0D
+!endif=0D
diff --git a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.=
dsc b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
index e214175eda..8e98154f3e 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
@@ -53,6 +53,11 @@
UserAuthFeaturePkg/UserAuthFeaturePkg.dec=0D
VirtualKeyboardFeaturePkg/VirtualKeyboardFeaturePkg.dec=0D
=0D
+ #=0D
+ # Individual features=0D
+ #=0D
+ PlatformPayloadPkg/PlatformPayloadPkg.dec=0D
+=0D
#=0D
# The section below sets all PCDs to FALSE in this DSC file so the feature=
is not enabled by default.=0D
# Board can set PCDs to TRUE in its DSC file to enable a subset of advance=
d features=0D
@@ -76,6 +81,8 @@
gUserAuthFeaturePkgTokenSpaceGuid.PcdUserAuthenticationFeatureEnable =
|FALSE=0D
gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable=
|FALSE=0D
=0D
+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable =
|FALSE=0D
+=0D
#=0D
# There seems to be some build parsing odd behavior that requires this PCD=
to be specified even though=0D
# the *.fdf that consumes it is dependent on the feature flag.=0D
diff --git a/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf b/Fea=
tures/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
index 99089f9a7b..a0975d4d43 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
+++ b/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
@@ -76,3 +76,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnab=
le =3D=3D TRUE=0D
!include VirtualKeyboardFeaturePkg/Include/PostMemory.fdf=0D
!endif=0D
+=0D
+#=0D
+# Individual features=0D
+#=0D
+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable =3D=
=3D TRUE=0D
+ !include PlatformPayloadPkg/Include/PostMemory.fdf=0D
+!endif=0D
diff --git a/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf b/Feat=
ures/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
index 1db258446a..b2b821c9c4 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
+++ b/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
@@ -76,3 +76,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnab=
le =3D=3D TRUE=0D
!include VirtualKeyboardFeaturePkg/Include/PreMemory.fdf=0D
!endif=0D
+=0D
+#=0D
+# Individual features=0D
+#=0D
+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable =3D=
=3D TRUE=0D
+ !include PlatformPayloadPkg/Include/PreMemory.fdf=0D
+!endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c b/Features/Int=
el/PlatformPayloadPkg/Fvb/FvbInfo.c
new file mode 100644
index 0000000000..d6dcfeb4e1
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c
@@ -0,0 +1,77 @@
+/** @file=0D
+=0D
+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#include <PiDxe.h>=0D
+#include <Protocol/FirmwareVolumeBlock.h>=0D
+#include <Library/PcdLib.h>=0D
+#include <Library/DebugLib.h>=0D
+#include <Library/BaseLib.h>=0D
+#include <Guid/FirmwareFileSystem2.h>=0D
+#include <Guid/SystemNvDataGuid.h>=0D
+=0D
+#define FVB_MEDIA_BLOCK_SIZE 0x1000=0D
+=0D
+typedef struct {=0D
+ EFI_FIRMWARE_VOLUME_HEADER FvInfo;=0D
+ EFI_FV_BLOCK_MAP_ENTRY End[1];=0D
+} EFI_FVB2_MEDIA_INFO;=0D
+=0D
+//=0D
+// This data structure contains a template of FV header which is used to r=
estore=0D
+// Fv header if it's corrupted.=0D
+//=0D
+EFI_FVB2_MEDIA_INFO mFvbMediaInfo =3D {=0D
+ {=0D
+ { 0, }, // ZeroVector[16]=0D
+ EFI_SYSTEM_NV_DATA_FV_GUID,=0D
+ 0,=0D
+ EFI_FVH_SIGNATURE,=0D
+ 0x0004feff, // check PiFirmwareVolume.h for details on EFI_FVB_ATT=
RIBUTES_2=0D
+ sizeof (EFI_FIRMWARE_VOLUME_HEADER) + sizeof (EFI_FV_BLOCK_MAP_ENTRY),=
=0D
+ 0, // CheckSum which will be calucated dynamically.=0D
+ 0, // ExtHeaderOffset=0D
+ { 0, },=0D
+ EFI_FVH_REVISION,=0D
+ {=0D
+ {=0D
+ 0,=0D
+ FVB_MEDIA_BLOCK_SIZE,=0D
+ }=0D
+ }=0D
+ },=0D
+ {=0D
+ {=0D
+ 0,=0D
+ 0=0D
+ }=0D
+ }=0D
+};=0D
+=0D
+=0D
+/**=0D
+ Get a heathy FV header used for variable store recovery=0D
+=0D
+ @retval The FV header.=0D
+=0D
+**/=0D
+EFI_FIRMWARE_VOLUME_HEADER *=0D
+GetFvHeaderTemplate (=0D
+ VOID=0D
+ )=0D
+{=0D
+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;=0D
+ UINTN FvSize;=0D
+=0D
+ FvSize =3D PcdGet32 (PcdFlashNvStorageFtwSpareS=
ize) * 2;=0D
+ FvHeader =3D &mFvbMediaInfo.FvInfo;=0D
+ FvHeader->FvLength =3D FvSize;=0D
+ FvHeader->BlockMap[0].NumBlocks =3D (UINT32)(FvSize / FvHeader->BlockMap=
[0].Length);=0D
+ FvHeader->Checksum =3D 0;=0D
+ FvHeader->Checksum =3D CalculateCheckSum16 ((UINT16 *)FvHea=
der, FvHeader->HeaderLength);=0D
+=0D
+ return FvHeader;=0D
+}=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c b/Features/=
Intel/PlatformPayloadPkg/Fvb/FvbService.c
new file mode 100644
index 0000000000..1d19f3726b
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c
@@ -0,0 +1,1088 @@
+/** @file=0D
+Firmware Volume Block Driver to provide FVB service.=0D
+=0D
+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#include "FvbService.h"=0D
+=0D
+//=0D
+// Global variable for this FVB driver which contains=0D
+// the private data of all firmware volume block instances=0D
+//=0D
+FWB_GLOBAL mFvbModuleGlobal;=0D
+=0D
+FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate =3D {=0D
+ {=0D
+ {=0D
+ HARDWARE_DEVICE_PATH,=0D
+ HW_MEMMAP_DP,=0D
+ {=0D
+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH)),=0D
+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH) >> 8)=0D
+ }=0D
+ },=0D
+ EfiMemoryMappedIO,=0D
+ (EFI_PHYSICAL_ADDRESS)0,=0D
+ (EFI_PHYSICAL_ADDRESS)0,=0D
+ },=0D
+ {=0D
+ END_DEVICE_PATH_TYPE,=0D
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,=0D
+ {=0D
+ END_DEVICE_PATH_LENGTH,=0D
+ 0=0D
+ }=0D
+ }=0D
+};=0D
+=0D
+FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate =3D {=0D
+ {=0D
+ {=0D
+ MEDIA_DEVICE_PATH,=0D
+ MEDIA_PIWG_FW_VOL_DP,=0D
+ {=0D
+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH)),=0D
+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH) >> 8)=0D
+ }=0D
+ },=0D
+ { 0 }=0D
+ },=0D
+ {=0D
+ END_DEVICE_PATH_TYPE,=0D
+ END_ENTIRE_DEVICE_PATH_SUBTYPE,=0D
+ {=0D
+ END_DEVICE_PATH_LENGTH,=0D
+ 0=0D
+ }=0D
+ }=0D
+};=0D
+=0D
+EFI_FW_VOL_BLOCK_DEVICE mFvbDeviceTemplate =3D {=0D
+ FVB_DEVICE_SIGNATURE,=0D
+ NULL,=0D
+ 0, // Instance=0D
+ {=0D
+ FvbProtocolGetAttributes,=0D
+ FvbProtocolSetAttributes,=0D
+ FvbProtocolGetPhysicalAddress,=0D
+ FvbProtocolGetBlockSize,=0D
+ FvbProtocolRead,=0D
+ FvbProtocolWrite,=0D
+ FvbProtocolEraseBlocks,=0D
+ NULL=0D
+ } // FwVolBlockInstance=0D
+};=0D
+=0D
+/**=0D
+ Get the pointer to EFI_FW_VOL_INSTANCE from the buffer pointed=0D
+ by mFvbModuleGlobal.FvInstance based on a index.=0D
+ Each EFI_FW_VOL_INSTANCE is with variable length as=0D
+ we have a block map at the end of the EFI_FIRMWARE_VOLUME_HEADER.=0D
+=0D
+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.=0D
+=0D
+ @return A pointer to EFI_FW_VOL_INSTANCE.=0D
+=0D
+**/=0D
+EFI_FW_VOL_INSTANCE *=0D
+GetFvbInstance (=0D
+ IN UINTN Instance=0D
+ )=0D
+{=0D
+ EFI_FW_VOL_INSTANCE *FwhRecord;=0D
+=0D
+ if ( Instance >=3D mFvbModuleGlobal.NumFv ) {=0D
+ ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER);=0D
+ return NULL;=0D
+ }=0D
+=0D
+ //=0D
+ // Find the right instance of the FVB private data=0D
+ //=0D
+ FwhRecord =3D mFvbModuleGlobal.FvInstance;=0D
+ while ( Instance > 0 ) {=0D
+ FwhRecord =3D (EFI_FW_VOL_INSTANCE *)((UINTN)((UINT8 *)FwhRecord) +=0D
+ FwhRecord->VolumeHeader.HeaderLeng=
th +=0D
+ (sizeof (EFI_FW_VOL_INSTANCE) - si=
zeof (EFI_FIRMWARE_VOLUME_HEADER)));=0D
+ Instance--;=0D
+ }=0D
+=0D
+ return FwhRecord;=0D
+}=0D
+=0D
+/**=0D
+ Get the EFI_FVB_ATTRIBUTES_2 of a FV.=0D
+=0D
+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.=0D
+=0D
+ @retval EFI_FVB_ATTRIBUTES_2 of the FV identified by Instance.=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_FVB_ATTRIBUTES_2=0D
+FvbGetVolumeAttributes (=0D
+ IN UINTN Instance=0D
+ )=0D
+{=0D
+ EFI_FW_VOL_INSTANCE *FwInstance;=0D
+=0D
+ FwInstance =3D GetFvbInstance (Instance);=0D
+ ASSERT (FwInstance !=3D NULL);=0D
+=0D
+ if (FwInstance =3D=3D NULL) {=0D
+ return 0;=0D
+ }=0D
+=0D
+ return FwInstance->VolumeHeader.Attributes;=0D
+}=0D
+=0D
+/**=0D
+ Retrieves the starting address of an LBA in an FV. It also=0D
+ return a few other attribut of the FV.=0D
+=0D
+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.=0D
+ @param[in] Lba The logical block address=0D
+ @param[out] LbaAddress On output, contains the physical starting ad=
dress=0D
+ of the Lba=0D
+ @param[out] LbaLength On output, contains the length of the block=
=0D
+ @param[out] NumOfBlocks A pointer to a caller allocated UINTN in whi=
ch the=0D
+ number of consecutive blocks starting with L=
ba is=0D
+ returned. All blocks in this range have a si=
ze of=0D
+ BlockSize=0D
+=0D
+ @retval EFI_SUCCESS Successfully returns=0D
+ @retval EFI_INVALID_PARAMETER Instance not found=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+FvbGetLbaAddress (=0D
+ IN UINTN Instance,=0D
+ IN EFI_LBA Lba,=0D
+ OUT UINTN *LbaAddress,=0D
+ OUT UINTN *LbaLength,=0D
+ OUT UINTN *NumOfBlocks=0D
+ )=0D
+{=0D
+ UINT32 NumBlocks;=0D
+ UINT32 BlockLength;=0D
+ UINTN Offset;=0D
+ EFI_LBA StartLba;=0D
+ EFI_LBA NextLba;=0D
+ EFI_FW_VOL_INSTANCE *FwhInstance;=0D
+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;=0D
+=0D
+ //=0D
+ // Find the right instance of the FVB private data=0D
+ //=0D
+ FwhInstance =3D GetFvbInstance (Instance);=0D
+ if (FwhInstance =3D=3D NULL) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ StartLba =3D 0;=0D
+ Offset =3D 0;=0D
+ BlockMap =3D &FwhInstance->VolumeHeader.BlockMap[0];=0D
+ ASSERT (BlockMap !=3D NULL);=0D
+=0D
+ //=0D
+ // Parse the blockmap of the FV to find which map entry the Lba belongs =
to=0D
+ //=0D
+ while (TRUE) {=0D
+ if ( BlockMap !=3D NULL) {=0D
+ NumBlocks =3D BlockMap->NumBlocks;=0D
+ BlockLength =3D BlockMap->Length;=0D
+ }=0D
+=0D
+ if ((NumBlocks =3D=3D 0) || (BlockLength =3D=3D 0)) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ NextLba =3D StartLba + NumBlocks;=0D
+=0D
+ //=0D
+ // The map entry found=0D
+ //=0D
+ if ((Lba >=3D StartLba) && (Lba < NextLba)) {=0D
+ Offset =3D Offset + (UINTN)MultU64x32 ((Lba - StartLba), BlockLength=
);=0D
+ if (LbaAddress !=3D NULL) {=0D
+ *LbaAddress =3D FwhInstance->FvBase + Offset;=0D
+ }=0D
+=0D
+ if (LbaLength !=3D NULL) {=0D
+ *LbaLength =3D BlockLength;=0D
+ }=0D
+=0D
+ if (NumOfBlocks !=3D NULL) {=0D
+ *NumOfBlocks =3D (UINTN)(NextLba - Lba);=0D
+ }=0D
+=0D
+ return EFI_SUCCESS;=0D
+ }=0D
+=0D
+ StartLba =3D NextLba;=0D
+ Offset =3D Offset + NumBlocks * BlockLength;=0D
+ BlockMap++;=0D
+ }=0D
+}=0D
+=0D
+/**=0D
+ Reads specified number of bytes into a buffer from the specified block=0D
+=0D
+ @param[in] Instance The FV instance to be read from=0D
+ @param[in] Lba The logical block address to be read fro=
m=0D
+ @param[in] BlockOffset Offset into the block at which to begin =
reading=0D
+ @param[in, out] NumBytes Pointer that on input contains the total=
size of=0D
+ the buffer. On output, it contains the t=
otal number=0D
+ of bytes read=0D
+ @param[in] Buffer Pointer to a caller allocated buffer tha=
t will be=0D
+ used to hold the data read=0D
+=0D
+=0D
+ @retval EFI_SUCCESS The firmware volume was read success=
fully and=0D
+ contents are in Buffer=0D
+ @retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boundary=
. On output,=0D
+ NumBytes contains the total number o=
f bytes returned=0D
+ in Buffer=0D
+ @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDi=
sabled state=0D
+ @retval EFI_DEVICE_ERROR The block device is not functioning =
correctly and=0D
+ could not be read=0D
+ @retval EFI_INVALID_PARAMETER Instance not found, or NumBytes, B=
uffer are NULL=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+FvbReadBlock (=0D
+ IN UINTN Instance,=0D
+ IN EFI_LBA Lba,=0D
+ IN UINTN BlockOffset,=0D
+ IN OUT UINTN *NumBytes,=0D
+ IN UINT8 *Buffer=0D
+ )=0D
+{=0D
+ EFI_FVB_ATTRIBUTES_2 Attributes;=0D
+ UINTN LbaAddress;=0D
+ UINTN LbaLength;=0D
+ EFI_STATUS Status;=0D
+ EFI_STATUS ReadStatus;=0D
+=0D
+ if ((NumBytes =3D=3D NULL) || (Buffer =3D=3D NULL)) {=0D
+ return (EFI_INVALID_PARAMETER);=0D
+ }=0D
+=0D
+ if (*NumBytes =3D=3D 0) {=0D
+ return (EFI_INVALID_PARAMETER);=0D
+ }=0D
+=0D
+ Status =3D FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NUL=
L);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+=0D
+ Attributes =3D FvbGetVolumeAttributes (Instance);=0D
+=0D
+ if ((Attributes & EFI_FVB2_READ_STATUS) =3D=3D 0) {=0D
+ return (EFI_ACCESS_DENIED);=0D
+ }=0D
+=0D
+ if (BlockOffset > LbaLength) {=0D
+ return (EFI_INVALID_PARAMETER);=0D
+ }=0D
+=0D
+ if (LbaLength < (*NumBytes + BlockOffset)) {=0D
+ *NumBytes =3D (UINT32)(LbaLength - BlockOffset);=0D
+ Status =3D EFI_BAD_BUFFER_SIZE;=0D
+ }=0D
+=0D
+ ReadStatus =3D LibFvbFlashDeviceRead (LbaAddress + BlockOffset, NumBytes=
, Buffer);=0D
+ if (EFI_ERROR (ReadStatus)) {=0D
+ return ReadStatus;=0D
+ }=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Writes specified number of bytes from the input buffer to the block=0D
+=0D
+ @param[in] Instance The FV instance to be written to=0D
+ @param[in] Lba The starting logical block index to write =
to=0D
+ @param[in] BlockOffset Offset into the block at which to begin wr=
iting=0D
+ @param[in, out] NumBytes Pointer that on input contains the total s=
ize of=0D
+ the buffer. On output, it contains the to=
tal number=0D
+ of bytes actually written=0D
+ @param[in] Buffer Pointer to a caller allocated buffer that =
contains=0D
+ the source for the write=0D
+ @retval EFI_SUCCESS The firmware volume was written successf=
ully=0D
+ @retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundary. O=
n output,=0D
+ NumBytes contains the total number of by=
tes=0D
+ actually written=0D
+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisab=
led state=0D
+ @retval EFI_DEVICE_ERROR The block device is not functioning corr=
ectly and=0D
+ could not be written=0D
+ @retval EFI_INVALID_PARAMETER Instance not found, or NumBytes, Buffe=
r are NULL=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+FvbWriteBlock (=0D
+ IN UINTN Instance,=0D
+ IN EFI_LBA Lba,=0D
+ IN UINTN BlockOffset,=0D
+ IN OUT UINTN *NumBytes,=0D
+ IN UINT8 *Buffer=0D
+ )=0D
+{=0D
+ EFI_FVB_ATTRIBUTES_2 Attributes;=0D
+ UINTN LbaAddress;=0D
+ UINTN LbaLength;=0D
+ EFI_STATUS Status;=0D
+=0D
+ if ((NumBytes =3D=3D NULL) || (Buffer =3D=3D NULL)) {=0D
+ return (EFI_INVALID_PARAMETER);=0D
+ }=0D
+=0D
+ if (*NumBytes =3D=3D 0) {=0D
+ return (EFI_INVALID_PARAMETER);=0D
+ }=0D
+=0D
+ Status =3D FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NUL=
L);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+=0D
+ //=0D
+ // Check if the FV is write enabled=0D
+ //=0D
+ Attributes =3D FvbGetVolumeAttributes (Instance);=0D
+ if ((Attributes & EFI_FVB2_WRITE_STATUS) =3D=3D 0) {=0D
+ return EFI_ACCESS_DENIED;=0D
+ }=0D
+=0D
+ //=0D
+ // Perform boundary checks and adjust NumBytes=0D
+ //=0D
+ if (BlockOffset > LbaLength) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ if ( LbaLength < (*NumBytes + BlockOffset)) {=0D
+ DEBUG ((=0D
+ DEBUG_ERROR,=0D
+ "FvWriteBlock: Reducing Numbytes from 0x%x to 0x%x\n",=0D
+ *NumBytes,=0D
+ (UINT32)(LbaLength - BlockOffset)=0D
+ ));=0D
+ *NumBytes =3D (UINT32)(LbaLength - BlockOffset);=0D
+ return EFI_BAD_BUFFER_SIZE;=0D
+ }=0D
+=0D
+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, FALSE);=0D
+ Status =3D LibFvbFlashDeviceWrite (LbaAddress + BlockOffset, NumBytes, B=
uffer);=0D
+=0D
+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, TRUE);=0D
+ WriteBackInvalidateDataCacheRange ((VOID *)(LbaAddress + BlockOffset), *=
NumBytes);=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Erases and initializes a firmware volume block=0D
+=0D
+ @param[in] Instance The FV instance to be erased=0D
+ @param[in] Lba The logical block index to be erased=0D
+=0D
+ @retval EFI_SUCCESS The erase request was successfully completed=
=0D
+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled =
state=0D
+ @retval EFI_DEVICE_ERROR The block device is not functioning correctl=
y and=0D
+ could not be written. Firmware device may ha=
ve been=0D
+ partially erased=0D
+ @retval EFI_INVALID_PARAMETER Instance not found=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+FvbEraseBlock (=0D
+ IN UINTN Instance,=0D
+ IN EFI_LBA Lba=0D
+ )=0D
+{=0D
+ EFI_FVB_ATTRIBUTES_2 Attributes;=0D
+ UINTN LbaAddress;=0D
+ UINTN LbaLength;=0D
+ EFI_STATUS Status;=0D
+=0D
+ //=0D
+ // Check if the FV is write enabled=0D
+ //=0D
+ Attributes =3D FvbGetVolumeAttributes (Instance);=0D
+=0D
+ if ((Attributes & EFI_FVB2_WRITE_STATUS) =3D=3D 0) {=0D
+ return (EFI_ACCESS_DENIED);=0D
+ }=0D
+=0D
+ //=0D
+ // Get the starting address of the block for erase.=0D
+ //=0D
+ Status =3D FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NUL=
L);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+=0D
+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, FALSE);=0D
+=0D
+ Status =3D LibFvbFlashDeviceBlockErase (LbaAddress, LbaLength);=0D
+=0D
+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, TRUE);=0D
+=0D
+ WriteBackInvalidateDataCacheRange ((VOID *)LbaAddress, LbaLength);=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Modifies the current settings of the firmware volume according to the=0D
+ input parameter, and returns the new setting of the volume=0D
+=0D
+ @param[in] Instance The FV instance whose attributes is go=
ing to be=0D
+ modified=0D
+ @param[in, out] Attributes On input, it is a pointer to EFI_FVB_A=
TTRIBUTES_2=0D
+ containing the desired firmware volume=
settings.=0D
+ On successful return, it contains the =
new settings=0D
+ of the firmware volume=0D
+=0D
+ @retval EFI_SUCCESS Successfully returns=0D
+ @retval EFI_ACCESS_DENIED The volume setting is locked and canno=
t be modified=0D
+ @retval EFI_INVALID_PARAMETER Instance not found, or The attributes =
requested are=0D
+ in conflict with the capabilities as d=
eclared in the=0D
+ firmware volume header=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+FvbSetVolumeAttributes (=0D
+ IN UINTN Instance,=0D
+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes=0D
+ )=0D
+{=0D
+ EFI_FW_VOL_INSTANCE *FwhInstance;=0D
+ EFI_FVB_ATTRIBUTES_2 OldAttributes;=0D
+ EFI_FVB_ATTRIBUTES_2 *AttribPtr;=0D
+ EFI_FVB_ATTRIBUTES_2 UnchangedAttributes;=0D
+ UINT32 Capabilities;=0D
+ UINT32 OldStatus;=0D
+ UINT32 NewStatus;=0D
+=0D
+ //=0D
+ // Find the right instance of the FVB private data=0D
+ //=0D
+ FwhInstance =3D GetFvbInstance (Instance);=0D
+ if (FwhInstance =3D=3D NULL) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ AttribPtr =3D (EFI_FVB_ATTRIBUTES_2 *)&(FwhInstance->VolumeHeader.Attrib=
utes);=0D
+ ASSERT (AttribPtr !=3D NULL);=0D
+ if ( AttribPtr =3D=3D NULL) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ OldAttributes =3D *AttribPtr;=0D
+ Capabilities =3D OldAttributes & EFI_FVB2_CAPABILITIES;=0D
+ OldStatus =3D OldAttributes & EFI_FVB2_STATUS;=0D
+ NewStatus =3D *Attributes & EFI_FVB2_STATUS;=0D
+=0D
+ UnchangedAttributes =3D EFI_FVB2_READ_DISABLED_CAP | \=0D
+ EFI_FVB2_READ_ENABLED_CAP | \=0D
+ EFI_FVB2_WRITE_DISABLED_CAP | \=0D
+ EFI_FVB2_WRITE_ENABLED_CAP | \=0D
+ EFI_FVB2_LOCK_CAP | \=0D
+ EFI_FVB2_STICKY_WRITE | \=0D
+ EFI_FVB2_MEMORY_MAPPED | \=0D
+ EFI_FVB2_ERASE_POLARITY | \=0D
+ EFI_FVB2_READ_LOCK_CAP | \=0D
+ EFI_FVB2_WRITE_LOCK_CAP | \=0D
+ EFI_FVB2_ALIGNMENT;=0D
+=0D
+ //=0D
+ // Some attributes of FV is read only can *not* be set=0D
+ //=0D
+ if ((OldAttributes & UnchangedAttributes) ^ (*Attributes & UnchangedAttr=
ibutes)) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ //=0D
+ // If firmware volume is locked, no status bit can be updated=0D
+ //=0D
+ if ((OldAttributes & EFI_FVB2_LOCK_STATUS) !=3D 0) {=0D
+ if ((OldStatus ^ NewStatus) !=3D 0) {=0D
+ return EFI_ACCESS_DENIED;=0D
+ }=0D
+ }=0D
+=0D
+ //=0D
+ // Test read disable=0D
+ //=0D
+ if ((Capabilities & EFI_FVB2_READ_DISABLED_CAP) =3D=3D 0) {=0D
+ if ((NewStatus & EFI_FVB2_READ_STATUS) =3D=3D 0) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+ }=0D
+=0D
+ //=0D
+ // Test read enable=0D
+ //=0D
+ if ((Capabilities & EFI_FVB2_READ_ENABLED_CAP) =3D=3D 0) {=0D
+ if ((NewStatus & EFI_FVB2_READ_STATUS) !=3D 0) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+ }=0D
+=0D
+ //=0D
+ // Test write disable=0D
+ //=0D
+ if ((Capabilities & EFI_FVB2_WRITE_DISABLED_CAP) =3D=3D 0) {=0D
+ if ((NewStatus & EFI_FVB2_WRITE_STATUS) =3D=3D 0) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+ }=0D
+=0D
+ //=0D
+ // Test write enable=0D
+ //=0D
+ if ((Capabilities & EFI_FVB2_WRITE_ENABLED_CAP) =3D=3D 0) {=0D
+ if ((NewStatus & EFI_FVB2_WRITE_STATUS) !=3D 0) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+ }=0D
+=0D
+ //=0D
+ // Test lock=0D
+ //=0D
+ if ((Capabilities & EFI_FVB2_LOCK_CAP) =3D=3D 0) {=0D
+ if ((NewStatus & EFI_FVB2_LOCK_STATUS) !=3D 0) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+ }=0D
+=0D
+ *AttribPtr =3D (*AttribPtr) & (0xFFFFFFFF & (~EFI_FVB2_STATUS));=0D
+ *AttribPtr =3D (*AttribPtr) | NewStatus;=0D
+ *Attributes =3D *AttribPtr;=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Retrieves the physical address of the device.=0D
+=0D
+ @param[in] This A pointer to EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL.=0D
+ @param[out] Address Output buffer containing the address.=0D
+=0D
+ @retval EFI_SUCCESS The function always return successfully.=0D
+ @retval EFI_INVALID_PARAMETER Instance not found.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolGetPhysicalAddress (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ OUT EFI_PHYSICAL_ADDRESS *Address=0D
+ )=0D
+{=0D
+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;=0D
+ EFI_FW_VOL_INSTANCE *FwhInstance;=0D
+=0D
+ FvbDevice =3D FVB_DEVICE_FROM_THIS (This);=0D
+ FwhInstance =3D GetFvbInstance (FvbDevice->Instance);=0D
+ if (FwhInstance =3D=3D NULL) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ *Address =3D FwhInstance->FvBase;=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Retrieve the size of a logical block=0D
+=0D
+ @param[in] This Calling context=0D
+ @param[in] Lba Indicates which block to return the size for.=0D
+ @param[out] BlockSize A pointer to a caller allocated UINTN in which=0D
+ the size of the block is returned=0D
+ @param[out] NumOfBlocks A pointer to a caller allocated UINTN in which t=
he=0D
+ number of consecutive blocks starting with Lba i=
s=0D
+ returned. All blocks in this range have a size o=
f=0D
+ BlockSize=0D
+=0D
+ @retval EFI_SUCCESS The function always return successfully.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolGetBlockSize (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ IN EFI_LBA Lba,=0D
+ OUT UINTN *BlockSize,=0D
+ OUT UINTN *NumOfBlocks=0D
+ )=0D
+{=0D
+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;=0D
+=0D
+ FvbDevice =3D FVB_DEVICE_FROM_THIS (This);=0D
+ return FvbGetLbaAddress (FvbDevice->Instance, Lba, NULL, BlockSize, NumO=
fBlocks);=0D
+}=0D
+=0D
+/**=0D
+ Retrieves Volume attributes. No polarity translations are done.=0D
+=0D
+ @param[in] This Calling context=0D
+ @param[out] Attributes Output buffer which contains attributes=0D
+=0D
+ @retval EFI_SUCCESS The function always return successfully.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolGetAttributes (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes=0D
+ )=0D
+{=0D
+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;=0D
+=0D
+ FvbDevice =3D FVB_DEVICE_FROM_THIS (This);=0D
+ *Attributes =3D FvbGetVolumeAttributes (FvbDevice->Instance);=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Sets Volume attributes. No polarity translations are done.=0D
+=0D
+ @param[in] This Calling context=0D
+ @param[in, out] Attributes Output buffer which contains attributes=0D
+=0D
+ @retval EFI_SUCCESS The function always return successfully.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolSetAttributes (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;=0D
+=0D
+ FvbDevice =3D FVB_DEVICE_FROM_THIS (This);=0D
+ Status =3D FvbSetVolumeAttributes (FvbDevice->Instance, Attributes);=
=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ This function erases one or more blocks as denoted by the=0D
+ variable argument list. The entire parameter list of blocks must be veri=
fied=0D
+ prior to erasing any blocks. If a block is requested that does not exis=
t=0D
+ within the associated firmware volume (it has a larger index than the la=
st=0D
+ block of the firmware volume), the EraseBlock() function must return=0D
+ EFI_INVALID_PARAMETER without modifying the contents of the firmware vol=
ume.=0D
+=0D
+ @param[in] This Calling context=0D
+ @param[in] ... Starting LBA followed by Number of Lba to erase.=
=0D
+ a -1 to terminate the list.=0D
+=0D
+ @retval EFI_SUCCESS The erase request was successfully completed=0D
+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled st=
ate=0D
+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly =
and=0D
+ could not be written. Firmware device may have=
been=0D
+ partially erased=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolEraseBlocks (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ ...=0D
+ )=0D
+{=0D
+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;=0D
+ EFI_FW_VOL_INSTANCE *FwhInstance;=0D
+ UINTN NumOfBlocks;=0D
+ VA_LIST args;=0D
+ EFI_LBA StartingLba;=0D
+ UINTN NumOfLba;=0D
+ EFI_STATUS Status;=0D
+=0D
+ FvbDevice =3D FVB_DEVICE_FROM_THIS (This);=0D
+ FwhInstance =3D GetFvbInstance (FvbDevice->Instance);=0D
+ if (FwhInstance =3D=3D NULL) {=0D
+ return EFI_OUT_OF_RESOURCES;=0D
+ }=0D
+=0D
+ NumOfBlocks =3D FwhInstance->NumOfBlocks;=0D
+ VA_START (args, This);=0D
+=0D
+ do {=0D
+ StartingLba =3D VA_ARG (args, EFI_LBA);=0D
+ if ( StartingLba =3D=3D EFI_LBA_LIST_TERMINATOR ) {=0D
+ break;=0D
+ }=0D
+=0D
+ NumOfLba =3D VA_ARG (args, UINT32);=0D
+=0D
+ //=0D
+ // Check input parameters=0D
+ //=0D
+ if (NumOfLba =3D=3D 0) {=0D
+ VA_END (args);=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ if ((StartingLba + NumOfLba) > NumOfBlocks ) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+ } while (1);=0D
+=0D
+ VA_END (args);=0D
+=0D
+ VA_START (args, This);=0D
+ do {=0D
+ StartingLba =3D VA_ARG (args, EFI_LBA);=0D
+ if (StartingLba =3D=3D EFI_LBA_LIST_TERMINATOR) {=0D
+ break;=0D
+ }=0D
+=0D
+ NumOfLba =3D VA_ARG (args, UINT32);=0D
+=0D
+ while ( NumOfLba > 0 ) {=0D
+ Status =3D FvbEraseBlock (FvbDevice->Instance, StartingLba);=0D
+ if ( EFI_ERROR (Status)) {=0D
+ VA_END (args);=0D
+ return Status;=0D
+ }=0D
+=0D
+ StartingLba++;=0D
+ NumOfLba--;=0D
+ }=0D
+ } while (1);=0D
+=0D
+ VA_END (args);=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Writes data beginning at Lba:Offset from FV. The write terminates either=
=0D
+ when *NumBytes of data have been written, or when a block boundary is=0D
+ reached. *NumBytes is updated to reflect the actual number of bytes=0D
+ written. The write opertion does not include erase. This routine will=0D
+ attempt to write only the specified bytes. If the writes do not stick,=0D
+ it will return an error.=0D
+=0D
+ @param[in] This Calling context=0D
+ @param[in] Lba Block in which to begin write=0D
+ @param[in] Offset Offset in the block at which to begin write=0D
+ @param[in,out] NumBytes On input, indicates the requested write size. =
On=0D
+ output, indicates the actual number of bytes w=
ritten=0D
+ @param[in] Buffer Buffer containing source data for the write.=0D
+=0D
+ @retval EFI_SUCCESS The firmware volume was written successful=
ly=0D
+ @retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundary. On =
output,=0D
+ NumBytes contains the total number of byte=
s=0D
+ actually written=0D
+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisable=
d state=0D
+ @retval EFI_DEVICE_ERROR The block device is not functioning correc=
tly and=0D
+ could not be written=0D
+ @retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolWrite (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ IN EFI_LBA Lba,=0D
+ IN UINTN Offset,=0D
+ IN OUT UINTN *NumBytes,=0D
+ IN UINT8 *Buffer=0D
+ )=0D
+{=0D
+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;=0D
+ EFI_STATUS Status;=0D
+=0D
+ FvbDevice =3D FVB_DEVICE_FROM_THIS (This);=0D
+ Status =3D FvbWriteBlock (FvbDevice->Instance, Lba, Offset, NumBytes,=
Buffer);=0D
+ DEBUG ((=0D
+ DEBUG_VERBOSE,=0D
+ "FvbWrite: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0x%x Status=
:%r\n",=0D
+ Lba,=0D
+ Offset,=0D
+ *NumBytes,=0D
+ Buffer,=0D
+ Status=0D
+ ));=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Reads data beginning at Lba:Offset from FV. The Read terminates either=0D
+ when *NumBytes of data have been read, or when a block boundary is=0D
+ reached. *NumBytes is updated to reflect the actual number of bytes=0D
+ written. The write opertion does not include erase. This routine will=0D
+ attempt to write only the specified bytes. If the writes do not stick,=0D
+ it will return an error.=0D
+=0D
+ @param[in] This Calling context=0D
+ @param[in] Lba Block in which to begin write=0D
+ @param[in] Offset Offset in the block at which to begin write=0D
+ @param[in,out] NumBytes On input, indicates the requested write size. =
On=0D
+ output, indicates the actual number of bytes w=
ritten=0D
+ @param[out] Buffer Buffer containing source data for the write.=0D
+=0D
+=0D
+Returns:=0D
+ @retval EFI_SUCCESS The firmware volume was read successfully =
and=0D
+ contents are in Buffer=0D
+ @retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boundary. On o=
utput,=0D
+ NumBytes contains the total number of byte=
s returned=0D
+ in Buffer=0D
+ @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled=
state=0D
+ @retval EFI_DEVICE_ERROR The block device is not functioning correc=
tly and=0D
+ could not be read=0D
+ @retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolRead (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ IN EFI_LBA Lba,=0D
+ IN UINTN Offset,=0D
+ IN OUT UINTN *NumBytes,=0D
+ OUT UINT8 *Buffer=0D
+ )=0D
+{=0D
+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;=0D
+ EFI_STATUS Status;=0D
+=0D
+ FvbDevice =3D FVB_DEVICE_FROM_THIS (This);=0D
+ Status =3D FvbReadBlock (FvbDevice->Instance, Lba, Offset, NumBytes, =
Buffer);=0D
+ DEBUG ((=0D
+ DEBUG_VERBOSE,=0D
+ "FvbRead: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0x%x, Status=
:%r\n",=0D
+ Lba,=0D
+ Offset,=0D
+ *NumBytes,=0D
+ Buffer,=0D
+ Status=0D
+ ));=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Check the integrity of firmware volume header in FvBase=0D
+=0D
+ @param[in] FvBase A pointer to firmware volume base address.=0D
+=0D
+ @retval TRUE The firmware volume is consistent=0D
+ @retval FALSE The firmware volume has corrupted.=0D
+=0D
+**/=0D
+BOOLEAN=0D
+IsFvHeaderValid (=0D
+ IN EFI_PHYSICAL_ADDRESS FvBase=0D
+ )=0D
+{=0D
+ UINT16 Sum;=0D
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;=0D
+=0D
+ FwVolHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvBase;=0D
+ if (FvBase =3D=3D PcdGet32 (PcdFlashNvStorageVariableBase)) {=0D
+ if (CompareMem (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid,=
sizeof (EFI_GUID)) !=3D 0 ) {=0D
+ DEBUG ((DEBUG_INFO, " --FileSystemGuid not match: %g\n", &FwVolHead=
er->FileSystemGuid));=0D
+ return FALSE;=0D
+ }=0D
+ } else {=0D
+ if (CompareMem (&FwVolHeader->FileSystemGuid, &gEfiFirmwareFileSystem2=
Guid, sizeof (EFI_GUID)) !=3D 0 ) {=0D
+ DEBUG ((DEBUG_INFO, " --not expected guid.\n"));=0D
+ return FALSE;=0D
+ }=0D
+ }=0D
+=0D
+ if ((FwVolHeader->Revision !=3D EFI_FVH_REVISION) ||=0D
+ (FwVolHeader->Signature !=3D EFI_FVH_SIGNATURE) ||=0D
+ (FwVolHeader->FvLength =3D=3D ((UINTN)-1)) ||=0D
+ ((FwVolHeader->HeaderLength & 0x01) !=3D 0))=0D
+ {=0D
+ DEBUG ((DEBUG_INFO, " -- >Revision =3D 0x%x, Signature =3D 0x%x\n", F=
wVolHeader->Revision, FwVolHeader->Signature));=0D
+ DEBUG ((DEBUG_INFO, " -- >FvLength =3D 0x%lx, HeaderLength =3D 0x%x\n=
", FwVolHeader->FvLength, FwVolHeader->HeaderLength));=0D
+ return FALSE;=0D
+ }=0D
+=0D
+ Sum =3D CalculateSum16 ((UINT16 *)FwVolHeader, FwVolHeader->HeaderLength=
);=0D
+ if (Sum !=3D 0) {=0D
+ DEBUG ((DEBUG_INFO, "error: checksum: 0x%04X (expect 0x0)\n", Sum));=0D
+ return FALSE;=0D
+ }=0D
+=0D
+ return TRUE;=0D
+}=0D
+=0D
+/**=0D
+ Get intial variable data.=0D
+=0D
+ @param[out] VarData Valid variable data.=0D
+ @param[out] VarSize Valid variable size.=0D
+=0D
+ @retval RETURN_SUCCESS Successfully found initial variable data.=
=0D
+ @retval RETURN_NOT_FOUND Failed to find the variable data file from=
FV.=0D
+ @retval EFI_INVALID_PARAMETER VarData or VarSize is null.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+GetInitialVariableData (=0D
+ OUT VOID **VarData,=0D
+ OUT UINTN *VarSize=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ VOID *ImageData;=0D
+ UINTN ImageSize;=0D
+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;=0D
+ VARIABLE_STORE_HEADER *VariableStore;=0D
+ AUTHENTICATED_VARIABLE_HEADER *Variable;=0D
+ UINTN VariableSize;=0D
+ UINTN VarEndAddr;=0D
+=0D
+ if ((VarData =3D=3D NULL) || (VarSize =3D=3D NULL)) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ Status =3D GetSectionFromAnyFv (PcdGetPtr (PcdNvsDataFile), EFI_SECTION_=
RAW, 0, &ImageData, &ImageSize);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+=0D
+ FvHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *)ImageData;=0D
+ VariableStore =3D (VARIABLE_STORE_HEADER *)((UINT8 *)ImageData + FvHeade=
r->HeaderLength);=0D
+ VarEndAddr =3D (UINTN)VariableStore + VariableStore->Size;=0D
+ Variable =3D (AUTHENTICATED_VARIABLE_HEADER *)HEADER_ALIGN (Variabl=
eStore + 1);=0D
+ *VarData =3D (VOID *)Variable;=0D
+ while (((UINTN)Variable < VarEndAddr)) {=0D
+ if (Variable->StartId !=3D VARIABLE_DATA) {=0D
+ break;=0D
+ }=0D
+=0D
+ VariableSize =3D sizeof (AUTHENTICATED_VARIABLE_HEADER) + Variable->Da=
taSize + Variable->NameSize;=0D
+ Variable =3D (AUTHENTICATED_VARIABLE_HEADER *)HEADER_ALIGN ((UINTN=
)Variable + VariableSize);=0D
+ }=0D
+=0D
+ *VarSize =3D (UINTN)Variable - HEADER_ALIGN (VariableStore + 1);=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ The function does the necessary initialization work for=0D
+ Firmware Volume Block Driver.=0D
+=0D
+ @retval EFI_SUCCESS This funtion always return EFI_SUCCESS.=0D
+ It will ASSERT on errors.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+FvbInitialize (=0D
+ VOID=0D
+ )=0D
+{=0D
+ EFI_FW_VOL_INSTANCE *FwVolInstance;=0D
+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;=0D
+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;=0D
+ EFI_PHYSICAL_ADDRESS BaseAddress;=0D
+ UINTN WriteAddr;=0D
+ EFI_STATUS Status;=0D
+ UINTN BufferSize;=0D
+ UINTN Length;=0D
+ VARIABLE_STORE_HEADER VariableStore;=0D
+ VOID *VarData;=0D
+=0D
+ BaseAddress =3D PcdGet32 (PcdFlashNvStorageVariableBase);=0D
+ FvHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)BaseAddress;=0D
+=0D
+ //=0D
+ // Check FV header and variable store header=0D
+ //=0D
+ if (!IsFvHeaderValid (BaseAddress)) {=0D
+ //=0D
+ // Write back a healthy FV header=0D
+ //=0D
+ DEBUG ((DEBUG_ERROR, "Fvb: Writing back a healthy FV header: 0x%lx\n",=
BaseAddress));=0D
+ FvHeader =3D GetFvHeaderTemplate ();=0D
+ LibFvbFlashDeviceBlockLock ((UINTN)BaseAddress, FvHeader->BlockMap->Le=
ngth, FALSE);=0D
+=0D
+ Status =3D LibFvbFlashDeviceBlockErase ((UINTN)BaseAddress, FvHeader->=
BlockMap->Length);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ Length =3D FvHeader->HeaderLength;=0D
+ WriteAddr =3D (UINTN)BaseAddress;=0D
+ Status =3D LibFvbFlashDeviceWrite (WriteAddr, &Length, (UINT8 *)Fv=
Header);=0D
+ WriteAddr +=3D Length;=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ //=0D
+ // Write back variable store header=0D
+ //=0D
+ VariableStore.Size =3D PcdGet32 (PcdFlashNvStorageVariableSize) - Fv=
Header->HeaderLength;=0D
+ VariableStore.Format =3D VARIABLE_STORE_FORMATTED;=0D
+ VariableStore.State =3D VARIABLE_STORE_HEALTHY;=0D
+ CopyGuid (&VariableStore.Signature, &gEfiAuthenticatedVariableGuid);=0D
+ BufferSize =3D sizeof (VARIABLE_STORE_HEADER);=0D
+ Status =3D LibFvbFlashDeviceWrite (WriteAddr, &BufferSize, (UINT8 =
*)&VariableStore);=0D
+ WriteAddr +=3D BufferSize;=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ //=0D
+ // Write initial variable data if found=0D
+ //=0D
+ Status =3D GetInitialVariableData (&VarData, &Length);=0D
+ if (!EFI_ERROR (Status)) {=0D
+ Status =3D LibFvbFlashDeviceWrite (WriteAddr, &Length, (UINT8 *)VarD=
ata);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+ }=0D
+=0D
+ LibFvbFlashDeviceBlockLock ((UINTN)BaseAddress, FvHeader->BlockMap->Le=
ngth, TRUE);=0D
+ WriteBackInvalidateDataCacheRange ((VOID *)(UINTN)BaseAddress, FvHeade=
r->BlockMap->Length);=0D
+ }=0D
+=0D
+ //=0D
+ // Create a new FW volume instance for NVS variable=0D
+ //=0D
+ BufferSize =3D FvHeader->HeaderLength + sizeof (EFI_FW_VOL_INSTANCE) =
- sizeof (EFI_FIRMWARE_VOLUME_HEADER);=0D
+ FwVolInstance =3D (EFI_FW_VOL_INSTANCE *)AllocateRuntimeZeroPool (Buffer=
Size);=0D
+ if (FwVolInstance =3D=3D NULL) {=0D
+ return EFI_OUT_OF_RESOURCES;=0D
+ }=0D
+=0D
+ FwVolInstance->FvBase =3D (UINTN)BaseAddress;=0D
+ CopyMem (&FwVolInstance->VolumeHeader, FvHeader, FvHeader->HeaderLength)=
;=0D
+=0D
+ //=0D
+ // Process the block map for each FV. Assume it has same block size.=0D
+ //=0D
+ FwVolInstance->NumOfBlocks =3D 0;=0D
+ FvHeader =3D &FwVolInstance->VolumeHeader;=0D
+ for (BlockMap =3D FvHeader->BlockMap; BlockMap->NumBlocks !=3D 0; BlockM=
ap++) {=0D
+ FwVolInstance->NumOfBlocks +=3D BlockMap->NumBlocks;=0D
+ }=0D
+=0D
+ //=0D
+ // Add a FVB Protocol Instance=0D
+ //=0D
+ Status =3D InstallFvbProtocol (FwVolInstance, mFvbModuleGlobal.NumFv);=0D
+ mFvbModuleGlobal.NumFv++;=0D
+ mFvbModuleGlobal.FvInstance =3D FwVolInstance;=0D
+=0D
+ return Status;=0D
+}=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h b/Features/=
Intel/PlatformPayloadPkg/Fvb/FvbService.h
new file mode 100644
index 0000000000..54428d8391
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h
@@ -0,0 +1,185 @@
+/** @file=0D
+The header file for Firmware volume block driver.=0D
+=0D
+Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef FW_BLOCK_SERVICE_H_=0D
+#define FW_BLOCK_SERVICE_H_=0D
+=0D
+#include <Guid/EventGroup.h>=0D
+#include <Guid/FirmwareFileSystem2.h>=0D
+#include <Guid/SystemNvDataGuid.h>=0D
+#include <Guid/VariableFormat.h>=0D
+#include <Protocol/DevicePath.h>=0D
+#include <Protocol/FirmwareVolumeBlock.h>=0D
+#include <Library/UefiDriverEntryPoint.h>=0D
+#include <Library/UefiBootServicesTableLib.h>=0D
+#include <Library/UefiLib.h>=0D
+#include <Library/BaseLib.h>=0D
+#include <Library/DebugLib.h>=0D
+#include <Library/BaseMemoryLib.h>=0D
+#include <Library/IoLib.h>=0D
+#include <Library/CacheMaintenanceLib.h>=0D
+#include <Library/MemoryAllocationLib.h>=0D
+#include <Library/PcdLib.h>=0D
+#include <Library/FlashDeviceLib.h>=0D
+#include <Library/DevicePathLib.h>=0D
+#include <Library/HobLib.h>=0D
+#include <Library/DxeServicesLib.h>=0D
+#include <Guid/NvVariableInfoGuid.h>=0D
+#include <Register/ArchitecturalMsr.h>=0D
+=0D
+//=0D
+// Define two helper macro to extract the Capability field or Status field=
in FVB=0D
+// bit fields=0D
+//=0D
+#define EFI_FVB2_CAPABILITIES (EFI_FVB2_READ_DISABLED_CAP |\=0D
+ EFI_FVB2_READ_ENABLED_CAP | \=0D
+ EFI_FVB2_WRITE_DISABLED_CAP | \=0D
+ EFI_FVB2_WRITE_ENABLED_CAP | \=0D
+ EFI_FVB2_LOCK_CAP \=0D
+ )=0D
+=0D
+#define EFI_FVB2_STATUS (EFI_FVB2_READ_STATUS | EFI_FVB2_WRITE_STATUS | E=
FI_FVB2_LOCK_STATUS)=0D
+=0D
+typedef struct {=0D
+ UINTN FvBase;=0D
+ UINTN NumOfBlocks;=0D
+ //=0D
+ // Note!!!: VolumeHeader must be the last element=0D
+ // of the structure.=0D
+ //=0D
+ EFI_FIRMWARE_VOLUME_HEADER VolumeHeader;=0D
+} EFI_FW_VOL_INSTANCE;=0D
+=0D
+typedef struct {=0D
+ EFI_FW_VOL_INSTANCE *FvInstance;=0D
+ UINT32 NumFv;=0D
+ UINT32 Flags;=0D
+} FWB_GLOBAL;=0D
+=0D
+//=0D
+// Fvb Protocol instance data=0D
+//=0D
+#define FVB_DEVICE_FROM_THIS(a) CR(a, EFI_FW_VOL_BLOCK_DEVICE, FwV=
olBlockInstance, FVB_DEVICE_SIGNATURE)=0D
+#define FVB_EXTEND_DEVICE_FROM_THIS(a) CR(a, EFI_FW_VOL_BLOCK_DEVICE, Fvb=
Extension, FVB_DEVICE_SIGNATURE)=0D
+#define FVB_DEVICE_SIGNATURE SIGNATURE_32('F','V','B','C')=0D
+=0D
+typedef struct {=0D
+ MEDIA_FW_VOL_DEVICE_PATH FvDevPath;=0D
+ EFI_DEVICE_PATH_PROTOCOL EndDevPath;=0D
+} FV_PIWG_DEVICE_PATH;=0D
+=0D
+typedef struct {=0D
+ MEMMAP_DEVICE_PATH MemMapDevPath;=0D
+ EFI_DEVICE_PATH_PROTOCOL EndDevPath;=0D
+} FV_MEMMAP_DEVICE_PATH;=0D
+=0D
+typedef struct {=0D
+ UINT32 Signature;=0D
+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;=0D
+ UINTN Instance;=0D
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL FwVolBlockInstance;=0D
+} EFI_FW_VOL_BLOCK_DEVICE;=0D
+=0D
+/**=0D
+ Get a heathy FV header used for variable store recovery=0D
+=0D
+ @retval The FV header.=0D
+=0D
+**/=0D
+EFI_FIRMWARE_VOLUME_HEADER *=0D
+GetFvHeaderTemplate (=0D
+ VOID=0D
+ );=0D
+=0D
+EFI_STATUS=0D
+InitVariableStore (=0D
+ VOID=0D
+ );=0D
+=0D
+//=0D
+// Protocol APIs=0D
+//=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolGetAttributes (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes=0D
+ );=0D
+=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolSetAttributes (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes=0D
+ );=0D
+=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolGetPhysicalAddress (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ OUT EFI_PHYSICAL_ADDRESS *Address=0D
+ );=0D
+=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolGetBlockSize (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ IN EFI_LBA Lba,=0D
+ OUT UINTN *BlockSize,=0D
+ OUT UINTN *NumOfBlocks=0D
+ );=0D
+=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolRead (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ IN EFI_LBA Lba,=0D
+ IN UINTN Offset,=0D
+ IN OUT UINTN *NumBytes,=0D
+ OUT UINT8 *Buffer=0D
+ );=0D
+=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolWrite (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ IN EFI_LBA Lba,=0D
+ IN UINTN Offset,=0D
+ IN OUT UINTN *NumBytes,=0D
+ IN UINT8 *Buffer=0D
+ );=0D
+=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbProtocolEraseBlocks (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ ...=0D
+ );=0D
+=0D
+EFI_FW_VOL_INSTANCE *=0D
+GetFvbInstance (=0D
+ IN UINTN Instance=0D
+ );=0D
+=0D
+EFI_STATUS=0D
+InstallFvbProtocol (=0D
+ IN EFI_FW_VOL_INSTANCE *FwhInstance,=0D
+ IN UINTN InstanceNum=0D
+ );=0D
+=0D
+EFI_STATUS=0D
+FvbInitialize (=0D
+ VOID=0D
+ );=0D
+=0D
+extern FWB_GLOBAL mFvbModuleGlobal;=0D
+extern EFI_FW_VOL_BLOCK_DEVICE mFvbDeviceTemplate;=0D
+extern FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate;=0D
+extern FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate;=0D
+=0D
+#endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c b/Featur=
es/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c
new file mode 100644
index 0000000000..e2b87a74d2
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c
@@ -0,0 +1,139 @@
+/** @file=0D
+ SMM Firmware Volume Block Driver.=0D
+=0D
+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#include <PiSmm.h>=0D
+#include <Library/SmmServicesTableLib.h>=0D
+#include "FvbSmmCommon.h"=0D
+#include "FvbService.h"=0D
+=0D
+/**=0D
+ The function installs EFI_SMM_FIRMWARE_VOLUME_BLOCK protocol=0D
+ for each FV in the system.=0D
+=0D
+ @param[in] FwhInstance The pointer to a FW volume instance structure,=
=0D
+ which contains the information about one FV.=0D
+ @param[in] InstanceNum The instance number which can be used as a ID=
=0D
+ to locate this FwhInstance in other functions.=
=0D
+=0D
+ @retval EFI_SUCESS Installed successfully.=0D
+ @retval Else Did not install successfully.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+InstallFvbProtocol (=0D
+ IN EFI_FW_VOL_INSTANCE *FwhInstance,=0D
+ IN UINTN InstanceNum=0D
+ )=0D
+{=0D
+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;=0D
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;=0D
+ EFI_STATUS Status;=0D
+ EFI_HANDLE FvbHandle;=0D
+ FV_MEMMAP_DEVICE_PATH *FvDevicePath;=0D
+ VOID *TempPtr;=0D
+=0D
+ FvbDevice =3D (EFI_FW_VOL_BLOCK_DEVICE *)AllocateRuntimeCopyPool (=0D
+ sizeof (EFI_FW_VOL_BLOCK_DEVICE=
),=0D
+ &mFvbDeviceTemplate=0D
+ );=0D
+ if (FvbDevice =3D=3D NULL) {=0D
+ return EFI_OUT_OF_RESOURCES;=0D
+ }=0D
+=0D
+ FvbDevice->Instance =3D InstanceNum;=0D
+ FwVolHeader =3D &FwhInstance->VolumeHeader;=0D
+=0D
+ //=0D
+ // Set up the devicepath=0D
+ //=0D
+ if (FwVolHeader->ExtHeaderOffset =3D=3D 0) {=0D
+ //=0D
+ // FV does not contains extension header, then produce MEMMAP_DEVICE_P=
ATH=0D
+ //=0D
+ TempPtr =3D AllocateRuntimeCopyPool (sizeof (FV_MEMMAP_D=
EVICE_PATH), &mFvMemmapDevicePathTemplate);=0D
+ FvbDevice->DevicePath =3D (EFI_DEVICE_PATH_PROTOCOL *)TempPtr;=0D
+ if (FvbDevice->DevicePath =3D=3D NULL) {=0D
+ ASSERT (FALSE);=0D
+ return EFI_OUT_OF_RESOURCES;=0D
+ }=0D
+=0D
+ FvDevicePath =3D (FV_MEMMAP_DEVICE_PATH=
*)FvbDevice->DevicePath;=0D
+ FvDevicePath->MemMapDevPath.StartingAddress =3D FwhInstance->FvBase;=0D
+ FvDevicePath->MemMapDevPath.EndingAddress =3D FwhInstance->FvBase + =
FwVolHeader->FvLength - 1;=0D
+ } else {=0D
+ TempPtr =3D AllocateRuntimeCopyPool (sizeof (FV_PIWG_DEV=
ICE_PATH), &mFvPIWGDevicePathTemplate);=0D
+ FvbDevice->DevicePath =3D (EFI_DEVICE_PATH_PROTOCOL *)TempPtr;=0D
+ if (FvbDevice->DevicePath =3D=3D NULL) {=0D
+ ASSERT (FALSE);=0D
+ return EFI_OUT_OF_RESOURCES;=0D
+ }=0D
+=0D
+ CopyGuid (=0D
+ &((FV_PIWG_DEVICE_PATH *)FvbDevice->DevicePath)->FvDevPath.FvName,=0D
+ (GUID *)(UINTN)(FwhInstance->FvBase + FwVolHeader->ExtHeaderOffset)=
=0D
+ );=0D
+ }=0D
+=0D
+ //=0D
+ // Install the SMM Firmware Volume Block Protocol and Device Path Protoc=
ol=0D
+ //=0D
+ FvbHandle =3D NULL;=0D
+ Status =3D gSmst->SmmInstallProtocolInterface (=0D
+ &FvbHandle,=0D
+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,=0D
+ EFI_NATIVE_INTERFACE,=0D
+ &FvbDevice->FwVolBlockInstance=0D
+ );=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ Status =3D gSmst->SmmInstallProtocolInterface (=0D
+ &FvbHandle,=0D
+ &gEfiDevicePathProtocolGuid,=0D
+ EFI_NATIVE_INTERFACE,=0D
+ FvbDevice->DevicePath=0D
+ );=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ //=0D
+ // Notify the Fvb wrapper driver SMM fvb is ready=0D
+ //=0D
+ FvbHandle =3D NULL;=0D
+ Status =3D gBS->InstallProtocolInterface (=0D
+ &FvbHandle,=0D
+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,=0D
+ EFI_NATIVE_INTERFACE,=0D
+ &FvbDevice->FwVolBlockInstance=0D
+ );=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ The driver entry point for SMM Firmware Volume Block Driver.=0D
+=0D
+ The function does the necessary initialization work=0D
+ Firmware Volume Block Driver.=0D
+=0D
+ @param[in] ImageHandle The firmware allocated handle for the UEFI=
image.=0D
+ @param[in] SystemTable A pointer to the EFI system table.=0D
+=0D
+ @retval EFI_SUCCESS This funtion always return EFI_SUCCESS.=0D
+ It will ASSERT on errors.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbSmmInitialize (=0D
+ IN EFI_HANDLE ImageHandle,=0D
+ IN EFI_SYSTEM_TABLE *SystemTable=0D
+ )=0D
+{=0D
+ FvbInitialize ();=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf b/Features/In=
tel/PlatformPayloadPkg/Fvb/FvbSmm.inf
new file mode 100644
index 0000000000..a56654ba09
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf
@@ -0,0 +1,66 @@
+## @file=0D
+# This driver installs the EFI_SMM_FIRMWARE_VOLUMEN_PROTOCOL.=0D
+#=0D
+#=0D
+# Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>=
=0D
+#=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+[Defines]=0D
+ INF_VERSION =3D 0x00010005=0D
+ BASE_NAME =3D FvbSmm=0D
+ FILE_GUID =3D A4EC8ADB-B7A8-47d1-8E52-EC820D0ACF6F=
=0D
+ MODULE_TYPE =3D DXE_SMM_DRIVER=0D
+ VERSION_STRING =3D 1.0=0D
+ PI_SPECIFICATION_VERSION =3D 0x0001000A=0D
+ ENTRY_POINT =3D FvbSmmInitialize=0D
+=0D
+[Sources]=0D
+ FvbInfo.c=0D
+ FvbService.h=0D
+ FvbService.c=0D
+ FvbServiceSmm.c=0D
+ FvbSmmCommon.h=0D
+=0D
+[Packages]=0D
+ MdePkg/MdePkg.dec=0D
+ MdeModulePkg/MdeModulePkg.dec=0D
+ UefiCpuPkg/UefiCpuPkg.dec=0D
+ PlatformPayloadPkg/PlatformPayloadPkg.dec=0D
+=0D
+[LibraryClasses]=0D
+ FlashDeviceLib=0D
+ PcdLib=0D
+ MemoryAllocationLib=0D
+ CacheMaintenanceLib=0D
+ IoLib=0D
+ BaseMemoryLib=0D
+ DebugLib=0D
+ BaseLib=0D
+ UefiLib=0D
+ SmmServicesTableLib=0D
+ UefiBootServicesTableLib=0D
+ UefiDriverEntryPoint=0D
+ HobLib=0D
+ DxeServicesLib=0D
+=0D
+[Guids]=0D
+ gEfiFirmwareFileSystem2Guid # ALWAYS_CONSUMED=0D
+ gEfiSystemNvDataFvGuid # ALWAYS_CONSUMED=0D
+ gEfiAuthenticatedVariableGuid=0D
+ gNvVariableInfoGuid=0D
+=0D
+ [Protocols]=0D
+ gEfiDevicePathProtocolGuid # PROTOCOL ALWAYS_PRODUCED=
=0D
+ gEfiSmmFirmwareVolumeBlockProtocolGuid # PROTOCOL ALWAYS_PRODUCED=
=0D
+=0D
+[Pcd]=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize=0D
+ gPlatformPayloadPkgTokenSpaceGuid.PcdNvsDataFile=0D
+=0D
+[Depex]=0D
+ TRUE=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h b/Feature=
s/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h
new file mode 100644
index 0000000000..0eadabe13f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h
@@ -0,0 +1,68 @@
+/** @file=0D
+ The common header file for SMM FVB module.=0D
+=0D
+Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef SMM_FVB_COMMON_H_=0D
+#define SMM_FVB_COMMON_H_=0D
+=0D
+#include <Protocol/SmmFirmwareVolumeBlock.h>=0D
+=0D
+#define EFI_FUNCTION_GET_ATTRIBUTES 1=0D
+#define EFI_FUNCTION_SET_ATTRIBUTES 2=0D
+#define EFI_FUNCTION_GET_PHYSICAL_ADDRESS 3=0D
+#define EFI_FUNCTION_GET_BLOCK_SIZE 4=0D
+#define EFI_FUNCTION_READ 5=0D
+#define EFI_FUNCTION_WRITE 6=0D
+#define EFI_FUNCTION_ERASE_BLOCKS 7=0D
+=0D
+typedef struct {=0D
+ UINTN Function;=0D
+ EFI_STATUS ReturnStatus;=0D
+ UINT8 Data[1];=0D
+} SMM_FVB_COMMUNICATE_FUNCTION_HEADER;=0D
+=0D
+///=0D
+/// Size of SMM communicate header, without including the payload.=0D
+///=0D
+#define SMM_COMMUNICATE_HEADER_SIZE (OFFSET_OF (EFI_SMM_COMMUNICATE_HEADE=
R, Data))=0D
+=0D
+///=0D
+/// Size of SMM FVB communicate function header, without including the pay=
load.=0D
+///=0D
+#define SMM_FVB_COMMUNICATE_HEADER_SIZE (OFFSET_OF (SMM_FVB_COMMUNICATE_F=
UNCTION_HEADER, Data))=0D
+=0D
+typedef struct {=0D
+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;=0D
+ EFI_FVB_ATTRIBUTES_2 Attributes;=0D
+} SMM_FVB_ATTRIBUTES_HEADER;=0D
+=0D
+typedef struct {=0D
+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;=0D
+ EFI_PHYSICAL_ADDRESS Address;=0D
+} SMM_FVB_PHYSICAL_ADDRESS_HEADER;=0D
+=0D
+typedef struct {=0D
+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;=0D
+ EFI_LBA Lba;=0D
+ UINTN BlockSize;=0D
+ UINTN NumOfBlocks;=0D
+} SMM_FVB_BLOCK_SIZE_HEADER;=0D
+=0D
+typedef struct {=0D
+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;=0D
+ EFI_LBA Lba;=0D
+ UINTN Offset;=0D
+ UINTN NumBytes;=0D
+} SMM_FVB_READ_WRITE_HEADER;=0D
+=0D
+typedef struct {=0D
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;=0D
+ EFI_LBA StartLba;=0D
+ UINTN NumOfLba;=0D
+} SMM_FVB_BLOCKS_HEADER;=0D
+=0D
+#endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoG=
uid.h b/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h
new file mode 100644
index 0000000000..fd0bd73529
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h
@@ -0,0 +1,24 @@
+/** @file=0D
+ This file defines the hob structure for the SPI flash variable info.=0D
+=0D
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef NV_VARIABLE_INFO_GUID_H_=0D
+#define NV_VARIABLE_INFO_GUID_H_=0D
+=0D
+//=0D
+// NV variable hob info GUID=0D
+//=0D
+extern EFI_GUID gNvVariableInfoGuid;=0D
+=0D
+typedef struct {=0D
+ UINT8 Revision;=0D
+ UINT8 Reserved[3];=0D
+ UINT32 VariableStoreBase;=0D
+ UINT32 VariableStoreSize;=0D
+} NV_VARIABLE_INFO;=0D
+=0D
+#endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGui=
d.h b/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h
new file mode 100644
index 0000000000..59b81851d5
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h
@@ -0,0 +1,38 @@
+/** @file=0D
+ This file defines the hob structure for the SPI flash variable info.=0D
+=0D
+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef SPI_FLASH_INFO_GUID_H_=0D
+#define SPI_FLASH_INFO_GUID_H_=0D
+=0D
+#include <IndustryStandard/Acpi.h>=0D
+//=0D
+// SPI Flash infor hob GUID=0D
+//=0D
+extern EFI_GUID gSpiFlashInfoGuid;=0D
+=0D
+//=0D
+// Set this bit if platform need disable SMM write protection when writing=
flash=0D
+// in SMM mode using this method: -- AsmWriteMsr32 (0x1FE, MmioRead32 (0x=
FED30880) | BIT0);=0D
+//=0D
+#define FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT BIT0=0D
+=0D
+//=0D
+// Reuse ACPI definition=0D
+//=0D
+typedef EFI_ACPI_3_0_GENERIC_ADDRESS_STRUCTURE PLD_GENERIC_ADDRESS;=0D
+#define SPACE_ID_PCI_CONFIGURATION EFI_ACPI_3_0_PCI_CONFIGURATION_SPACE=0D
+#define REGISTER_BIT_WIDTH_DWORD EFI_ACPI_3_0_DWORD=0D
+=0D
+typedef struct {=0D
+ UINT8 Revision;=0D
+ UINT8 Reserved;=0D
+ UINT16 Flags;=0D
+ PLD_GENERIC_ADDRESS SpiAddress;=0D
+} SPI_FLASH_INFO;=0D
+=0D
+#endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceL=
ib.h b/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h
new file mode 100644
index 0000000000..b5e8be225e
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h
@@ -0,0 +1,104 @@
+/** @file=0D
+ Flash device library class header file.=0D
+=0D
+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef FLASHDEVICE_LIB_H_=0D
+#define FLASHDEVICE_LIB_H_=0D
+=0D
+/**=0D
+ Read NumBytes bytes of data from the address specified by=0D
+ PAddress into Buffer.=0D
+=0D
+ @param[in] PAddress The starting physical address of the read.=0D
+ @param[in,out] NumBytes On input, the number of bytes to read. On ou=
tput, the number=0D
+ of bytes actually read.=0D
+ @param[out] Buffer The destination data buffer for the read.=0D
+=0D
+ @retval EFI_SUCCESS. Opertion is successful.=0D
+ @retval EFI_DEVICE_ERROR If there is any device errors.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+LibFvbFlashDeviceRead (=0D
+ IN UINTN PAddress,=0D
+ IN OUT UINTN *NumBytes,=0D
+ OUT UINT8 *Buffer=0D
+ );=0D
+=0D
+/**=0D
+ Write NumBytes bytes of data from Buffer to the address specified by=0D
+ PAddresss.=0D
+=0D
+ @param[in] PAddress The starting physical address of the write.=0D
+ @param[in,out] NumBytes On input, the number of bytes to write. On outp=
ut,=0D
+ the actual number of bytes written.=0D
+ @param[in] Buffer The source data buffer for the write.=0D
+=0D
+ @retval EFI_SUCCESS. Opertion is successful.=0D
+ @retval EFI_DEVICE_ERROR If there is any device errors.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+LibFvbFlashDeviceWrite (=0D
+ IN UINTN PAddress,=0D
+ IN OUT UINTN *NumBytes,=0D
+ IN UINT8 *Buffer=0D
+ );=0D
+=0D
+/**=0D
+ Erase the block starting at PAddress.=0D
+=0D
+ @param[in] PAddress The starting physical address of the region to be e=
rased.=0D
+ @param[in] LbaLength The length of the region to be erased. This para=
meter is necessary=0D
+ as the physical block size on a flash device could =
be different than=0D
+ the logical block size of Firmware Volume Block pro=
tocol. Erase on=0D
+ flash chip is always performed block by block. Ther=
efore, the ERASE=0D
+ operation to a logical block is converted a number =
of ERASE operation=0D
+ (or a partial erase) on the hardware.=0D
+=0D
+ @retval EFI_SUCCESS. Opertion is successful.=0D
+ @retval EFI_DEVICE_ERROR If there is any device errors.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+LibFvbFlashDeviceBlockErase (=0D
+ IN UINTN PAddress,=0D
+ IN UINTN LbaLength=0D
+ );=0D
+=0D
+/**=0D
+ Lock or unlock the block starting at PAddress.=0D
+=0D
+ @param[in] PAddress The starting physical address of region to be (un)l=
ocked.=0D
+ @param[in] LbaLength The length of the region to be (un)locked. This =
parameter is necessary=0D
+ as the physical block size on a flash device could =
be different than=0D
+ the logical block size of Firmware Volume Block pro=
tocol. (Un)Lock on=0D
+ flash chip is always performed block by block. Ther=
efore, the (Un)Lock=0D
+ operation to a logical block is converted a number =
of (Un)Lock operation=0D
+ (or a partial erase) on the hardware.=0D
+ @param[in] Lock TRUE to lock. FALSE to unlock.=0D
+=0D
+ @retval EFI_SUCCESS. Opertion is successful.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+LibFvbFlashDeviceBlockLock (=0D
+ IN UINTN PAddress,=0D
+ IN UINTN LbaLength,=0D
+ IN BOOLEAN Lock=0D
+ );=0D
+=0D
+PHYSICAL_ADDRESS=0D
+EFIAPI=0D
+LibFvbFlashDeviceMemoryMap (=0D
+ );=0D
+=0D
+#endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.=
h b/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h
new file mode 100644
index 0000000000..07f40502f2
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h
@@ -0,0 +1,213 @@
+/** @file=0D
+ PCH SPI Common Driver implements the SPI Host Controller Compatibility I=
nterface.=0D
+=0D
+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef SPI_FLASH_LIB_H_=0D
+#define SPI_FLASH_LIB_H_=0D
+=0D
+/**=0D
+ Flash Region Type=0D
+**/=0D
+typedef enum {=0D
+ FlashRegionDescriptor,=0D
+ FlashRegionBios,=0D
+ FlashRegionMe,=0D
+ FlashRegionGbE,=0D
+ FlashRegionPlatformData,=0D
+ FlashRegionDer,=0D
+ FlashRegionAll,=0D
+ FlashRegionMax=0D
+} FLASH_REGION_TYPE;=0D
+=0D
+/**=0D
+ Read SFDP data from the flash part.=0D
+=0D
+ @param[in] ComponentNumber The Component Number for chip select=0D
+ @param[in] ByteCount Number of bytes in SFDP data portion of =
the SPI cycle, the max number is 64=0D
+ @param[out] SfdpData The Pointer to caller-allocated buffer c=
ontaining the SFDP data received=0D
+ It is the caller's responsibility to mak=
e sure Buffer is large enough for the total number of bytes read.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashReadSfdp (=0D
+ IN UINT8 ComponentNumber,=0D
+ IN UINT32 ByteCount,=0D
+ OUT UINT8 *SfdpData=0D
+ );=0D
+=0D
+/**=0D
+ Read Jedec Id from the flash part.=0D
+=0D
+ @param[in] ComponentNumber The Component Number for chip select=0D
+ @param[in] ByteCount Number of bytes in JedecId data portion =
of the SPI cycle, the data size is 3 typically=0D
+ @param[out] JedecId The Pointer to caller-allocated buffer c=
ontaining JEDEC ID received=0D
+ It is the caller's responsibility to mak=
e sure Buffer is large enough for the total number of bytes read.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashReadJedecId (=0D
+ IN UINT8 ComponentNumber,=0D
+ IN UINT32 ByteCount,=0D
+ OUT UINT8 *JedecId=0D
+ );=0D
+=0D
+/**=0D
+ Write the status register in the flash part.=0D
+=0D
+ @param[in] ByteCount Number of bytes in Status data portion o=
f the SPI cycle, the data size is 1 typically=0D
+ @param[in] StatusValue The Pointer to caller-allocated buffer c=
ontaining the value of Status register writing=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashWriteStatus (=0D
+ IN UINT32 ByteCount,=0D
+ IN UINT8 *StatusValue=0D
+ );=0D
+=0D
+/**=0D
+ Read status register in the flash part.=0D
+=0D
+ @param[in] ByteCount Number of bytes in Status data portion o=
f the SPI cycle, the data size is 1 typically=0D
+ @param[out] StatusValue The Pointer to caller-allocated buffer c=
ontaining the value of Status register received.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashReadStatus (=0D
+ IN UINT32 ByteCount,=0D
+ OUT UINT8 *StatusValue=0D
+ );=0D
+=0D
+/**=0D
+ Read SC Soft Strap Values=0D
+=0D
+ @param[in] SoftStrapAddr SC Soft Strap address offset from FPSBA.=
=0D
+ @param[in] ByteCount Number of bytes in SoftStrap data portio=
n of the SPI cycle=0D
+ @param[out] SoftStrapValue The Pointer to caller-allocated buffer c=
ontaining SC Soft Strap Value.=0D
+ It is the caller's responsibility to mak=
e sure Buffer is large enough for the total number of bytes read.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiReadPchSoftStrap (=0D
+ IN UINT32 SoftStrapAddr,=0D
+ IN UINT32 ByteCount,=0D
+ OUT UINT8 *SoftStrapValue=0D
+ );=0D
+=0D
+/**=0D
+ Read data from the flash part.=0D
+=0D
+ @param[in] FlashRegionType The Flash Region type for flash cycle wh=
ich is listed in the Descriptor.=0D
+ @param[in] Address The Flash Linear Address must fall withi=
n a region for which BIOS has access permissions.=0D
+ @param[in] ByteCount Number of bytes in the data portion of t=
he SPI cycle.=0D
+ @param[out] Buffer The Pointer to caller-allocated buffer c=
ontaining the dada received.=0D
+ It is the caller's responsibility to mak=
e sure Buffer is large enough for the total number of bytes read.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashRead (=0D
+ IN FLASH_REGION_TYPE FlashRegionType,=0D
+ IN UINT32 Address,=0D
+ IN UINT32 ByteCount,=0D
+ OUT UINT8 *Buffer=0D
+ );=0D
+=0D
+/**=0D
+ Erase some area on the flash part.=0D
+=0D
+ @param[in] FlashRegionType The Flash Region type for flash cycle wh=
ich is listed in the Descriptor.=0D
+ @param[in] Address The Flash Linear Address must fall withi=
n a region for which BIOS has access permissions.=0D
+ @param[in] ByteCount Number of bytes in the data portion of t=
he SPI cycle.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashErase (=0D
+ IN FLASH_REGION_TYPE FlashRegionType,=0D
+ IN UINT32 Address,=0D
+ IN UINT32 ByteCount=0D
+ );=0D
+=0D
+/**=0D
+ Write data to the flash part.=0D
+=0D
+ @param[in] FlashRegionType The Flash Region type for flash cycle wh=
ich is listed in the Descriptor.=0D
+ @param[in] Address The Flash Linear Address must fall withi=
n a region for which BIOS has access permissions.=0D
+ @param[in] ByteCount Number of bytes in the data portion of t=
he SPI cycle.=0D
+ @param[in] Buffer Pointer to caller-allocated buffer conta=
ining the data sent during the SPI cycle.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashWrite (=0D
+ IN FLASH_REGION_TYPE FlashRegionType,=0D
+ IN UINT32 Address,=0D
+ IN UINT32 ByteCount,=0D
+ IN UINT8 *Buffer=0D
+ );=0D
+=0D
+/**=0D
+ Initialize an SPI library.=0D
+=0D
+ @retval EFI_SUCCESS The protocol instance was properly initi=
alized=0D
+ @retval EFI_NOT_FOUND The expected SPI info could not be found=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiConstructor (=0D
+ VOID=0D
+ );=0D
+=0D
+/**=0D
+ Get the SPI region base and size, based on the enum type=0D
+=0D
+ @param[in] FlashRegionType The Flash Region type for for the base a=
ddress which is listed in the Descriptor.=0D
+ @param[out] BaseAddress The Flash Linear Address for the Region =
'n' Base=0D
+ @param[out] RegionSize The size for the Region 'n'=0D
+=0D
+ @retval EFI_SUCCESS Read success=0D
+ @retval EFI_INVALID_PARAMETER Invalid region type given=0D
+ @retval EFI_DEVICE_ERROR The region is not used=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiGetRegionAddress (=0D
+ IN FLASH_REGION_TYPE FlashRegionType,=0D
+ OUT UINT32 *BaseAddress OPTIONAL,=0D
+ OUT UINT32 *RegionSize OPTIONAL=0D
+ );=0D
+=0D
+#endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeatu=
re.dsc b/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.d=
sc
new file mode 100644
index 0000000000..3003c563c9
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc
@@ -0,0 +1,112 @@
+## @file=0D
+# This is a build description file for the Payload Platform advanced featu=
re.=0D
+# This file should be included into another package DSC file to build this=
feature.=0D
+#=0D
+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>=0D
+#=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+##########################################################################=
######=0D
+#=0D
+# Defines Section - statements that will be processed to create a Makefile=
.=0D
+#=0D
+##########################################################################=
######=0D
+=0D
+[Defines]=0D
+ !ifndef $(DXE_ARCH)=0D
+ !error "DXE_ARCH must be specified to build this feature!"=0D
+ !endif=0D
+=0D
+ DEFINE SMM_VARIABLE =3D TRUE=0D
+=0D
+=0D
+##########################################################################=
######=0D
+#=0D
+# PCD definitions section - list of all PCD definitions needed by this Pla=
tform.=0D
+#=0D
+##########################################################################=
######=0D
+=0D
+[PcdsPatchableInModule.X64]=0D
+!if $(SMM_VARIABLE) =3D=3D TRUE=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64|0=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase |0=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize |0=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize|0=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize |0=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase |0=0D
+!endif=0D
+=0D
+##########################################################################=
######=0D
+#=0D
+# Library Class section - list of all Library Classes needed by this featu=
re.=0D
+#=0D
+##########################################################################=
######=0D
+=0D
+[LibraryClasses]=0D
+ !if $(SMM_VARIABLE) =3D=3D TRUE=0D
+ PciLib|MdePkg/Library/BasePciLibPciExpress/BasePciLibPciExpress.inf=0D
+ PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf=0D
+ # (Optional for variable modules debug output=0D
+ PlatformHookLib|UefiPayloadPkg/Library/PlatformHookLib/PlatformHookLib=
.inf=0D
+ DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/Bas=
eDebugPrintErrorLevelLib.inf=0D
+ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf=0D
+ DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.=
inf=0D
+ !endif=0D
+=0D
+[LibraryClasses.common.DXE_SMM_DRIVER,LibraryClasses.common.DXE_RUNTIME_DR=
IVER]=0D
+ !if $(SMM_VARIABLE) =3D=3D TRUE=0D
+ SpiFlashLib|PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf=0D
+ FlashDeviceLib|PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLi=
b.inf=0D
+ DxeHobListLib|UefiPayloadPkg/Library/DxeHobListLib/DxeHobListLib.inf=0D
+ HobLib|UefiPayloadPkg/Library/DxeHobLib/DxeHobLib.inf=0D
+ TimerLib|UefiCpuPkg/Library/CpuTimerLib/BaseCpuTimerLib.inf=0D
+ !endif=0D
+=0D
+##########################################################################=
######=0D
+#=0D
+# Component section - list of all components that need built for this feat=
ure.=0D
+#=0D
+# Note: The EDK II DSC file is not used to specify how compiled binary ima=
ges get placed=0D
+# into firmware volume images. This section is just a list of module=
s to compile from=0D
+# source into UEFI-compliant binaries.=0D
+# It is the FDF file that contains information on combining binary f=
iles into firmware=0D
+# volume images, whose concept is beyond UEFI and is described in PI=
specification.=0D
+# There may also be modules listed in this section that are not requ=
ired in the FDF file,=0D
+# When a module listed here is excluded from FDF file, then UEFI-com=
pliant binary will be=0D
+# generated for it, but the binary will not be put into any firmware=
volume.=0D
+#=0D
+##########################################################################=
######=0D
+#=0D
+# Feature DXE Components=0D
+#=0D
+=0D
+# @todo: Change below line to [Components.$(DXE_ARCH)] after https://bugzi=
lla.tianocore.org/show_bug.cgi?id=3D2308=0D
+# is completed.=0D
+[Components.X64]=0D
+ #=0D
+ # SMM Variable Support=0D
+ #=0D
+ !if $(SMM_VARIABLE) =3D=3D TRUE=0D
+ PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf=0D
+ PlatformPayloadPkg/Fvb/FvbSmm.inf {=0D
+ <LibraryClasses>=0D
+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf=0D
+ }=0D
+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf {=0D
+ <LibraryClasses>=0D
+ NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf=0D
+ NULL|MdeModulePkg/Library/VarCheckHiiLib/VarCheckHiiLib.inf=0D
+ NULL|MdeModulePkg/Library/VarCheckPcdLib/VarCheckPcdLib.inf=0D
+ NULL|MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.inf=
=0D
+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf=0D
+ }=0D
+=0D
+ MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf=
{=0D
+ <LibraryClasses>=0D
+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf=0D
+ }=0D
+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf=0D
+ !endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf b/Fea=
tures/Intel/PlatformPayloadPkg/Include/PostMemory.fdf
new file mode 100644
index 0000000000..54800b972c
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf
@@ -0,0 +1,20 @@
+## @file=0D
+# FDF file for post-memory ACPI Debug advanced feature modules.=0D
+#=0D
+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>=0D
+#=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+#=0D
+# SMM Support=0D
+#=0D
+!if $(SMM_VARIABLE) =3D=3D TRUE=0D
+ INF PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf=0D
+ INF PlatformPayloadPkg/Fvb/FvbSmm.inf=0D
+ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.i=
nf=0D
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf=0D
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf=
=0D
+=0D
+!endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf b/Feat=
ures/Intel/PlatformPayloadPkg/Include/PreMemory.fdf
new file mode 100644
index 0000000000..003b7a3e56
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf
@@ -0,0 +1,8 @@
+## @file=0D
+# FDF file for pre-memory payload platform advanced feature modules.=0D
+#=0D
+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>=0D
+#=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/Flash=
DeviceLib.c b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/Flas=
hDeviceLib.c
new file mode 100644
index 0000000000..5a27043285
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceL=
ib.c
@@ -0,0 +1,160 @@
+/** @file=0D
+ Flash Device Library based on SPI Flash library.=0D
+=0D
+Copyright (c) 2018 - 2021, Intel Corporation. All rights reserved. <BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#include <PiDxe.h>=0D
+#include <Library/BaseMemoryLib.h>=0D
+#include <Library/DebugLib.h>=0D
+#include <Library/SpiFlashLib.h>=0D
+=0D
+/**=0D
+ Initialize spi flash device.=0D
+=0D
+ @retval EFI_SUCCESS The tested spi flash device is supporte=
d.=0D
+ @retval EFI_UNSUPPORTED The tested spi flash device is not supp=
orted.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+LibFvbFlashDeviceInit (=0D
+ VOID=0D
+ )=0D
+{=0D
+ return SpiConstructor ();=0D
+}=0D
+=0D
+/**=0D
+ Read NumBytes bytes of data from the address specified by=0D
+ PAddress into Buffer.=0D
+=0D
+ @param[in] PAddress The starting physical address of the read.=
=0D
+ @param[in,out] NumBytes On input, the number of bytes to read. On =
output, the number=0D
+ of bytes actually read.=0D
+ @param[out] Buffer The destination data buffer for the read.=
=0D
+=0D
+ @retval EFI_SUCCESS. Opertion is successful.=0D
+ @retval EFI_DEVICE_ERROR If there is any device errors.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+LibFvbFlashDeviceRead (=0D
+ IN UINTN PAddress,=0D
+ IN OUT UINTN *NumBytes,=0D
+ OUT UINT8 *Buffer=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ UINT32 ByteCount;=0D
+ UINT32 RgnSize;=0D
+ UINT32 AddrOffset;=0D
+=0D
+ Status =3D SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+=0D
+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - Rg=
nSize))=0D
+ // which equal (PAddress + RgnSize) here.=0D
+ AddrOffset =3D (UINT32)((UINT32)PAddress + RgnSize);=0D
+ ByteCount =3D (UINT32)*NumBytes;=0D
+ return SpiFlashRead (FlashRegionBios, AddrOffset, ByteCount, Buffer);=0D
+}=0D
+=0D
+/**=0D
+ Write NumBytes bytes of data from Buffer to the address specified by=0D
+ PAddresss.=0D
+=0D
+ @param[in] PAddress The starting physical address of the wri=
te.=0D
+ @param[in,out] NumBytes On input, the number of bytes to write. =
On output,=0D
+ the actual number of bytes written.=0D
+ @param[in] Buffer The source data buffer for the write.=0D
+=0D
+ @retval EFI_SUCCESS. Opertion is successful.=0D
+ @retval EFI_DEVICE_ERROR If there is any device errors.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+LibFvbFlashDeviceWrite (=0D
+ IN UINTN PAddress,=0D
+ IN OUT UINTN *NumBytes,=0D
+ IN UINT8 *Buffer=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ UINT32 ByteCount;=0D
+ UINT32 RgnSize;=0D
+ UINT32 AddrOffset;=0D
+=0D
+ Status =3D SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+=0D
+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - Rg=
nSize))=0D
+ // which equal (PAddress + RgnSize) here.=0D
+ AddrOffset =3D (UINT32)((UINT32)PAddress + RgnSize);=0D
+ ByteCount =3D (UINT32)*NumBytes;=0D
+ return SpiFlashWrite (FlashRegionBios, AddrOffset, ByteCount, Buffer);=0D
+}=0D
+=0D
+/**=0D
+ Erase the block starting at PAddress.=0D
+=0D
+ @param[in] PAddress The starting physical address of the block t=
o be erased.=0D
+ This library assume that caller garantee tha=
t the PAddress=0D
+ is at the starting address of this block.=0D
+ @param[in] LbaLength The length of the logical block to be erased=
.=0D
+=0D
+ @retval EFI_SUCCESS. Opertion is successful.=0D
+ @retval EFI_DEVICE_ERROR If there is any device errors.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+LibFvbFlashDeviceBlockErase (=0D
+ IN UINTN PAddress,=0D
+ IN UINTN LbaLength=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ UINT32 RgnSize;=0D
+ UINT32 AddrOffset;=0D
+=0D
+ Status =3D SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+=0D
+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - Rg=
nSize))=0D
+ // which equal (PAddress + RgnSize) here.=0D
+ AddrOffset =3D (UINT32)((UINT32)PAddress + RgnSize);=0D
+ return SpiFlashErase (FlashRegionBios, AddrOffset, (UINT32)LbaLength);=0D
+}=0D
+=0D
+/**=0D
+ Lock or unlock the block starting at PAddress.=0D
+=0D
+ @param[in] PAddress The starting physical address of region to b=
e (un)locked.=0D
+ @param[in] LbaLength The length of the logical block to be erased=
.=0D
+ @param[in] Lock TRUE to lock. FALSE to unlock.=0D
+=0D
+ @retval EFI_SUCCESS. Opertion is successful.=0D
+ @retval EFI_DEVICE_ERROR If there is any device errors.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+LibFvbFlashDeviceBlockLock (=0D
+ IN UINTN PAddress,=0D
+ IN UINTN LbaLength,=0D
+ IN BOOLEAN Lock=0D
+ )=0D
+{=0D
+ return EFI_SUCCESS;=0D
+}=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/Flash=
DeviceLib.inf b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/Fl=
ashDeviceLib.inf
new file mode 100644
index 0000000000..7285a37944
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceL=
ib.inf
@@ -0,0 +1,38 @@
+## @file=0D
+# Library instace of Flash Device Library Class=0D
+#=0D
+# This library implement the flash device library class for the lakeport p=
latform.=0D
+#@copyright=0D
+# Copyright (c) 2014 - 2021 Intel Corporation. All rights reserved=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+[Defines]=0D
+ INF_VERSION =3D 0x00010005=0D
+ BASE_NAME =3D FlashDeviceLib=0D
+ FILE_GUID =3D BA7CA537-1C65-4a90-9379-622A24A08141=
=0D
+ MODULE_TYPE =3D DXE_DRIVER=0D
+ VERSION_STRING =3D 1.0=0D
+ LIBRARY_CLASS =3D FlashDeviceLib | DXE_SMM_DRIVER DXE_R=
UNTIME_DRIVER=0D
+=0D
+=0D
+#=0D
+# The following information is for reference only and not required by the =
build tools.=0D
+#=0D
+# VALID_ARCHITECTURES =3D IA32 X64=0D
+#=0D
+=0D
+[Sources]=0D
+ FlashDeviceLib.c=0D
+=0D
+[Packages]=0D
+ MdePkg/MdePkg.dec=0D
+ MdeModulePkg/MdeModulePkg.dec=0D
+ PlatformPayloadPkg/PlatformPayloadPkg.dec=0D
+=0D
+[LibraryClasses]=0D
+ DebugLib=0D
+ BaseMemoryLib=0D
+ SpiFlashLib=0D
+=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLi=
b.c b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c
new file mode 100644
index 0000000000..4ea89582f3
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c
@@ -0,0 +1,89 @@
+/** @file=0D
+=0D
+ Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#include <PiDxe.h>=0D
+#include <Library/PcdLib.h>=0D
+#include <Library/DebugLib.h>=0D
+#include <Library/BaseLib.h>=0D
+#include <Guid/SystemNvDataGuid.h>=0D
+#include <Guid/NvVariableInfoGuid.h>=0D
+#include <Library/HobLib.h>=0D
+=0D
+=0D
+/**=0D
+ Initialize the variable store=0D
+=0D
+ @retval EFI_SUCCESS if initialize the store success.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+PcdInitConstructor (=0D
+ VOID=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ UINT32 NvStorageBase;=0D
+ UINT32 NvStorageSize;=0D
+ UINT32 NvVariableSize;=0D
+ UINT32 FtwWorkingSize;=0D
+ UINT32 FtwSpareSize;=0D
+ EFI_HOB_GUID_TYPE *GuidHob;=0D
+ NV_VARIABLE_INFO *NvVariableInfo;=0D
+=0D
+ //=0D
+ // Find SPI flash variable hob=0D
+ //=0D
+ GuidHob =3D GetFirstGuidHob (&gNvVariableInfoGuid);=0D
+ if (GuidHob =3D=3D NULL) {=0D
+ ASSERT (FALSE);=0D
+ return EFI_NOT_FOUND;=0D
+ }=0D
+=0D
+ NvVariableInfo =3D (NV_VARIABLE_INFO *)GET_GUID_HOB_DATA (GuidHob);=0D
+=0D
+ //=0D
+ // Get variable region base and size.=0D
+ //=0D
+ NvStorageSize =3D NvVariableInfo->VariableStoreSize;=0D
+ NvStorageBase =3D NvVariableInfo->VariableStoreBase;=0D
+=0D
+ //=0D
+ // NvStorageBase needs to be 4KB aligned, NvStorageSize needs to be 8KB =
* n=0D
+ //=0D
+ if (((NvStorageBase & (SIZE_4KB - 1)) !=3D 0) || ((NvStorageSize & (SIZE=
_8KB - 1)) !=3D 0)) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ FtwSpareSize =3D NvStorageSize / 2;=0D
+ FtwWorkingSize =3D 0x2000;=0D
+ NvVariableSize =3D NvStorageSize / 2 - FtwWorkingSize;=0D
+ DEBUG ((DEBUG_INFO, "NvStorageBase:0x%x, NvStorageSize:0x%x\n", NvStorag=
eBase, NvStorageSize));=0D
+=0D
+ if (NvVariableSize >=3D 0x80000000) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ Status =3D PcdSet32S (PcdFlashNvStorageVariableSize, NvVariableSize);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+ Status =3D PcdSet32S (PcdFlashNvStorageVariableBase, NvStorageBase);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+ Status =3D PcdSet64S (PcdFlashNvStorageVariableBase64, NvStorageBase);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ Status =3D PcdSet32S (PcdFlashNvStorageFtwWorkingSize, FtwWorkingSize);=
=0D
+ ASSERT_EFI_ERROR (Status);=0D
+ Status =3D PcdSet32S (PcdFlashNvStorageFtwWorkingBase, NvStorageBase + N=
vVariableSize);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ Status =3D PcdSet32S (PcdFlashNvStorageFtwSpareSize, FtwSpareSize);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+ Status =3D PcdSet32S (PcdFlashNvStorageFtwSpareBase, NvStorageBase + Ftw=
SpareSize);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLi=
b.inf b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf
new file mode 100644
index 0000000000..05411b00d8
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf
@@ -0,0 +1,50 @@
+## @file=0D
+# Initialize patchable PCDs using HOB info=0D
+#=0D
+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+[Defines]=0D
+ INF_VERSION =3D 0x00010005=0D
+ BASE_NAME =3D PcdInitLib=0D
+ FILE_GUID =3D 2C4A8902-B55A-472E-9845-3B931CE68071=
=0D
+ MODULE_TYPE =3D BASE=0D
+ VERSION_STRING =3D 1.0=0D
+ LIBRARY_CLASS =3D NULL=0D
+ CONSTRUCTOR =3D PcdInitConstructor=0D
+=0D
+#=0D
+# The following information is for reference only and not required by the =
build tools.=0D
+#=0D
+# VALID_ARCHITECTURES =3D IA32 X64=0D
+#=0D
+=0D
+[Sources]=0D
+ PcdInitLib.c=0D
+=0D
+[Packages]=0D
+ MdePkg/MdePkg.dec=0D
+ MdeModulePkg/MdeModulePkg.dec=0D
+ PlatformPayloadPkg/PlatformPayloadPkg.dec=0D
+=0D
+[LibraryClasses]=0D
+ BaseLib=0D
+ PcdLib=0D
+ PciLib=0D
+ HobLib=0D
+ BaseLib=0D
+=0D
+[Guids]=0D
+ gNvVariableInfoGuid=0D
+=0D
+[Pcd]=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase=0D
+=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c=
b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c
new file mode 100644
index 0000000000..18f4a0ba3f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c
@@ -0,0 +1,170 @@
+/** @file=0D
+=0D
+ Copyright (c) 2017-2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+#include "SpiCommon.h"=0D
+=0D
+/**=0D
+ Acquire SPI MMIO BAR.=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+=0D
+ @retval Return SPI BAR Address=0D
+=0D
+**/=0D
+UINT32=0D
+AcquireSpiBar0 (=0D
+ IN UINTN PchSpiBase=0D
+ )=0D
+{=0D
+ return MmioRead32 (PchSpiBase + R_SPI_BASE) & ~(B_SPI_BAR0_MASK);=0D
+}=0D
+=0D
+/**=0D
+ Release SPI MMIO BAR. Do nothing.=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+=0D
+**/=0D
+VOID=0D
+ReleaseSpiBar0 (=0D
+ IN UINTN PchSpiBase=0D
+ )=0D
+{=0D
+}=0D
+=0D
+/**=0D
+ This function is to enable/disable BIOS Write Protect in SMM phase.=0D
+=0D
+ @param[in] EnableSmmSts Flag to Enable/disable Bios write protect=
=0D
+=0D
+**/=0D
+VOID=0D
+CpuSmmDisableBiosWriteProtect (=0D
+ IN BOOLEAN EnableSmmSts=0D
+ )=0D
+{=0D
+ UINT32 Data32;=0D
+=0D
+ if (EnableSmmSts) {=0D
+ //=0D
+ // Disable BIOS Write Protect in SMM phase.=0D
+ //=0D
+ Data32 =3D MmioRead32 ((UINTN)(0xFED30880)) | (UINT32)(BIT0);=0D
+ AsmWriteMsr32 (0x000001FE, Data32);=0D
+ } else {=0D
+ //=0D
+ // Enable BIOS Write Protect in SMM phase=0D
+ //=0D
+ Data32 =3D MmioRead32 ((UINTN)(0xFED30880)) & (UINT32)(~BIT0);=0D
+ AsmWriteMsr32 (0x000001FE, Data32);=0D
+ }=0D
+=0D
+ //=0D
+ // Read FED30880h back to ensure the setting went through.=0D
+ //=0D
+ Data32 =3D MmioRead32 (0xFED30880);=0D
+}=0D
+=0D
+/**=0D
+ This function is a hook for Spi to disable BIOS Write Protect.=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write prote=
ction or not=0D
+=0D
+ @retval EFI_SUCCESS The protocol instance was properly initi=
alized=0D
+ @retval EFI_ACCESS_DENIED The BIOS Region can only be updated in S=
MM phase=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+DisableBiosWriteProtect (=0D
+ IN UINTN PchSpiBase,=0D
+ IN UINT8 CpuSmmBwp=0D
+ )=0D
+{=0D
+ //=0D
+ // Write clear BC_SYNC_SS prior to change WPD from 0 to 1.=0D
+ //=0D
+ MmioOr8 (PchSpiBase + R_SPI_BCR + 1, (B_SPI_BCR_SYNC_SS >> 8));=0D
+=0D
+ //=0D
+ // Enable the access to the BIOS space for both read and write cycles=0D
+ //=0D
+ MmioOr8 (PchSpiBase + R_SPI_BCR, B_SPI_BCR_BIOSWE);=0D
+=0D
+ if (CpuSmmBwp !=3D 0) {=0D
+ CpuSmmDisableBiosWriteProtect (TRUE);=0D
+ }=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ This function is a hook for Spi to enable BIOS Write Protect.=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write prote=
ction or not=0D
+=0D
+**/=0D
+VOID=0D
+EFIAPI=0D
+EnableBiosWriteProtect (=0D
+ IN UINTN PchSpiBase,=0D
+ IN UINT8 CpuSmmBwp=0D
+ )=0D
+{=0D
+ //=0D
+ // Disable the access to the BIOS space for write cycles=0D
+ //=0D
+ MmioAnd8 (PchSpiBase + R_SPI_BCR, (UINT8)(~B_SPI_BCR_BIOSWE));=0D
+=0D
+ if (CpuSmmBwp !=3D 0) {=0D
+ CpuSmmDisableBiosWriteProtect (FALSE);=0D
+ }=0D
+}=0D
+=0D
+/**=0D
+ This function disables SPI Prefetching and caching,=0D
+ and returns previous BIOS Control Register value before disabling.=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+=0D
+ @retval Previous BIOS Control Register value=0D
+=0D
+**/=0D
+UINT8=0D
+SaveAndDisableSpiPrefetchCache (=0D
+ IN UINTN PchSpiBase=0D
+ )=0D
+{=0D
+ UINT8 BiosCtlSave;=0D
+=0D
+ BiosCtlSave =3D MmioRead8 (PchSpiBase + R_SPI_BCR) & B_SPI_BCR_SRC;=0D
+=0D
+ MmioAndThenOr32 (=0D
+ PchSpiBase + R_SPI_BCR, \=0D
+ (UINT32)(~B_SPI_BCR_SRC), \=0D
+ (UINT32)(V_SPI_BCR_SRC_PREF_DIS_CACHE_DIS << B_SPI_BCR_SRC)=0D
+ );=0D
+=0D
+ return BiosCtlSave;=0D
+}=0D
+=0D
+/**=0D
+ This function updates BIOS Control Register with the given value.=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+ @param[in] BiosCtlValue BIOS Control Register Value to be update=
d=0D
+=0D
+**/=0D
+VOID=0D
+SetSpiBiosControlRegister (=0D
+ IN UINTN PchSpiBase,=0D
+ IN UINT8 BiosCtlValue=0D
+ )=0D
+{=0D
+ MmioAndThenOr8 (PchSpiBase + R_SPI_BCR, (UINT8) ~B_SPI_BCR_SRC, BiosCtlV=
alue);=0D
+}=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.=
h b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h
new file mode 100644
index 0000000000..b741904143
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h
@@ -0,0 +1,120 @@
+/** @file=0D
+ Register names for SPI device.=0D
+=0D
+ Copyright (c) 2017 - 2019, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef REGS_SPI_H_=0D
+#define REGS_SPI_H_=0D
+=0D
+#define R_SPI_BASE 0x10 ///< 32-bit Memory =
Base Address Register=0D
+#define B_SPI_BAR0_MASK 0x0FFF=0D
+#define R_SPI_BCR 0xDC ///< BIOS Control =
Register=0D
+#define B_SPI_BCR_SRC (BIT3 | BIT2) ///< SPI Read Conf=
iguration (SRC)=0D
+#define V_SPI_BCR_SRC_PREF_DIS_CACHE_DIS 0x04 ///< Prefetch Disa=
ble, Cache Disable=0D
+#define B_SPI_BCR_SYNC_SS BIT8=0D
+#define B_SPI_BCR_BIOSWE BIT0 ///< Write Protect =
Disable (WPD)=0D
+=0D
+///=0D
+/// SPI Host Interface Registers=0D
+#define R_SPI_HSFS 0x04 ///< Hardware Seque=
ncing Flash Status and Control Register(32bits)=0D
+#define B_SPI_HSFS_FDBC_MASK 0x3F000000 ///< Flash Data Byt=
e Count ( <=3D 64), Count =3D (Value in this field) + 1.=0D
+#define N_SPI_HSFS_FDBC 24=0D
+#define B_SPI_HSFS_CYCLE_MASK 0x001E0000 ///< Flash Cycle.=0D
+#define N_SPI_HSFS_CYCLE 17=0D
+#define V_SPI_HSFS_CYCLE_READ 0 ///< Flash Cycle Re=
ad=0D
+#define V_SPI_HSFS_CYCLE_WRITE 2 ///< Flash Cycle Wr=
ite=0D
+#define V_SPI_HSFS_CYCLE_4K_ERASE 3 ///< Flash Cycle 4K=
Block Erase=0D
+#define V_SPI_HSFS_CYCLE_64K_ERASE 4 ///< Flash Cycle 64=
K Sector Erase=0D
+#define V_SPI_HSFS_CYCLE_READ_SFDP 5 ///< Flash Cycle Re=
ad SFDP=0D
+#define V_SPI_HSFS_CYCLE_READ_JEDEC_ID 6 ///< Flash Cycle Re=
ad JEDEC ID=0D
+#define V_SPI_HSFS_CYCLE_WRITE_STATUS 7 ///< Flash Cycle Wr=
ite Status=0D
+#define V_SPI_HSFS_CYCLE_READ_STATUS 8 ///< Flash Cycle Re=
ad Status=0D
+#define B_SPI_HSFS_CYCLE_FGO BIT16 ///< Flash Cycle Go=
.=0D
+#define B_SPI_HSFS_FDV BIT14 ///< Flash Descript=
or Valid=0D
+#define B_SPI_HSFS_SCIP BIT5 ///< SPI Cycle in P=
rogress=0D
+#define B_SPI_HSFS_FCERR BIT1 ///< Flash Cycle Er=
ror=0D
+#define B_SPI_HSFS_FDONE BIT0 ///< Flash Cycle Do=
ne=0D
+=0D
+#define R_SPI_FADDR 0x08 ///< SPI Flash Address=0D
+#define B_SPI_FADDR_MASK 0x07FFFFFF ///< SPI Flash Address Mas=
k (0~26bit)=0D
+=0D
+#define R_SPI_FDATA00 0x10 ///< SPI Data 00 (32 bits)=
=0D
+=0D
+#define R_SPI_FRAP 0x50 ///< SPI Flash Regions Acce=
ss Permissions Register=0D
+#define B_SPI_FRAP_BRWA_PLATFORM BIT12 // < Region write access fo=
r Region4 PlatformData=0D
+#define B_SPI_FRAP_BRWA_GBE BIT11 // < Region write access fo=
r Region3 GbE=0D
+#define B_SPI_FRAP_BRWA_SEC BIT10 ///< Region Write Access fo=
r Region2 SEC=0D
+#define B_SPI_FRAP_BRWA_BIOS BIT9 ///< Region Write Access fo=
r Region1 BIOS=0D
+#define B_SPI_FRAP_BRWA_FLASHD BIT8 ///< Region Write Access fo=
r Region0 Flash Descriptor=0D
+#define B_SPI_FRAP_BRRA_PLATFORM BIT4 ///< Region read access for=
Region4 PlatformData=0D
+#define B_SPI_FRAP_BRRA_GBE BIT3 ///< Region read access for=
Region3 GbE=0D
+#define B_SPI_FRAP_BRRA_SEC BIT2 ///< Region Read Access for=
Region2 SEC=0D
+#define B_SPI_FRAP_BRRA_BIOS BIT1 ///< Region Read Access for=
Region1 BIOS=0D
+#define B_SPI_FRAP_BRRA_FLASHD BIT0 ///< Region Read Access for=
Region0 Flash Descriptor=0D
+=0D
+#define R_SPI_FREG0_FLASHD 0x54 ///< Flash Region 0 (F=
lash Descriptor) (32bits)=0D
+#define B_SPI_FREG0_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] her=
e represents limit[26:12]=0D
+#define N_SPI_FREG0_LIMIT 4 ///< Bit 30:16 identif=
ies address bits [26:12]=0D
+#define B_SPI_FREG0_BASE_MASK 0x00007FFF ///< Base, [14:0] her=
e represents base [26:12]=0D
+#define N_SPI_FREG0_BASE 12 ///< Bit 14:0 identifi=
es address bits [26:2]=0D
+=0D
+#define R_SPI_FREG1_BIOS 0x58 ///< Flash Region 1 (B=
IOS) (32bits)=0D
+#define B_SPI_FREG1_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] her=
e represents limit[26:12]=0D
+#define N_SPI_FREG1_LIMIT 4 ///< Bit 30:16 identif=
ies address bits [26:12]=0D
+#define B_SPI_FREG1_BASE_MASK 0x00007FFF ///< Base, [14:0] her=
e represents base [26:12]=0D
+#define N_SPI_FREG1_BASE 12 ///< Bit 14:0 identifi=
es address bits [26:2]=0D
+=0D
+#define R_SPI_FREG2_SEC 0x5C ///< Flash Region 2 (S=
EC) (32bits)=0D
+#define B_SPI_FREG2_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] her=
e represents limit[26:12]=0D
+#define N_SPI_FREG2_LIMIT 4 // < Bit 30:16 identif=
ies address bits [26:12]=0D
+#define B_SPI_FREG2_BASE_MASK 0x00007FFF ///< Base, [14:0] her=
e represents base [26:12]=0D
+#define N_SPI_FREG2_BASE 12 // < Bit 14:0 identifi=
es address bits [26:2]=0D
+=0D
+#define R_SPI_FREG3_GBE 0x60 // < Flash Region 3(Gb=
E)(32bits)=0D
+#define B_SPI_FREG3_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] her=
e represents limit[26:12]=0D
+#define N_SPI_FREG3_LIMIT 4 // < Bit 30:16 identif=
ies address bits [26:12]=0D
+#define B_SPI_FREG3_BASE_MASK 0x00007FFF ///< Base, [14:0] her=
e represents base [26:12]=0D
+#define N_SPI_FREG3_BASE 12 // < Bit 14:0 identifi=
es address bits [26:2]=0D
+=0D
+#define R_SPI_FREG4_PLATFORM_DATA 0x64 ///< Flash Region 4 (P=
latform Data) (32bits)=0D
+#define B_SPI_FREG4_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] her=
e represents limit[26:12]=0D
+#define N_SPI_FREG4_LIMIT 4 ///< Bit 30:16 identif=
ies address bits [26:12]=0D
+#define B_SPI_FREG4_BASE_MASK 0x00007FFF ///< Base, [14:0] her=
e represents base [26:12]=0D
+#define N_SPI_FREG4_BASE 12 ///< Bit 14:0 identifi=
es address bits [26:2]=0D
+=0D
+#define S_SPI_FREGX 4 ///< Size of Flash Reg=
ion register=0D
+#define B_SPI_FREGX_LIMIT_MASK 0x7FFF0000 ///< Flash Region Limi=
t [30:16] represents [26:12], [11:0] are assumed to be FFFh=0D
+#define N_SPI_FREGX_LIMIT 16 ///< Region limit bit =
position=0D
+#define N_SPI_FREGX_LIMIT_REPR 12 ///< Region limit bit =
represents position=0D
+#define B_SPI_FREGX_BASE_MASK 0x00007FFF ///< Flash Region Base=
, [14:0] represents [26:12]=0D
+=0D
+#define R_SPI_FDOC 0xB4 ///< Flash Descripto=
r Observability Control Register (32 bits)=0D
+#define B_SPI_FDOC_FDSS_MASK (BIT14 | BIT13 | BIT12) ///< Flash Descripto=
r Section Select=0D
+#define V_SPI_FDOC_FDSS_FSDM 0x0000 ///< Flash Signature=
and Descriptor Map=0D
+#define V_SPI_FDOC_FDSS_COMP 0x1000 ///< Component=0D
+#define B_SPI_FDOC_FDSI_MASK 0x0FFC ///< Flash Descripto=
r Section Index=0D
+=0D
+#define R_SPI_FDOD 0xB8 ///< Flash Descriptor Obser=
vability Data Register (32 bits)=0D
+=0D
+#define R_SPI_LVSCC 0xC4 ///< Vendor Specific Compon=
ent Capabilities for Component 0 (32 bits)=0D
+#define B_SPI_LVSCC_EO_64K BIT29 ///< < 64k Erase valid (EO_=
64k_valid)=0D
+=0D
+#define R_SPI_UVSCC 0xC8 ///< Vendor Specific Compon=
ent Capabilities for Component 1 (32 bits)=0D
+=0D
+#define R_SPI_FDBAR_FLASH_MAP0 0x14 ///< Flash MAP 0=0D
+#define N_SPI_FDBAR_NC 8 ///< < Number Of Components=
=0D
+#define B_SPI_FDBAR_NC 0x00000300 ///< Number Of Components=0D
+=0D
+#define R_SPI_FDBAR_FLASH_MAP1 0x18 ///< Flash MAP 1=0D
+#define B_SPI_FDBAR_FPSBA 0x00FF0000 ///< Flash Strap Base Addre=
ss=0D
+=0D
+//=0D
+// Flash Component Base Address (FCBA) from Flash Region 0=0D
+//=0D
+#define R_SPI_FCBA_FLCOMP 0x00 ///< Flash Components Regis=
ter=0D
+#define B_SPI_FLCOMP_COMP1_MASK 0x0F ///< Flash Component 1 Dens=
ity=0D
+=0D
+#endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommo=
n.h b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h
new file mode 100644
index 0000000000..95e9b9b1e7
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h
@@ -0,0 +1,203 @@
+/** @file=0D
+ Header file for the SPI flash module.=0D
+=0D
+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef SPI_COMMON_LIB_H_=0D
+#define SPI_COMMON_LIB_H_=0D
+=0D
+#include <PiDxe.h>=0D
+#include <Uefi/UefiBaseType.h>=0D
+#include <IndustryStandard/Pci30.h>=0D
+#include <Library/IoLib.h>=0D
+#include <Library/DebugLib.h>=0D
+#include <Library/BaseMemoryLib.h>=0D
+#include <Library/SpiFlashLib.h>=0D
+#include <Library/MemoryAllocationLib.h>=0D
+#include <Library/BaseLib.h>=0D
+#include <Library/HobLib.h>=0D
+#include <Library/TimerLib.h>=0D
+#include <Guid/SpiFlashInfoGuid.h>=0D
+#include "RegsSpi.h"=0D
+=0D
+///=0D
+/// Maximum time allowed while waiting the SPI cycle to complete=0D
+/// Wait Time =3D 6 seconds =3D 6000000 microseconds=0D
+/// Wait Period =3D 10 microseconds=0D
+///=0D
+#define WAIT_TIME 6000000 ///< Wait Time =3D 6 seconds =3D 6000000 m=
icroseconds=0D
+#define WAIT_PERIOD 10 ///< Wait Period =3D 10 microseconds=0D
+=0D
+///=0D
+/// Flash cycle Type=0D
+///=0D
+typedef enum {=0D
+ FlashCycleRead,=0D
+ FlashCycleWrite,=0D
+ FlashCycleErase,=0D
+ FlashCycleReadSfdp,=0D
+ FlashCycleReadJedecId,=0D
+ FlashCycleWriteStatus,=0D
+ FlashCycleReadStatus,=0D
+ FlashCycleMax=0D
+} FLASH_CYCLE_TYPE;=0D
+=0D
+///=0D
+/// Flash Component Number=0D
+///=0D
+typedef enum {=0D
+ FlashComponent0,=0D
+ FlashComponent1,=0D
+ FlashComponentMax=0D
+} FLASH_COMPONENT_NUM;=0D
+=0D
+///=0D
+/// Private data structure definitions for the driver=0D
+///=0D
+#define SC_SPI_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('P', 'S', 'P', 'I')=0D
+=0D
+typedef struct {=0D
+ UINTN Signature;=0D
+ EFI_HANDLE Handle;=0D
+ UINT32 AcpiTmrReg;=0D
+ UINTN PchSpiBase;=0D
+ UINT16 RegionPermission;=0D
+ UINT32 SfdpVscc0Value;=0D
+ UINT32 SfdpVscc1Value;=0D
+ UINT32 StrapBaseAddress;=0D
+ UINT8 NumberOfComponents;=0D
+ UINT16 Flags;=0D
+ UINT32 Component1StartAddr;=0D
+} SPI_INSTANCE;=0D
+=0D
+/**=0D
+ Acquire SPI MMIO BAR=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+=0D
+ @retval Return SPI BAR Address=0D
+=0D
+**/=0D
+UINT32=0D
+AcquireSpiBar0 (=0D
+ IN UINTN PchSpiBase=0D
+ );=0D
+=0D
+/**=0D
+ Release SPI MMIO BAR. Do nothing.=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+=0D
+ @retval None=0D
+=0D
+**/=0D
+VOID=0D
+ReleaseSpiBar0 (=0D
+ IN UINTN PchSpiBase=0D
+ );=0D
+=0D
+/**=0D
+ This function is a hook for Spi to disable BIOS Write Protect=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write prote=
ction or not=0D
+=0D
+ @retval EFI_SUCCESS The protocol instance was properly initi=
alized=0D
+ @retval EFI_ACCESS_DENIED The BIOS Region can only be updated in S=
MM phase=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+DisableBiosWriteProtect (=0D
+ IN UINTN PchSpiBase,=0D
+ IN UINT8 CpuSmmBwp=0D
+ );=0D
+=0D
+/**=0D
+ This function is a hook for Spi to enable BIOS Write Protect=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write prote=
ction or not=0D
+=0D
+ @retval None=0D
+=0D
+**/=0D
+VOID=0D
+EFIAPI=0D
+EnableBiosWriteProtect (=0D
+ IN UINTN PchSpiBase,=0D
+ IN UINT8 CpuSmmBwp=0D
+ );=0D
+=0D
+/**=0D
+ This function disables SPI Prefetching and caching,=0D
+ and returns previous BIOS Control Register value before disabling.=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+=0D
+ @retval Previous BIOS Control Register value=0D
+=0D
+**/=0D
+UINT8=0D
+SaveAndDisableSpiPrefetchCache (=0D
+ IN UINTN PchSpiBase=0D
+ );=0D
+=0D
+/**=0D
+ This function updates BIOS Control Register with the given value.=0D
+=0D
+ @param[in] PchSpiBase PCH SPI PCI Base Address=0D
+ @param[in] BiosCtlValue BIOS Control Register Value to be update=
d=0D
+=0D
+ @retval None=0D
+=0D
+**/=0D
+VOID=0D
+SetSpiBiosControlRegister (=0D
+ IN UINTN PchSpiBase,=0D
+ IN UINT8 BiosCtlValue=0D
+ );=0D
+=0D
+/**=0D
+ This function sends the programmed SPI command to the slave device.=0D
+=0D
+ @param[in] SpiRegionType The SPI Region type for flash cycle whic=
h is listed in the Descriptor=0D
+ @param[in] FlashCycleType The Flash SPI cycle type list in HSFC (H=
ardware Sequencing Flash Control Register) register=0D
+ @param[in] Address The Flash Linear Address must fall withi=
n a region for which BIOS has access permissions.=0D
+ @param[in] ByteCount Number of bytes in the data portion of t=
he SPI cycle.=0D
+ @param[in,out] Buffer Pointer to caller-allocated buffer conta=
ining the data received or sent during the SPI cycle.=0D
+=0D
+ @retval EFI_SUCCESS SPI command completes successfully.=0D
+ @retval EFI_DEVICE_ERROR Device error, the command aborts abnorma=
lly.=0D
+ @retval EFI_ACCESS_DENIED Some unrecognized command encountered in=
hardware sequencing mode=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+**/=0D
+EFI_STATUS=0D
+SendSpiCmd (=0D
+ IN FLASH_REGION_TYPE FlashRegionType,=0D
+ IN FLASH_CYCLE_TYPE FlashCycleType,=0D
+ IN UINT32 Address,=0D
+ IN UINT32 ByteCount,=0D
+ IN OUT UINT8 *Buffer=0D
+ );=0D
+=0D
+/**=0D
+ Wait execution cycle to complete on the SPI interface.=0D
+=0D
+ @param[in] PchSpiBar0 Spi MMIO base address=0D
+ @param[in] ErrorCheck TRUE if the SpiCycle needs to do the err=
or check=0D
+=0D
+ @retval TRUE SPI cycle completed on the interface.=0D
+ @retval FALSE Time out while waiting the SPI cycle to =
complete.=0D
+ It's not safe to program the next comman=
d on the SPI interface.=0D
+**/=0D
+BOOLEAN=0D
+WaitForSpiCycleComplete (=0D
+ IN UINT32 PchSpiBar0,=0D
+ IN BOOLEAN ErrorCheck=0D
+ );=0D
+=0D
+#endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlash=
Lib.c b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c
new file mode 100644
index 0000000000..22639a748c
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c
@@ -0,0 +1,874 @@
+/** @file=0D
+ Generic driver using Hardware Sequencing registers.=0D
+=0D
+ Copyright (c) 2017-2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+#include "SpiCommon.h"=0D
+=0D
+SPI_INSTANCE *mSpiInstance =3D NULL;=0D
+=0D
+/**=0D
+ Get SPI Instance from library global data..=0D
+=0D
+ @retval SpiInstance Return SPI instance=0D
+**/=0D
+SPI_INSTANCE *=0D
+GetSpiInstance (=0D
+ VOID=0D
+ )=0D
+{=0D
+ if (mSpiInstance =3D=3D NULL) {=0D
+ mSpiInstance =3D AllocatePool (sizeof (SPI_INSTANCE));=0D
+ if (mSpiInstance =3D=3D NULL) {=0D
+ return NULL;=0D
+ }=0D
+=0D
+ ZeroMem (mSpiInstance, sizeof (SPI_INSTANCE));=0D
+ }=0D
+=0D
+ return mSpiInstance;=0D
+}=0D
+=0D
+/**=0D
+ Initialize an SPI library.=0D
+=0D
+ @retval EFI_SUCCESS The protocol instance was properly initi=
alized=0D
+ @retval EFI_NOT_FOUND The expected SPI info could not be found=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiConstructor (=0D
+ VOID=0D
+ )=0D
+{=0D
+ UINT32 ScSpiBar0;=0D
+ UINT8 Comp0Density;=0D
+ SPI_INSTANCE *SpiInstance;=0D
+ EFI_HOB_GUID_TYPE *GuidHob;=0D
+ SPI_FLASH_INFO *SpiFlashInfo;=0D
+=0D
+ //=0D
+ // Find SPI flash hob=0D
+ //=0D
+ GuidHob =3D GetFirstGuidHob (&gSpiFlashInfoGuid);=0D
+ if (GuidHob =3D=3D NULL) {=0D
+ ASSERT (FALSE);=0D
+ return EFI_NOT_FOUND;=0D
+ }=0D
+=0D
+ SpiFlashInfo =3D (SPI_FLASH_INFO *)GET_GUID_HOB_DATA (GuidHob);=0D
+=0D
+ //=0D
+ // Initialize the SPI instance=0D
+ //=0D
+ SpiInstance =3D GetSpiInstance ();=0D
+ if (SpiInstance =3D=3D NULL) {=0D
+ return EFI_NOT_FOUND;=0D
+ }=0D
+=0D
+ DEBUG ((DEBUG_INFO, "SpiInstance =3D %08X\n", SpiInstance));=0D
+=0D
+ SpiInstance->Signature =3D SC_SPI_PRIVATE_DATA_SIGNATURE;=0D
+ SpiInstance->Handle =3D NULL;=0D
+=0D
+ //=0D
+ // Check the SPI address=0D
+ //=0D
+ if ((SpiFlashInfo->SpiAddress.AddressSpaceId !=3D EFI_ACPI_3_0_PCI_CONF=
IGURATION_SPACE) ||=0D
+ (SpiFlashInfo->SpiAddress.RegisterBitWidth !=3D 32) ||=0D
+ (SpiFlashInfo->SpiAddress.RegisterBitOffset !=3D 0) ||=0D
+ (SpiFlashInfo->SpiAddress.AccessSize !=3D EFI_ACPI_3_0_DWORD))=0D
+ {=0D
+ DEBUG ((DEBUG_ERROR, "SPI FLASH HOB is not expected. need check the ho=
b or enhance SPI flash driver.\n"));=0D
+ }=0D
+=0D
+ SpiInstance->PchSpiBase =3D (UINT32)(UINTN)SpiFlashInfo->SpiAddress.Addr=
ess;=0D
+ SpiInstance->Flags =3D SpiFlashInfo->Flags;=0D
+ DEBUG ((DEBUG_INFO, "PchSpiBase at 0x%x\n", SpiInstance->PchSpiBase));=0D
+=0D
+ ScSpiBar0 =3D AcquireSpiBar0 (SpiInstance->PchSpiBase);=0D
+ DEBUG ((DEBUG_INFO, "ScSpiBar0 at 0x%08X\n", ScSpiBar0));=0D
+=0D
+ if (ScSpiBar0 =3D=3D 0) {=0D
+ ASSERT (FALSE);=0D
+ }=0D
+=0D
+ if ((MmioRead32 (ScSpiBar0 + R_SPI_HSFS) & B_SPI_HSFS_FDV) =3D=3D 0) {=0D
+ DEBUG ((DEBUG_ERROR, "SPI Flash descriptor invalid, cannot use Hardwar=
e Sequencing registers!\n"));=0D
+ ASSERT (FALSE);=0D
+ }=0D
+=0D
+ MmioOr32 (SpiInstance->PchSpiBase + PCI_COMMAND_OFFSET, EFI_PCI_COMMAND_=
MEMORY_SPACE);=0D
+ SpiInstance->RegionPermission =3D MmioRead16 (ScSpiBar0 + R_SPI_FRAP);=0D
+ SpiInstance->SfdpVscc0Value =3D MmioRead32 (ScSpiBar0 + R_SPI_LVSCC);=
=0D
+ SpiInstance->SfdpVscc1Value =3D MmioRead32 (ScSpiBar0 + R_SPI_UVSCC);=
=0D
+=0D
+ //=0D
+ // Select to Flash Map 0 Register to get the number of flash Component=0D
+ //=0D
+ MmioAndThenOr32 (=0D
+ ScSpiBar0 + R_SPI_FDOC,=0D
+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),=0D
+ (UINT32)(V_SPI_FDOC_FDSS_FSDM | R_SPI_FDBAR_FLASH_MAP0)=0D
+ );=0D
+=0D
+ //=0D
+ // Copy Zero based Number Of Components=0D
+ //=0D
+ SpiInstance->NumberOfComponents =3D (UINT8)((MmioRead16 (ScSpiBar0 + R_S=
PI_FDOD) & B_SPI_FDBAR_NC) >> N_SPI_FDBAR_NC);=0D
+=0D
+ MmioAndThenOr32 (=0D
+ ScSpiBar0 + R_SPI_FDOC,=0D
+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),=0D
+ (UINT32)(V_SPI_FDOC_FDSS_COMP | R_SPI_FCBA_FLCOMP)=0D
+ );=0D
+=0D
+ //=0D
+ // Copy Component 0 Density=0D
+ //=0D
+ Comp0Density =3D (UINT8)MmioRead32 (ScSpiBar0 + R_SP=
I_FDOD) & B_SPI_FLCOMP_COMP1_MASK;=0D
+ SpiInstance->Component1StartAddr =3D (UINT32)(SIZE_512KB << Comp0Density=
);=0D
+=0D
+ //=0D
+ // Select FLASH_MAP1 to get Flash SC Strap Base Address=0D
+ //=0D
+ MmioAndThenOr32 (=0D
+ (ScSpiBar0 + R_SPI_FDOC),=0D
+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),=0D
+ (UINT32)(V_SPI_FDOC_FDSS_FSDM | R_SPI_FDBAR_FLASH_MAP1)=0D
+ );=0D
+=0D
+ SpiInstance->StrapBaseAddress =3D MmioRead32 (ScSpiBar0 + R_SPI_FDOD) & =
B_SPI_FDBAR_FPSBA;=0D
+=0D
+ //=0D
+ // Align FPSBA with address bits for the SC Strap portion of flash descr=
iptor=0D
+ //=0D
+ SpiInstance->StrapBaseAddress &=3D B_SPI_FDBAR_FPSBA;=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Read data from the flash part.=0D
+=0D
+ @param[in] FlashRegionType The Flash Region type for flash cycle wh=
ich is listed in the Descriptor.=0D
+ @param[in] Address The Flash Linear Address must fall withi=
n a region for which BIOS has access permissions.=0D
+ @param[in] ByteCount Number of bytes in the data portion of t=
he SPI cycle.=0D
+ @param[out] Buffer The Pointer to caller-allocated buffer c=
ontaining the data received.=0D
+ It is the caller's responsibility to mak=
e sure Buffer is large enough for the total number of bytes read.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashRead (=0D
+ IN FLASH_REGION_TYPE FlashRegionType,=0D
+ IN UINT32 Address,=0D
+ IN UINT32 ByteCount,=0D
+ OUT UINT8 *Buffer=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+=0D
+ Status =3D SendSpiCmd (FlashRegionType, FlashCycleRead, Address, ByteCou=
nt, Buffer);=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Write data to the flash part.=0D
+=0D
+ @param[in] FlashRegionType The Flash Region type for flash cycle wh=
ich is listed in the Descriptor.=0D
+ @param[in] Address The Flash Linear Address must fall withi=
n a region for which BIOS has access permissions.=0D
+ @param[in] ByteCount Number of bytes in the data portion of t=
he SPI cycle.=0D
+ @param[in] Buffer Pointer to caller-allocated buffer conta=
ining the data sent during the SPI cycle.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashWrite (=0D
+ IN FLASH_REGION_TYPE FlashRegionType,=0D
+ IN UINT32 Address,=0D
+ IN UINT32 ByteCount,=0D
+ IN UINT8 *Buffer=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+=0D
+ Status =3D SendSpiCmd (FlashRegionType, FlashCycleWrite, Address, ByteCo=
unt, Buffer);=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Erase some area on the flash part.=0D
+=0D
+ @param[in] FlashRegionType The Flash Region type for flash cycle wh=
ich is listed in the Descriptor.=0D
+ @param[in] Address The Flash Linear Address must fall withi=
n a region for which BIOS has access permissions.=0D
+ @param[in] ByteCount Number of bytes in the data portion of t=
he SPI cycle.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashErase (=0D
+ IN FLASH_REGION_TYPE FlashRegionType,=0D
+ IN UINT32 Address,=0D
+ IN UINT32 ByteCount=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+=0D
+ Status =3D SendSpiCmd (FlashRegionType, FlashCycleErase, Address, ByteCo=
unt, NULL);=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Read SFDP data from the flash part.=0D
+=0D
+ @param[in] ComponentNumber The Component Number for chip select=0D
+ @param[in] ByteCount Number of bytes in SFDP data portion of =
the SPI cycle, the max number is 64=0D
+ @param[out] SfdpData The Pointer to caller-allocated buffer c=
ontaining the SFDP data received=0D
+ It is the caller's responsibility to mak=
e sure Buffer is large enough for the total number of bytes read.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashReadSfdp (=0D
+ IN UINT8 ComponentNumber,=0D
+ IN UINT32 ByteCount,=0D
+ OUT UINT8 *SfdpData=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ UINT32 Address;=0D
+ SPI_INSTANCE *SpiInstance;=0D
+=0D
+ SpiInstance =3D GetSpiInstance ();=0D
+ if (SpiInstance =3D=3D NULL) {=0D
+ return EFI_DEVICE_ERROR;=0D
+ }=0D
+=0D
+ if ((ByteCount > 64) || (ComponentNumber > SpiInstance->NumberOfComponen=
ts)) {=0D
+ ASSERT (FALSE);=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ Address =3D 0;=0D
+ if (ComponentNumber =3D=3D FlashComponent1) {=0D
+ Address =3D SpiInstance->Component1StartAddr;=0D
+ }=0D
+=0D
+ Status =3D SendSpiCmd (0, FlashCycleReadSfdp, Address, ByteCount, SfdpDa=
ta);=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Read Jedec Id from the flash part.=0D
+=0D
+ @param[in] ComponentNumber The Component Number for chip select=0D
+ @param[in] ByteCount Number of bytes in JedecId data portion =
of the SPI cycle, the data size is 3 typically=0D
+ @param[out] JedecId The Pointer to caller-allocated buffer c=
ontaining JEDEC ID received=0D
+ It is the caller's responsibility to mak=
e sure Buffer is large enough for the total number of bytes read.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashReadJedecId (=0D
+ IN UINT8 ComponentNumber,=0D
+ IN UINT32 ByteCount,=0D
+ OUT UINT8 *JedecId=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ UINT32 Address;=0D
+ SPI_INSTANCE *SpiInstance;=0D
+=0D
+ SpiInstance =3D GetSpiInstance ();=0D
+ if (SpiInstance =3D=3D NULL) {=0D
+ return EFI_DEVICE_ERROR;=0D
+ }=0D
+=0D
+ if (ComponentNumber > SpiInstance->NumberOfComponents) {=0D
+ ASSERT (FALSE);=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ Address =3D 0;=0D
+ if (ComponentNumber =3D=3D FlashComponent1) {=0D
+ Address =3D SpiInstance->Component1StartAddr;=0D
+ }=0D
+=0D
+ Status =3D SendSpiCmd (0, FlashCycleReadJedecId, Address, ByteCount, Jed=
ecId);=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Write the status register in the flash part.=0D
+=0D
+ @param[in] ByteCount Number of bytes in Status data portion o=
f the SPI cycle, the data size is 1 typically=0D
+ @param[in] StatusValue The Pointer to caller-allocated buffer c=
ontaining the value of Status register writing=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashWriteStatus (=0D
+ IN UINT32 ByteCount,=0D
+ IN UINT8 *StatusValue=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+=0D
+ Status =3D SendSpiCmd (0, FlashCycleWriteStatus, 0, ByteCount, StatusVal=
ue);=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Read status register in the flash part.=0D
+=0D
+ @param[in] ByteCount Number of bytes in Status data portion o=
f the SPI cycle, the data size is 1 typically=0D
+ @param[out] StatusValue The Pointer to caller-allocated buffer c=
ontaining the value of Status register received.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiFlashReadStatus (=0D
+ IN UINT32 ByteCount,=0D
+ OUT UINT8 *StatusValue=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+=0D
+ Status =3D SendSpiCmd (0, FlashCycleReadStatus, 0, ByteCount, StatusValu=
e);=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Read SC Soft Strap Values=0D
+=0D
+ @param[in] SoftStrapAddr SC Soft Strap address offset from FPSBA.=
=0D
+ @param[in] ByteCount Number of bytes in SoftStrap data portio=
n of the SPI cycle=0D
+ @param[out] SoftStrapValue The Pointer to caller-allocated buffer c=
ontaining SC Soft Strap Value.=0D
+ It is the caller's responsibility to mak=
e sure Buffer is large enough for the total number of bytes read.=0D
+=0D
+ @retval EFI_SUCCESS Command succeed.=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.=
=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiReadPchSoftStrap (=0D
+ IN UINT32 SoftStrapAddr,=0D
+ IN UINT32 ByteCount,=0D
+ OUT UINT8 *SoftStrapValue=0D
+ )=0D
+{=0D
+ UINT32 StrapFlashAddr;=0D
+ EFI_STATUS Status;=0D
+ SPI_INSTANCE *SpiInstance;=0D
+=0D
+ SpiInstance =3D GetSpiInstance ();=0D
+ if (SpiInstance =3D=3D NULL) {=0D
+ return EFI_DEVICE_ERROR;=0D
+ }=0D
+=0D
+ ASSERT (SpiInstance->StrapBaseAddress !=3D 0);=0D
+ //=0D
+ // SC Strap Flash Address =3D FPSBA + RamAddr=0D
+ //=0D
+ StrapFlashAddr =3D SpiInstance->StrapBaseAddress + SoftStrapAddr;=0D
+=0D
+ Status =3D SendSpiCmd (FlashRegionDescriptor, FlashCycleRead, StrapFlash=
Addr, ByteCount, SoftStrapValue);=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ This function sends the programmed SPI command to the slave device.=0D
+=0D
+ @param[in] FlashRegionType The SPI Region type for flash cycle whic=
h is listed in the Descriptor=0D
+ @param[in] FlashCycleType The Flash SPI cycle type list in HSFC (H=
ardware Sequencing Flash Control Register) register=0D
+ @param[in] Address The Flash Linear Address must fall withi=
n a region for which BIOS has access permissions.=0D
+ @param[in] ByteCount Number of bytes in the data portion of t=
he SPI cycle.=0D
+ @param[in,out] Buffer Pointer to caller-allocated buffer conta=
ining the data received or sent during the SPI cycle.=0D
+=0D
+ @retval EFI_SUCCESS SPI command completes successfully.=0D
+ @retval EFI_DEVICE_ERROR Device error, the command aborts abnorma=
lly.=0D
+ @retval EFI_ACCESS_DENIED Some unrecognized command encountered in=
hardware sequencing mode=0D
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.=
=0D
+**/=0D
+EFI_STATUS=0D
+SendSpiCmd (=0D
+ IN FLASH_REGION_TYPE FlashRegionType,=0D
+ IN FLASH_CYCLE_TYPE FlashCycleType,=0D
+ IN UINT32 Address,=0D
+ IN UINT32 ByteCount,=0D
+ IN OUT UINT8 *Buffer=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ UINT32 Index;=0D
+ UINTN SpiBaseAddress;=0D
+ UINT32 ScSpiBar0;=0D
+ UINT32 LimitAddress;=0D
+ UINT32 HardwareSpiAddr;=0D
+ UINT16 PermissionBit;=0D
+ UINT32 SpiDataCount;=0D
+ UINT32 FlashCycle;=0D
+ UINT8 BiosCtlSave;=0D
+ SPI_INSTANCE *SpiInstance;=0D
+ UINT32 Data32;=0D
+=0D
+ SpiInstance =3D GetSpiInstance ();=0D
+ if (SpiInstance =3D=3D NULL) {=0D
+ return EFI_DEVICE_ERROR;=0D
+ }=0D
+=0D
+ Status =3D EFI_SUCCESS;=0D
+ SpiBaseAddress =3D SpiInstance->PchSpiBase;=0D
+ ScSpiBar0 =3D AcquireSpiBar0 (SpiBaseAddress);=0D
+ BiosCtlSave =3D 0;=0D
+ SpiInstance->RegionPermission =3D MmioRead16 (ScSpiBar0 + R_SPI_FRAP);=0D
+=0D
+ //=0D
+ // If it's write cycle, disable Prefetching, Caching and disable BIOS Wr=
ite Protect=0D
+ //=0D
+ if ((FlashCycleType =3D=3D FlashCycleWrite) || (FlashCycleType =3D=3D Fl=
ashCycleErase)) {=0D
+ Status =3D DisableBiosWriteProtect (SpiBaseAddress, mSpiInstance->Flag=
s & FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT);=0D
+ if (EFI_ERROR (Status)) {=0D
+ goto SendSpiCmdEnd;=0D
+ }=0D
+=0D
+ BiosCtlSave =3D SaveAndDisableSpiPrefetchCache (SpiBaseAddress);=0D
+ }=0D
+=0D
+ //=0D
+ // Make sure it's safe to program the command.=0D
+ //=0D
+ if (!WaitForSpiCycleComplete (ScSpiBar0, FALSE)) {=0D
+ Status =3D EFI_DEVICE_ERROR;=0D
+ goto SendSpiCmdEnd;=0D
+ }=0D
+=0D
+ HardwareSpiAddr =3D Address;=0D
+ if ((FlashCycleType =3D=3D FlashCycleRead) ||=0D
+ (FlashCycleType =3D=3D FlashCycleWrite) ||=0D
+ (FlashCycleType =3D=3D FlashCycleErase))=0D
+ {=0D
+ switch (FlashRegionType) {=0D
+ case FlashRegionDescriptor:=0D
+ if (FlashCycleType =3D=3D FlashCycleRead) {=0D
+ PermissionBit =3D B_SPI_FRAP_BRRA_FLASHD;=0D
+ } else {=0D
+ PermissionBit =3D B_SPI_FRAP_BRWA_FLASHD;=0D
+ }=0D
+=0D
+ Data32 =3D MmioRead32 (ScSpiBar0 + R_SPI_FREG0_FLASHD);=
=0D
+ HardwareSpiAddr +=3D (Data32 & B_SPI_FREG0_BASE_MASK) << N_SPI_FRE=
G0_BASE;=0D
+ LimitAddress =3D (Data32 & B_SPI_FREG0_LIMIT_MASK) >> N_SPI_FR=
EG0_LIMIT;=0D
+ break;=0D
+=0D
+ case FlashRegionBios:=0D
+ if (FlashCycleType =3D=3D FlashCycleRead) {=0D
+ PermissionBit =3D B_SPI_FRAP_BRRA_BIOS;=0D
+ } else {=0D
+ PermissionBit =3D B_SPI_FRAP_BRWA_BIOS;=0D
+ }=0D
+=0D
+ Data32 =3D MmioRead32 (ScSpiBar0 + R_SPI_FREG1_BIOS);=0D
+ HardwareSpiAddr +=3D (Data32 & B_SPI_FREG1_BASE_MASK) << N_SPI_FRE=
G1_BASE;=0D
+ LimitAddress =3D (Data32 & B_SPI_FREG1_LIMIT_MASK) >> N_SPI_FR=
EG1_LIMIT;=0D
+ break;=0D
+=0D
+ case FlashRegionMe:=0D
+ if (FlashCycleType =3D=3D FlashCycleRead) {=0D
+ PermissionBit =3D B_SPI_FRAP_BRRA_SEC;=0D
+ } else {=0D
+ PermissionBit =3D B_SPI_FRAP_BRWA_SEC;=0D
+ }=0D
+=0D
+ Data32 =3D MmioRead32 (ScSpiBar0 + R_SPI_FREG2_SEC);=0D
+ HardwareSpiAddr +=3D (Data32 & B_SPI_FREG2_BASE_MASK) << N_SPI_FRE=
G2_BASE;=0D
+ LimitAddress =3D (Data32 & B_SPI_FREG2_LIMIT_MASK) >> N_SPI_FR=
EG2_LIMIT;=0D
+ break;=0D
+=0D
+ case FlashRegionGbE:=0D
+ if (FlashCycleType =3D=3D FlashCycleRead) {=0D
+ PermissionBit =3D B_SPI_FRAP_BRRA_GBE;=0D
+ } else {=0D
+ PermissionBit =3D B_SPI_FRAP_BRWA_GBE;=0D
+ }=0D
+=0D
+ Data32 =3D MmioRead32 (ScSpiBar0 + R_SPI_FREG3_GBE);=0D
+ HardwareSpiAddr +=3D (Data32 & B_SPI_FREG3_BASE_MASK) << N_SPI_FRE=
G3_BASE;=0D
+ LimitAddress =3D (Data32 & B_SPI_FREG3_LIMIT_MASK) >> N_SPI_FR=
EG3_LIMIT;=0D
+ break;=0D
+=0D
+ case FlashRegionPlatformData:=0D
+ if (FlashCycleType =3D=3D FlashCycleRead) {=0D
+ PermissionBit =3D B_SPI_FRAP_BRRA_PLATFORM;=0D
+ } else {=0D
+ PermissionBit =3D B_SPI_FRAP_BRWA_PLATFORM;=0D
+ }=0D
+=0D
+ Data32 =3D MmioRead32 (ScSpiBar0 + R_SPI_FREG4_PLATFORM_=
DATA);=0D
+ HardwareSpiAddr +=3D (Data32 & B_SPI_FREG4_BASE_MASK) << N_SPI_FRE=
G4_BASE;=0D
+ LimitAddress =3D (Data32 & B_SPI_FREG4_LIMIT_MASK) >> N_SPI_FR=
EG4_LIMIT;=0D
+ break;=0D
+=0D
+ case FlashRegionAll:=0D
+ //=0D
+ // FlashRegionAll indicates address is relative to flash device=0D
+ // No error checking for this case=0D
+ //=0D
+ LimitAddress =3D 0;=0D
+ PermissionBit =3D 0;=0D
+ break;=0D
+=0D
+ default:=0D
+ Status =3D EFI_UNSUPPORTED;=0D
+ goto SendSpiCmdEnd;=0D
+ }=0D
+=0D
+ if ((LimitAddress !=3D 0) && (Address > LimitAddress)) {=0D
+ Status =3D EFI_INVALID_PARAMETER;=0D
+ goto SendSpiCmdEnd;=0D
+ }=0D
+=0D
+ //=0D
+ // If the operation is read, but the region attribute is not read allo=
wed, return error.=0D
+ // If the operation is write, but the region attribute is not write al=
lowed, return error.=0D
+ //=0D
+ if ((PermissionBit !=3D 0) && ((SpiInstance->RegionPermission & Permis=
sionBit) =3D=3D 0)) {=0D
+ Status =3D EFI_ACCESS_DENIED;=0D
+ goto SendSpiCmdEnd;=0D
+ }=0D
+ }=0D
+=0D
+ //=0D
+ // Check for SC SPI hardware sequencing required commands=0D
+ //=0D
+ FlashCycle =3D 0;=0D
+ switch (FlashCycleType) {=0D
+ case FlashCycleRead:=0D
+ FlashCycle =3D (UINT32)(V_SPI_HSFS_CYCLE_READ << N_SPI_HSFS_CYCLE);=
=0D
+ break;=0D
+=0D
+ case FlashCycleWrite:=0D
+ FlashCycle =3D (UINT32)(V_SPI_HSFS_CYCLE_WRITE << N_SPI_HSFS_CYCLE);=
=0D
+ break;=0D
+=0D
+ case FlashCycleErase:=0D
+ if (((ByteCount % SIZE_4KB) !=3D 0) || ((HardwareSpiAddr % SIZE_4KB)=
!=3D 0)) {=0D
+ DEBUG ((DEBUG_ERROR, "Erase and erase size must be 4KB aligned. \n=
"));=0D
+ ASSERT (FALSE);=0D
+ Status =3D EFI_INVALID_PARAMETER;=0D
+ goto SendSpiCmdEnd;=0D
+ }=0D
+=0D
+ break;=0D
+=0D
+ case FlashCycleReadSfdp:=0D
+ FlashCycle =3D (UINT32)(V_SPI_HSFS_CYCLE_READ_SFDP << N_SPI_HSFS_CYC=
LE);=0D
+ break;=0D
+=0D
+ case FlashCycleReadJedecId:=0D
+ FlashCycle =3D (UINT32)(V_SPI_HSFS_CYCLE_READ_JEDEC_ID << N_SPI_HSFS=
_CYCLE);=0D
+ break;=0D
+=0D
+ case FlashCycleWriteStatus:=0D
+ FlashCycle =3D (UINT32)(V_SPI_HSFS_CYCLE_WRITE_STATUS << N_SPI_HSFS_=
CYCLE);=0D
+ break;=0D
+=0D
+ case FlashCycleReadStatus:=0D
+ FlashCycle =3D (UINT32)(V_SPI_HSFS_CYCLE_READ_STATUS << N_SPI_HSFS_C=
YCLE);=0D
+ break;=0D
+=0D
+ default:=0D
+ //=0D
+ // Unrecognized Operation=0D
+ //=0D
+ ASSERT (FALSE);=0D
+ Status =3D EFI_INVALID_PARAMETER;=0D
+ goto SendSpiCmdEnd;=0D
+ break;=0D
+ }=0D
+=0D
+ do {=0D
+ SpiDataCount =3D ByteCount;=0D
+ if ((FlashCycleType =3D=3D FlashCycleRead) || (FlashCycleType =3D=3D F=
lashCycleWrite)) {=0D
+ //=0D
+ // Trim at 256 byte boundary per operation,=0D
+ // - SC SPI controller requires trimming at 4KB boundary=0D
+ // - Some SPI chips require trimming at 256 byte boundary for write =
operation=0D
+ // - Trimming has limited performance impact as we can read / write =
at most 64 byte=0D
+ // per operation=0D
+ //=0D
+ if (HardwareSpiAddr + ByteCount > ((HardwareSpiAddr + BIT8) &~(BIT8 =
- 1))) {=0D
+ SpiDataCount =3D (((UINT32)(HardwareSpiAddr) + BIT8) &~(BIT8 - 1))=
- (UINT32)(HardwareSpiAddr);=0D
+ }=0D
+=0D
+ //=0D
+ // Calculate the number of bytes to shift in/out during the SPI data=
cycle.=0D
+ // Valid settings for the number of bytes during each data portion o=
f the=0D
+ // SC SPI cycles are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 24, 32, 40, 48,=
56, 64=0D
+ //=0D
+ if (SpiDataCount >=3D 64) {=0D
+ SpiDataCount =3D 64;=0D
+ } else if ((SpiDataCount &~0x07) !=3D 0) {=0D
+ SpiDataCount =3D SpiDataCount &~0x07;=0D
+ }=0D
+ }=0D
+=0D
+ if (FlashCycleType =3D=3D FlashCycleErase) {=0D
+ if (((ByteCount / SIZE_64KB) !=3D 0) &&=0D
+ ((ByteCount % SIZE_64KB) =3D=3D 0) &&=0D
+ ((HardwareSpiAddr % SIZE_64KB) =3D=3D 0))=0D
+ {=0D
+ if (HardwareSpiAddr < SpiInstance->Component1StartAddr) {=0D
+ //=0D
+ // Check whether Component0 support 64k Erase=0D
+ //=0D
+ if ((SpiInstance->SfdpVscc0Value & B_SPI_LVSCC_EO_64K) !=3D 0) {=
=0D
+ SpiDataCount =3D SIZE_64KB;=0D
+ } else {=0D
+ SpiDataCount =3D SIZE_4KB;=0D
+ }=0D
+ } else {=0D
+ //=0D
+ // Check whether Component1 support 64k Erase=0D
+ //=0D
+ if ((SpiInstance->SfdpVscc1Value & B_SPI_LVSCC_EO_64K) !=3D 0) {=
=0D
+ SpiDataCount =3D SIZE_64KB;=0D
+ } else {=0D
+ SpiDataCount =3D SIZE_4KB;=0D
+ }=0D
+ }=0D
+ } else {=0D
+ SpiDataCount =3D SIZE_4KB;=0D
+ }=0D
+=0D
+ if (SpiDataCount =3D=3D SIZE_4KB) {=0D
+ FlashCycle =3D (UINT32)(V_SPI_HSFS_CYCLE_4K_ERASE << N_SPI_HSFS_CY=
CLE);=0D
+ } else {=0D
+ FlashCycle =3D (UINT32)(V_SPI_HSFS_CYCLE_64K_ERASE << N_SPI_HSFS_C=
YCLE);=0D
+ }=0D
+ }=0D
+=0D
+ //=0D
+ // If it's write cycle, load data into the SPI data buffer.=0D
+ //=0D
+ if ((FlashCycleType =3D=3D FlashCycleWrite) || (FlashCycleType =3D=3D =
FlashCycleWriteStatus)) {=0D
+ if ((SpiDataCount & 0x07) !=3D 0) {=0D
+ //=0D
+ // Use Byte write if Data Count is 0, 1, 2, 3, 4, 5, 6, 7=0D
+ //=0D
+ for (Index =3D 0; Index < SpiDataCount; Index++) {=0D
+ MmioWrite8 (ScSpiBar0 + R_SPI_FDATA00 + Index, Buffer[Index]);=0D
+ }=0D
+ } else {=0D
+ //=0D
+ // Use Dword write if Data Count is 8, 16, 24, 32, 40, 48, 56, 64=
=0D
+ //=0D
+ for (Index =3D 0; Index < SpiDataCount; Index +=3D sizeof (UINT32)=
) {=0D
+ MmioWrite32 (ScSpiBar0 + R_SPI_FDATA00 + Index, *(UINT32 *)(Buff=
er + Index));=0D
+ }=0D
+ }=0D
+ }=0D
+=0D
+ //=0D
+ // Set the Flash Address=0D
+ //=0D
+ MmioWrite32 (ScSpiBar0 + R_SPI_FADDR, (UINT32)(HardwareSpiAddr & B_SPI=
_FADDR_MASK));=0D
+=0D
+ //=0D
+ // Set Data count, Flash cycle, and Set Go bit to start a cycle=0D
+ //=0D
+ MmioAndThenOr32 (=0D
+ ScSpiBar0 + R_SPI_HSFS,=0D
+ (UINT32)(~(B_SPI_HSFS_FDBC_MASK | B_SPI_HSFS_CYCLE_MASK)),=0D
+ (UINT32)(((SpiDataCount - 1) << N_SPI_HSFS_FDBC) | FlashCycle | B_SP=
I_HSFS_CYCLE_FGO)=0D
+ );=0D
+=0D
+ //=0D
+ // Wait for command execution complete.=0D
+ //=0D
+ if (!WaitForSpiCycleComplete (ScSpiBar0, TRUE)) {=0D
+ Status =3D EFI_DEVICE_ERROR;=0D
+ goto SendSpiCmdEnd;=0D
+ }=0D
+=0D
+ //=0D
+ // If it's read cycle, load data into the caller's buffer.=0D
+ //=0D
+ if ((FlashCycleType =3D=3D FlashCycleRead) ||=0D
+ (FlashCycleType =3D=3D FlashCycleReadSfdp) ||=0D
+ (FlashCycleType =3D=3D FlashCycleReadJedecId) ||=0D
+ (FlashCycleType =3D=3D FlashCycleReadStatus))=0D
+ {=0D
+ if ((SpiDataCount & 0x07) !=3D 0) {=0D
+ //=0D
+ // Use Byte read if Data Count is 0, 1, 2, 3, 4, 5, 6, 7=0D
+ //=0D
+ for (Index =3D 0; Index < SpiDataCount; Index++) {=0D
+ Buffer[Index] =3D MmioRead8 (ScSpiBar0 + R_SPI_FDATA00 + Index);=
=0D
+ }=0D
+ } else {=0D
+ //=0D
+ // Use Dword read if Data Count is 8, 16, 24, 32, 40, 48, 56, 64=0D
+ //=0D
+ for (Index =3D 0; Index < SpiDataCount; Index +=3D sizeof (UINT32)=
) {=0D
+ *(UINT32 *)(Buffer + Index) =3D MmioRead32 (ScSpiBar0 + R_SPI_FD=
ATA00 + Index);=0D
+ }=0D
+ }=0D
+ }=0D
+=0D
+ HardwareSpiAddr +=3D SpiDataCount;=0D
+ Buffer +=3D SpiDataCount;=0D
+ ByteCount -=3D SpiDataCount;=0D
+ } while (ByteCount > 0);=0D
+=0D
+SendSpiCmdEnd:=0D
+ ///=0D
+ /// Restore the settings for SPI Prefetching and Caching and enable BIOS=
Write Protect=0D
+ ///=0D
+ if ((FlashCycleType =3D=3D FlashCycleWrite) || (FlashCycleType =3D=3D Fl=
ashCycleErase)) {=0D
+ EnableBiosWriteProtect (SpiBaseAddress, mSpiInstance->Flags & FLAGS_SP=
I_DISABLE_SMM_WRITE_PROTECT);=0D
+ SetSpiBiosControlRegister (SpiBaseAddress, BiosCtlSave);=0D
+ }=0D
+=0D
+ ReleaseSpiBar0 (SpiBaseAddress);=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Wait execution cycle to complete on the SPI interface.=0D
+=0D
+ @param[in] ScSpiBar0 Spi MMIO base address=0D
+ @param[in] ErrorCheck TRUE if the SpiCycle needs to do the err=
or check=0D
+=0D
+ @retval TRUE SPI cycle completed on the interface.=0D
+ @retval FALSE Time out while waiting the SPI cycle to =
complete.=0D
+ It's not safe to program the next comman=
d on the SPI interface.=0D
+**/=0D
+BOOLEAN=0D
+WaitForSpiCycleComplete (=0D
+ IN UINT32 ScSpiBar0,=0D
+ IN BOOLEAN ErrorCheck=0D
+ )=0D
+{=0D
+ UINT64 WaitTicks;=0D
+ UINT64 WaitCount;=0D
+ UINT32 Data32;=0D
+=0D
+ //=0D
+ // Convert the wait period allowed into to tick count=0D
+ //=0D
+ WaitCount =3D WAIT_TIME / WAIT_PERIOD;=0D
+ //=0D
+ // Wait for the SPI cycle to complete.=0D
+ //=0D
+ for (WaitTicks =3D 0; WaitTicks < WaitCount; WaitTicks++) {=0D
+ Data32 =3D MmioRead32 (ScSpiBar0 + R_SPI_HSFS);=0D
+ if ((Data32 & B_SPI_HSFS_SCIP) =3D=3D 0) {=0D
+ MmioWrite32 (ScSpiBar0 + R_SPI_HSFS, B_SPI_HSFS_FCERR | B_SPI_HSFS_F=
DONE);=0D
+ if (((Data32 & B_SPI_HSFS_FCERR) !=3D 0) && ErrorCheck) {=0D
+ return FALSE;=0D
+ } else {=0D
+ return TRUE;=0D
+ }=0D
+ }=0D
+=0D
+ MicroSecondDelay (WAIT_PERIOD);=0D
+ }=0D
+=0D
+ return FALSE;=0D
+}=0D
+=0D
+/**=0D
+ Get the SPI region base and size, based on the enum type=0D
+=0D
+ @param[in] FlashRegionType The Flash Region type for for the base a=
ddress which is listed in the Descriptor.=0D
+ @param[out] BaseAddress The Flash Linear Address for the Region =
'n' Base=0D
+ @param[out] RegionSize The size for the Region 'n'=0D
+=0D
+ @retval EFI_SUCCESS Read success=0D
+ @retval EFI_INVALID_PARAMETER Invalid region type given=0D
+ @retval EFI_DEVICE_ERROR The region is not used=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SpiGetRegionAddress (=0D
+ IN FLASH_REGION_TYPE FlashRegionType,=0D
+ OUT UINT32 *BaseAddress OPTIONAL,=0D
+ OUT UINT32 *RegionSize OPTIONAL=0D
+ )=0D
+{=0D
+ UINT32 ScSpiBar0;=0D
+ UINT32 ReadValue;=0D
+ UINT32 Base;=0D
+ SPI_INSTANCE *SpiInstance;=0D
+=0D
+ if (FlashRegionType >=3D FlashRegionMax) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ SpiInstance =3D GetSpiInstance ();=0D
+ if (SpiInstance =3D=3D NULL) {=0D
+ return EFI_DEVICE_ERROR;=0D
+ }=0D
+=0D
+ if (FlashRegionType =3D=3D FlashRegionAll) {=0D
+ if (BaseAddress !=3D NULL) {=0D
+ *BaseAddress =3D 0;=0D
+ }=0D
+=0D
+ if (RegionSize !=3D NULL) {=0D
+ *RegionSize =3D SpiInstance->Component1StartAddr;=0D
+ }=0D
+=0D
+ return EFI_SUCCESS;=0D
+ }=0D
+=0D
+ ScSpiBar0 =3D AcquireSpiBar0 (SpiInstance->PchSpiBase);=0D
+ ReadValue =3D MmioRead32 (ScSpiBar0 + R_SPI_FREG0_FLASHD + S_SPI_FREGX *=
(UINT32)FlashRegionType);=0D
+ ReleaseSpiBar0 (SpiInstance->PchSpiBase);=0D
+=0D
+ //=0D
+ // If the region is not used, the Region Base is 7FFFh and Region Limit =
is 0000h=0D
+ //=0D
+ if (ReadValue =3D=3D B_SPI_FREGX_BASE_MASK) {=0D
+ return EFI_DEVICE_ERROR;=0D
+ }=0D
+=0D
+ Base =3D (ReadValue & B_SPI_FREG1_BASE_MASK) << N_SPI_FREG1_BASE;=0D
+ if (BaseAddress !=3D NULL) {=0D
+ *BaseAddress =3D Base;=0D
+ }=0D
+=0D
+ if (RegionSize !=3D NULL) {=0D
+ *RegionSize =3D ((((ReadValue & B_SPI_FREGX_LIMIT_MASK) >> N_SPI_FREG=
X_LIMIT) + 1) <<=0D
+ N_SPI_FREGX_LIMIT_REPR) - Base;=0D
+ }=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlash=
Lib.inf b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib=
.inf
new file mode 100644
index 0000000000..fae851c12f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf
@@ -0,0 +1,48 @@
+## @file=0D
+# Library instance for SPI flash library using SPI hardware sequence=0D
+#=0D
+# Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>=
=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+[Defines]=0D
+ INF_VERSION =3D 0x00010005=0D
+ BASE_NAME =3D SpiFlashLib=0D
+ FILE_GUID =3D 6F96AFCB-DE89-4ca1-A63F-8703EE8FDE50=
=0D
+ MODULE_TYPE =3D BASE=0D
+ VERSION_STRING =3D 1.0=0D
+ LIBRARY_CLASS =3D SpiFlashLib=0D
+ CONSTRUCTOR =3D SpiConstructor=0D
+=0D
+#=0D
+# The following information is for reference only and not required by the =
build tools.=0D
+#=0D
+# VALID_ARCHITECTURES =3D IA32 X64=0D
+#=0D
+=0D
+[Sources]=0D
+ RegsSpi.h=0D
+ SpiCommon.h=0D
+ PchSpi.c=0D
+ SpiFlashLib.c=0D
+=0D
+[Packages]=0D
+ MdePkg/MdePkg.dec=0D
+ MdeModulePkg/MdeModulePkg.dec=0D
+ PlatformPayloadPkg/PlatformPayloadPkg.dec=0D
+=0D
+[LibraryClasses]=0D
+ BaseLib=0D
+ PcdLib=0D
+ IoLib=0D
+ PciLib=0D
+ HobLib=0D
+ TimerLib=0D
+ BaseLib=0D
+=0D
+[Guids]=0D
+ gSpiFlashInfoGuid=0D
+=0D
+[Pcd]=0D
+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress=0D
diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDisp=
atchSmm.c b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispa=
tchSmm.c
new file mode 100644
index 0000000000..7fc589303e
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm=
.c
@@ -0,0 +1,455 @@
+/** @file=0D
+ SMM SwDispatch2 Protocol.=0D
+=0D
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+=0D
+=0D
+**/=0D
+=0D
+#include "PchSmiDispatchSmm.h"=0D
+=0D
+typedef struct {=0D
+ UINT8 EosBitOffset;=0D
+ UINT8 ApmBitOffset;=0D
+ UINT32 SmiEosAddr;=0D
+ UINT32 SmiApmStsAddr;=0D
+} SMM_PCH_REGISTER;=0D
+=0D
+SMM_PCH_REGISTER mSmiPchReg;=0D
+=0D
+EFI_SMM_CPU_PROTOCOL *mSmmCpuProtocol;=0D
+LIST_ENTRY mSmmSwDispatch2Queue =3D INITIALIZE_LIST_HEAD_VARIAB=
LE (mSmmSwDispatch2Queue);=0D
+=0D
+/**=0D
+ Find SmmSwDispatch2Context by SwSmiInputValue.=0D
+=0D
+ @param[in] SwSmiInputValue The value to indentify the SmmSwDispatch=
2 context=0D
+=0D
+ @return Pointer to EFI_SMM_SW_DISPATCH2_CONTEXT context=0D
+**/=0D
+EFI_SMM_SW_DISPATCH2_CONTEXT *=0D
+FindContextBySwSmiInputValue (=0D
+ IN UINTN SwSmiInputValue=0D
+ )=0D
+{=0D
+ LIST_ENTRY *Node;=0D
+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;=0D
+=0D
+ Node =3D mSmmSwDispatch2Queue.ForwardLink;=0D
+ for ( ; Node !=3D &mSmmSwDispatch2Queue; Node =3D Node->ForwardLink) {=0D
+ Dispatch2Context =3D BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link=
);=0D
+ if (Dispatch2Context->SwSmiInputValue =3D=3D SwSmiInputValue) {=0D
+ return Dispatch2Context;=0D
+ }=0D
+ }=0D
+=0D
+ return NULL;=0D
+}=0D
+=0D
+/**=0D
+ Find SmmSwDispatch2Context by DispatchHandle.=0D
+=0D
+ @param DispatchHandle The handle to indentify the SmmSwDispatch2 cont=
ext=0D
+=0D
+ @return Pointer to EFI_SMM_SW_DISPATCH2_CONTEXT context=0D
+**/=0D
+EFI_SMM_SW_DISPATCH2_CONTEXT *=0D
+FindContextByDispatchHandle (=0D
+ IN EFI_HANDLE DispatchHandle=0D
+ )=0D
+{=0D
+ LIST_ENTRY *Node;=0D
+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;=0D
+=0D
+ Node =3D mSmmSwDispatch2Queue.ForwardLink;=0D
+ for ( ; Node !=3D &mSmmSwDispatch2Queue; Node =3D Node->ForwardLink) {=0D
+ Dispatch2Context =3D BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link=
);=0D
+ if (Dispatch2Context->DispatchHandle =3D=3D DispatchHandle) {=0D
+ return Dispatch2Context;=0D
+ }=0D
+ }=0D
+=0D
+ return NULL;=0D
+}=0D
+=0D
+/**=0D
+ Dispatch registered SMM handlers=0D
+=0D
+ @param DispatchHandle The unique handle assigned to this handler by Sm=
iHandlerRegister().=0D
+ @param RegisterContext Points to an optional handler context which was =
specified when the handler was registered.=0D
+ @param CommBuffer A pointer to a collection of data in memory that=
will=0D
+ be conveyed from a non-SMM environment into an S=
MM environment.=0D
+ @param CommBufferSize The size of the CommBuffer.=0D
+=0D
+ @return Status Code=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+SmmSwDispatcher (=0D
+ IN EFI_HANDLE DispatchHandle,=0D
+ IN CONST VOID *RegisterContext,=0D
+ IN OUT VOID *CommBuffer,=0D
+ IN OUT UINTN *CommBufferSize=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ EFI_SMM_SW_CONTEXT SwContext;=0D
+ UINTN Index;=0D
+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;=0D
+ EFI_SMM_HANDLER_ENTRY_POINT2 DispatchFunction;=0D
+ EFI_SMM_SW_REGISTER_CONTEXT DispatchContext;=0D
+ UINTN Size;=0D
+ EFI_SMM_SAVE_STATE_IO_INFO IoInfo;=0D
+=0D
+ //=0D
+ // Construct new context=0D
+ //=0D
+ SwContext.SwSmiCpuIndex =3D 0;=0D
+ SwContext.CommandPort =3D IoRead8 (SMM_CONTROL_PORT);=0D
+ SwContext.DataPort =3D IoRead8 (SMM_DATA_PORT);=0D
+=0D
+ //=0D
+ // Try to find which CPU trigger SWSMI=0D
+ //=0D
+ for (Index =3D 0; Index < gSmst->NumberOfCpus; Index++) {=0D
+ Status =3D mSmmCpuProtocol->ReadSaveState (=0D
+ mSmmCpuProtocol,=0D
+ sizeof (IoInfo),=0D
+ EFI_SMM_SAVE_STATE_REGISTER_IO,=0D
+ Index,=0D
+ &IoInfo=0D
+ );=0D
+ if (EFI_ERROR (Status)) {=0D
+ continue;=0D
+ }=0D
+=0D
+ if (IoInfo.IoPort =3D=3D SMM_CONTROL_PORT) {=0D
+ //=0D
+ // Great! Find it.=0D
+ //=0D
+ SwContext.SwSmiCpuIndex =3D Index;=0D
+ DEBUG ((DEBUG_VERBOSE, "CPU index =3D 0x%x/0x%x\n", Index, gSmst->Nu=
mberOfCpus));=0D
+ break;=0D
+ }=0D
+ }=0D
+=0D
+ if (SwContext.CommandPort =3D=3D 0) {=0D
+ DEBUG ((DEBUG_VERBOSE, "NOT SW SMI\n"));=0D
+ Status =3D EFI_SUCCESS;=0D
+ goto End;=0D
+ }=0D
+=0D
+ //=0D
+ // Search context=0D
+ //=0D
+ Context =3D FindContextBySwSmiInputValue (SwContext.CommandPort);=0D
+ if (Context =3D=3D NULL) {=0D
+ DEBUG ((DEBUG_INFO, "No handler for SMI value 0x%x\n", SwContext.Comma=
ndPort));=0D
+ Status =3D EFI_SUCCESS;=0D
+ goto End;=0D
+ }=0D
+=0D
+ DEBUG ((DEBUG_VERBOSE, "Prepare to call handler for 0x%x\n", SwContext.C=
ommandPort));=0D
+=0D
+ //=0D
+ // Dispatch=0D
+ //=0D
+ DispatchContext.SwSmiInputValue =3D SwContext.CommandPort;=0D
+ Size =3D sizeof (SwContext);=0D
+ DispatchFunction =3D (EFI_SMM_HANDLER_ENTRY_POINT2)Contex=
t->DispatchFunction;=0D
+ Status =3D DispatchFunction (DispatchHandle, &D=
ispatchContext, &SwContext, &Size);=0D
+=0D
+End:=0D
+ //=0D
+ // Clear SMI APM status=0D
+ //=0D
+ IoOr32 (mSmiPchReg.SmiApmStsAddr, 1 << mSmiPchReg.ApmBitOffset);=0D
+=0D
+ //=0D
+ // Set EOS bit=0D
+ //=0D
+ IoOr32 (mSmiPchReg.SmiEosAddr, 1 << mSmiPchReg.EosBitOffset);=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+Check the SwSmiInputValue is already used=0D
+=0D
+@param[in] SwSmiInputValue To indentify the SmmSwDispatch2 context=0D
+=0D
+@retval EFI_SUCCESS SwSmiInputValue could be used.=0D
+@retval EFI_INVALID_PARAMETER SwSmiInputValue is already be used.=0D
+=0D
+**/=0D
+EFI_STATUS=0D
+SmiInputValueCheck (=0D
+ IN UINTN SwSmiInputValue=0D
+ )=0D
+{=0D
+ LIST_ENTRY *Node;=0D
+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;=0D
+=0D
+ Node =3D mSmmSwDispatch2Queue.ForwardLink;=0D
+ for ( ; Node !=3D &mSmmSwDispatch2Queue; Node =3D Node->ForwardLink) {=0D
+ Dispatch2Context =3D BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link=
);=0D
+ if (Dispatch2Context->SwSmiInputValue =3D=3D SwSmiInputValue) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+ }=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Register a child SMI source dispatch function for the specified software=
SMI.=0D
+=0D
+ This service registers a function (DispatchFunction) which will be calle=
d when the software=0D
+ SMI source specified by RegContext->SwSmiCpuIndex is detected. On return=
, DispatchHandle=0D
+ contains a unique handle which may be used later to unregister the funct=
ion using UnRegister().=0D
+=0D
+ @param[in] This Pointer to the EFI_SMM_SW_DISPATCH2_PROTO=
COL instance.=0D
+ @param[in] DispatchFunction Function to register for handler when the=
specified software=0D
+ SMI is generated.=0D
+ @param[in, out] RegContext Pointer to the dispatch function's contex=
t.=0D
+ The caller fills this context in before c=
alling=0D
+ the register function to indicate to the =
register=0D
+ function which Software SMI input value t=
he=0D
+ dispatch function should be invoked for.=
=0D
+ @param[out] DispatchHandle Handle generated by the dispatcher to tra=
ck the=0D
+ function instance.=0D
+=0D
+ @retval EFI_SUCCESS The dispatch function has been successful=
ly=0D
+ registered and the SMI source has been en=
abled.=0D
+ @retval EFI_DEVICE_ERROR The SW driver was unable to enable the SM=
I source.=0D
+ @retval EFI_INVALID_PARAMETER RegisterContext is invalid. The SW SMI in=
put value=0D
+ is not within valid range.=0D
+ @retval EFI_OUT_OF_RESOURCES There is not enough memory (system or SMM=
) to manage this=0D
+ child.=0D
+ @retval EFI_OUT_OF_RESOURCES A unique software SMI value could not be =
assigned=0D
+ for this dispatch.=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SmmSwDispatch2Register (=0D
+ IN CONST EFI_SMM_SW_DISPATCH2_PROTOCOL *This,=0D
+ IN EFI_SMM_HANDLER_ENTRY_POINT2 DispatchFunction,=0D
+ IN OUT EFI_SMM_SW_REGISTER_CONTEXT *RegContext,=0D
+ OUT EFI_HANDLE *DispatchHandle=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ UINTN Index;=0D
+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;=0D
+=0D
+ if (RegContext->SwSmiInputValue =3D=3D (UINTN)-1) {=0D
+ //=0D
+ // If SwSmiInputValue is set to (UINTN) -1 then a unique value=0D
+ // will be assigned and returned in the structure.=0D
+ //=0D
+ Status =3D EFI_NOT_FOUND;=0D
+ for (Index =3D 1; Index < MAXIMUM_SWI_VALUE; Index++) {=0D
+ Status =3D SmiInputValueCheck (Index);=0D
+ if (!EFI_ERROR (Status)) {=0D
+ RegContext->SwSmiInputValue =3D Index;=0D
+ break;=0D
+ }=0D
+ }=0D
+=0D
+ if (RegContext->SwSmiInputValue =3D=3D (UINTN)-1) {=0D
+ return EFI_OUT_OF_RESOURCES;=0D
+ }=0D
+ }=0D
+=0D
+ if ((RegContext->SwSmiInputValue > MAXIMUM_SWI_VALUE) || (RegContext->Sw=
SmiInputValue =3D=3D 0)) {=0D
+ DEBUG ((DEBUG_ERROR, "ERROR: SMI value range (1 ~ 0x%x)\n", MAXIMUM_SW=
I_VALUE));=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ //=0D
+ // Register=0D
+ //=0D
+ Status =3D gSmst->SmmAllocatePool (EfiRuntimeServicesData, sizeof (*Cont=
ext), (VOID **)&Context);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return EFI_OUT_OF_RESOURCES;=0D
+ }=0D
+=0D
+ *DispatchHandle =3D (EFI_HANDLE)Context;=0D
+ Context->Signature =3D SMI_SW_HANDLER_SIGNATURE;=0D
+ Context->SwSmiInputValue =3D RegContext->SwSmiInputValue;=0D
+ Context->DispatchFunction =3D (UINTN)DispatchFunction;=0D
+ Context->DispatchHandle =3D *DispatchHandle;=0D
+ InsertTailList (&mSmmSwDispatch2Queue, &Context->Link);=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Unregister a child SMI source dispatch function for the specified softwa=
re SMI.=0D
+=0D
+ This service removes the handler associated with DispatchHandle so that =
it will no longer be=0D
+ called in response to a software SMI.=0D
+=0D
+ @param[in] This Pointer to the EFI_SMM_SW_DISPATCH2_PROTO=
COL instance.=0D
+ @param[in] DispatchHandle Handle of dispatch function to deregister=
.=0D
+=0D
+ @retval EFI_SUCCESS The dispatch function has been successful=
ly unregistered.=0D
+ @retval EFI_INVALID_PARAMETER The DispatchHandle was not valid.=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+SmmSwDispatch2UnRegister (=0D
+ IN CONST EFI_SMM_SW_DISPATCH2_PROTOCOL *This,=0D
+ IN EFI_HANDLE DispatchHandle=0D
+ )=0D
+{=0D
+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;=0D
+=0D
+ //=0D
+ // Unregister=0D
+ //=0D
+ Context =3D FindContextByDispatchHandle (DispatchHandle);=0D
+ ASSERT (Context !=3D NULL);=0D
+ if (Context !=3D NULL) {=0D
+ RemoveEntryList (&Context->Link);=0D
+ gSmst->SmmFreePool (Context);=0D
+ }=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+EFI_SMM_SW_DISPATCH2_PROTOCOL gSmmSwDispatch2 =3D {=0D
+ SmmSwDispatch2Register,=0D
+ SmmSwDispatch2UnRegister,=0D
+ MAXIMUM_SWI_VALUE=0D
+};=0D
+=0D
+/**=0D
+ Get specified SMI register based on given register ID=0D
+=0D
+ @param[in] SmmRegister SMI related register array from bootloader=0D
+ @param[in] Id The register ID to get.=0D
+=0D
+ @retval NULL The register is not found or the format is not =
expected.=0D
+ @return smi register=0D
+=0D
+**/=0D
+PLD_GENERIC_REGISTER *=0D
+GetSmmCtrlRegById (=0D
+ IN PLD_SMM_REGISTERS *SmmRegister,=0D
+ IN UINT32 Id=0D
+ )=0D
+{=0D
+ UINT32 Index;=0D
+ PLD_GENERIC_REGISTER *PldReg;=0D
+=0D
+ PldReg =3D NULL;=0D
+ for (Index =3D 0; Index < SmmRegister->Count; Index++) {=0D
+ if (SmmRegister->Registers[Index].Id =3D=3D Id) {=0D
+ PldReg =3D &SmmRegister->Registers[Index];=0D
+ break;=0D
+ }=0D
+ }=0D
+=0D
+ if (PldReg =3D=3D NULL) {=0D
+ DEBUG ((DEBUG_INFO, "Register %d not found.\n", Id));=0D
+ return NULL;=0D
+ }=0D
+=0D
+ //=0D
+ // Checking the register if it is expected.=0D
+ //=0D
+ if ((PldReg->Address.AccessSize !=3D EFI_ACPI_3_0_DWORD) ||=0D
+ (PldReg->Address.Address =3D=3D 0) ||=0D
+ (PldReg->Address.RegisterBitWidth !=3D 1) ||=0D
+ (PldReg->Address.AddressSpaceId !=3D EFI_ACPI_3_0_SYSTEM_IO) ||=0D
+ (PldReg->Value !=3D 1))=0D
+ {=0D
+ DEBUG ((DEBUG_INFO, "Unexpected SMM register.\n"));=0D
+ DEBUG ((DEBUG_INFO, "AddressSpaceId=3D 0x%x\n", PldReg->Address.Addres=
sSpaceId));=0D
+ DEBUG ((DEBUG_INFO, "RegBitWidth =3D 0x%x\n", PldReg->Address.Regist=
erBitWidth));=0D
+ DEBUG ((DEBUG_INFO, "RegBitOffset =3D 0x%x\n", PldReg->Address.Regist=
erBitOffset));=0D
+ DEBUG ((DEBUG_INFO, "AccessSize =3D 0x%x\n", PldReg->Address.Access=
Size));=0D
+ DEBUG ((DEBUG_INFO, "Address =3D 0x%lx\n", PldReg->Address.Addre=
ss));=0D
+ return NULL;=0D
+ }=0D
+=0D
+ return PldReg;=0D
+}=0D
+=0D
+/**=0D
+ Entry Point for this driver.=0D
+=0D
+ @param[in] ImageHandle Image handle of this driver.=0D
+ @param[in] SystemTable A Pointer to the EFI System Table.=0D
+=0D
+ @retval EFI_SUCCESS The entry point is executed successfully.=0D
+ @retval other Some error occurred when executing this entry point=
.=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+PchSmiDispatchEntryPoint (=0D
+ IN EFI_HANDLE ImageHandle,=0D
+ IN EFI_SYSTEM_TABLE *SystemTable=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ EFI_HANDLE DispatchHandle;=0D
+ EFI_HOB_GUID_TYPE *GuidHob;=0D
+ PLD_SMM_REGISTERS *SmmRegister;=0D
+ PLD_GENERIC_REGISTER *SmiEosReg;=0D
+ PLD_GENERIC_REGISTER *SmiApmStsReg;=0D
+=0D
+ GuidHob =3D GetFirstGuidHob (&gSmmRegisterInfoGuid);=0D
+ if (GuidHob =3D=3D NULL) {=0D
+ return EFI_UNSUPPORTED;=0D
+ }=0D
+=0D
+ SmmRegister =3D (PLD_SMM_REGISTERS *)GET_GUID_HOB_DATA (GuidHob);=0D
+ SmiEosReg =3D GetSmmCtrlRegById (SmmRegister, REGISTER_ID_SMI_EOS);=0D
+ if (SmiEosReg =3D=3D NULL) {=0D
+ DEBUG ((DEBUG_ERROR, "SMI EOS reg not found.\n"));=0D
+ return EFI_NOT_FOUND;=0D
+ }=0D
+=0D
+ mSmiPchReg.SmiEosAddr =3D (UINT32)SmiEosReg->Address.Address;=0D
+ mSmiPchReg.EosBitOffset =3D SmiEosReg->Address.RegisterBitOffset;=0D
+=0D
+ SmiApmStsReg =3D GetSmmCtrlRegById (SmmRegister, REGISTER_ID_SMI_APM_STS=
);=0D
+ if (SmiApmStsReg =3D=3D NULL) {=0D
+ DEBUG ((DEBUG_ERROR, "SMI APM status reg not found.\n"));=0D
+ return EFI_NOT_FOUND;=0D
+ }=0D
+=0D
+ mSmiPchReg.SmiApmStsAddr =3D (UINT32)SmiApmStsReg->Address.Address;=0D
+ mSmiPchReg.ApmBitOffset =3D SmiApmStsReg->Address.RegisterBitOffset;=0D
+=0D
+ //=0D
+ // Locate PI SMM CPU protocol=0D
+ //=0D
+ Status =3D gSmst->SmmLocateProtocol (&gEfiSmmCpuProtocolGuid, NULL, (VOI=
D **)&mSmmCpuProtocol);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ //=0D
+ // Register a SMM handler to handle subsequent SW SMIs.=0D
+ //=0D
+ Status =3D gSmst->SmiHandlerRegister ((EFI_MM_HANDLER_ENTRY_POINT)SmmSwD=
ispatcher, NULL, &DispatchHandle);=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ //=0D
+ // Publish PI SMM SwDispatch2 Protocol=0D
+ //=0D
+ ImageHandle =3D NULL;=0D
+ Status =3D gSmst->SmmInstallProtocolInterface (=0D
+ &ImageHandle,=0D
+ &gEfiSmmSwDispatch2ProtocolGuid,=0D
+ EFI_NATIVE_INTERFACE,=0D
+ &gSmmSwDispatch2=0D
+ );=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ return Status;=0D
+}=0D
diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDisp=
atchSmm.h b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispa=
tchSmm.h
new file mode 100644
index 0000000000..c14fe99929
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm=
.h
@@ -0,0 +1,36 @@
+/** @file=0D
+ The header file for SMM SwDispatch2 module.=0D
+=0D
+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef SMM_SW_DISPATCH2_H_=0D
+#define SMM_SW_DISPATCH2_H_=0D
+=0D
+#include <PiDxe.h>=0D
+#include <Protocol/SmmSwDispatch2.h>=0D
+#include <Protocol/SmmCpu.h>=0D
+#include <Library/UefiDriverEntryPoint.h>=0D
+#include <Library/SmmServicesTableLib.h>=0D
+#include <Library/BaseLib.h>=0D
+#include <Library/IoLib.h>=0D
+#include <Library/DebugLib.h>=0D
+#include <Guid/SmmRegisterInfoGuid.h>=0D
+#include <Library/HobLib.h>=0D
+=0D
+#define SMI_SW_HANDLER_SIGNATURE SIGNATURE_32('s','s','w','h')=0D
+#define MAXIMUM_SWI_VALUE 0xFF=0D
+#define SMM_CONTROL_PORT 0xB2=0D
+#define SMM_DATA_PORT 0xB3=0D
+=0D
+typedef struct {=0D
+ UINTN Signature;=0D
+ LIST_ENTRY Link;=0D
+ EFI_HANDLE DispatchHandle;=0D
+ UINTN SwSmiInputValue;=0D
+ UINTN DispatchFunction;=0D
+} EFI_SMM_SW_DISPATCH2_CONTEXT;=0D
+=0D
+#endif=0D
diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDisp=
atchSmm.inf b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDis=
patchSmm.inf
new file mode 100644
index 0000000000..96a154e888
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm=
.inf
@@ -0,0 +1,51 @@
+## @file=0D
+# PCH SMM SMI Software dispatch module.=0D
+#=0D
+# Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>=0D
+#=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+[Defines]=0D
+ INF_VERSION =3D 0x00010005=0D
+ BASE_NAME =3D PchSmiDispatchSmm=0D
+ FILE_GUID =3D 60F343E3-2AE2-4AA7-B01E-BF9BD5C04A3B=
=0D
+ MODULE_TYPE =3D DXE_SMM_DRIVER=0D
+ VERSION_STRING =3D 1.0=0D
+ PI_SPECIFICATION_VERSION =3D 0x0001000A=0D
+ ENTRY_POINT =3D PchSmiDispatchEntryPoint=0D
+=0D
+#=0D
+# The following information is for reference only and not required by the =
build tools.=0D
+#=0D
+# VALID_ARCHITECTURES =3D IA32 X64=0D
+#=0D
+=0D
+[Sources]=0D
+ PchSmiDispatchSmm.c=0D
+ PchSmiDispatchSmm.h=0D
+=0D
+[Packages]=0D
+ MdePkg/MdePkg.dec=0D
+ UefiPayloadPkg/UefiPayloadPkg.dec=0D
+=0D
+[LibraryClasses]=0D
+ UefiDriverEntryPoint=0D
+ MemoryAllocationLib=0D
+ DebugLib=0D
+ UefiBootServicesTableLib=0D
+ SmmServicesTableLib=0D
+ BaseLib=0D
+ IoLib=0D
+ HobLib=0D
+=0D
+[Protocols]=0D
+ gEfiSmmCpuProtocolGuid # PROTOCOL ALWAYS_CONSUMED=0D
+ gEfiSmmSwDispatch2ProtocolGuid # PROTOCOL ALWAYS_PRODUCED=0D
+=0D
+[Guids]=0D
+ gSmmRegisterInfoGuid=0D
+=0D
+[Depex]=0D
+ gEfiSmmCpuProtocolGuid=0D
diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec b/Fea=
tures/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec
new file mode 100644
index 0000000000..549f96d85f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec
@@ -0,0 +1,49 @@
+## @file=0D
+# Payload Platform Package=0D
+#=0D
+# Provides drivers and definitions to create payload platform FV.=0D
+#=0D
+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+[Defines]=0D
+ DEC_SPECIFICATION =3D 0x00010005=0D
+ PACKAGE_NAME =3D PlatformPayloadPkg=0D
+ PACKAGE_GUID =3D 17F3ACAC-079D-4518-9EBF-E33289733E8C=
=0D
+ PACKAGE_VERSION =3D 0.1=0D
+=0D
+[Includes]=0D
+ Include=0D
+=0D
+[Guids]=0D
+ #=0D
+ ## Defines the token space for the Payload platform Package PCDs.=0D
+ #=0D
+ gPlatformPayloadPkgTokenSpaceGuid =3D {0xa375ddc6, 0x74fb, 0x4de1, {0x8=
2, 0x6d, 0xa3, 0x10, 0xa3, 0x3b, 0x89, 0x77}}=0D
+=0D
+ #=0D
+ # SPI variable support=0D
+ #=0D
+ gNvVariableInfoGuid =3D { 0x7a345dca, 0xc26, 0x4f2a, { 0xa8, 0x9a,=
0x57, 0xc0, 0x8d, 0xdd, 0x22, 0xee } }=0D
+ gSpiFlashInfoGuid =3D { 0x2d4aac1b, 0x91a5, 0x4cd5, { 0x9b, 0x5c,=
0xb4, 0x0f, 0x5d, 0x28, 0x51, 0xa1 } }=0D
+=0D
+=0D
+##########################################################################=
######=0D
+#=0D
+# PCD Declarations section - list of all PCDs Declared by this Package=0D
+# Only this package should be providing the=0D
+# declaration, other packages should not.=0D
+#=0D
+##########################################################################=
######=0D
+=0D
+[PcdsFeatureFlag]=0D
+ ## Feature enabling control=0D
+ # @Prompt Enable payload platform FV common for most Intel platforms=0D
+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable|FALSE|B=
OOLEAN|0x00000001=0D
+=0D
+[PcdsFixedAtBuild, PcdsPatchableInModule]=0D
+ ## FFS filename to find the default variable initial data file.=0D
+ # @Prompt FFS Name of variable initial data file=0D
+ gPlatformPayloadPkgTokenSpaceGuid.PcdNvsDataFile |{ 0x1a, 0xf1, 0xb1, 0x=
ae, 0x42, 0xcc, 0xcf, 0x4e, 0xac, 0x60, 0xdb, 0xab, 0xf6, 0xca, 0x69, 0xe6 =
}|VOID*|0x00000025=0D
diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc b/Fea=
tures/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc
new file mode 100644
index 0000000000..adf028c511
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc
@@ -0,0 +1,110 @@
+## @file=0D
+# platform Payload Package=0D
+#=0D
+# Provides platform specific drivers and definitions to create a platform =
FV=0D
+# to work with universal UEFI payload to provide support for common Intel =
platforms.=0D
+#=0D
+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+##########################################################################=
######=0D
+#=0D
+# Defines Section - statements that will be processed to create a Makefile=
.=0D
+#=0D
+##########################################################################=
######=0D
+[Defines]=0D
+ PLATFORM_NAME =3D PlatformPayloadPkg=0D
+ PLATFORM_GUID =3D D3C551BE-9BC6-48F5-AA8A-F49425C2=
8CA9=0D
+ PLATFORM_VERSION =3D 0.1=0D
+ DSC_SPECIFICATION =3D 0x00010005=0D
+ SUPPORTED_ARCHITECTURES =3D X64=0D
+ BUILD_TARGETS =3D DEBUG|RELEASE|NOOPT=0D
+ SKUID_IDENTIFIER =3D DEFAULT=0D
+ OUTPUT_DIRECTORY =3D Build/$(PLATFORM_NAME)=0D
+ FLASH_DEFINITION =3D $(PLATFORM_NAME)/PlatformPayload=
Pkg.fdf=0D
+ PCD_DYNAMIC_AS_DYNAMICEX =3D TRUE=0D
+ DXE_ARCH =3D X64=0D
+=0D
+[Packages]=0D
+ MinPlatformPkg/MinPlatformPkg.dec=0D
+=0D
+##########################################################################=
######=0D
+#=0D
+# SKU Identification section - list of all SKU IDs supported by this Platf=
orm.=0D
+#=0D
+##########################################################################=
######=0D
+[SkuIds]=0D
+ 0|DEFAULT=0D
+=0D
+##########################################################################=
######=0D
+#=0D
+# Library Class section - list of all Library Classes needed by this Platf=
orm.=0D
+#=0D
+##########################################################################=
######=0D
+=0D
+#=0D
+# Since there are no 32b libraries or components in this package, these PC=
D are specified for 64b only=0D
+#=0D
+[PcdsFeatureFlag]=0D
+ #=0D
+ # PCD needed for MinPlatform build includes=0D
+ #=0D
+ gMinPlatformPkgTokenSpaceGuid.PcdSmiHandlerProfileEnable =
|FALSE=0D
+ gMinPlatformPkgTokenSpaceGuid.PcdUefiSecureBootEnable =
|FALSE=0D
+ gMinPlatformPkgTokenSpaceGuid.PcdPerformanceEnable =
|FALSE=0D
+=0D
+[PcdsPatchableInModule.X64]=0D
+ gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x7=0D
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000004F=0D
+!if $(SOURCE_DEBUG_ENABLE)=0D
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x17=0D
+!else=0D
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2F=0D
+!endif=0D
+=0D
+ #=0D
+ # The following parameters are set by Library/PlatformHookLib=0D
+ #=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialUseMmio|FALSE=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterBase|0=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialBaudRate|115200=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterStride|1=0D
+=0D
+##########################################################################=
######=0D
+#=0D
+# Pcd DynamicEx Section - list of all EDK II PCD Entries defined by this P=
latform=0D
+#=0D
+##########################################################################=
######=0D
+=0D
+[PcdsDynamicExDefault]=0D
+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0=0D
+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseSize|0=0D
+=0D
+=0D
+#=0D
+# Include common libraries=0D
+#=0D
+!include MinPlatformPkg/Include/Dsc/CoreCommonLib.dsc=0D
+!include MinPlatformPkg/Include/Dsc/CorePeiLib.dsc=0D
+!include MinPlatformPkg/Include/Dsc/CoreDxeLib.dsc=0D
+=0D
+#=0D
+# This package always builds the feature.=0D
+#=0D
+!include Include/PlatformPayloadFeature.dsc=0D
+=0D
+[BuildOptions]=0D
+ *_*_*_CC_FLAGS =3D -D DISABLE_NEW_DEPRECATED_INTERFACES=
=0D
+ GCC:*_UNIXGCC_*_CC_FLAGS =3D -DMDEPKG_NDEBUG=0D
+ GCC:RELEASE_*_*_CC_FLAGS =3D -DMDEPKG_NDEBUG=0D
+ INTEL:RELEASE_*_*_CC_FLAGS =3D /D MDEPKG_NDEBUG=0D
+ MSFT:RELEASE_*_*_CC_FLAGS =3D /D MDEPKG_NDEBUG=0D
+=0D
+[BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER]=0D
+ GCC:*_*_*_DLINK_FLAGS =3D -z common-page-size=3D0x1000=0D
+ XCODE:*_*_*_DLINK_FLAGS =3D -seg1addr 0x1000 -segalign 0x1000=0D
+ XCODE:*_*_*_MTOC_FLAGS =3D -align 0x1000=0D
+ CLANGPDB:*_*_*_DLINK_FLAGS =3D /ALIGN:4096=0D
+ MSFT:*_*_*_DLINK_FLAGS =3D /ALIGN:4096=0D
diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf b/Fea=
tures/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf
new file mode 100644
index 0000000000..f781a364d7
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf
@@ -0,0 +1,50 @@
+## @file=0D
+# Payload platform Package=0D
+#=0D
+# Provides platform specific drivers and definitions to create a platform =
FV=0D
+# to work with universal UEF payload.=0D
+#=0D
+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+[Defines]=0D
+ DEFINE FD_BASE =3D 0x00800000=0D
+ DEFINE FD_BLOCK_SIZE =3D 0x00001000=0D
+=0D
+ !if $(TARGET) =3D=3D "NOOPT"=0D
+ DEFINE FD_SIZE =3D 0x00090000=0D
+ DEFINE NUM_BLOCKS =3D 0x90=0D
+ !else=0D
+ DEFINE FD_SIZE =3D 0x00050000=0D
+ DEFINE NUM_BLOCKS =3D 0x50=0D
+ !endif=0D
+=0D
+[FD.PlatformPayload]=0D
+ BaseAddress =3D $(FD_BASE) | gUefiPayloadPkgTokenSpaceGuid.PcdPayloadF=
dMemBase=0D
+ Size =3D $(FD_SIZE) | gUefiPayloadPkgTokenSpaceGuid.PcdPayloadF=
dMemSize=0D
+ ErasePolarity =3D 1=0D
+ BlockSize =3D $(FD_BLOCK_SIZE)=0D
+ NumBlocks =3D $(NUM_BLOCKS)=0D
+=0D
+ 0x00000000 | $(FD_SIZE)=0D
+ FV =3D PlatformPayload=0D
+=0D
+[FV.PlatformPayload]=0D
+ !include MinPlatformPkg/Include/Fdf/CommonSpiFvHeaderInfo.fdf=0D
+ FvNameGuid =3D 96E75986-6FDD-491E-9FD5-35E21AC45B45=0D
+ FvForceRebase =3D FALSE=0D
+=0D
+ !include Include/PostMemory.fdf=0D
+=0D
+##########################################################################=
######=0D
+#=0D
+# Rules are use with the [FV] section's module INF type to define=0D
+# how an FFS file is created for a given INF file. The following Rule are =
the default=0D
+# rules for the different module type. User can add the customized rules t=
o define the=0D
+# content of the FFS file.=0D
+#=0D
+##########################################################################=
######=0D
+=0D
+!include MinPlatformPkg/Include/Fdf/RuleInclude.fdf=0D
diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py b/Feat=
ures/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py
new file mode 100644
index 0000000000..1e3e1cce21
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py
@@ -0,0 +1,113 @@
+## @file=0D
+# This file contains the script to build UniversalPayload with platform pa=
yload=0D
+#=0D
+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+##=0D
+=0D
+import argparse=0D
+import subprocess=0D
+import os=0D
+import shutil=0D
+import sys=0D
+from ctypes import *=0D
+=0D
+sys.dont_write_bytecode =3D True=0D
+=0D
+def RunCommand(cmd):=0D
+ print(cmd)=0D
+ p =3D subprocess.Popen(cmd, shell=3DTrue, stdout=3Dsubprocess.PIPE, st=
derr=3Dsubprocess.STDOUT,cwd=3Dos.environ['WORKSPACE'])=0D
+ while True:=0D
+ line =3D p.stdout.readline()=0D
+ if not line:=0D
+ break=0D
+ print(line.strip().decode(errors=3D'ignore'))=0D
+=0D
+ p.communicate()=0D
+ if p.returncode !=3D 0:=0D
+ print("- Failed - error happened when run command: %s"%cmd)=0D
+ raise Exception("ERROR: when run command: %s"%cmd)=0D
+=0D
+def BuildUniversalPayload(Args, MacroList):=0D
+ BuildTarget =3D Args.Target=0D
+ ToolChain =3D Args.ToolChain=0D
+ ElfToolChain =3D 'CLANGDWARF'=0D
+ ObjCopyFlag =3D "elf64-x86-64" if Args.Arch =3D=3D 'X64' else "elf32-=
i386"=0D
+=0D
+ #=0D
+ # Find universal UEFI payload build build script=0D
+ #=0D
+ Edk2PayloadBuildScript =3D os.path.normpath("UefiPayloadPkg/UniversalP=
ayloadBuild.py")=0D
+ for package_path in os.environ['PACKAGES_PATH'].split(';'):=0D
+ if os.path.exists (os.path.join (package_path, Edk2PayloadBuildScr=
ipt)):=0D
+ Edk2PayloadBuildScript =3D os.path.join (package_path, Edk2Pay=
loadBuildScript)=0D
+ break=0D
+ if not os.path.exists (Edk2PayloadBuildScript):=0D
+ raise Exception("Could not find universal UEFI payload build scrip=
t UniversalPayloadBuild.py")=0D
+=0D
+ PlatformFvDscPath =3D os.path.normpath("PlatformPayloadPkg/Platfo=
rmPayloadPkg.dsc")=0D
+ BuildDir =3D os.path.join(os.environ['WORKSPACE'], os.pa=
th.normpath("Build/UefiPayloadPkgX64"))=0D
+ PlatformFvReportPath =3D os.path.join(BuildDir, "PlatformPayloadRepo=
rt.txt")=0D
+ UniversalUefiPld =3D os.path.join(BuildDir, 'UniversalPayload.el=
f')=0D
+ PlatformFv =3D os.path.join(os.environ['WORKSPACE'], os.pa=
th.normpath("Build/PlatformPayloadPkg"), f"{BuildTarget}_{ToolChain}", os.p=
ath.normpath("FV/PlatformPayload.Fv"))=0D
+=0D
+ if "CLANG_BIN" in os.environ:=0D
+ LlvmObjcopyPath =3D os.path.join(os.environ["CLANG_BIN"], "llvm-ob=
jcopy")=0D
+ else:=0D
+ LlvmObjcopyPath =3D "llvm-objcopy"=0D
+ try:=0D
+ RunCommand('"%s" --version'%LlvmObjcopyPath)=0D
+ except:=0D
+ print("- Failed - Please check if LLVM is installed or if CLANG_BI=
N is set correctly")=0D
+ sys.exit(1)=0D
+=0D
+ Defines =3D ""=0D
+ for key in MacroList:=0D
+ Defines +=3D" -D {0}=3D{1}".format(key, MacroList[key])=0D
+=0D
+ #=0D
+ # Building Universal Payload entry.=0D
+ #=0D
+ if not Args.Skip:=0D
+ BuildPayload =3D f"python {Edk2PayloadBuildScript} -b {BuildTarge=
t} -t {ToolChain} -a {Args.Arch} {Defines}"=0D
+ RunCommand(BuildPayload)=0D
+=0D
+ #=0D
+ # Building Platform Payload.=0D
+ #=0D
+ BuildPayload =3D f"build -p {PlatformFvDscPath} -b {BuildTarget} -a X6=
4 -t {ToolChain} -y {PlatformFvReportPath}"=0D
+ BuildPayload +=3D Defines=0D
+ RunCommand(BuildPayload)=0D
+=0D
+ #=0D
+ # Copy the Platform Payload as a section in elf format Universal Paylo=
ad.=0D
+ #=0D
+ remove_section =3D f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyF=
lag} --remove-section .upld.platform_fv {UniversalUefiP=
ld}'=0D
+ add_section =3D f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyF=
lag} --add-section .upld.platform_fv=3D{PlatformFv} {UniversalUef=
iPld}'=0D
+ set_section =3D f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyF=
lag} --set-section-alignment .upld.platform_fv=3D16 {UniversalUef=
iPld}'=0D
+ RunCommand(remove_section)=0D
+ RunCommand(add_section)=0D
+ RunCommand(set_section)=0D
+=0D
+=0D
+def main():=0D
+ parser =3D argparse.ArgumentParser(description=3D'Build Platform Paylo=
ad FV and add it to Universal UEFI Payload')=0D
+ parser.add_argument('-t', '--ToolChain')=0D
+ parser.add_argument('-b', '--Target', default=3D'DEBUG')=0D
+ parser.add_argument('-a', '--Arch', choices=3D['IA32', 'X64'], help=3D=
'Specify the ARCH for payload entry module. Default build X64 image.', defa=
ult =3D'X64')=0D
+ parser.add_argument("-D", "--Macro", action=3D"append")=0D
+ parser.add_argument('-s', '--Skip', action=3D'store_true', help=3D'Sk=
ip Universal UEFI payload build (just build platform FV and add to Universa=
l UEFI payload.')=0D
+ MacroList =3D {}=0D
+ args =3D parser.parse_args()=0D
+ if args.Macro is not None:=0D
+ for Argument in args.Macro:=0D
+ if Argument.count('=3D') !=3D 1:=0D
+ print("Unknown variable passed in: %s"%Argument)=0D
+ raise Exception("ERROR: Unknown variable passed in: %s"%Ar=
gument)=0D
+ tokens =3D Argument.strip().split('=3D')=0D
+ MacroList[tokens[0].upper()] =3D tokens[1]=0D
+ BuildUniversalPayload(args, MacroList)=0D
+ print ("Successfully build Universal Payload with platform FV")=0D
+=0D
+if __name__ =3D=3D '__main__':=0D
+ main()=0D
diff --git a/Features/Intel/PlatformPayloadPkg/Readme.md b/Features/Intel/P=
latformPayloadPkg/Readme.md
new file mode 100644
index 0000000000..10e863b5e0
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Readme.md
@@ -0,0 +1,96 @@
+# Overview=0D
+* **Feature Name:** Platform Payload=0D
+* **PI Phase(s) Supported:** SMM DXE=0D
+=0D
+## Purpose=0D
+This package provides a common platform payload which is expected to work =
on most=0D
+Intel platforms with a bootloader.=0D
+=0D
+# High-Level Theory of Operation=0D
+Bootloader initialize memory/silicon/platform and payload focus on boot me=
dia initializaiton=0D
+and OS boot. Payload is expected to be re-used on different Platforms.=0D
+=0D
+In the reality, some payload modules have platform dependency (e.g. only f=
or Intel PCH)=0D
+or bootloader dependency (only for coreboot). These modules would be locat=
ed in=0D
+edk2-platform repo.=0D
+=0D
+The generic UEFI payload could be built from EDK2 UefiPayloadPkg in ELF fo=
rmat following=0D
+universal payload specification. And a Platform Payload could be built fro=
m PlatformPayloadPkg=0D
+to provide Intel platform specific features (e.g. SPI module, PCH SMM) in =
FV/FD format.=0D
+This platform payload could be inserted into universal UEFI payload as an =
ELF section=0D
+to generate a full-feature payload.=0D
+## Firmware Volumes=0D
+* FvPlatformPayload=0D
+=0D
+## Build Flows=0D
+use windows host as example to generate a full-feature payload:=0D
+=0D
+** Setup the build env=0D
+set WORKSPACE=3Dc:\payload=0D
+set PACKAGES_PATH=3D%WORKSPACE%\edk2;%WORKSPACE%\edk2-platforms\Features\I=
ntel;=0D
+ %WORKSPACE%\edk2-platforms\Platform\Intel=0D
+edk2\edksetup.bat=0D
+=0D
+** Build universal UEFI payload with platform Payload=0D
+python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg=
.py -t VS2019=0D
+ -D SMM_SUPPORT=3DTRUE -DVARIABLE_SUPPORT=3DNONE -D SMM_VARIABLE=3DTRUE=0D
+or=0D
+python edk2\UefiPayloadPkg\UniversalPayloadBuild.py -t VS2019 -D SMM_SUPPO=
RT=3DTRUE -DVARIABLE_SUPPORT=3DNONE=0D
+python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg=
.py -t VS2019 -D SMM_VARIABLE=3DTRUE -s=0D
+=0D
+ If build success, the final UEFI payload is at Build\UefiPayloadPkgX64\U=
niversalPayload.elf.=0D
+=0D
+## Features=0D
+=0D
+1. Modules=0D
+Currently only SMM veriable feature is available.=0D
+Several build macros are used as below for SMM variable feature modules.=0D
+!if $(SMM_VARIABLE) =3D=3D TRUE=0D
+ ## PchSmiDispatchSmm=0D
+ ## FvbSmm=0D
+ ## FaultTolerantWriteSmm=0D
+ ## VariableSmm=0D
+ ## VariableSmmRuntimeDxe=0D
+!endif=0D
+=0D
+2. Data Flows=0D
+SMM variable: =0D
+The interface with bootloader are defined in PlatformPayloadPkg\Include\Gu=
id=0D
+SpiFlashInfoGuid.h -- SPI related information for SPI flash operation.=
=0D
+NvVariableInfoGuid.h -- Variable related information for SPI NV variables=
.=0D
+=0D
+## Control Flows=0D
+EDK2 DXE/SMM core from universal UEFI payload would dispatch all the modul=
es=0D
+from this platform payload.=0D
+=0D
+## Test Point Results=0D
+*_TODO_*=0D
+The test(s) that can verify porting is complete for the feature.=0D
+=0D
+Each feature must describe at least one test point to verify the feature i=
s successful. If the test point is not=0D
+implemented, this should be stated.=0D
+=0D
+## Functional Exit Criteria=0D
+*_TODO_*=0D
+The testable functionality for the feature.=0D
+=0D
+This section should provide an ordered list of criteria that a board integ=
rator can reference to ensure the feature is=0D
+functional on their board.=0D
+=0D
+## Feature Enabling Checklist=0D
+*_TODO_*=0D
+An ordered list of required activities to achieve desired functionality fo=
r the feature.=0D
+=0D
+## Performance Impact=0D
+A general expectation for the impact on overall boot performance due to us=
ing this feature.=0D
+=0D
+This section is expected to provide guidance on:=0D
+* How to estimate performance impact due to the feature=0D
+* How to measure performance impact of the feature=0D
+* How to manage performance impact of the feature=0D
+=0D
+## Common Optimizations=0D
+*_TODO_*=0D
+Common size or performance tuning options for this feature.=0D
+=0D
+This section is recommended but not required. If not used, the contents sh=
ould be left empty.=0D
--=20
2.35.1.windows.2


Isaac Oram
 

Added Features/Intel maintainers for review.

-----Original Message-----
From: Dong, Guo <guo.dong@...>
Sent: Friday, May 6, 2022 5:49 PM
To: devel@edk2.groups.io
Cc: Dong, Guo <guo.dong@...>; Kinney, Michael D <michael.d.kinney@...>; Ni, Ray <ray.ni@...>; Rhodes, Sean <sean@...>; Oram, Isaac W <isaac.w.oram@...>
Subject: [edk2-devel][edk2-platforms][PATCH V2 1/1] Features/Intel/PlatformPayloadPkg: add platform payload FV

From: Guo Dong <guo.dong@...>

UefiPayloadPkg in EDK2 repo was added SMM variable support for Intel
platform with SPI flash. But some of the modules for SMM variable are
Intel PCH specific (e.g. SPI library, SMM PCH module), so move these
modules into edk2-platforms repo.

A platform payload FV could be built from PlatformPayloadPkg which works
on Intel platforms (e.g.. ICX, APL, CML, CFL, KBL, TGL, ADL, etc.) with
SMM variable. This platform payload FV could be added into universal UEFI
payload built from EDK2 UefiPayloadPkg.

The steps to build a complete payload (use windows host as example):

set WORKSPACE=c:\payload
set PACKAGES_PATH=C:\payload\edk2;C:\payload\edk2-platforms\Platform\Intel;
C:\payload\edk2-platforms\Features\Intel;
edk2\edksetup.bat

python edk2\UefiPayloadPkg\UniversalPayloadBuild.py -t VS2019
-D SMM_SUPPORT=TRUE -DVARIABLE_SUPPORT=NONE

python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg.py
-t VS2019 -D SMM_VARIABLE=TRUE -s

The final UEFI payload generated at Build\UefiPayloadPkgX64\UniversalPayload.elf
if build success.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Ray Ni <ray.ni@...>
Cc: Sean Rhodes <sean@...>
Signed-off-by: Guo Dong <guo.dong@...>
Signed-off-by: Isaac Oram <isaac.w.oram@...>
---
Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc | 5 +++++
Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf | 7 ++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c | 1088 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h | 185 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c | 139 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h | 24 +++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h | 38 ++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h | 213 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc | 112 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf | 20 +++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf | 8 +++++++
Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c | 160 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf | 38 ++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf | 50 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c | 170 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h | 120 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h | 203 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c | 874 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf | 48 +++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c | 455 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h | 36 +++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf | 51 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec | 49 ++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc | 110 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf | 50 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py | 113 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Readme.md | 96 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
35 files changed, 4887 insertions(+)

diff --git a/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc b/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
index 28530b8c67..17cc3224b7 100644
--- a/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
@@ -80,6 +80,11 @@
gUserAuthFeaturePkgTokenSpaceGuid.PcdUserAuthenticationFeatureEnable |TRUE

gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable |TRUE



+ #

+ # Individual features

+ #

+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable |TRUE

+

#

# PCD that are required to be set by the build target should be configured here for test purposes

# These settings are only for the purposes of buildings, boards should follow instructions in Readme files.

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
index 2b36938df6..2a93ca1ec7 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
@@ -75,3 +75,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/VirtualKeyboardFeature.dsc

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc

+!endif

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
index e214175eda..8e98154f3e 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
@@ -53,6 +53,11 @@
UserAuthFeaturePkg/UserAuthFeaturePkg.dec

VirtualKeyboardFeaturePkg/VirtualKeyboardFeaturePkg.dec



+ #

+ # Individual features

+ #

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

#

# The section below sets all PCDs to FALSE in this DSC file so the feature is not enabled by default.

# Board can set PCDs to TRUE in its DSC file to enable a subset of advanced features

@@ -76,6 +81,8 @@
gUserAuthFeaturePkgTokenSpaceGuid.PcdUserAuthenticationFeatureEnable |FALSE

gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable |FALSE



+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable |FALSE

+

#

# There seems to be some build parsing odd behavior that requires this PCD to be specified even though

# the *.fdf that consumes it is dependent on the feature flag.

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf b/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
index 99089f9a7b..a0975d4d43 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
+++ b/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
@@ -76,3 +76,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/PostMemory.fdf

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PostMemory.fdf

+!endif

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf b/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
index 1db258446a..b2b821c9c4 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
+++ b/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
@@ -76,3 +76,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/PreMemory.fdf

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PreMemory.fdf

+!endif

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c b/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c
new file mode 100644
index 0000000000..d6dcfeb4e1
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c
@@ -0,0 +1,77 @@
+/** @file

+

+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiDxe.h>

+#include <Protocol/FirmwareVolumeBlock.h>

+#include <Library/PcdLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseLib.h>

+#include <Guid/FirmwareFileSystem2.h>

+#include <Guid/SystemNvDataGuid.h>

+

+#define FVB_MEDIA_BLOCK_SIZE 0x1000

+

+typedef struct {

+ EFI_FIRMWARE_VOLUME_HEADER FvInfo;

+ EFI_FV_BLOCK_MAP_ENTRY End[1];

+} EFI_FVB2_MEDIA_INFO;

+

+//

+// This data structure contains a template of FV header which is used to restore

+// Fv header if it's corrupted.

+//

+EFI_FVB2_MEDIA_INFO mFvbMediaInfo = {

+ {

+ { 0, }, // ZeroVector[16]

+ EFI_SYSTEM_NV_DATA_FV_GUID,

+ 0,

+ EFI_FVH_SIGNATURE,

+ 0x0004feff, // check PiFirmwareVolume.h for details on EFI_FVB_ATTRIBUTES_2

+ sizeof (EFI_FIRMWARE_VOLUME_HEADER) + sizeof (EFI_FV_BLOCK_MAP_ENTRY),

+ 0, // CheckSum which will be calucated dynamically.

+ 0, // ExtHeaderOffset

+ { 0, },

+ EFI_FVH_REVISION,

+ {

+ {

+ 0,

+ FVB_MEDIA_BLOCK_SIZE,

+ }

+ }

+ },

+ {

+ {

+ 0,

+ 0

+ }

+ }

+};

+

+

+/**

+ Get a heathy FV header used for variable store recovery

+

+ @retval The FV header.

+

+**/

+EFI_FIRMWARE_VOLUME_HEADER *

+GetFvHeaderTemplate (

+ VOID

+ )

+{

+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;

+ UINTN FvSize;

+

+ FvSize = PcdGet32 (PcdFlashNvStorageFtwSpareSize) * 2;

+ FvHeader = &mFvbMediaInfo.FvInfo;

+ FvHeader->FvLength = FvSize;

+ FvHeader->BlockMap[0].NumBlocks = (UINT32)(FvSize / FvHeader->BlockMap[0].Length);

+ FvHeader->Checksum = 0;

+ FvHeader->Checksum = CalculateCheckSum16 ((UINT16 *)FvHeader, FvHeader->HeaderLength);

+

+ return FvHeader;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c
new file mode 100644
index 0000000000..1d19f3726b
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c
@@ -0,0 +1,1088 @@
+/** @file

+Firmware Volume Block Driver to provide FVB service.

+

+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include "FvbService.h"

+

+//

+// Global variable for this FVB driver which contains

+// the private data of all firmware volume block instances

+//

+FWB_GLOBAL mFvbModuleGlobal;

+

+FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate = {

+ {

+ {

+ HARDWARE_DEVICE_PATH,

+ HW_MEMMAP_DP,

+ {

+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH)),

+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH) >> 8)

+ }

+ },

+ EfiMemoryMappedIO,

+ (EFI_PHYSICAL_ADDRESS)0,

+ (EFI_PHYSICAL_ADDRESS)0,

+ },

+ {

+ END_DEVICE_PATH_TYPE,

+ END_ENTIRE_DEVICE_PATH_SUBTYPE,

+ {

+ END_DEVICE_PATH_LENGTH,

+ 0

+ }

+ }

+};

+

+FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate = {

+ {

+ {

+ MEDIA_DEVICE_PATH,

+ MEDIA_PIWG_FW_VOL_DP,

+ {

+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH)),

+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH) >> 8)

+ }

+ },

+ { 0 }

+ },

+ {

+ END_DEVICE_PATH_TYPE,

+ END_ENTIRE_DEVICE_PATH_SUBTYPE,

+ {

+ END_DEVICE_PATH_LENGTH,

+ 0

+ }

+ }

+};

+

+EFI_FW_VOL_BLOCK_DEVICE mFvbDeviceTemplate = {

+ FVB_DEVICE_SIGNATURE,

+ NULL,

+ 0, // Instance

+ {

+ FvbProtocolGetAttributes,

+ FvbProtocolSetAttributes,

+ FvbProtocolGetPhysicalAddress,

+ FvbProtocolGetBlockSize,

+ FvbProtocolRead,

+ FvbProtocolWrite,

+ FvbProtocolEraseBlocks,

+ NULL

+ } // FwVolBlockInstance

+};

+

+/**

+ Get the pointer to EFI_FW_VOL_INSTANCE from the buffer pointed

+ by mFvbModuleGlobal.FvInstance based on a index.

+ Each EFI_FW_VOL_INSTANCE is with variable length as

+ we have a block map at the end of the EFI_FIRMWARE_VOLUME_HEADER.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+

+ @return A pointer to EFI_FW_VOL_INSTANCE.

+

+**/

+EFI_FW_VOL_INSTANCE *

+GetFvbInstance (

+ IN UINTN Instance

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwhRecord;

+

+ if ( Instance >= mFvbModuleGlobal.NumFv ) {

+ ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER);

+ return NULL;

+ }

+

+ //

+ // Find the right instance of the FVB private data

+ //

+ FwhRecord = mFvbModuleGlobal.FvInstance;

+ while ( Instance > 0 ) {

+ FwhRecord = (EFI_FW_VOL_INSTANCE *)((UINTN)((UINT8 *)FwhRecord) +

+ FwhRecord->VolumeHeader.HeaderLength +

+ (sizeof (EFI_FW_VOL_INSTANCE) - sizeof (EFI_FIRMWARE_VOLUME_HEADER)));

+ Instance--;

+ }

+

+ return FwhRecord;

+}

+

+/**

+ Get the EFI_FVB_ATTRIBUTES_2 of a FV.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+

+ @retval EFI_FVB_ATTRIBUTES_2 of the FV identified by Instance.

+

+**/

+STATIC

+EFI_FVB_ATTRIBUTES_2

+FvbGetVolumeAttributes (

+ IN UINTN Instance

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwInstance;

+

+ FwInstance = GetFvbInstance (Instance);

+ ASSERT (FwInstance != NULL);

+

+ if (FwInstance == NULL) {

+ return 0;

+ }

+

+ return FwInstance->VolumeHeader.Attributes;

+}

+

+/**

+ Retrieves the starting address of an LBA in an FV. It also

+ return a few other attribut of the FV.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+ @param[in] Lba The logical block address

+ @param[out] LbaAddress On output, contains the physical starting address

+ of the Lba

+ @param[out] LbaLength On output, contains the length of the block

+ @param[out] NumOfBlocks A pointer to a caller allocated UINTN in which the

+ number of consecutive blocks starting with Lba is

+ returned. All blocks in this range have a size of

+ BlockSize

+

+ @retval EFI_SUCCESS Successfully returns

+ @retval EFI_INVALID_PARAMETER Instance not found

+

+**/

+STATIC

+EFI_STATUS

+FvbGetLbaAddress (

+ IN UINTN Instance,

+ IN EFI_LBA Lba,

+ OUT UINTN *LbaAddress,

+ OUT UINTN *LbaLength,

+ OUT UINTN *NumOfBlocks

+ )

+{

+ UINT32 NumBlocks;

+ UINT32 BlockLength;

+ UINTN Offset;

+ EFI_LBA StartLba;

+ EFI_LBA NextLba;

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;

+

+ //

+ // Find the right instance of the FVB private data

+ //

+ FwhInstance = GetFvbInstance (Instance);

+ if (FwhInstance == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ StartLba = 0;

+ Offset = 0;

+ BlockMap = &FwhInstance->VolumeHeader.BlockMap[0];

+ ASSERT (BlockMap != NULL);

+

+ //

+ // Parse the blockmap of the FV to find which map entry the Lba belongs to

+ //

+ while (TRUE) {

+ if ( BlockMap != NULL) {

+ NumBlocks = BlockMap->NumBlocks;

+ BlockLength = BlockMap->Length;

+ }

+

+ if ((NumBlocks == 0) || (BlockLength == 0)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ NextLba = StartLba + NumBlocks;

+

+ //

+ // The map entry found

+ //

+ if ((Lba >= StartLba) && (Lba < NextLba)) {

+ Offset = Offset + (UINTN)MultU64x32 ((Lba - StartLba), BlockLength);

+ if (LbaAddress != NULL) {

+ *LbaAddress = FwhInstance->FvBase + Offset;

+ }

+

+ if (LbaLength != NULL) {

+ *LbaLength = BlockLength;

+ }

+

+ if (NumOfBlocks != NULL) {

+ *NumOfBlocks = (UINTN)(NextLba - Lba);

+ }

+

+ return EFI_SUCCESS;

+ }

+

+ StartLba = NextLba;

+ Offset = Offset + NumBlocks * BlockLength;

+ BlockMap++;

+ }

+}

+

+/**

+ Reads specified number of bytes into a buffer from the specified block

+

+ @param[in] Instance The FV instance to be read from

+ @param[in] Lba The logical block address to be read from

+ @param[in] BlockOffset Offset into the block at which to begin reading

+ @param[in, out] NumBytes Pointer that on input contains the total size of

+ the buffer. On output, it contains the total number

+ of bytes read

+ @param[in] Buffer Pointer to a caller allocated buffer that will be

+ used to hold the data read

+

+

+ @retval EFI_SUCCESS The firmware volume was read successfully and

+ contents are in Buffer

+ @retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes returned

+ in Buffer

+ @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be read

+ @retval EFI_INVALID_PARAMETER Instance not found, or NumBytes, Buffer are NULL

+

+**/

+STATIC

+EFI_STATUS

+FvbReadBlock (

+ IN UINTN Instance,

+ IN EFI_LBA Lba,

+ IN UINTN BlockOffset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+ UINTN LbaAddress;

+ UINTN LbaLength;

+ EFI_STATUS Status;

+ EFI_STATUS ReadStatus;

+

+ if ((NumBytes == NULL) || (Buffer == NULL)) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ if (*NumBytes == 0) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ Attributes = FvbGetVolumeAttributes (Instance);

+

+ if ((Attributes & EFI_FVB2_READ_STATUS) == 0) {

+ return (EFI_ACCESS_DENIED);

+ }

+

+ if (BlockOffset > LbaLength) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ if (LbaLength < (*NumBytes + BlockOffset)) {

+ *NumBytes = (UINT32)(LbaLength - BlockOffset);

+ Status = EFI_BAD_BUFFER_SIZE;

+ }

+

+ ReadStatus = LibFvbFlashDeviceRead (LbaAddress + BlockOffset, NumBytes, Buffer);

+ if (EFI_ERROR (ReadStatus)) {

+ return ReadStatus;

+ }

+

+ return Status;

+}

+

+/**

+ Writes specified number of bytes from the input buffer to the block

+

+ @param[in] Instance The FV instance to be written to

+ @param[in] Lba The starting logical block index to write to

+ @param[in] BlockOffset Offset into the block at which to begin writing

+ @param[in, out] NumBytes Pointer that on input contains the total size of

+ the buffer. On output, it contains the total number

+ of bytes actually written

+ @param[in] Buffer Pointer to a caller allocated buffer that contains

+ the source for the write

+ @retval EFI_SUCCESS The firmware volume was written successfully

+ @retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes

+ actually written

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written

+ @retval EFI_INVALID_PARAMETER Instance not found, or NumBytes, Buffer are NULL

+

+**/

+EFI_STATUS

+FvbWriteBlock (

+ IN UINTN Instance,

+ IN EFI_LBA Lba,

+ IN UINTN BlockOffset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+ UINTN LbaAddress;

+ UINTN LbaLength;

+ EFI_STATUS Status;

+

+ if ((NumBytes == NULL) || (Buffer == NULL)) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ if (*NumBytes == 0) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ //

+ // Check if the FV is write enabled

+ //

+ Attributes = FvbGetVolumeAttributes (Instance);

+ if ((Attributes & EFI_FVB2_WRITE_STATUS) == 0) {

+ return EFI_ACCESS_DENIED;

+ }

+

+ //

+ // Perform boundary checks and adjust NumBytes

+ //

+ if (BlockOffset > LbaLength) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ if ( LbaLength < (*NumBytes + BlockOffset)) {

+ DEBUG ((

+ DEBUG_ERROR,

+ "FvWriteBlock: Reducing Numbytes from 0x%x to 0x%x\n",

+ *NumBytes,

+ (UINT32)(LbaLength - BlockOffset)

+ ));

+ *NumBytes = (UINT32)(LbaLength - BlockOffset);

+ return EFI_BAD_BUFFER_SIZE;

+ }

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, FALSE);

+ Status = LibFvbFlashDeviceWrite (LbaAddress + BlockOffset, NumBytes, Buffer);

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, TRUE);

+ WriteBackInvalidateDataCacheRange ((VOID *)(LbaAddress + BlockOffset), *NumBytes);

+ return Status;

+}

+

+/**

+ Erases and initializes a firmware volume block

+

+ @param[in] Instance The FV instance to be erased

+ @param[in] Lba The logical block index to be erased

+

+ @retval EFI_SUCCESS The erase request was successfully completed

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written. Firmware device may have been

+ partially erased

+ @retval EFI_INVALID_PARAMETER Instance not found

+

+**/

+EFI_STATUS

+FvbEraseBlock (

+ IN UINTN Instance,

+ IN EFI_LBA Lba

+ )

+{

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+ UINTN LbaAddress;

+ UINTN LbaLength;

+ EFI_STATUS Status;

+

+ //

+ // Check if the FV is write enabled

+ //

+ Attributes = FvbGetVolumeAttributes (Instance);

+

+ if ((Attributes & EFI_FVB2_WRITE_STATUS) == 0) {

+ return (EFI_ACCESS_DENIED);

+ }

+

+ //

+ // Get the starting address of the block for erase.

+ //

+ Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, FALSE);

+

+ Status = LibFvbFlashDeviceBlockErase (LbaAddress, LbaLength);

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, TRUE);

+

+ WriteBackInvalidateDataCacheRange ((VOID *)LbaAddress, LbaLength);

+

+ return Status;

+}

+

+/**

+ Modifies the current settings of the firmware volume according to the

+ input parameter, and returns the new setting of the volume

+

+ @param[in] Instance The FV instance whose attributes is going to be

+ modified

+ @param[in, out] Attributes On input, it is a pointer to EFI_FVB_ATTRIBUTES_2

+ containing the desired firmware volume settings.

+ On successful return, it contains the new settings

+ of the firmware volume

+

+ @retval EFI_SUCCESS Successfully returns

+ @retval EFI_ACCESS_DENIED The volume setting is locked and cannot be modified

+ @retval EFI_INVALID_PARAMETER Instance not found, or The attributes requested are

+ in conflict with the capabilities as declared in the

+ firmware volume header

+

+**/

+STATIC

+EFI_STATUS

+FvbSetVolumeAttributes (

+ IN UINTN Instance,

+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+ EFI_FVB_ATTRIBUTES_2 OldAttributes;

+ EFI_FVB_ATTRIBUTES_2 *AttribPtr;

+ EFI_FVB_ATTRIBUTES_2 UnchangedAttributes;

+ UINT32 Capabilities;

+ UINT32 OldStatus;

+ UINT32 NewStatus;

+

+ //

+ // Find the right instance of the FVB private data

+ //

+ FwhInstance = GetFvbInstance (Instance);

+ if (FwhInstance == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ AttribPtr = (EFI_FVB_ATTRIBUTES_2 *)&(FwhInstance->VolumeHeader.Attributes);

+ ASSERT (AttribPtr != NULL);

+ if ( AttribPtr == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ OldAttributes = *AttribPtr;

+ Capabilities = OldAttributes & EFI_FVB2_CAPABILITIES;

+ OldStatus = OldAttributes & EFI_FVB2_STATUS;

+ NewStatus = *Attributes & EFI_FVB2_STATUS;

+

+ UnchangedAttributes = EFI_FVB2_READ_DISABLED_CAP | \

+ EFI_FVB2_READ_ENABLED_CAP | \

+ EFI_FVB2_WRITE_DISABLED_CAP | \

+ EFI_FVB2_WRITE_ENABLED_CAP | \

+ EFI_FVB2_LOCK_CAP | \

+ EFI_FVB2_STICKY_WRITE | \

+ EFI_FVB2_MEMORY_MAPPED | \

+ EFI_FVB2_ERASE_POLARITY | \

+ EFI_FVB2_READ_LOCK_CAP | \

+ EFI_FVB2_WRITE_LOCK_CAP | \

+ EFI_FVB2_ALIGNMENT;

+

+ //

+ // Some attributes of FV is read only can *not* be set

+ //

+ if ((OldAttributes & UnchangedAttributes) ^ (*Attributes & UnchangedAttributes)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ //

+ // If firmware volume is locked, no status bit can be updated

+ //

+ if ((OldAttributes & EFI_FVB2_LOCK_STATUS) != 0) {

+ if ((OldStatus ^ NewStatus) != 0) {

+ return EFI_ACCESS_DENIED;

+ }

+ }

+

+ //

+ // Test read disable

+ //

+ if ((Capabilities & EFI_FVB2_READ_DISABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_READ_STATUS) == 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test read enable

+ //

+ if ((Capabilities & EFI_FVB2_READ_ENABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_READ_STATUS) != 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test write disable

+ //

+ if ((Capabilities & EFI_FVB2_WRITE_DISABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_WRITE_STATUS) == 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test write enable

+ //

+ if ((Capabilities & EFI_FVB2_WRITE_ENABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_WRITE_STATUS) != 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test lock

+ //

+ if ((Capabilities & EFI_FVB2_LOCK_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_LOCK_STATUS) != 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ *AttribPtr = (*AttribPtr) & (0xFFFFFFFF & (~EFI_FVB2_STATUS));

+ *AttribPtr = (*AttribPtr) | NewStatus;

+ *Attributes = *AttribPtr;

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Retrieves the physical address of the device.

+

+ @param[in] This A pointer to EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL.

+ @param[out] Address Output buffer containing the address.

+

+ @retval EFI_SUCCESS The function always return successfully.

+ @retval EFI_INVALID_PARAMETER Instance not found.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolGetPhysicalAddress (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_PHYSICAL_ADDRESS *Address

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ FwhInstance = GetFvbInstance (FvbDevice->Instance);

+ if (FwhInstance == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ *Address = FwhInstance->FvBase;

+ return EFI_SUCCESS;

+}

+

+/**

+ Retrieve the size of a logical block

+

+ @param[in] This Calling context

+ @param[in] Lba Indicates which block to return the size for.

+ @param[out] BlockSize A pointer to a caller allocated UINTN in which

+ the size of the block is returned

+ @param[out] NumOfBlocks A pointer to a caller allocated UINTN in which the

+ number of consecutive blocks starting with Lba is

+ returned. All blocks in this range have a size of

+ BlockSize

+

+ @retval EFI_SUCCESS The function always return successfully.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolGetBlockSize (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ OUT UINTN *BlockSize,

+ OUT UINTN *NumOfBlocks

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ return FvbGetLbaAddress (FvbDevice->Instance, Lba, NULL, BlockSize, NumOfBlocks);

+}

+

+/**

+ Retrieves Volume attributes. No polarity translations are done.

+

+ @param[in] This Calling context

+ @param[out] Attributes Output buffer which contains attributes

+

+ @retval EFI_SUCCESS The function always return successfully.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolGetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ *Attributes = FvbGetVolumeAttributes (FvbDevice->Instance);

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Sets Volume attributes. No polarity translations are done.

+

+ @param[in] This Calling context

+ @param[in, out] Attributes Output buffer which contains attributes

+

+ @retval EFI_SUCCESS The function always return successfully.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolSetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ )

+{

+ EFI_STATUS Status;

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ Status = FvbSetVolumeAttributes (FvbDevice->Instance, Attributes);

+ return Status;

+}

+

+/**

+ This function erases one or more blocks as denoted by the

+ variable argument list. The entire parameter list of blocks must be verified

+ prior to erasing any blocks. If a block is requested that does not exist

+ within the associated firmware volume (it has a larger index than the last

+ block of the firmware volume), the EraseBlock() function must return

+ EFI_INVALID_PARAMETER without modifying the contents of the firmware volume.

+

+ @param[in] This Calling context

+ @param[in] ... Starting LBA followed by Number of Lba to erase.

+ a -1 to terminate the list.

+

+ @retval EFI_SUCCESS The erase request was successfully completed

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written. Firmware device may have been

+ partially erased

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolEraseBlocks (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ ...

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+ UINTN NumOfBlocks;

+ VA_LIST args;

+ EFI_LBA StartingLba;

+ UINTN NumOfLba;

+ EFI_STATUS Status;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ FwhInstance = GetFvbInstance (FvbDevice->Instance);

+ if (FwhInstance == NULL) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ NumOfBlocks = FwhInstance->NumOfBlocks;

+ VA_START (args, This);

+

+ do {

+ StartingLba = VA_ARG (args, EFI_LBA);

+ if ( StartingLba == EFI_LBA_LIST_TERMINATOR ) {

+ break;

+ }

+

+ NumOfLba = VA_ARG (args, UINT32);

+

+ //

+ // Check input parameters

+ //

+ if (NumOfLba == 0) {

+ VA_END (args);

+ return EFI_INVALID_PARAMETER;

+ }

+

+ if ((StartingLba + NumOfLba) > NumOfBlocks ) {

+ return EFI_INVALID_PARAMETER;

+ }

+ } while (1);

+

+ VA_END (args);

+

+ VA_START (args, This);

+ do {

+ StartingLba = VA_ARG (args, EFI_LBA);

+ if (StartingLba == EFI_LBA_LIST_TERMINATOR) {

+ break;

+ }

+

+ NumOfLba = VA_ARG (args, UINT32);

+

+ while ( NumOfLba > 0 ) {

+ Status = FvbEraseBlock (FvbDevice->Instance, StartingLba);

+ if ( EFI_ERROR (Status)) {

+ VA_END (args);

+ return Status;

+ }

+

+ StartingLba++;

+ NumOfLba--;

+ }

+ } while (1);

+

+ VA_END (args);

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Writes data beginning at Lba:Offset from FV. The write terminates either

+ when *NumBytes of data have been written, or when a block boundary is

+ reached. *NumBytes is updated to reflect the actual number of bytes

+ written. The write opertion does not include erase. This routine will

+ attempt to write only the specified bytes. If the writes do not stick,

+ it will return an error.

+

+ @param[in] This Calling context

+ @param[in] Lba Block in which to begin write

+ @param[in] Offset Offset in the block at which to begin write

+ @param[in,out] NumBytes On input, indicates the requested write size. On

+ output, indicates the actual number of bytes written

+ @param[in] Buffer Buffer containing source data for the write.

+

+ @retval EFI_SUCCESS The firmware volume was written successfully

+ @retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes

+ actually written

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written

+ @retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolWrite (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_STATUS Status;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ Status = FvbWriteBlock (FvbDevice->Instance, Lba, Offset, NumBytes, Buffer);

+ DEBUG ((

+ DEBUG_VERBOSE,

+ "FvbWrite: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0x%x Status:%r\n",

+ Lba,

+ Offset,

+ *NumBytes,

+ Buffer,

+ Status

+ ));

+

+ return Status;

+}

+

+/**

+ Reads data beginning at Lba:Offset from FV. The Read terminates either

+ when *NumBytes of data have been read, or when a block boundary is

+ reached. *NumBytes is updated to reflect the actual number of bytes

+ written. The write opertion does not include erase. This routine will

+ attempt to write only the specified bytes. If the writes do not stick,

+ it will return an error.

+

+ @param[in] This Calling context

+ @param[in] Lba Block in which to begin write

+ @param[in] Offset Offset in the block at which to begin write

+ @param[in,out] NumBytes On input, indicates the requested write size. On

+ output, indicates the actual number of bytes written

+ @param[out] Buffer Buffer containing source data for the write.

+

+

+Returns:

+ @retval EFI_SUCCESS The firmware volume was read successfully and

+ contents are in Buffer

+ @retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes returned

+ in Buffer

+ @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be read

+ @retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolRead (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_STATUS Status;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ Status = FvbReadBlock (FvbDevice->Instance, Lba, Offset, NumBytes, Buffer);

+ DEBUG ((

+ DEBUG_VERBOSE,

+ "FvbRead: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0x%x, Status:%r\n",

+ Lba,

+ Offset,

+ *NumBytes,

+ Buffer,

+ Status

+ ));

+

+ return Status;

+}

+

+/**

+ Check the integrity of firmware volume header in FvBase

+

+ @param[in] FvBase A pointer to firmware volume base address.

+

+ @retval TRUE The firmware volume is consistent

+ @retval FALSE The firmware volume has corrupted.

+

+**/

+BOOLEAN

+IsFvHeaderValid (

+ IN EFI_PHYSICAL_ADDRESS FvBase

+ )

+{

+ UINT16 Sum;

+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;

+

+ FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvBase;

+ if (FvBase == PcdGet32 (PcdFlashNvStorageVariableBase)) {

+ if (CompareMem (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid, sizeof (EFI_GUID)) != 0 ) {

+ DEBUG ((DEBUG_INFO, " --FileSystemGuid not match: %g\n", &FwVolHeader->FileSystemGuid));

+ return FALSE;

+ }

+ } else {

+ if (CompareMem (&FwVolHeader->FileSystemGuid, &gEfiFirmwareFileSystem2Guid, sizeof (EFI_GUID)) != 0 ) {

+ DEBUG ((DEBUG_INFO, " --not expected guid.\n"));

+ return FALSE;

+ }

+ }

+

+ if ((FwVolHeader->Revision != EFI_FVH_REVISION) ||

+ (FwVolHeader->Signature != EFI_FVH_SIGNATURE) ||

+ (FwVolHeader->FvLength == ((UINTN)-1)) ||

+ ((FwVolHeader->HeaderLength & 0x01) != 0))

+ {

+ DEBUG ((DEBUG_INFO, " -- >Revision = 0x%x, Signature = 0x%x\n", FwVolHeader->Revision, FwVolHeader->Signature));

+ DEBUG ((DEBUG_INFO, " -- >FvLength = 0x%lx, HeaderLength = 0x%x\n", FwVolHeader->FvLength, FwVolHeader->HeaderLength));

+ return FALSE;

+ }

+

+ Sum = CalculateSum16 ((UINT16 *)FwVolHeader, FwVolHeader->HeaderLength);

+ if (Sum != 0) {

+ DEBUG ((DEBUG_INFO, "error: checksum: 0x%04X (expect 0x0)\n", Sum));

+ return FALSE;

+ }

+

+ return TRUE;

+}

+

+/**

+ Get intial variable data.

+

+ @param[out] VarData Valid variable data.

+ @param[out] VarSize Valid variable size.

+

+ @retval RETURN_SUCCESS Successfully found initial variable data.

+ @retval RETURN_NOT_FOUND Failed to find the variable data file from FV.

+ @retval EFI_INVALID_PARAMETER VarData or VarSize is null.

+

+**/

+EFI_STATUS

+GetInitialVariableData (

+ OUT VOID **VarData,

+ OUT UINTN *VarSize

+ )

+{

+ EFI_STATUS Status;

+ VOID *ImageData;

+ UINTN ImageSize;

+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;

+ VARIABLE_STORE_HEADER *VariableStore;

+ AUTHENTICATED_VARIABLE_HEADER *Variable;

+ UINTN VariableSize;

+ UINTN VarEndAddr;

+

+ if ((VarData == NULL) || (VarSize == NULL)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Status = GetSectionFromAnyFv (PcdGetPtr (PcdNvsDataFile), EFI_SECTION_RAW, 0, &ImageData, &ImageSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)ImageData;

+ VariableStore = (VARIABLE_STORE_HEADER *)((UINT8 *)ImageData + FvHeader->HeaderLength);

+ VarEndAddr = (UINTN)VariableStore + VariableStore->Size;

+ Variable = (AUTHENTICATED_VARIABLE_HEADER *)HEADER_ALIGN (VariableStore + 1);

+ *VarData = (VOID *)Variable;

+ while (((UINTN)Variable < VarEndAddr)) {

+ if (Variable->StartId != VARIABLE_DATA) {

+ break;

+ }

+

+ VariableSize = sizeof (AUTHENTICATED_VARIABLE_HEADER) + Variable->DataSize + Variable->NameSize;

+ Variable = (AUTHENTICATED_VARIABLE_HEADER *)HEADER_ALIGN ((UINTN)Variable + VariableSize);

+ }

+

+ *VarSize = (UINTN)Variable - HEADER_ALIGN (VariableStore + 1);

+

+ return EFI_SUCCESS;

+}

+

+/**

+ The function does the necessary initialization work for

+ Firmware Volume Block Driver.

+

+ @retval EFI_SUCCESS This funtion always return EFI_SUCCESS.

+ It will ASSERT on errors.

+

+**/

+EFI_STATUS

+FvbInitialize (

+ VOID

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwVolInstance;

+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;

+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;

+ EFI_PHYSICAL_ADDRESS BaseAddress;

+ UINTN WriteAddr;

+ EFI_STATUS Status;

+ UINTN BufferSize;

+ UINTN Length;

+ VARIABLE_STORE_HEADER VariableStore;

+ VOID *VarData;

+

+ BaseAddress = PcdGet32 (PcdFlashNvStorageVariableBase);

+ FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)BaseAddress;

+

+ //

+ // Check FV header and variable store header

+ //

+ if (!IsFvHeaderValid (BaseAddress)) {

+ //

+ // Write back a healthy FV header

+ //

+ DEBUG ((DEBUG_ERROR, "Fvb: Writing back a healthy FV header: 0x%lx\n", BaseAddress));

+ FvHeader = GetFvHeaderTemplate ();

+ LibFvbFlashDeviceBlockLock ((UINTN)BaseAddress, FvHeader->BlockMap->Length, FALSE);

+

+ Status = LibFvbFlashDeviceBlockErase ((UINTN)BaseAddress, FvHeader->BlockMap->Length);

+ ASSERT_EFI_ERROR (Status);

+

+ Length = FvHeader->HeaderLength;

+ WriteAddr = (UINTN)BaseAddress;

+ Status = LibFvbFlashDeviceWrite (WriteAddr, &Length, (UINT8 *)FvHeader);

+ WriteAddr += Length;

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Write back variable store header

+ //

+ VariableStore.Size = PcdGet32 (PcdFlashNvStorageVariableSize) - FvHeader->HeaderLength;

+ VariableStore.Format = VARIABLE_STORE_FORMATTED;

+ VariableStore.State = VARIABLE_STORE_HEALTHY;

+ CopyGuid (&VariableStore.Signature, &gEfiAuthenticatedVariableGuid);

+ BufferSize = sizeof (VARIABLE_STORE_HEADER);

+ Status = LibFvbFlashDeviceWrite (WriteAddr, &BufferSize, (UINT8 *)&VariableStore);

+ WriteAddr += BufferSize;

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Write initial variable data if found

+ //

+ Status = GetInitialVariableData (&VarData, &Length);

+ if (!EFI_ERROR (Status)) {

+ Status = LibFvbFlashDeviceWrite (WriteAddr, &Length, (UINT8 *)VarData);

+ ASSERT_EFI_ERROR (Status);

+ }

+

+ LibFvbFlashDeviceBlockLock ((UINTN)BaseAddress, FvHeader->BlockMap->Length, TRUE);

+ WriteBackInvalidateDataCacheRange ((VOID *)(UINTN)BaseAddress, FvHeader->BlockMap->Length);

+ }

+

+ //

+ // Create a new FW volume instance for NVS variable

+ //

+ BufferSize = FvHeader->HeaderLength + sizeof (EFI_FW_VOL_INSTANCE) - sizeof (EFI_FIRMWARE_VOLUME_HEADER);

+ FwVolInstance = (EFI_FW_VOL_INSTANCE *)AllocateRuntimeZeroPool (BufferSize);

+ if (FwVolInstance == NULL) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ FwVolInstance->FvBase = (UINTN)BaseAddress;

+ CopyMem (&FwVolInstance->VolumeHeader, FvHeader, FvHeader->HeaderLength);

+

+ //

+ // Process the block map for each FV. Assume it has same block size.

+ //

+ FwVolInstance->NumOfBlocks = 0;

+ FvHeader = &FwVolInstance->VolumeHeader;

+ for (BlockMap = FvHeader->BlockMap; BlockMap->NumBlocks != 0; BlockMap++) {

+ FwVolInstance->NumOfBlocks += BlockMap->NumBlocks;

+ }

+

+ //

+ // Add a FVB Protocol Instance

+ //

+ Status = InstallFvbProtocol (FwVolInstance, mFvbModuleGlobal.NumFv);

+ mFvbModuleGlobal.NumFv++;

+ mFvbModuleGlobal.FvInstance = FwVolInstance;

+

+ return Status;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h
new file mode 100644
index 0000000000..54428d8391
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h
@@ -0,0 +1,185 @@
+/** @file

+The header file for Firmware volume block driver.

+

+Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef FW_BLOCK_SERVICE_H_

+#define FW_BLOCK_SERVICE_H_

+

+#include <Guid/EventGroup.h>

+#include <Guid/FirmwareFileSystem2.h>

+#include <Guid/SystemNvDataGuid.h>

+#include <Guid/VariableFormat.h>

+#include <Protocol/DevicePath.h>

+#include <Protocol/FirmwareVolumeBlock.h>

+#include <Library/UefiDriverEntryPoint.h>

+#include <Library/UefiBootServicesTableLib.h>

+#include <Library/UefiLib.h>

+#include <Library/BaseLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseMemoryLib.h>

+#include <Library/IoLib.h>

+#include <Library/CacheMaintenanceLib.h>

+#include <Library/MemoryAllocationLib.h>

+#include <Library/PcdLib.h>

+#include <Library/FlashDeviceLib.h>

+#include <Library/DevicePathLib.h>

+#include <Library/HobLib.h>

+#include <Library/DxeServicesLib.h>

+#include <Guid/NvVariableInfoGuid.h>

+#include <Register/ArchitecturalMsr.h>

+

+//

+// Define two helper macro to extract the Capability field or Status field in FVB

+// bit fields

+//

+#define EFI_FVB2_CAPABILITIES (EFI_FVB2_READ_DISABLED_CAP |\

+ EFI_FVB2_READ_ENABLED_CAP | \

+ EFI_FVB2_WRITE_DISABLED_CAP | \

+ EFI_FVB2_WRITE_ENABLED_CAP | \

+ EFI_FVB2_LOCK_CAP \

+ )

+

+#define EFI_FVB2_STATUS (EFI_FVB2_READ_STATUS | EFI_FVB2_WRITE_STATUS | EFI_FVB2_LOCK_STATUS)

+

+typedef struct {

+ UINTN FvBase;

+ UINTN NumOfBlocks;

+ //

+ // Note!!!: VolumeHeader must be the last element

+ // of the structure.

+ //

+ EFI_FIRMWARE_VOLUME_HEADER VolumeHeader;

+} EFI_FW_VOL_INSTANCE;

+

+typedef struct {

+ EFI_FW_VOL_INSTANCE *FvInstance;

+ UINT32 NumFv;

+ UINT32 Flags;

+} FWB_GLOBAL;

+

+//

+// Fvb Protocol instance data

+//

+#define FVB_DEVICE_FROM_THIS(a) CR(a, EFI_FW_VOL_BLOCK_DEVICE, FwVolBlockInstance, FVB_DEVICE_SIGNATURE)

+#define FVB_EXTEND_DEVICE_FROM_THIS(a) CR(a, EFI_FW_VOL_BLOCK_DEVICE, FvbExtension, FVB_DEVICE_SIGNATURE)

+#define FVB_DEVICE_SIGNATURE SIGNATURE_32('F','V','B','C')

+

+typedef struct {

+ MEDIA_FW_VOL_DEVICE_PATH FvDevPath;

+ EFI_DEVICE_PATH_PROTOCOL EndDevPath;

+} FV_PIWG_DEVICE_PATH;

+

+typedef struct {

+ MEMMAP_DEVICE_PATH MemMapDevPath;

+ EFI_DEVICE_PATH_PROTOCOL EndDevPath;

+} FV_MEMMAP_DEVICE_PATH;

+

+typedef struct {

+ UINT32 Signature;

+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;

+ UINTN Instance;

+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL FwVolBlockInstance;

+} EFI_FW_VOL_BLOCK_DEVICE;

+

+/**

+ Get a heathy FV header used for variable store recovery

+

+ @retval The FV header.

+

+**/

+EFI_FIRMWARE_VOLUME_HEADER *

+GetFvHeaderTemplate (

+ VOID

+ );

+

+EFI_STATUS

+InitVariableStore (

+ VOID

+ );

+

+//

+// Protocol APIs

+//

+EFI_STATUS

+EFIAPI

+FvbProtocolGetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolSetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolGetPhysicalAddress (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_PHYSICAL_ADDRESS *Address

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolGetBlockSize (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ OUT UINTN *BlockSize,

+ OUT UINTN *NumOfBlocks

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolRead (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolWrite (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolEraseBlocks (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ ...

+ );

+

+EFI_FW_VOL_INSTANCE *

+GetFvbInstance (

+ IN UINTN Instance

+ );

+

+EFI_STATUS

+InstallFvbProtocol (

+ IN EFI_FW_VOL_INSTANCE *FwhInstance,

+ IN UINTN InstanceNum

+ );

+

+EFI_STATUS

+FvbInitialize (

+ VOID

+ );

+

+extern FWB_GLOBAL mFvbModuleGlobal;

+extern EFI_FW_VOL_BLOCK_DEVICE mFvbDeviceTemplate;

+extern FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate;

+extern FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c b/Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c
new file mode 100644
index 0000000000..e2b87a74d2
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c
@@ -0,0 +1,139 @@
+/** @file

+ SMM Firmware Volume Block Driver.

+

+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiSmm.h>

+#include <Library/SmmServicesTableLib.h>

+#include "FvbSmmCommon.h"

+#include "FvbService.h"

+

+/**

+ The function installs EFI_SMM_FIRMWARE_VOLUME_BLOCK protocol

+ for each FV in the system.

+

+ @param[in] FwhInstance The pointer to a FW volume instance structure,

+ which contains the information about one FV.

+ @param[in] InstanceNum The instance number which can be used as a ID

+ to locate this FwhInstance in other functions.

+

+ @retval EFI_SUCESS Installed successfully.

+ @retval Else Did not install successfully.

+

+**/

+EFI_STATUS

+InstallFvbProtocol (

+ IN EFI_FW_VOL_INSTANCE *FwhInstance,

+ IN UINTN InstanceNum

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;

+ EFI_STATUS Status;

+ EFI_HANDLE FvbHandle;

+ FV_MEMMAP_DEVICE_PATH *FvDevicePath;

+ VOID *TempPtr;

+

+ FvbDevice = (EFI_FW_VOL_BLOCK_DEVICE *)AllocateRuntimeCopyPool (

+ sizeof (EFI_FW_VOL_BLOCK_DEVICE),

+ &mFvbDeviceTemplate

+ );

+ if (FvbDevice == NULL) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ FvbDevice->Instance = InstanceNum;

+ FwVolHeader = &FwhInstance->VolumeHeader;

+

+ //

+ // Set up the devicepath

+ //

+ if (FwVolHeader->ExtHeaderOffset == 0) {

+ //

+ // FV does not contains extension header, then produce MEMMAP_DEVICE_PATH

+ //

+ TempPtr = AllocateRuntimeCopyPool (sizeof (FV_MEMMAP_DEVICE_PATH), &mFvMemmapDevicePathTemplate);

+ FvbDevice->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)TempPtr;

+ if (FvbDevice->DevicePath == NULL) {

+ ASSERT (FALSE);

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ FvDevicePath = (FV_MEMMAP_DEVICE_PATH *)FvbDevice->DevicePath;

+ FvDevicePath->MemMapDevPath.StartingAddress = FwhInstance->FvBase;

+ FvDevicePath->MemMapDevPath.EndingAddress = FwhInstance->FvBase + FwVolHeader->FvLength - 1;

+ } else {

+ TempPtr = AllocateRuntimeCopyPool (sizeof (FV_PIWG_DEVICE_PATH), &mFvPIWGDevicePathTemplate);

+ FvbDevice->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)TempPtr;

+ if (FvbDevice->DevicePath == NULL) {

+ ASSERT (FALSE);

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ CopyGuid (

+ &((FV_PIWG_DEVICE_PATH *)FvbDevice->DevicePath)->FvDevPath.FvName,

+ (GUID *)(UINTN)(FwhInstance->FvBase + FwVolHeader->ExtHeaderOffset)

+ );

+ }

+

+ //

+ // Install the SMM Firmware Volume Block Protocol and Device Path Protocol

+ //

+ FvbHandle = NULL;

+ Status = gSmst->SmmInstallProtocolInterface (

+ &FvbHandle,

+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ &FvbDevice->FwVolBlockInstance

+ );

+ ASSERT_EFI_ERROR (Status);

+

+ Status = gSmst->SmmInstallProtocolInterface (

+ &FvbHandle,

+ &gEfiDevicePathProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ FvbDevice->DevicePath

+ );

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Notify the Fvb wrapper driver SMM fvb is ready

+ //

+ FvbHandle = NULL;

+ Status = gBS->InstallProtocolInterface (

+ &FvbHandle,

+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ &FvbDevice->FwVolBlockInstance

+ );

+

+ return Status;

+}

+

+/**

+ The driver entry point for SMM Firmware Volume Block Driver.

+

+ The function does the necessary initialization work

+ Firmware Volume Block Driver.

+

+ @param[in] ImageHandle The firmware allocated handle for the UEFI image.

+ @param[in] SystemTable A pointer to the EFI system table.

+

+ @retval EFI_SUCCESS This funtion always return EFI_SUCCESS.

+ It will ASSERT on errors.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbSmmInitialize (

+ IN EFI_HANDLE ImageHandle,

+ IN EFI_SYSTEM_TABLE *SystemTable

+ )

+{

+ FvbInitialize ();

+

+ return EFI_SUCCESS;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf
new file mode 100644
index 0000000000..a56654ba09
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf
@@ -0,0 +1,66 @@
+## @file

+# This driver installs the EFI_SMM_FIRMWARE_VOLUMEN_PROTOCOL.

+#

+#

+# Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = FvbSmm

+ FILE_GUID = A4EC8ADB-B7A8-47d1-8E52-EC820D0ACF6F

+ MODULE_TYPE = DXE_SMM_DRIVER

+ VERSION_STRING = 1.0

+ PI_SPECIFICATION_VERSION = 0x0001000A

+ ENTRY_POINT = FvbSmmInitialize

+

+[Sources]

+ FvbInfo.c

+ FvbService.h

+ FvbService.c

+ FvbServiceSmm.c

+ FvbSmmCommon.h

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ UefiCpuPkg/UefiCpuPkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ FlashDeviceLib

+ PcdLib

+ MemoryAllocationLib

+ CacheMaintenanceLib

+ IoLib

+ BaseMemoryLib

+ DebugLib

+ BaseLib

+ UefiLib

+ SmmServicesTableLib

+ UefiBootServicesTableLib

+ UefiDriverEntryPoint

+ HobLib

+ DxeServicesLib

+

+[Guids]

+ gEfiFirmwareFileSystem2Guid # ALWAYS_CONSUMED

+ gEfiSystemNvDataFvGuid # ALWAYS_CONSUMED

+ gEfiAuthenticatedVariableGuid

+ gNvVariableInfoGuid

+

+ [Protocols]

+ gEfiDevicePathProtocolGuid # PROTOCOL ALWAYS_PRODUCED

+ gEfiSmmFirmwareVolumeBlockProtocolGuid # PROTOCOL ALWAYS_PRODUCED

+

+[Pcd]

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize

+ gPlatformPayloadPkgTokenSpaceGuid.PcdNvsDataFile

+

+[Depex]

+ TRUE

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h
new file mode 100644
index 0000000000..0eadabe13f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h
@@ -0,0 +1,68 @@
+/** @file

+ The common header file for SMM FVB module.

+

+Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SMM_FVB_COMMON_H_

+#define SMM_FVB_COMMON_H_

+

+#include <Protocol/SmmFirmwareVolumeBlock.h>

+

+#define EFI_FUNCTION_GET_ATTRIBUTES 1

+#define EFI_FUNCTION_SET_ATTRIBUTES 2

+#define EFI_FUNCTION_GET_PHYSICAL_ADDRESS 3

+#define EFI_FUNCTION_GET_BLOCK_SIZE 4

+#define EFI_FUNCTION_READ 5

+#define EFI_FUNCTION_WRITE 6

+#define EFI_FUNCTION_ERASE_BLOCKS 7

+

+typedef struct {

+ UINTN Function;

+ EFI_STATUS ReturnStatus;

+ UINT8 Data[1];

+} SMM_FVB_COMMUNICATE_FUNCTION_HEADER;

+

+///

+/// Size of SMM communicate header, without including the payload.

+///

+#define SMM_COMMUNICATE_HEADER_SIZE (OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data))

+

+///

+/// Size of SMM FVB communicate function header, without including the payload.

+///

+#define SMM_FVB_COMMUNICATE_HEADER_SIZE (OFFSET_OF (SMM_FVB_COMMUNICATE_FUNCTION_HEADER, Data))

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+} SMM_FVB_ATTRIBUTES_HEADER;

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_PHYSICAL_ADDRESS Address;

+} SMM_FVB_PHYSICAL_ADDRESS_HEADER;

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_LBA Lba;

+ UINTN BlockSize;

+ UINTN NumOfBlocks;

+} SMM_FVB_BLOCK_SIZE_HEADER;

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_LBA Lba;

+ UINTN Offset;

+ UINTN NumBytes;

+} SMM_FVB_READ_WRITE_HEADER;

+

+typedef struct {

+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_LBA StartLba;

+ UINTN NumOfLba;

+} SMM_FVB_BLOCKS_HEADER;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h b/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h
new file mode 100644
index 0000000000..fd0bd73529
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h
@@ -0,0 +1,24 @@
+/** @file

+ This file defines the hob structure for the SPI flash variable info.

+

+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef NV_VARIABLE_INFO_GUID_H_

+#define NV_VARIABLE_INFO_GUID_H_

+

+//

+// NV variable hob info GUID

+//

+extern EFI_GUID gNvVariableInfoGuid;

+

+typedef struct {

+ UINT8 Revision;

+ UINT8 Reserved[3];

+ UINT32 VariableStoreBase;

+ UINT32 VariableStoreSize;

+} NV_VARIABLE_INFO;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h b/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h
new file mode 100644
index 0000000000..59b81851d5
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h
@@ -0,0 +1,38 @@
+/** @file

+ This file defines the hob structure for the SPI flash variable info.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SPI_FLASH_INFO_GUID_H_

+#define SPI_FLASH_INFO_GUID_H_

+

+#include <IndustryStandard/Acpi.h>

+//

+// SPI Flash infor hob GUID

+//

+extern EFI_GUID gSpiFlashInfoGuid;

+

+//

+// Set this bit if platform need disable SMM write protection when writing flash

+// in SMM mode using this method: -- AsmWriteMsr32 (0x1FE, MmioRead32 (0xFED30880) | BIT0);

+//

+#define FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT BIT0

+

+//

+// Reuse ACPI definition

+//

+typedef EFI_ACPI_3_0_GENERIC_ADDRESS_STRUCTURE PLD_GENERIC_ADDRESS;

+#define SPACE_ID_PCI_CONFIGURATION EFI_ACPI_3_0_PCI_CONFIGURATION_SPACE

+#define REGISTER_BIT_WIDTH_DWORD EFI_ACPI_3_0_DWORD

+

+typedef struct {

+ UINT8 Revision;

+ UINT8 Reserved;

+ UINT16 Flags;

+ PLD_GENERIC_ADDRESS SpiAddress;

+} SPI_FLASH_INFO;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h b/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h
new file mode 100644
index 0000000000..b5e8be225e
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h
@@ -0,0 +1,104 @@
+/** @file

+ Flash device library class header file.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef FLASHDEVICE_LIB_H_

+#define FLASHDEVICE_LIB_H_

+

+/**

+ Read NumBytes bytes of data from the address specified by

+ PAddress into Buffer.

+

+ @param[in] PAddress The starting physical address of the read.

+ @param[in,out] NumBytes On input, the number of bytes to read. On output, the number

+ of bytes actually read.

+ @param[out] Buffer The destination data buffer for the read.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceRead (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ );

+

+/**

+ Write NumBytes bytes of data from Buffer to the address specified by

+ PAddresss.

+

+ @param[in] PAddress The starting physical address of the write.

+ @param[in,out] NumBytes On input, the number of bytes to write. On output,

+ the actual number of bytes written.

+ @param[in] Buffer The source data buffer for the write.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceWrite (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ );

+

+/**

+ Erase the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of the region to be erased.

+ @param[in] LbaLength The length of the region to be erased. This parameter is necessary

+ as the physical block size on a flash device could be different than

+ the logical block size of Firmware Volume Block protocol. Erase on

+ flash chip is always performed block by block. Therefore, the ERASE

+ operation to a logical block is converted a number of ERASE operation

+ (or a partial erase) on the hardware.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockErase (

+ IN UINTN PAddress,

+ IN UINTN LbaLength

+ );

+

+/**

+ Lock or unlock the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of region to be (un)locked.

+ @param[in] LbaLength The length of the region to be (un)locked. This parameter is necessary

+ as the physical block size on a flash device could be different than

+ the logical block size of Firmware Volume Block protocol. (Un)Lock on

+ flash chip is always performed block by block. Therefore, the (Un)Lock

+ operation to a logical block is converted a number of (Un)Lock operation

+ (or a partial erase) on the hardware.

+ @param[in] Lock TRUE to lock. FALSE to unlock.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockLock (

+ IN UINTN PAddress,

+ IN UINTN LbaLength,

+ IN BOOLEAN Lock

+ );

+

+PHYSICAL_ADDRESS

+EFIAPI

+LibFvbFlashDeviceMemoryMap (

+ );

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h b/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h
new file mode 100644
index 0000000000..07f40502f2
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h
@@ -0,0 +1,213 @@
+/** @file

+ PCH SPI Common Driver implements the SPI Host Controller Compatibility Interface.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SPI_FLASH_LIB_H_

+#define SPI_FLASH_LIB_H_

+

+/**

+ Flash Region Type

+**/

+typedef enum {

+ FlashRegionDescriptor,

+ FlashRegionBios,

+ FlashRegionMe,

+ FlashRegionGbE,

+ FlashRegionPlatformData,

+ FlashRegionDer,

+ FlashRegionAll,

+ FlashRegionMax

+} FLASH_REGION_TYPE;

+

+/**

+ Read SFDP data from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in SFDP data portion of the SPI cycle, the max number is 64

+ @param[out] SfdpData The Pointer to caller-allocated buffer containing the SFDP data received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadSfdp (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SfdpData

+ );

+

+/**

+ Read Jedec Id from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in JedecId data portion of the SPI cycle, the data size is 3 typically

+ @param[out] JedecId The Pointer to caller-allocated buffer containing JEDEC ID received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadJedecId (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *JedecId

+ );

+

+/**

+ Write the status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[in] StatusValue The Pointer to caller-allocated buffer containing the value of Status register writing

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWriteStatus (

+ IN UINT32 ByteCount,

+ IN UINT8 *StatusValue

+ );

+

+/**

+ Read status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[out] StatusValue The Pointer to caller-allocated buffer containing the value of Status register received.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadStatus (

+ IN UINT32 ByteCount,

+ OUT UINT8 *StatusValue

+ );

+

+/**

+ Read SC Soft Strap Values

+

+ @param[in] SoftStrapAddr SC Soft Strap address offset from FPSBA.

+ @param[in] ByteCount Number of bytes in SoftStrap data portion of the SPI cycle

+ @param[out] SoftStrapValue The Pointer to caller-allocated buffer containing SC Soft Strap Value.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiReadPchSoftStrap (

+ IN UINT32 SoftStrapAddr,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SoftStrapValue

+ );

+

+/**

+ Read data from the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[out] Buffer The Pointer to caller-allocated buffer containing the dada received.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashRead (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ OUT UINT8 *Buffer

+ );

+

+/**

+ Erase some area on the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashErase (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount

+ );

+

+/**

+ Write data to the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in] Buffer Pointer to caller-allocated buffer containing the data sent during the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWrite (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN UINT8 *Buffer

+ );

+

+/**

+ Initialize an SPI library.

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_NOT_FOUND The expected SPI info could not be found

+**/

+EFI_STATUS

+EFIAPI

+SpiConstructor (

+ VOID

+ );

+

+/**

+ Get the SPI region base and size, based on the enum type

+

+ @param[in] FlashRegionType The Flash Region type for for the base address which is listed in the Descriptor.

+ @param[out] BaseAddress The Flash Linear Address for the Region 'n' Base

+ @param[out] RegionSize The size for the Region 'n'

+

+ @retval EFI_SUCCESS Read success

+ @retval EFI_INVALID_PARAMETER Invalid region type given

+ @retval EFI_DEVICE_ERROR The region is not used

+**/

+EFI_STATUS

+EFIAPI

+SpiGetRegionAddress (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ OUT UINT32 *BaseAddress OPTIONAL,

+ OUT UINT32 *RegionSize OPTIONAL

+ );

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc b/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc
new file mode 100644
index 0000000000..3003c563c9
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc
@@ -0,0 +1,112 @@
+## @file

+# This is a build description file for the Payload Platform advanced feature.

+# This file should be included into another package DSC file to build this feature.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+################################################################################

+#

+# Defines Section - statements that will be processed to create a Makefile.

+#

+################################################################################

+

+[Defines]

+ !ifndef $(DXE_ARCH)

+ !error "DXE_ARCH must be specified to build this feature!"

+ !endif

+

+ DEFINE SMM_VARIABLE = TRUE

+

+

+################################################################################

+#

+# PCD definitions section - list of all PCD definitions needed by this Platform.

+#

+################################################################################

+

+[PcdsPatchableInModule.X64]

+!if $(SMM_VARIABLE) == TRUE

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase |0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize |0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize |0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase |0

+!endif

+

+################################################################################

+#

+# Library Class section - list of all Library Classes needed by this feature.

+#

+################################################################################

+

+[LibraryClasses]

+ !if $(SMM_VARIABLE) == TRUE

+ PciLib|MdePkg/Library/BasePciLibPciExpress/BasePciLibPciExpress.inf

+ PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf

+ # (Optional for variable modules debug output

+ PlatformHookLib|UefiPayloadPkg/Library/PlatformHookLib/PlatformHookLib.inf

+ DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf

+ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf

+ DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf

+ !endif

+

+[LibraryClasses.common.DXE_SMM_DRIVER,LibraryClasses.common.DXE_RUNTIME_DRIVER]

+ !if $(SMM_VARIABLE) == TRUE

+ SpiFlashLib|PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf

+ FlashDeviceLib|PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf

+ DxeHobListLib|UefiPayloadPkg/Library/DxeHobListLib/DxeHobListLib.inf

+ HobLib|UefiPayloadPkg/Library/DxeHobLib/DxeHobLib.inf

+ TimerLib|UefiCpuPkg/Library/CpuTimerLib/BaseCpuTimerLib.inf

+ !endif

+

+################################################################################

+#

+# Component section - list of all components that need built for this feature.

+#

+# Note: The EDK II DSC file is not used to specify how compiled binary images get placed

+# into firmware volume images. This section is just a list of modules to compile from

+# source into UEFI-compliant binaries.

+# It is the FDF file that contains information on combining binary files into firmware

+# volume images, whose concept is beyond UEFI and is described in PI specification.

+# There may also be modules listed in this section that are not required in the FDF file,

+# When a module listed here is excluded from FDF file, then UEFI-compliant binary will be

+# generated for it, but the binary will not be put into any firmware volume.

+#

+################################################################################

+#

+# Feature DXE Components

+#

+

+# @todo: Change below line to [Components.$(DXE_ARCH)] after https://bugzilla.tianocore.org/show_bug.cgi?id=2308

+# is completed.

+[Components.X64]

+ #

+ # SMM Variable Support

+ #

+ !if $(SMM_VARIABLE) == TRUE

+ PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf

+ PlatformPayloadPkg/Fvb/FvbSmm.inf {

+ <LibraryClasses>

+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf

+ }

+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf {

+ <LibraryClasses>

+ NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf

+ NULL|MdeModulePkg/Library/VarCheckHiiLib/VarCheckHiiLib.inf

+ NULL|MdeModulePkg/Library/VarCheckPcdLib/VarCheckPcdLib.inf

+ NULL|MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.inf

+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf

+ }

+

+ MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf {

+ <LibraryClasses>

+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf

+ }

+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf

+ !endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf b/Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf
new file mode 100644
index 0000000000..54800b972c
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf
@@ -0,0 +1,20 @@
+## @file

+# FDF file for post-memory ACPI Debug advanced feature modules.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+#

+# SMM Support

+#

+!if $(SMM_VARIABLE) == TRUE

+ INF PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf

+ INF PlatformPayloadPkg/Fvb/FvbSmm.inf

+ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf

+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf

+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf

+

+!endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf b/Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf
new file mode 100644
index 0000000000..003b7a3e56
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf
@@ -0,0 +1,8 @@
+## @file

+# FDF file for pre-memory payload platform advanced feature modules.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

diff --git a/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c
new file mode 100644
index 0000000000..5a27043285
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c
@@ -0,0 +1,160 @@
+/** @file

+ Flash Device Library based on SPI Flash library.

+

+Copyright (c) 2018 - 2021, Intel Corporation. All rights reserved. <BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiDxe.h>

+#include <Library/BaseMemoryLib.h>

+#include <Library/DebugLib.h>

+#include <Library/SpiFlashLib.h>

+

+/**

+ Initialize spi flash device.

+

+ @retval EFI_SUCCESS The tested spi flash device is supported.

+ @retval EFI_UNSUPPORTED The tested spi flash device is not supported.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceInit (

+ VOID

+ )

+{

+ return SpiConstructor ();

+}

+

+/**

+ Read NumBytes bytes of data from the address specified by

+ PAddress into Buffer.

+

+ @param[in] PAddress The starting physical address of the read.

+ @param[in,out] NumBytes On input, the number of bytes to read. On output, the number

+ of bytes actually read.

+ @param[out] Buffer The destination data buffer for the read.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceRead (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+ UINT32 ByteCount;

+ UINT32 RgnSize;

+ UINT32 AddrOffset;

+

+ Status = SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - RgnSize))

+ // which equal (PAddress + RgnSize) here.

+ AddrOffset = (UINT32)((UINT32)PAddress + RgnSize);

+ ByteCount = (UINT32)*NumBytes;

+ return SpiFlashRead (FlashRegionBios, AddrOffset, ByteCount, Buffer);

+}

+

+/**

+ Write NumBytes bytes of data from Buffer to the address specified by

+ PAddresss.

+

+ @param[in] PAddress The starting physical address of the write.

+ @param[in,out] NumBytes On input, the number of bytes to write. On output,

+ the actual number of bytes written.

+ @param[in] Buffer The source data buffer for the write.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceWrite (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+ UINT32 ByteCount;

+ UINT32 RgnSize;

+ UINT32 AddrOffset;

+

+ Status = SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - RgnSize))

+ // which equal (PAddress + RgnSize) here.

+ AddrOffset = (UINT32)((UINT32)PAddress + RgnSize);

+ ByteCount = (UINT32)*NumBytes;

+ return SpiFlashWrite (FlashRegionBios, AddrOffset, ByteCount, Buffer);

+}

+

+/**

+ Erase the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of the block to be erased.

+ This library assume that caller garantee that the PAddress

+ is at the starting address of this block.

+ @param[in] LbaLength The length of the logical block to be erased.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockErase (

+ IN UINTN PAddress,

+ IN UINTN LbaLength

+ )

+{

+ EFI_STATUS Status;

+ UINT32 RgnSize;

+ UINT32 AddrOffset;

+

+ Status = SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - RgnSize))

+ // which equal (PAddress + RgnSize) here.

+ AddrOffset = (UINT32)((UINT32)PAddress + RgnSize);

+ return SpiFlashErase (FlashRegionBios, AddrOffset, (UINT32)LbaLength);

+}

+

+/**

+ Lock or unlock the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of region to be (un)locked.

+ @param[in] LbaLength The length of the logical block to be erased.

+ @param[in] Lock TRUE to lock. FALSE to unlock.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockLock (

+ IN UINTN PAddress,

+ IN UINTN LbaLength,

+ IN BOOLEAN Lock

+ )

+{

+ return EFI_SUCCESS;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf
new file mode 100644
index 0000000000..7285a37944
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf
@@ -0,0 +1,38 @@
+## @file

+# Library instace of Flash Device Library Class

+#

+# This library implement the flash device library class for the lakeport platform.

+#@copyright

+# Copyright (c) 2014 - 2021 Intel Corporation. All rights reserved

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = FlashDeviceLib

+ FILE_GUID = BA7CA537-1C65-4a90-9379-622A24A08141

+ MODULE_TYPE = DXE_DRIVER

+ VERSION_STRING = 1.0

+ LIBRARY_CLASS = FlashDeviceLib | DXE_SMM_DRIVER DXE_RUNTIME_DRIVER

+

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ FlashDeviceLib.c

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ DebugLib

+ BaseMemoryLib

+ SpiFlashLib

+

diff --git a/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c
new file mode 100644
index 0000000000..4ea89582f3
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c
@@ -0,0 +1,89 @@
+/** @file

+

+ Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiDxe.h>

+#include <Library/PcdLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseLib.h>

+#include <Guid/SystemNvDataGuid.h>

+#include <Guid/NvVariableInfoGuid.h>

+#include <Library/HobLib.h>

+

+

+/**

+ Initialize the variable store

+

+ @retval EFI_SUCCESS if initialize the store success.

+

+**/

+EFI_STATUS

+PcdInitConstructor (

+ VOID

+ )

+{

+ EFI_STATUS Status;

+ UINT32 NvStorageBase;

+ UINT32 NvStorageSize;

+ UINT32 NvVariableSize;

+ UINT32 FtwWorkingSize;

+ UINT32 FtwSpareSize;

+ EFI_HOB_GUID_TYPE *GuidHob;

+ NV_VARIABLE_INFO *NvVariableInfo;

+

+ //

+ // Find SPI flash variable hob

+ //

+ GuidHob = GetFirstGuidHob (&gNvVariableInfoGuid);

+ if (GuidHob == NULL) {

+ ASSERT (FALSE);

+ return EFI_NOT_FOUND;

+ }

+

+ NvVariableInfo = (NV_VARIABLE_INFO *)GET_GUID_HOB_DATA (GuidHob);

+

+ //

+ // Get variable region base and size.

+ //

+ NvStorageSize = NvVariableInfo->VariableStoreSize;

+ NvStorageBase = NvVariableInfo->VariableStoreBase;

+

+ //

+ // NvStorageBase needs to be 4KB aligned, NvStorageSize needs to be 8KB * n

+ //

+ if (((NvStorageBase & (SIZE_4KB - 1)) != 0) || ((NvStorageSize & (SIZE_8KB - 1)) != 0)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ FtwSpareSize = NvStorageSize / 2;

+ FtwWorkingSize = 0x2000;

+ NvVariableSize = NvStorageSize / 2 - FtwWorkingSize;

+ DEBUG ((DEBUG_INFO, "NvStorageBase:0x%x, NvStorageSize:0x%x\n", NvStorageBase, NvStorageSize));

+

+ if (NvVariableSize >= 0x80000000) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Status = PcdSet32S (PcdFlashNvStorageVariableSize, NvVariableSize);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet32S (PcdFlashNvStorageVariableBase, NvStorageBase);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet64S (PcdFlashNvStorageVariableBase64, NvStorageBase);

+ ASSERT_EFI_ERROR (Status);

+

+ Status = PcdSet32S (PcdFlashNvStorageFtwWorkingSize, FtwWorkingSize);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet32S (PcdFlashNvStorageFtwWorkingBase, NvStorageBase + NvVariableSize);

+ ASSERT_EFI_ERROR (Status);

+

+ Status = PcdSet32S (PcdFlashNvStorageFtwSpareSize, FtwSpareSize);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet32S (PcdFlashNvStorageFtwSpareBase, NvStorageBase + FtwSpareSize);

+ ASSERT_EFI_ERROR (Status);

+

+ return EFI_SUCCESS;

+}

+

diff --git a/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf
new file mode 100644
index 0000000000..05411b00d8
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf
@@ -0,0 +1,50 @@
+## @file

+# Initialize patchable PCDs using HOB info

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = PcdInitLib

+ FILE_GUID = 2C4A8902-B55A-472E-9845-3B931CE68071

+ MODULE_TYPE = BASE

+ VERSION_STRING = 1.0

+ LIBRARY_CLASS = NULL

+ CONSTRUCTOR = PcdInitConstructor

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ PcdInitLib.c

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ BaseLib

+ PcdLib

+ PciLib

+ HobLib

+ BaseLib

+

+[Guids]

+ gNvVariableInfoGuid

+

+[Pcd]

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase

+

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c
new file mode 100644
index 0000000000..18f4a0ba3f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c
@@ -0,0 +1,170 @@
+/** @file

+

+ Copyright (c) 2017-2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+#include "SpiCommon.h"

+

+/**

+ Acquire SPI MMIO BAR.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Return SPI BAR Address

+

+**/

+UINT32

+AcquireSpiBar0 (

+ IN UINTN PchSpiBase

+ )

+{

+ return MmioRead32 (PchSpiBase + R_SPI_BASE) & ~(B_SPI_BAR0_MASK);

+}

+

+/**

+ Release SPI MMIO BAR. Do nothing.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+**/

+VOID

+ReleaseSpiBar0 (

+ IN UINTN PchSpiBase

+ )

+{

+}

+

+/**

+ This function is to enable/disable BIOS Write Protect in SMM phase.

+

+ @param[in] EnableSmmSts Flag to Enable/disable Bios write protect

+

+**/

+VOID

+CpuSmmDisableBiosWriteProtect (

+ IN BOOLEAN EnableSmmSts

+ )

+{

+ UINT32 Data32;

+

+ if (EnableSmmSts) {

+ //

+ // Disable BIOS Write Protect in SMM phase.

+ //

+ Data32 = MmioRead32 ((UINTN)(0xFED30880)) | (UINT32)(BIT0);

+ AsmWriteMsr32 (0x000001FE, Data32);

+ } else {

+ //

+ // Enable BIOS Write Protect in SMM phase

+ //

+ Data32 = MmioRead32 ((UINTN)(0xFED30880)) & (UINT32)(~BIT0);

+ AsmWriteMsr32 (0x000001FE, Data32);

+ }

+

+ //

+ // Read FED30880h back to ensure the setting went through.

+ //

+ Data32 = MmioRead32 (0xFED30880);

+}

+

+/**

+ This function is a hook for Spi to disable BIOS Write Protect.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_ACCESS_DENIED The BIOS Region can only be updated in SMM phase

+

+**/

+EFI_STATUS

+EFIAPI

+DisableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ )

+{

+ //

+ // Write clear BC_SYNC_SS prior to change WPD from 0 to 1.

+ //

+ MmioOr8 (PchSpiBase + R_SPI_BCR + 1, (B_SPI_BCR_SYNC_SS >> 8));

+

+ //

+ // Enable the access to the BIOS space for both read and write cycles

+ //

+ MmioOr8 (PchSpiBase + R_SPI_BCR, B_SPI_BCR_BIOSWE);

+

+ if (CpuSmmBwp != 0) {

+ CpuSmmDisableBiosWriteProtect (TRUE);

+ }

+

+ return EFI_SUCCESS;

+}

+

+/**

+ This function is a hook for Spi to enable BIOS Write Protect.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+**/

+VOID

+EFIAPI

+EnableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ )

+{

+ //

+ // Disable the access to the BIOS space for write cycles

+ //

+ MmioAnd8 (PchSpiBase + R_SPI_BCR, (UINT8)(~B_SPI_BCR_BIOSWE));

+

+ if (CpuSmmBwp != 0) {

+ CpuSmmDisableBiosWriteProtect (FALSE);

+ }

+}

+

+/**

+ This function disables SPI Prefetching and caching,

+ and returns previous BIOS Control Register value before disabling.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Previous BIOS Control Register value

+

+**/

+UINT8

+SaveAndDisableSpiPrefetchCache (

+ IN UINTN PchSpiBase

+ )

+{

+ UINT8 BiosCtlSave;

+

+ BiosCtlSave = MmioRead8 (PchSpiBase + R_SPI_BCR) & B_SPI_BCR_SRC;

+

+ MmioAndThenOr32 (

+ PchSpiBase + R_SPI_BCR, \

+ (UINT32)(~B_SPI_BCR_SRC), \

+ (UINT32)(V_SPI_BCR_SRC_PREF_DIS_CACHE_DIS << B_SPI_BCR_SRC)

+ );

+

+ return BiosCtlSave;

+}

+

+/**

+ This function updates BIOS Control Register with the given value.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] BiosCtlValue BIOS Control Register Value to be updated

+

+**/

+VOID

+SetSpiBiosControlRegister (

+ IN UINTN PchSpiBase,

+ IN UINT8 BiosCtlValue

+ )

+{

+ MmioAndThenOr8 (PchSpiBase + R_SPI_BCR, (UINT8) ~B_SPI_BCR_SRC, BiosCtlValue);

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h
new file mode 100644
index 0000000000..b741904143
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h
@@ -0,0 +1,120 @@
+/** @file

+ Register names for SPI device.

+

+ Copyright (c) 2017 - 2019, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef REGS_SPI_H_

+#define REGS_SPI_H_

+

+#define R_SPI_BASE 0x10 ///< 32-bit Memory Base Address Register

+#define B_SPI_BAR0_MASK 0x0FFF

+#define R_SPI_BCR 0xDC ///< BIOS Control Register

+#define B_SPI_BCR_SRC (BIT3 | BIT2) ///< SPI Read Configuration (SRC)

+#define V_SPI_BCR_SRC_PREF_DIS_CACHE_DIS 0x04 ///< Prefetch Disable, Cache Disable

+#define B_SPI_BCR_SYNC_SS BIT8

+#define B_SPI_BCR_BIOSWE BIT0 ///< Write Protect Disable (WPD)

+

+///

+/// SPI Host Interface Registers

+#define R_SPI_HSFS 0x04 ///< Hardware Sequencing Flash Status and Control Register(32bits)

+#define B_SPI_HSFS_FDBC_MASK 0x3F000000 ///< Flash Data Byte Count ( <= 64), Count = (Value in this field) + 1.

+#define N_SPI_HSFS_FDBC 24

+#define B_SPI_HSFS_CYCLE_MASK 0x001E0000 ///< Flash Cycle.

+#define N_SPI_HSFS_CYCLE 17

+#define V_SPI_HSFS_CYCLE_READ 0 ///< Flash Cycle Read

+#define V_SPI_HSFS_CYCLE_WRITE 2 ///< Flash Cycle Write

+#define V_SPI_HSFS_CYCLE_4K_ERASE 3 ///< Flash Cycle 4K Block Erase

+#define V_SPI_HSFS_CYCLE_64K_ERASE 4 ///< Flash Cycle 64K Sector Erase

+#define V_SPI_HSFS_CYCLE_READ_SFDP 5 ///< Flash Cycle Read SFDP

+#define V_SPI_HSFS_CYCLE_READ_JEDEC_ID 6 ///< Flash Cycle Read JEDEC ID

+#define V_SPI_HSFS_CYCLE_WRITE_STATUS 7 ///< Flash Cycle Write Status

+#define V_SPI_HSFS_CYCLE_READ_STATUS 8 ///< Flash Cycle Read Status

+#define B_SPI_HSFS_CYCLE_FGO BIT16 ///< Flash Cycle Go.

+#define B_SPI_HSFS_FDV BIT14 ///< Flash Descriptor Valid

+#define B_SPI_HSFS_SCIP BIT5 ///< SPI Cycle in Progress

+#define B_SPI_HSFS_FCERR BIT1 ///< Flash Cycle Error

+#define B_SPI_HSFS_FDONE BIT0 ///< Flash Cycle Done

+

+#define R_SPI_FADDR 0x08 ///< SPI Flash Address

+#define B_SPI_FADDR_MASK 0x07FFFFFF ///< SPI Flash Address Mask (0~26bit)

+

+#define R_SPI_FDATA00 0x10 ///< SPI Data 00 (32 bits)

+

+#define R_SPI_FRAP 0x50 ///< SPI Flash Regions Access Permissions Register

+#define B_SPI_FRAP_BRWA_PLATFORM BIT12 // < Region write access for Region4 PlatformData

+#define B_SPI_FRAP_BRWA_GBE BIT11 // < Region write access for Region3 GbE

+#define B_SPI_FRAP_BRWA_SEC BIT10 ///< Region Write Access for Region2 SEC

+#define B_SPI_FRAP_BRWA_BIOS BIT9 ///< Region Write Access for Region1 BIOS

+#define B_SPI_FRAP_BRWA_FLASHD BIT8 ///< Region Write Access for Region0 Flash Descriptor

+#define B_SPI_FRAP_BRRA_PLATFORM BIT4 ///< Region read access for Region4 PlatformData

+#define B_SPI_FRAP_BRRA_GBE BIT3 ///< Region read access for Region3 GbE

+#define B_SPI_FRAP_BRRA_SEC BIT2 ///< Region Read Access for Region2 SEC

+#define B_SPI_FRAP_BRRA_BIOS BIT1 ///< Region Read Access for Region1 BIOS

+#define B_SPI_FRAP_BRRA_FLASHD BIT0 ///< Region Read Access for Region0 Flash Descriptor

+

+#define R_SPI_FREG0_FLASHD 0x54 ///< Flash Region 0 (Flash Descriptor) (32bits)

+#define B_SPI_FREG0_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG0_LIMIT 4 ///< Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG0_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG0_BASE 12 ///< Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG1_BIOS 0x58 ///< Flash Region 1 (BIOS) (32bits)

+#define B_SPI_FREG1_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG1_LIMIT 4 ///< Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG1_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG1_BASE 12 ///< Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG2_SEC 0x5C ///< Flash Region 2 (SEC) (32bits)

+#define B_SPI_FREG2_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG2_LIMIT 4 // < Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG2_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG2_BASE 12 // < Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG3_GBE 0x60 // < Flash Region 3(GbE)(32bits)

+#define B_SPI_FREG3_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG3_LIMIT 4 // < Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG3_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG3_BASE 12 // < Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG4_PLATFORM_DATA 0x64 ///< Flash Region 4 (Platform Data) (32bits)

+#define B_SPI_FREG4_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG4_LIMIT 4 ///< Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG4_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG4_BASE 12 ///< Bit 14:0 identifies address bits [26:2]

+

+#define S_SPI_FREGX 4 ///< Size of Flash Region register

+#define B_SPI_FREGX_LIMIT_MASK 0x7FFF0000 ///< Flash Region Limit [30:16] represents [26:12], [11:0] are assumed to be FFFh

+#define N_SPI_FREGX_LIMIT 16 ///< Region limit bit position

+#define N_SPI_FREGX_LIMIT_REPR 12 ///< Region limit bit represents position

+#define B_SPI_FREGX_BASE_MASK 0x00007FFF ///< Flash Region Base, [14:0] represents [26:12]

+

+#define R_SPI_FDOC 0xB4 ///< Flash Descriptor Observability Control Register (32 bits)

+#define B_SPI_FDOC_FDSS_MASK (BIT14 | BIT13 | BIT12) ///< Flash Descriptor Section Select

+#define V_SPI_FDOC_FDSS_FSDM 0x0000 ///< Flash Signature and Descriptor Map

+#define V_SPI_FDOC_FDSS_COMP 0x1000 ///< Component

+#define B_SPI_FDOC_FDSI_MASK 0x0FFC ///< Flash Descriptor Section Index

+

+#define R_SPI_FDOD 0xB8 ///< Flash Descriptor Observability Data Register (32 bits)

+

+#define R_SPI_LVSCC 0xC4 ///< Vendor Specific Component Capabilities for Component 0 (32 bits)

+#define B_SPI_LVSCC_EO_64K BIT29 ///< < 64k Erase valid (EO_64k_valid)

+

+#define R_SPI_UVSCC 0xC8 ///< Vendor Specific Component Capabilities for Component 1 (32 bits)

+

+#define R_SPI_FDBAR_FLASH_MAP0 0x14 ///< Flash MAP 0

+#define N_SPI_FDBAR_NC 8 ///< < Number Of Components

+#define B_SPI_FDBAR_NC 0x00000300 ///< Number Of Components

+

+#define R_SPI_FDBAR_FLASH_MAP1 0x18 ///< Flash MAP 1

+#define B_SPI_FDBAR_FPSBA 0x00FF0000 ///< Flash Strap Base Address

+

+//

+// Flash Component Base Address (FCBA) from Flash Region 0

+//

+#define R_SPI_FCBA_FLCOMP 0x00 ///< Flash Components Register

+#define B_SPI_FLCOMP_COMP1_MASK 0x0F ///< Flash Component 1 Density

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h
new file mode 100644
index 0000000000..95e9b9b1e7
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h
@@ -0,0 +1,203 @@
+/** @file

+ Header file for the SPI flash module.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SPI_COMMON_LIB_H_

+#define SPI_COMMON_LIB_H_

+

+#include <PiDxe.h>

+#include <Uefi/UefiBaseType.h>

+#include <IndustryStandard/Pci30.h>

+#include <Library/IoLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseMemoryLib.h>

+#include <Library/SpiFlashLib.h>

+#include <Library/MemoryAllocationLib.h>

+#include <Library/BaseLib.h>

+#include <Library/HobLib.h>

+#include <Library/TimerLib.h>

+#include <Guid/SpiFlashInfoGuid.h>

+#include "RegsSpi.h"

+

+///

+/// Maximum time allowed while waiting the SPI cycle to complete

+/// Wait Time = 6 seconds = 6000000 microseconds

+/// Wait Period = 10 microseconds

+///

+#define WAIT_TIME 6000000 ///< Wait Time = 6 seconds = 6000000 microseconds

+#define WAIT_PERIOD 10 ///< Wait Period = 10 microseconds

+

+///

+/// Flash cycle Type

+///

+typedef enum {

+ FlashCycleRead,

+ FlashCycleWrite,

+ FlashCycleErase,

+ FlashCycleReadSfdp,

+ FlashCycleReadJedecId,

+ FlashCycleWriteStatus,

+ FlashCycleReadStatus,

+ FlashCycleMax

+} FLASH_CYCLE_TYPE;

+

+///

+/// Flash Component Number

+///

+typedef enum {

+ FlashComponent0,

+ FlashComponent1,

+ FlashComponentMax

+} FLASH_COMPONENT_NUM;

+

+///

+/// Private data structure definitions for the driver

+///

+#define SC_SPI_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('P', 'S', 'P', 'I')

+

+typedef struct {

+ UINTN Signature;

+ EFI_HANDLE Handle;

+ UINT32 AcpiTmrReg;

+ UINTN PchSpiBase;

+ UINT16 RegionPermission;

+ UINT32 SfdpVscc0Value;

+ UINT32 SfdpVscc1Value;

+ UINT32 StrapBaseAddress;

+ UINT8 NumberOfComponents;

+ UINT16 Flags;

+ UINT32 Component1StartAddr;

+} SPI_INSTANCE;

+

+/**

+ Acquire SPI MMIO BAR

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Return SPI BAR Address

+

+**/

+UINT32

+AcquireSpiBar0 (

+ IN UINTN PchSpiBase

+ );

+

+/**

+ Release SPI MMIO BAR. Do nothing.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval None

+

+**/

+VOID

+ReleaseSpiBar0 (

+ IN UINTN PchSpiBase

+ );

+

+/**

+ This function is a hook for Spi to disable BIOS Write Protect

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_ACCESS_DENIED The BIOS Region can only be updated in SMM phase

+

+**/

+EFI_STATUS

+EFIAPI

+DisableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ );

+

+/**

+ This function is a hook for Spi to enable BIOS Write Protect

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+ @retval None

+

+**/

+VOID

+EFIAPI

+EnableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ );

+

+/**

+ This function disables SPI Prefetching and caching,

+ and returns previous BIOS Control Register value before disabling.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Previous BIOS Control Register value

+

+**/

+UINT8

+SaveAndDisableSpiPrefetchCache (

+ IN UINTN PchSpiBase

+ );

+

+/**

+ This function updates BIOS Control Register with the given value.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] BiosCtlValue BIOS Control Register Value to be updated

+

+ @retval None

+

+**/

+VOID

+SetSpiBiosControlRegister (

+ IN UINTN PchSpiBase,

+ IN UINT8 BiosCtlValue

+ );

+

+/**

+ This function sends the programmed SPI command to the slave device.

+

+ @param[in] SpiRegionType The SPI Region type for flash cycle which is listed in the Descriptor

+ @param[in] FlashCycleType The Flash SPI cycle type list in HSFC (Hardware Sequencing Flash Control Register) register

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in,out] Buffer Pointer to caller-allocated buffer containing the data received or sent during the SPI cycle.

+

+ @retval EFI_SUCCESS SPI command completes successfully.

+ @retval EFI_DEVICE_ERROR Device error, the command aborts abnormally.

+ @retval EFI_ACCESS_DENIED Some unrecognized command encountered in hardware sequencing mode

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+**/

+EFI_STATUS

+SendSpiCmd (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN FLASH_CYCLE_TYPE FlashCycleType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN OUT UINT8 *Buffer

+ );

+

+/**

+ Wait execution cycle to complete on the SPI interface.

+

+ @param[in] PchSpiBar0 Spi MMIO base address

+ @param[in] ErrorCheck TRUE if the SpiCycle needs to do the error check

+

+ @retval TRUE SPI cycle completed on the interface.

+ @retval FALSE Time out while waiting the SPI cycle to complete.

+ It's not safe to program the next command on the SPI interface.

+**/

+BOOLEAN

+WaitForSpiCycleComplete (

+ IN UINT32 PchSpiBar0,

+ IN BOOLEAN ErrorCheck

+ );

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c
new file mode 100644
index 0000000000..22639a748c
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c
@@ -0,0 +1,874 @@
+/** @file

+ Generic driver using Hardware Sequencing registers.

+

+ Copyright (c) 2017-2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+#include "SpiCommon.h"

+

+SPI_INSTANCE *mSpiInstance = NULL;

+

+/**

+ Get SPI Instance from library global data..

+

+ @retval SpiInstance Return SPI instance

+**/

+SPI_INSTANCE *

+GetSpiInstance (

+ VOID

+ )

+{

+ if (mSpiInstance == NULL) {

+ mSpiInstance = AllocatePool (sizeof (SPI_INSTANCE));

+ if (mSpiInstance == NULL) {

+ return NULL;

+ }

+

+ ZeroMem (mSpiInstance, sizeof (SPI_INSTANCE));

+ }

+

+ return mSpiInstance;

+}

+

+/**

+ Initialize an SPI library.

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_NOT_FOUND The expected SPI info could not be found

+**/

+EFI_STATUS

+EFIAPI

+SpiConstructor (

+ VOID

+ )

+{

+ UINT32 ScSpiBar0;

+ UINT8 Comp0Density;

+ SPI_INSTANCE *SpiInstance;

+ EFI_HOB_GUID_TYPE *GuidHob;

+ SPI_FLASH_INFO *SpiFlashInfo;

+

+ //

+ // Find SPI flash hob

+ //

+ GuidHob = GetFirstGuidHob (&gSpiFlashInfoGuid);

+ if (GuidHob == NULL) {

+ ASSERT (FALSE);

+ return EFI_NOT_FOUND;

+ }

+

+ SpiFlashInfo = (SPI_FLASH_INFO *)GET_GUID_HOB_DATA (GuidHob);

+

+ //

+ // Initialize the SPI instance

+ //

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_NOT_FOUND;

+ }

+

+ DEBUG ((DEBUG_INFO, "SpiInstance = %08X\n", SpiInstance));

+

+ SpiInstance->Signature = SC_SPI_PRIVATE_DATA_SIGNATURE;

+ SpiInstance->Handle = NULL;

+

+ //

+ // Check the SPI address

+ //

+ if ((SpiFlashInfo->SpiAddress.AddressSpaceId != EFI_ACPI_3_0_PCI_CONFIGURATION_SPACE) ||

+ (SpiFlashInfo->SpiAddress.RegisterBitWidth != 32) ||

+ (SpiFlashInfo->SpiAddress.RegisterBitOffset != 0) ||

+ (SpiFlashInfo->SpiAddress.AccessSize != EFI_ACPI_3_0_DWORD))

+ {

+ DEBUG ((DEBUG_ERROR, "SPI FLASH HOB is not expected. need check the hob or enhance SPI flash driver.\n"));

+ }

+

+ SpiInstance->PchSpiBase = (UINT32)(UINTN)SpiFlashInfo->SpiAddress.Address;

+ SpiInstance->Flags = SpiFlashInfo->Flags;

+ DEBUG ((DEBUG_INFO, "PchSpiBase at 0x%x\n", SpiInstance->PchSpiBase));

+

+ ScSpiBar0 = AcquireSpiBar0 (SpiInstance->PchSpiBase);

+ DEBUG ((DEBUG_INFO, "ScSpiBar0 at 0x%08X\n", ScSpiBar0));

+

+ if (ScSpiBar0 == 0) {

+ ASSERT (FALSE);

+ }

+

+ if ((MmioRead32 (ScSpiBar0 + R_SPI_HSFS) & B_SPI_HSFS_FDV) == 0) {

+ DEBUG ((DEBUG_ERROR, "SPI Flash descriptor invalid, cannot use Hardware Sequencing registers!\n"));

+ ASSERT (FALSE);

+ }

+

+ MmioOr32 (SpiInstance->PchSpiBase + PCI_COMMAND_OFFSET, EFI_PCI_COMMAND_MEMORY_SPACE);

+ SpiInstance->RegionPermission = MmioRead16 (ScSpiBar0 + R_SPI_FRAP);

+ SpiInstance->SfdpVscc0Value = MmioRead32 (ScSpiBar0 + R_SPI_LVSCC);

+ SpiInstance->SfdpVscc1Value = MmioRead32 (ScSpiBar0 + R_SPI_UVSCC);

+

+ //

+ // Select to Flash Map 0 Register to get the number of flash Component

+ //

+ MmioAndThenOr32 (

+ ScSpiBar0 + R_SPI_FDOC,

+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),

+ (UINT32)(V_SPI_FDOC_FDSS_FSDM | R_SPI_FDBAR_FLASH_MAP0)

+ );

+

+ //

+ // Copy Zero based Number Of Components

+ //

+ SpiInstance->NumberOfComponents = (UINT8)((MmioRead16 (ScSpiBar0 + R_SPI_FDOD) & B_SPI_FDBAR_NC) >> N_SPI_FDBAR_NC);

+

+ MmioAndThenOr32 (

+ ScSpiBar0 + R_SPI_FDOC,

+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),

+ (UINT32)(V_SPI_FDOC_FDSS_COMP | R_SPI_FCBA_FLCOMP)

+ );

+

+ //

+ // Copy Component 0 Density

+ //

+ Comp0Density = (UINT8)MmioRead32 (ScSpiBar0 + R_SPI_FDOD) & B_SPI_FLCOMP_COMP1_MASK;

+ SpiInstance->Component1StartAddr = (UINT32)(SIZE_512KB << Comp0Density);

+

+ //

+ // Select FLASH_MAP1 to get Flash SC Strap Base Address

+ //

+ MmioAndThenOr32 (

+ (ScSpiBar0 + R_SPI_FDOC),

+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),

+ (UINT32)(V_SPI_FDOC_FDSS_FSDM | R_SPI_FDBAR_FLASH_MAP1)

+ );

+

+ SpiInstance->StrapBaseAddress = MmioRead32 (ScSpiBar0 + R_SPI_FDOD) & B_SPI_FDBAR_FPSBA;

+

+ //

+ // Align FPSBA with address bits for the SC Strap portion of flash descriptor

+ //

+ SpiInstance->StrapBaseAddress &= B_SPI_FDBAR_FPSBA;

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Read data from the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[out] Buffer The Pointer to caller-allocated buffer containing the data received.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashRead (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ OUT UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (FlashRegionType, FlashCycleRead, Address, ByteCount, Buffer);

+ return Status;

+}

+

+/**

+ Write data to the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in] Buffer Pointer to caller-allocated buffer containing the data sent during the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWrite (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (FlashRegionType, FlashCycleWrite, Address, ByteCount, Buffer);

+ return Status;

+}

+

+/**

+ Erase some area on the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashErase (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (FlashRegionType, FlashCycleErase, Address, ByteCount, NULL);

+ return Status;

+}

+

+/**

+ Read SFDP data from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in SFDP data portion of the SPI cycle, the max number is 64

+ @param[out] SfdpData The Pointer to caller-allocated buffer containing the SFDP data received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadSfdp (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SfdpData

+ )

+{

+ EFI_STATUS Status;

+ UINT32 Address;

+ SPI_INSTANCE *SpiInstance;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ if ((ByteCount > 64) || (ComponentNumber > SpiInstance->NumberOfComponents)) {

+ ASSERT (FALSE);

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Address = 0;

+ if (ComponentNumber == FlashComponent1) {

+ Address = SpiInstance->Component1StartAddr;

+ }

+

+ Status = SendSpiCmd (0, FlashCycleReadSfdp, Address, ByteCount, SfdpData);

+ return Status;

+}

+

+/**

+ Read Jedec Id from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in JedecId data portion of the SPI cycle, the data size is 3 typically

+ @param[out] JedecId The Pointer to caller-allocated buffer containing JEDEC ID received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadJedecId (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *JedecId

+ )

+{

+ EFI_STATUS Status;

+ UINT32 Address;

+ SPI_INSTANCE *SpiInstance;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ if (ComponentNumber > SpiInstance->NumberOfComponents) {

+ ASSERT (FALSE);

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Address = 0;

+ if (ComponentNumber == FlashComponent1) {

+ Address = SpiInstance->Component1StartAddr;

+ }

+

+ Status = SendSpiCmd (0, FlashCycleReadJedecId, Address, ByteCount, JedecId);

+ return Status;

+}

+

+/**

+ Write the status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[in] StatusValue The Pointer to caller-allocated buffer containing the value of Status register writing

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWriteStatus (

+ IN UINT32 ByteCount,

+ IN UINT8 *StatusValue

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (0, FlashCycleWriteStatus, 0, ByteCount, StatusValue);

+ return Status;

+}

+

+/**

+ Read status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[out] StatusValue The Pointer to caller-allocated buffer containing the value of Status register received.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadStatus (

+ IN UINT32 ByteCount,

+ OUT UINT8 *StatusValue

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (0, FlashCycleReadStatus, 0, ByteCount, StatusValue);

+ return Status;

+}

+

+/**

+ Read SC Soft Strap Values

+

+ @param[in] SoftStrapAddr SC Soft Strap address offset from FPSBA.

+ @param[in] ByteCount Number of bytes in SoftStrap data portion of the SPI cycle

+ @param[out] SoftStrapValue The Pointer to caller-allocated buffer containing SC Soft Strap Value.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiReadPchSoftStrap (

+ IN UINT32 SoftStrapAddr,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SoftStrapValue

+ )

+{

+ UINT32 StrapFlashAddr;

+ EFI_STATUS Status;

+ SPI_INSTANCE *SpiInstance;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ ASSERT (SpiInstance->StrapBaseAddress != 0);

+ //

+ // SC Strap Flash Address = FPSBA + RamAddr

+ //

+ StrapFlashAddr = SpiInstance->StrapBaseAddress + SoftStrapAddr;

+

+ Status = SendSpiCmd (FlashRegionDescriptor, FlashCycleRead, StrapFlashAddr, ByteCount, SoftStrapValue);

+ return Status;

+}

+

+/**

+ This function sends the programmed SPI command to the slave device.

+

+ @param[in] FlashRegionType The SPI Region type for flash cycle which is listed in the Descriptor

+ @param[in] FlashCycleType The Flash SPI cycle type list in HSFC (Hardware Sequencing Flash Control Register) register

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in,out] Buffer Pointer to caller-allocated buffer containing the data received or sent during the SPI cycle.

+

+ @retval EFI_SUCCESS SPI command completes successfully.

+ @retval EFI_DEVICE_ERROR Device error, the command aborts abnormally.

+ @retval EFI_ACCESS_DENIED Some unrecognized command encountered in hardware sequencing mode

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+**/

+EFI_STATUS

+SendSpiCmd (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN FLASH_CYCLE_TYPE FlashCycleType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN OUT UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+ UINT32 Index;

+ UINTN SpiBaseAddress;

+ UINT32 ScSpiBar0;

+ UINT32 LimitAddress;

+ UINT32 HardwareSpiAddr;

+ UINT16 PermissionBit;

+ UINT32 SpiDataCount;

+ UINT32 FlashCycle;

+ UINT8 BiosCtlSave;

+ SPI_INSTANCE *SpiInstance;

+ UINT32 Data32;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ Status = EFI_SUCCESS;

+ SpiBaseAddress = SpiInstance->PchSpiBase;

+ ScSpiBar0 = AcquireSpiBar0 (SpiBaseAddress);

+ BiosCtlSave = 0;

+ SpiInstance->RegionPermission = MmioRead16 (ScSpiBar0 + R_SPI_FRAP);

+

+ //

+ // If it's write cycle, disable Prefetching, Caching and disable BIOS Write Protect

+ //

+ if ((FlashCycleType == FlashCycleWrite) || (FlashCycleType == FlashCycleErase)) {

+ Status = DisableBiosWriteProtect (SpiBaseAddress, mSpiInstance->Flags & FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT);

+ if (EFI_ERROR (Status)) {

+ goto SendSpiCmdEnd;

+ }

+

+ BiosCtlSave = SaveAndDisableSpiPrefetchCache (SpiBaseAddress);

+ }

+

+ //

+ // Make sure it's safe to program the command.

+ //

+ if (!WaitForSpiCycleComplete (ScSpiBar0, FALSE)) {

+ Status = EFI_DEVICE_ERROR;

+ goto SendSpiCmdEnd;

+ }

+

+ HardwareSpiAddr = Address;

+ if ((FlashCycleType == FlashCycleRead) ||

+ (FlashCycleType == FlashCycleWrite) ||

+ (FlashCycleType == FlashCycleErase))

+ {

+ switch (FlashRegionType) {

+ case FlashRegionDescriptor:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_FLASHD;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_FLASHD;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG0_FLASHD);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG0_BASE_MASK) << N_SPI_FREG0_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG0_LIMIT_MASK) >> N_SPI_FREG0_LIMIT;

+ break;

+

+ case FlashRegionBios:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_BIOS;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_BIOS;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG1_BIOS);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG1_BASE_MASK) << N_SPI_FREG1_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG1_LIMIT_MASK) >> N_SPI_FREG1_LIMIT;

+ break;

+

+ case FlashRegionMe:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_SEC;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_SEC;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG2_SEC);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG2_BASE_MASK) << N_SPI_FREG2_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG2_LIMIT_MASK) >> N_SPI_FREG2_LIMIT;

+ break;

+

+ case FlashRegionGbE:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_GBE;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_GBE;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG3_GBE);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG3_BASE_MASK) << N_SPI_FREG3_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG3_LIMIT_MASK) >> N_SPI_FREG3_LIMIT;

+ break;

+

+ case FlashRegionPlatformData:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_PLATFORM;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_PLATFORM;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG4_PLATFORM_DATA);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG4_BASE_MASK) << N_SPI_FREG4_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG4_LIMIT_MASK) >> N_SPI_FREG4_LIMIT;

+ break;

+

+ case FlashRegionAll:

+ //

+ // FlashRegionAll indicates address is relative to flash device

+ // No error checking for this case

+ //

+ LimitAddress = 0;

+ PermissionBit = 0;

+ break;

+

+ default:

+ Status = EFI_UNSUPPORTED;

+ goto SendSpiCmdEnd;

+ }

+

+ if ((LimitAddress != 0) && (Address > LimitAddress)) {

+ Status = EFI_INVALID_PARAMETER;

+ goto SendSpiCmdEnd;

+ }

+

+ //

+ // If the operation is read, but the region attribute is not read allowed, return error.

+ // If the operation is write, but the region attribute is not write allowed, return error.

+ //

+ if ((PermissionBit != 0) && ((SpiInstance->RegionPermission & PermissionBit) == 0)) {

+ Status = EFI_ACCESS_DENIED;

+ goto SendSpiCmdEnd;

+ }

+ }

+

+ //

+ // Check for SC SPI hardware sequencing required commands

+ //

+ FlashCycle = 0;

+ switch (FlashCycleType) {

+ case FlashCycleRead:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleWrite:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_WRITE << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleErase:

+ if (((ByteCount % SIZE_4KB) != 0) || ((HardwareSpiAddr % SIZE_4KB) != 0)) {

+ DEBUG ((DEBUG_ERROR, "Erase and erase size must be 4KB aligned. \n"));

+ ASSERT (FALSE);

+ Status = EFI_INVALID_PARAMETER;

+ goto SendSpiCmdEnd;

+ }

+

+ break;

+

+ case FlashCycleReadSfdp:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ_SFDP << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleReadJedecId:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ_JEDEC_ID << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleWriteStatus:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_WRITE_STATUS << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleReadStatus:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ_STATUS << N_SPI_HSFS_CYCLE);

+ break;

+

+ default:

+ //

+ // Unrecognized Operation

+ //

+ ASSERT (FALSE);

+ Status = EFI_INVALID_PARAMETER;

+ goto SendSpiCmdEnd;

+ break;

+ }

+

+ do {

+ SpiDataCount = ByteCount;

+ if ((FlashCycleType == FlashCycleRead) || (FlashCycleType == FlashCycleWrite)) {

+ //

+ // Trim at 256 byte boundary per operation,

+ // - SC SPI controller requires trimming at 4KB boundary

+ // - Some SPI chips require trimming at 256 byte boundary for write operation

+ // - Trimming has limited performance impact as we can read / write at most 64 byte

+ // per operation

+ //

+ if (HardwareSpiAddr + ByteCount > ((HardwareSpiAddr + BIT8) &~(BIT8 - 1))) {

+ SpiDataCount = (((UINT32)(HardwareSpiAddr) + BIT8) &~(BIT8 - 1)) - (UINT32)(HardwareSpiAddr);

+ }

+

+ //

+ // Calculate the number of bytes to shift in/out during the SPI data cycle.

+ // Valid settings for the number of bytes during each data portion of the

+ // SC SPI cycles are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 24, 32, 40, 48, 56, 64

+ //

+ if (SpiDataCount >= 64) {

+ SpiDataCount = 64;

+ } else if ((SpiDataCount &~0x07) != 0) {

+ SpiDataCount = SpiDataCount &~0x07;

+ }

+ }

+

+ if (FlashCycleType == FlashCycleErase) {

+ if (((ByteCount / SIZE_64KB) != 0) &&

+ ((ByteCount % SIZE_64KB) == 0) &&

+ ((HardwareSpiAddr % SIZE_64KB) == 0))

+ {

+ if (HardwareSpiAddr < SpiInstance->Component1StartAddr) {

+ //

+ // Check whether Component0 support 64k Erase

+ //

+ if ((SpiInstance->SfdpVscc0Value & B_SPI_LVSCC_EO_64K) != 0) {

+ SpiDataCount = SIZE_64KB;

+ } else {

+ SpiDataCount = SIZE_4KB;

+ }

+ } else {

+ //

+ // Check whether Component1 support 64k Erase

+ //

+ if ((SpiInstance->SfdpVscc1Value & B_SPI_LVSCC_EO_64K) != 0) {

+ SpiDataCount = SIZE_64KB;

+ } else {

+ SpiDataCount = SIZE_4KB;

+ }

+ }

+ } else {

+ SpiDataCount = SIZE_4KB;

+ }

+

+ if (SpiDataCount == SIZE_4KB) {

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_4K_ERASE << N_SPI_HSFS_CYCLE);

+ } else {

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_64K_ERASE << N_SPI_HSFS_CYCLE);

+ }

+ }

+

+ //

+ // If it's write cycle, load data into the SPI data buffer.

+ //

+ if ((FlashCycleType == FlashCycleWrite) || (FlashCycleType == FlashCycleWriteStatus)) {

+ if ((SpiDataCount & 0x07) != 0) {

+ //

+ // Use Byte write if Data Count is 0, 1, 2, 3, 4, 5, 6, 7

+ //

+ for (Index = 0; Index < SpiDataCount; Index++) {

+ MmioWrite8 (ScSpiBar0 + R_SPI_FDATA00 + Index, Buffer[Index]);

+ }

+ } else {

+ //

+ // Use Dword write if Data Count is 8, 16, 24, 32, 40, 48, 56, 64

+ //

+ for (Index = 0; Index < SpiDataCount; Index += sizeof (UINT32)) {

+ MmioWrite32 (ScSpiBar0 + R_SPI_FDATA00 + Index, *(UINT32 *)(Buffer + Index));

+ }

+ }

+ }

+

+ //

+ // Set the Flash Address

+ //

+ MmioWrite32 (ScSpiBar0 + R_SPI_FADDR, (UINT32)(HardwareSpiAddr & B_SPI_FADDR_MASK));

+

+ //

+ // Set Data count, Flash cycle, and Set Go bit to start a cycle

+ //

+ MmioAndThenOr32 (

+ ScSpiBar0 + R_SPI_HSFS,

+ (UINT32)(~(B_SPI_HSFS_FDBC_MASK | B_SPI_HSFS_CYCLE_MASK)),

+ (UINT32)(((SpiDataCount - 1) << N_SPI_HSFS_FDBC) | FlashCycle | B_SPI_HSFS_CYCLE_FGO)

+ );

+

+ //

+ // Wait for command execution complete.

+ //

+ if (!WaitForSpiCycleComplete (ScSpiBar0, TRUE)) {

+ Status = EFI_DEVICE_ERROR;

+ goto SendSpiCmdEnd;

+ }

+

+ //

+ // If it's read cycle, load data into the caller's buffer.

+ //

+ if ((FlashCycleType == FlashCycleRead) ||

+ (FlashCycleType == FlashCycleReadSfdp) ||

+ (FlashCycleType == FlashCycleReadJedecId) ||

+ (FlashCycleType == FlashCycleReadStatus))

+ {

+ if ((SpiDataCount & 0x07) != 0) {

+ //

+ // Use Byte read if Data Count is 0, 1, 2, 3, 4, 5, 6, 7

+ //

+ for (Index = 0; Index < SpiDataCount; Index++) {

+ Buffer[Index] = MmioRead8 (ScSpiBar0 + R_SPI_FDATA00 + Index);

+ }

+ } else {

+ //

+ // Use Dword read if Data Count is 8, 16, 24, 32, 40, 48, 56, 64

+ //

+ for (Index = 0; Index < SpiDataCount; Index += sizeof (UINT32)) {

+ *(UINT32 *)(Buffer + Index) = MmioRead32 (ScSpiBar0 + R_SPI_FDATA00 + Index);

+ }

+ }

+ }

+

+ HardwareSpiAddr += SpiDataCount;

+ Buffer += SpiDataCount;

+ ByteCount -= SpiDataCount;

+ } while (ByteCount > 0);

+

+SendSpiCmdEnd:

+ ///

+ /// Restore the settings for SPI Prefetching and Caching and enable BIOS Write Protect

+ ///

+ if ((FlashCycleType == FlashCycleWrite) || (FlashCycleType == FlashCycleErase)) {

+ EnableBiosWriteProtect (SpiBaseAddress, mSpiInstance->Flags & FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT);

+ SetSpiBiosControlRegister (SpiBaseAddress, BiosCtlSave);

+ }

+

+ ReleaseSpiBar0 (SpiBaseAddress);

+

+ return Status;

+}

+

+/**

+ Wait execution cycle to complete on the SPI interface.

+

+ @param[in] ScSpiBar0 Spi MMIO base address

+ @param[in] ErrorCheck TRUE if the SpiCycle needs to do the error check

+

+ @retval TRUE SPI cycle completed on the interface.

+ @retval FALSE Time out while waiting the SPI cycle to complete.

+ It's not safe to program the next command on the SPI interface.

+**/

+BOOLEAN

+WaitForSpiCycleComplete (

+ IN UINT32 ScSpiBar0,

+ IN BOOLEAN ErrorCheck

+ )

+{

+ UINT64 WaitTicks;

+ UINT64 WaitCount;

+ UINT32 Data32;

+

+ //

+ // Convert the wait period allowed into to tick count

+ //

+ WaitCount = WAIT_TIME / WAIT_PERIOD;

+ //

+ // Wait for the SPI cycle to complete.

+ //

+ for (WaitTicks = 0; WaitTicks < WaitCount; WaitTicks++) {

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_HSFS);

+ if ((Data32 & B_SPI_HSFS_SCIP) == 0) {

+ MmioWrite32 (ScSpiBar0 + R_SPI_HSFS, B_SPI_HSFS_FCERR | B_SPI_HSFS_FDONE);

+ if (((Data32 & B_SPI_HSFS_FCERR) != 0) && ErrorCheck) {

+ return FALSE;

+ } else {

+ return TRUE;

+ }

+ }

+

+ MicroSecondDelay (WAIT_PERIOD);

+ }

+

+ return FALSE;

+}

+

+/**

+ Get the SPI region base and size, based on the enum type

+

+ @param[in] FlashRegionType The Flash Region type for for the base address which is listed in the Descriptor.

+ @param[out] BaseAddress The Flash Linear Address for the Region 'n' Base

+ @param[out] RegionSize The size for the Region 'n'

+

+ @retval EFI_SUCCESS Read success

+ @retval EFI_INVALID_PARAMETER Invalid region type given

+ @retval EFI_DEVICE_ERROR The region is not used

+**/

+EFI_STATUS

+EFIAPI

+SpiGetRegionAddress (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ OUT UINT32 *BaseAddress OPTIONAL,

+ OUT UINT32 *RegionSize OPTIONAL

+ )

+{

+ UINT32 ScSpiBar0;

+ UINT32 ReadValue;

+ UINT32 Base;

+ SPI_INSTANCE *SpiInstance;

+

+ if (FlashRegionType >= FlashRegionMax) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ if (FlashRegionType == FlashRegionAll) {

+ if (BaseAddress != NULL) {

+ *BaseAddress = 0;

+ }

+

+ if (RegionSize != NULL) {

+ *RegionSize = SpiInstance->Component1StartAddr;

+ }

+

+ return EFI_SUCCESS;

+ }

+

+ ScSpiBar0 = AcquireSpiBar0 (SpiInstance->PchSpiBase);

+ ReadValue = MmioRead32 (ScSpiBar0 + R_SPI_FREG0_FLASHD + S_SPI_FREGX * (UINT32)FlashRegionType);

+ ReleaseSpiBar0 (SpiInstance->PchSpiBase);

+

+ //

+ // If the region is not used, the Region Base is 7FFFh and Region Limit is 0000h

+ //

+ if (ReadValue == B_SPI_FREGX_BASE_MASK) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ Base = (ReadValue & B_SPI_FREG1_BASE_MASK) << N_SPI_FREG1_BASE;

+ if (BaseAddress != NULL) {

+ *BaseAddress = Base;

+ }

+

+ if (RegionSize != NULL) {

+ *RegionSize = ((((ReadValue & B_SPI_FREGX_LIMIT_MASK) >> N_SPI_FREGX_LIMIT) + 1) <<

+ N_SPI_FREGX_LIMIT_REPR) - Base;

+ }

+

+ return EFI_SUCCESS;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf
new file mode 100644
index 0000000000..fae851c12f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf
@@ -0,0 +1,48 @@
+## @file

+# Library instance for SPI flash library using SPI hardware sequence

+#

+# Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = SpiFlashLib

+ FILE_GUID = 6F96AFCB-DE89-4ca1-A63F-8703EE8FDE50

+ MODULE_TYPE = BASE

+ VERSION_STRING = 1.0

+ LIBRARY_CLASS = SpiFlashLib

+ CONSTRUCTOR = SpiConstructor

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ RegsSpi.h

+ SpiCommon.h

+ PchSpi.c

+ SpiFlashLib.c

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ BaseLib

+ PcdLib

+ IoLib

+ PciLib

+ HobLib

+ TimerLib

+ BaseLib

+

+[Guids]

+ gSpiFlashInfoGuid

+

+[Pcd]

+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress

diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c
new file mode 100644
index 0000000000..7fc589303e
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c
@@ -0,0 +1,455 @@
+/** @file

+ SMM SwDispatch2 Protocol.

+

+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+

+

+**/

+

+#include "PchSmiDispatchSmm.h"

+

+typedef struct {

+ UINT8 EosBitOffset;

+ UINT8 ApmBitOffset;

+ UINT32 SmiEosAddr;

+ UINT32 SmiApmStsAddr;

+} SMM_PCH_REGISTER;

+

+SMM_PCH_REGISTER mSmiPchReg;

+

+EFI_SMM_CPU_PROTOCOL *mSmmCpuProtocol;

+LIST_ENTRY mSmmSwDispatch2Queue = INITIALIZE_LIST_HEAD_VARIABLE (mSmmSwDispatch2Queue);

+

+/**

+ Find SmmSwDispatch2Context by SwSmiInputValue.

+

+ @param[in] SwSmiInputValue The value to indentify the SmmSwDispatch2 context

+

+ @return Pointer to EFI_SMM_SW_DISPATCH2_CONTEXT context

+**/

+EFI_SMM_SW_DISPATCH2_CONTEXT *

+FindContextBySwSmiInputValue (

+ IN UINTN SwSmiInputValue

+ )

+{

+ LIST_ENTRY *Node;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;

+

+ Node = mSmmSwDispatch2Queue.ForwardLink;

+ for ( ; Node != &mSmmSwDispatch2Queue; Node = Node->ForwardLink) {

+ Dispatch2Context = BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link);

+ if (Dispatch2Context->SwSmiInputValue == SwSmiInputValue) {

+ return Dispatch2Context;

+ }

+ }

+

+ return NULL;

+}

+

+/**

+ Find SmmSwDispatch2Context by DispatchHandle.

+

+ @param DispatchHandle The handle to indentify the SmmSwDispatch2 context

+

+ @return Pointer to EFI_SMM_SW_DISPATCH2_CONTEXT context

+**/

+EFI_SMM_SW_DISPATCH2_CONTEXT *

+FindContextByDispatchHandle (

+ IN EFI_HANDLE DispatchHandle

+ )

+{

+ LIST_ENTRY *Node;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;

+

+ Node = mSmmSwDispatch2Queue.ForwardLink;

+ for ( ; Node != &mSmmSwDispatch2Queue; Node = Node->ForwardLink) {

+ Dispatch2Context = BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link);

+ if (Dispatch2Context->DispatchHandle == DispatchHandle) {

+ return Dispatch2Context;

+ }

+ }

+

+ return NULL;

+}

+

+/**

+ Dispatch registered SMM handlers

+

+ @param DispatchHandle The unique handle assigned to this handler by SmiHandlerRegister().

+ @param RegisterContext Points to an optional handler context which was specified when the handler was registered.

+ @param CommBuffer A pointer to a collection of data in memory that will

+ be conveyed from a non-SMM environment into an SMM environment.

+ @param CommBufferSize The size of the CommBuffer.

+

+ @return Status Code

+

+**/

+EFI_STATUS

+SmmSwDispatcher (

+ IN EFI_HANDLE DispatchHandle,

+ IN CONST VOID *RegisterContext,

+ IN OUT VOID *CommBuffer,

+ IN OUT UINTN *CommBufferSize

+ )

+{

+ EFI_STATUS Status;

+ EFI_SMM_SW_CONTEXT SwContext;

+ UINTN Index;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;

+ EFI_SMM_HANDLER_ENTRY_POINT2 DispatchFunction;

+ EFI_SMM_SW_REGISTER_CONTEXT DispatchContext;

+ UINTN Size;

+ EFI_SMM_SAVE_STATE_IO_INFO IoInfo;

+

+ //

+ // Construct new context

+ //

+ SwContext.SwSmiCpuIndex = 0;

+ SwContext.CommandPort = IoRead8 (SMM_CONTROL_PORT);

+ SwContext.DataPort = IoRead8 (SMM_DATA_PORT);

+

+ //

+ // Try to find which CPU trigger SWSMI

+ //

+ for (Index = 0; Index < gSmst->NumberOfCpus; Index++) {

+ Status = mSmmCpuProtocol->ReadSaveState (

+ mSmmCpuProtocol,

+ sizeof (IoInfo),

+ EFI_SMM_SAVE_STATE_REGISTER_IO,

+ Index,

+ &IoInfo

+ );

+ if (EFI_ERROR (Status)) {

+ continue;

+ }

+

+ if (IoInfo.IoPort == SMM_CONTROL_PORT) {

+ //

+ // Great! Find it.

+ //

+ SwContext.SwSmiCpuIndex = Index;

+ DEBUG ((DEBUG_VERBOSE, "CPU index = 0x%x/0x%x\n", Index, gSmst->NumberOfCpus));

+ break;

+ }

+ }

+

+ if (SwContext.CommandPort == 0) {

+ DEBUG ((DEBUG_VERBOSE, "NOT SW SMI\n"));

+ Status = EFI_SUCCESS;

+ goto End;

+ }

+

+ //

+ // Search context

+ //

+ Context = FindContextBySwSmiInputValue (SwContext.CommandPort);

+ if (Context == NULL) {

+ DEBUG ((DEBUG_INFO, "No handler for SMI value 0x%x\n", SwContext.CommandPort));

+ Status = EFI_SUCCESS;

+ goto End;

+ }

+

+ DEBUG ((DEBUG_VERBOSE, "Prepare to call handler for 0x%x\n", SwContext.CommandPort));

+

+ //

+ // Dispatch

+ //

+ DispatchContext.SwSmiInputValue = SwContext.CommandPort;

+ Size = sizeof (SwContext);

+ DispatchFunction = (EFI_SMM_HANDLER_ENTRY_POINT2)Context->DispatchFunction;

+ Status = DispatchFunction (DispatchHandle, &DispatchContext, &SwContext, &Size);

+

+End:

+ //

+ // Clear SMI APM status

+ //

+ IoOr32 (mSmiPchReg.SmiApmStsAddr, 1 << mSmiPchReg.ApmBitOffset);

+

+ //

+ // Set EOS bit

+ //

+ IoOr32 (mSmiPchReg.SmiEosAddr, 1 << mSmiPchReg.EosBitOffset);

+

+ return Status;

+}

+

+/**

+Check the SwSmiInputValue is already used

+

+@param[in] SwSmiInputValue To indentify the SmmSwDispatch2 context

+

+@retval EFI_SUCCESS SwSmiInputValue could be used.

+@retval EFI_INVALID_PARAMETER SwSmiInputValue is already be used.

+

+**/

+EFI_STATUS

+SmiInputValueCheck (

+ IN UINTN SwSmiInputValue

+ )

+{

+ LIST_ENTRY *Node;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;

+

+ Node = mSmmSwDispatch2Queue.ForwardLink;

+ for ( ; Node != &mSmmSwDispatch2Queue; Node = Node->ForwardLink) {

+ Dispatch2Context = BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link);

+ if (Dispatch2Context->SwSmiInputValue == SwSmiInputValue) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Register a child SMI source dispatch function for the specified software SMI.

+

+ This service registers a function (DispatchFunction) which will be called when the software

+ SMI source specified by RegContext->SwSmiCpuIndex is detected. On return, DispatchHandle

+ contains a unique handle which may be used later to unregister the function using UnRegister().

+

+ @param[in] This Pointer to the EFI_SMM_SW_DISPATCH2_PROTOCOL instance.

+ @param[in] DispatchFunction Function to register for handler when the specified software

+ SMI is generated.

+ @param[in, out] RegContext Pointer to the dispatch function's context.

+ The caller fills this context in before calling

+ the register function to indicate to the register

+ function which Software SMI input value the

+ dispatch function should be invoked for.

+ @param[out] DispatchHandle Handle generated by the dispatcher to track the

+ function instance.

+

+ @retval EFI_SUCCESS The dispatch function has been successfully

+ registered and the SMI source has been enabled.

+ @retval EFI_DEVICE_ERROR The SW driver was unable to enable the SMI source.

+ @retval EFI_INVALID_PARAMETER RegisterContext is invalid. The SW SMI input value

+ is not within valid range.

+ @retval EFI_OUT_OF_RESOURCES There is not enough memory (system or SMM) to manage this

+ child.

+ @retval EFI_OUT_OF_RESOURCES A unique software SMI value could not be assigned

+ for this dispatch.

+**/

+EFI_STATUS

+EFIAPI

+SmmSwDispatch2Register (

+ IN CONST EFI_SMM_SW_DISPATCH2_PROTOCOL *This,

+ IN EFI_SMM_HANDLER_ENTRY_POINT2 DispatchFunction,

+ IN OUT EFI_SMM_SW_REGISTER_CONTEXT *RegContext,

+ OUT EFI_HANDLE *DispatchHandle

+ )

+{

+ EFI_STATUS Status;

+ UINTN Index;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;

+

+ if (RegContext->SwSmiInputValue == (UINTN)-1) {

+ //

+ // If SwSmiInputValue is set to (UINTN) -1 then a unique value

+ // will be assigned and returned in the structure.

+ //

+ Status = EFI_NOT_FOUND;

+ for (Index = 1; Index < MAXIMUM_SWI_VALUE; Index++) {

+ Status = SmiInputValueCheck (Index);

+ if (!EFI_ERROR (Status)) {

+ RegContext->SwSmiInputValue = Index;

+ break;

+ }

+ }

+

+ if (RegContext->SwSmiInputValue == (UINTN)-1) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+ }

+

+ if ((RegContext->SwSmiInputValue > MAXIMUM_SWI_VALUE) || (RegContext->SwSmiInputValue == 0)) {

+ DEBUG ((DEBUG_ERROR, "ERROR: SMI value range (1 ~ 0x%x)\n", MAXIMUM_SWI_VALUE));

+ return EFI_INVALID_PARAMETER;

+ }

+

+ //

+ // Register

+ //

+ Status = gSmst->SmmAllocatePool (EfiRuntimeServicesData, sizeof (*Context), (VOID **)&Context);

+ ASSERT_EFI_ERROR (Status);

+ if (EFI_ERROR (Status)) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ *DispatchHandle = (EFI_HANDLE)Context;

+ Context->Signature = SMI_SW_HANDLER_SIGNATURE;

+ Context->SwSmiInputValue = RegContext->SwSmiInputValue;

+ Context->DispatchFunction = (UINTN)DispatchFunction;

+ Context->DispatchHandle = *DispatchHandle;

+ InsertTailList (&mSmmSwDispatch2Queue, &Context->Link);

+

+ return Status;

+}

+

+/**

+ Unregister a child SMI source dispatch function for the specified software SMI.

+

+ This service removes the handler associated with DispatchHandle so that it will no longer be

+ called in response to a software SMI.

+

+ @param[in] This Pointer to the EFI_SMM_SW_DISPATCH2_PROTOCOL instance.

+ @param[in] DispatchHandle Handle of dispatch function to deregister.

+

+ @retval EFI_SUCCESS The dispatch function has been successfully unregistered.

+ @retval EFI_INVALID_PARAMETER The DispatchHandle was not valid.

+**/

+EFI_STATUS

+EFIAPI

+SmmSwDispatch2UnRegister (

+ IN CONST EFI_SMM_SW_DISPATCH2_PROTOCOL *This,

+ IN EFI_HANDLE DispatchHandle

+ )

+{

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;

+

+ //

+ // Unregister

+ //

+ Context = FindContextByDispatchHandle (DispatchHandle);

+ ASSERT (Context != NULL);

+ if (Context != NULL) {

+ RemoveEntryList (&Context->Link);

+ gSmst->SmmFreePool (Context);

+ }

+

+ return EFI_SUCCESS;

+}

+

+EFI_SMM_SW_DISPATCH2_PROTOCOL gSmmSwDispatch2 = {

+ SmmSwDispatch2Register,

+ SmmSwDispatch2UnRegister,

+ MAXIMUM_SWI_VALUE

+};

+

+/**

+ Get specified SMI register based on given register ID

+

+ @param[in] SmmRegister SMI related register array from bootloader

+ @param[in] Id The register ID to get.

+

+ @retval NULL The register is not found or the format is not expected.

+ @return smi register

+

+**/

+PLD_GENERIC_REGISTER *

+GetSmmCtrlRegById (

+ IN PLD_SMM_REGISTERS *SmmRegister,

+ IN UINT32 Id

+ )

+{

+ UINT32 Index;

+ PLD_GENERIC_REGISTER *PldReg;

+

+ PldReg = NULL;

+ for (Index = 0; Index < SmmRegister->Count; Index++) {

+ if (SmmRegister->Registers[Index].Id == Id) {

+ PldReg = &SmmRegister->Registers[Index];

+ break;

+ }

+ }

+

+ if (PldReg == NULL) {

+ DEBUG ((DEBUG_INFO, "Register %d not found.\n", Id));

+ return NULL;

+ }

+

+ //

+ // Checking the register if it is expected.

+ //

+ if ((PldReg->Address.AccessSize != EFI_ACPI_3_0_DWORD) ||

+ (PldReg->Address.Address == 0) ||

+ (PldReg->Address.RegisterBitWidth != 1) ||

+ (PldReg->Address.AddressSpaceId != EFI_ACPI_3_0_SYSTEM_IO) ||

+ (PldReg->Value != 1))

+ {

+ DEBUG ((DEBUG_INFO, "Unexpected SMM register.\n"));

+ DEBUG ((DEBUG_INFO, "AddressSpaceId= 0x%x\n", PldReg->Address.AddressSpaceId));

+ DEBUG ((DEBUG_INFO, "RegBitWidth = 0x%x\n", PldReg->Address.RegisterBitWidth));

+ DEBUG ((DEBUG_INFO, "RegBitOffset = 0x%x\n", PldReg->Address.RegisterBitOffset));

+ DEBUG ((DEBUG_INFO, "AccessSize = 0x%x\n", PldReg->Address.AccessSize));

+ DEBUG ((DEBUG_INFO, "Address = 0x%lx\n", PldReg->Address.Address));

+ return NULL;

+ }

+

+ return PldReg;

+}

+

+/**

+ Entry Point for this driver.

+

+ @param[in] ImageHandle Image handle of this driver.

+ @param[in] SystemTable A Pointer to the EFI System Table.

+

+ @retval EFI_SUCCESS The entry point is executed successfully.

+ @retval other Some error occurred when executing this entry point.

+**/

+EFI_STATUS

+EFIAPI

+PchSmiDispatchEntryPoint (

+ IN EFI_HANDLE ImageHandle,

+ IN EFI_SYSTEM_TABLE *SystemTable

+ )

+{

+ EFI_STATUS Status;

+ EFI_HANDLE DispatchHandle;

+ EFI_HOB_GUID_TYPE *GuidHob;

+ PLD_SMM_REGISTERS *SmmRegister;

+ PLD_GENERIC_REGISTER *SmiEosReg;

+ PLD_GENERIC_REGISTER *SmiApmStsReg;

+

+ GuidHob = GetFirstGuidHob (&gSmmRegisterInfoGuid);

+ if (GuidHob == NULL) {

+ return EFI_UNSUPPORTED;

+ }

+

+ SmmRegister = (PLD_SMM_REGISTERS *)GET_GUID_HOB_DATA (GuidHob);

+ SmiEosReg = GetSmmCtrlRegById (SmmRegister, REGISTER_ID_SMI_EOS);

+ if (SmiEosReg == NULL) {

+ DEBUG ((DEBUG_ERROR, "SMI EOS reg not found.\n"));

+ return EFI_NOT_FOUND;

+ }

+

+ mSmiPchReg.SmiEosAddr = (UINT32)SmiEosReg->Address.Address;

+ mSmiPchReg.EosBitOffset = SmiEosReg->Address.RegisterBitOffset;

+

+ SmiApmStsReg = GetSmmCtrlRegById (SmmRegister, REGISTER_ID_SMI_APM_STS);

+ if (SmiApmStsReg == NULL) {

+ DEBUG ((DEBUG_ERROR, "SMI APM status reg not found.\n"));

+ return EFI_NOT_FOUND;

+ }

+

+ mSmiPchReg.SmiApmStsAddr = (UINT32)SmiApmStsReg->Address.Address;

+ mSmiPchReg.ApmBitOffset = SmiApmStsReg->Address.RegisterBitOffset;

+

+ //

+ // Locate PI SMM CPU protocol

+ //

+ Status = gSmst->SmmLocateProtocol (&gEfiSmmCpuProtocolGuid, NULL, (VOID **)&mSmmCpuProtocol);

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Register a SMM handler to handle subsequent SW SMIs.

+ //

+ Status = gSmst->SmiHandlerRegister ((EFI_MM_HANDLER_ENTRY_POINT)SmmSwDispatcher, NULL, &DispatchHandle);

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Publish PI SMM SwDispatch2 Protocol

+ //

+ ImageHandle = NULL;

+ Status = gSmst->SmmInstallProtocolInterface (

+ &ImageHandle,

+ &gEfiSmmSwDispatch2ProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ &gSmmSwDispatch2

+ );

+ ASSERT_EFI_ERROR (Status);

+

+ return Status;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h
new file mode 100644
index 0000000000..c14fe99929
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h
@@ -0,0 +1,36 @@
+/** @file

+ The header file for SMM SwDispatch2 module.

+

+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SMM_SW_DISPATCH2_H_

+#define SMM_SW_DISPATCH2_H_

+

+#include <PiDxe.h>

+#include <Protocol/SmmSwDispatch2.h>

+#include <Protocol/SmmCpu.h>

+#include <Library/UefiDriverEntryPoint.h>

+#include <Library/SmmServicesTableLib.h>

+#include <Library/BaseLib.h>

+#include <Library/IoLib.h>

+#include <Library/DebugLib.h>

+#include <Guid/SmmRegisterInfoGuid.h>

+#include <Library/HobLib.h>

+

+#define SMI_SW_HANDLER_SIGNATURE SIGNATURE_32('s','s','w','h')

+#define MAXIMUM_SWI_VALUE 0xFF

+#define SMM_CONTROL_PORT 0xB2

+#define SMM_DATA_PORT 0xB3

+

+typedef struct {

+ UINTN Signature;

+ LIST_ENTRY Link;

+ EFI_HANDLE DispatchHandle;

+ UINTN SwSmiInputValue;

+ UINTN DispatchFunction;

+} EFI_SMM_SW_DISPATCH2_CONTEXT;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf
new file mode 100644
index 0000000000..96a154e888
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf
@@ -0,0 +1,51 @@
+## @file

+# PCH SMM SMI Software dispatch module.

+#

+# Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = PchSmiDispatchSmm

+ FILE_GUID = 60F343E3-2AE2-4AA7-B01E-BF9BD5C04A3B

+ MODULE_TYPE = DXE_SMM_DRIVER

+ VERSION_STRING = 1.0

+ PI_SPECIFICATION_VERSION = 0x0001000A

+ ENTRY_POINT = PchSmiDispatchEntryPoint

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ PchSmiDispatchSmm.c

+ PchSmiDispatchSmm.h

+

+[Packages]

+ MdePkg/MdePkg.dec

+ UefiPayloadPkg/UefiPayloadPkg.dec

+

+[LibraryClasses]

+ UefiDriverEntryPoint

+ MemoryAllocationLib

+ DebugLib

+ UefiBootServicesTableLib

+ SmmServicesTableLib

+ BaseLib

+ IoLib

+ HobLib

+

+[Protocols]

+ gEfiSmmCpuProtocolGuid # PROTOCOL ALWAYS_CONSUMED

+ gEfiSmmSwDispatch2ProtocolGuid # PROTOCOL ALWAYS_PRODUCED

+

+[Guids]

+ gSmmRegisterInfoGuid

+

+[Depex]

+ gEfiSmmCpuProtocolGuid

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec
new file mode 100644
index 0000000000..549f96d85f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec
@@ -0,0 +1,49 @@
+## @file

+# Payload Platform Package

+#

+# Provides drivers and definitions to create payload platform FV.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ DEC_SPECIFICATION = 0x00010005

+ PACKAGE_NAME = PlatformPayloadPkg

+ PACKAGE_GUID = 17F3ACAC-079D-4518-9EBF-E33289733E8C

+ PACKAGE_VERSION = 0.1

+

+[Includes]

+ Include

+

+[Guids]

+ #

+ ## Defines the token space for the Payload platform Package PCDs.

+ #

+ gPlatformPayloadPkgTokenSpaceGuid = {0xa375ddc6, 0x74fb, 0x4de1, {0x82, 0x6d, 0xa3, 0x10, 0xa3, 0x3b, 0x89, 0x77}}

+

+ #

+ # SPI variable support

+ #

+ gNvVariableInfoGuid = { 0x7a345dca, 0xc26, 0x4f2a, { 0xa8, 0x9a, 0x57, 0xc0, 0x8d, 0xdd, 0x22, 0xee } }

+ gSpiFlashInfoGuid = { 0x2d4aac1b, 0x91a5, 0x4cd5, { 0x9b, 0x5c, 0xb4, 0x0f, 0x5d, 0x28, 0x51, 0xa1 } }

+

+

+################################################################################

+#

+# PCD Declarations section - list of all PCDs Declared by this Package

+# Only this package should be providing the

+# declaration, other packages should not.

+#

+################################################################################

+

+[PcdsFeatureFlag]

+ ## Feature enabling control

+ # @Prompt Enable payload platform FV common for most Intel platforms

+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable|FALSE|BOOLEAN|0x00000001

+

+[PcdsFixedAtBuild, PcdsPatchableInModule]

+ ## FFS filename to find the default variable initial data file.

+ # @Prompt FFS Name of variable initial data file

+ gPlatformPayloadPkgTokenSpaceGuid.PcdNvsDataFile |{ 0x1a, 0xf1, 0xb1, 0xae, 0x42, 0xcc, 0xcf, 0x4e, 0xac, 0x60, 0xdb, 0xab, 0xf6, 0xca, 0x69, 0xe6 }|VOID*|0x00000025

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc
new file mode 100644
index 0000000000..adf028c511
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc
@@ -0,0 +1,110 @@
+## @file

+# platform Payload Package

+#

+# Provides platform specific drivers and definitions to create a platform FV

+# to work with universal UEFI payload to provide support for common Intel platforms.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+################################################################################

+#

+# Defines Section - statements that will be processed to create a Makefile.

+#

+################################################################################

+[Defines]

+ PLATFORM_NAME = PlatformPayloadPkg

+ PLATFORM_GUID = D3C551BE-9BC6-48F5-AA8A-F49425C28CA9

+ PLATFORM_VERSION = 0.1

+ DSC_SPECIFICATION = 0x00010005

+ SUPPORTED_ARCHITECTURES = X64

+ BUILD_TARGETS = DEBUG|RELEASE|NOOPT

+ SKUID_IDENTIFIER = DEFAULT

+ OUTPUT_DIRECTORY = Build/$(PLATFORM_NAME)

+ FLASH_DEFINITION = $(PLATFORM_NAME)/PlatformPayloadPkg.fdf

+ PCD_DYNAMIC_AS_DYNAMICEX = TRUE

+ DXE_ARCH = X64

+

+[Packages]

+ MinPlatformPkg/MinPlatformPkg.dec

+

+################################################################################

+#

+# SKU Identification section - list of all SKU IDs supported by this Platform.

+#

+################################################################################

+[SkuIds]

+ 0|DEFAULT

+

+################################################################################

+#

+# Library Class section - list of all Library Classes needed by this Platform.

+#

+################################################################################

+

+#

+# Since there are no 32b libraries or components in this package, these PCD are specified for 64b only

+#

+[PcdsFeatureFlag]

+ #

+ # PCD needed for MinPlatform build includes

+ #

+ gMinPlatformPkgTokenSpaceGuid.PcdSmiHandlerProfileEnable |FALSE

+ gMinPlatformPkgTokenSpaceGuid.PcdUefiSecureBootEnable |FALSE

+ gMinPlatformPkgTokenSpaceGuid.PcdPerformanceEnable |FALSE

+

+[PcdsPatchableInModule.X64]

+ gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x7

+ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000004F

+!if $(SOURCE_DEBUG_ENABLE)

+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x17

+!else

+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2F

+!endif

+

+ #

+ # The following parameters are set by Library/PlatformHookLib

+ #

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialUseMmio|FALSE

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterBase|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialBaudRate|115200

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterStride|1

+

+################################################################################

+#

+# Pcd DynamicEx Section - list of all EDK II PCD Entries defined by this Platform

+#

+################################################################################

+

+[PcdsDynamicExDefault]

+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0

+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseSize|0

+

+

+#

+# Include common libraries

+#

+!include MinPlatformPkg/Include/Dsc/CoreCommonLib.dsc

+!include MinPlatformPkg/Include/Dsc/CorePeiLib.dsc

+!include MinPlatformPkg/Include/Dsc/CoreDxeLib.dsc

+

+#

+# This package always builds the feature.

+#

+!include Include/PlatformPayloadFeature.dsc

+

+[BuildOptions]

+ *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES

+ GCC:*_UNIXGCC_*_CC_FLAGS = -DMDEPKG_NDEBUG

+ GCC:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG

+ INTEL:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG

+ MSFT:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG

+

+[BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER]

+ GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000

+ XCODE:*_*_*_DLINK_FLAGS = -seg1addr 0x1000 -segalign 0x1000

+ XCODE:*_*_*_MTOC_FLAGS = -align 0x1000

+ CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:4096

+ MSFT:*_*_*_DLINK_FLAGS = /ALIGN:4096

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf
new file mode 100644
index 0000000000..f781a364d7
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf
@@ -0,0 +1,50 @@
+## @file

+# Payload platform Package

+#

+# Provides platform specific drivers and definitions to create a platform FV

+# to work with universal UEF payload.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ DEFINE FD_BASE = 0x00800000

+ DEFINE FD_BLOCK_SIZE = 0x00001000

+

+ !if $(TARGET) == "NOOPT"

+ DEFINE FD_SIZE = 0x00090000

+ DEFINE NUM_BLOCKS = 0x90

+ !else

+ DEFINE FD_SIZE = 0x00050000

+ DEFINE NUM_BLOCKS = 0x50

+ !endif

+

+[FD.PlatformPayload]

+ BaseAddress = $(FD_BASE) | gUefiPayloadPkgTokenSpaceGuid.PcdPayloadFdMemBase

+ Size = $(FD_SIZE) | gUefiPayloadPkgTokenSpaceGuid.PcdPayloadFdMemSize

+ ErasePolarity = 1

+ BlockSize = $(FD_BLOCK_SIZE)

+ NumBlocks = $(NUM_BLOCKS)

+

+ 0x00000000 | $(FD_SIZE)

+ FV = PlatformPayload

+

+[FV.PlatformPayload]

+ !include MinPlatformPkg/Include/Fdf/CommonSpiFvHeaderInfo.fdf

+ FvNameGuid = 96E75986-6FDD-491E-9FD5-35E21AC45B45

+ FvForceRebase = FALSE

+

+ !include Include/PostMemory.fdf

+

+################################################################################

+#

+# Rules are use with the [FV] section's module INF type to define

+# how an FFS file is created for a given INF file. The following Rule are the default

+# rules for the different module type. User can add the customized rules to define the

+# content of the FFS file.

+#

+################################################################################

+

+!include MinPlatformPkg/Include/Fdf/RuleInclude.fdf

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py
new file mode 100644
index 0000000000..1e3e1cce21
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py
@@ -0,0 +1,113 @@
+## @file

+# This file contains the script to build UniversalPayload with platform payload

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+##

+

+import argparse

+import subprocess

+import os

+import shutil

+import sys

+from ctypes import *

+

+sys.dont_write_bytecode = True

+

+def RunCommand(cmd):

+ print(cmd)

+ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,cwd=os.environ['WORKSPACE'])

+ while True:

+ line = p.stdout.readline()

+ if not line:

+ break

+ print(line.strip().decode(errors='ignore'))

+

+ p.communicate()

+ if p.returncode != 0:

+ print("- Failed - error happened when run command: %s"%cmd)

+ raise Exception("ERROR: when run command: %s"%cmd)

+

+def BuildUniversalPayload(Args, MacroList):

+ BuildTarget = Args.Target

+ ToolChain = Args.ToolChain

+ ElfToolChain = 'CLANGDWARF'

+ ObjCopyFlag = "elf64-x86-64" if Args.Arch == 'X64' else "elf32-i386"

+

+ #

+ # Find universal UEFI payload build build script

+ #

+ Edk2PayloadBuildScript = os.path.normpath("UefiPayloadPkg/UniversalPayloadBuild.py")

+ for package_path in os.environ['PACKAGES_PATH'].split(';'):

+ if os.path.exists (os.path.join (package_path, Edk2PayloadBuildScript)):

+ Edk2PayloadBuildScript = os.path.join (package_path, Edk2PayloadBuildScript)

+ break

+ if not os.path.exists (Edk2PayloadBuildScript):

+ raise Exception("Could not find universal UEFI payload build script UniversalPayloadBuild.py")

+

+ PlatformFvDscPath = os.path.normpath("PlatformPayloadPkg/PlatformPayloadPkg.dsc")

+ BuildDir = os.path.join(os.environ['WORKSPACE'], os.path.normpath("Build/UefiPayloadPkgX64"))

+ PlatformFvReportPath = os.path.join(BuildDir, "PlatformPayloadReport.txt")

+ UniversalUefiPld = os.path.join(BuildDir, 'UniversalPayload.elf')

+ PlatformFv = os.path.join(os.environ['WORKSPACE'], os.path.normpath("Build/PlatformPayloadPkg"), f"{BuildTarget}_{ToolChain}", os.path.normpath("FV/PlatformPayload.Fv"))

+

+ if "CLANG_BIN" in os.environ:

+ LlvmObjcopyPath = os.path.join(os.environ["CLANG_BIN"], "llvm-objcopy")

+ else:

+ LlvmObjcopyPath = "llvm-objcopy"

+ try:

+ RunCommand('"%s" --version'%LlvmObjcopyPath)

+ except:

+ print("- Failed - Please check if LLVM is installed or if CLANG_BIN is set correctly")

+ sys.exit(1)

+

+ Defines = ""

+ for key in MacroList:

+ Defines +=" -D {0}={1}".format(key, MacroList[key])

+

+ #

+ # Building Universal Payload entry.

+ #

+ if not Args.Skip:

+ BuildPayload = f"python {Edk2PayloadBuildScript} -b {BuildTarget} -t {ToolChain} -a {Args.Arch} {Defines}"

+ RunCommand(BuildPayload)

+

+ #

+ # Building Platform Payload.

+ #

+ BuildPayload = f"build -p {PlatformFvDscPath} -b {BuildTarget} -a X64 -t {ToolChain} -y {PlatformFvReportPath}"

+ BuildPayload += Defines

+ RunCommand(BuildPayload)

+

+ #

+ # Copy the Platform Payload as a section in elf format Universal Payload.

+ #

+ remove_section = f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyFlag} --remove-section .upld.platform_fv {UniversalUefiPld}'

+ add_section = f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyFlag} --add-section .upld.platform_fv={PlatformFv} {UniversalUefiPld}'

+ set_section = f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyFlag} --set-section-alignment .upld.platform_fv=16 {UniversalUefiPld}'

+ RunCommand(remove_section)

+ RunCommand(add_section)

+ RunCommand(set_section)

+

+

+def main():

+ parser = argparse.ArgumentParser(description='Build Platform Payload FV and add it to Universal UEFI Payload')

+ parser.add_argument('-t', '--ToolChain')

+ parser.add_argument('-b', '--Target', default='DEBUG')

+ parser.add_argument('-a', '--Arch', choices=['IA32', 'X64'], help='Specify the ARCH for payload entry module. Default build X64 image.', default ='X64')

+ parser.add_argument("-D", "--Macro", action="append")

+ parser.add_argument('-s', '--Skip', action='store_true', help='Skip Universal UEFI payload build (just build platform FV and add to Universal UEFI payload.')

+ MacroList = {}

+ args = parser.parse_args()

+ if args.Macro is not None:

+ for Argument in args.Macro:

+ if Argument.count('=') != 1:

+ print("Unknown variable passed in: %s"%Argument)

+ raise Exception("ERROR: Unknown variable passed in: %s"%Argument)

+ tokens = Argument.strip().split('=')

+ MacroList[tokens[0].upper()] = tokens[1]

+ BuildUniversalPayload(args, MacroList)

+ print ("Successfully build Universal Payload with platform FV")

+

+if __name__ == '__main__':

+ main()

diff --git a/Features/Intel/PlatformPayloadPkg/Readme.md b/Features/Intel/PlatformPayloadPkg/Readme.md
new file mode 100644
index 0000000000..10e863b5e0
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Readme.md
@@ -0,0 +1,96 @@
+# Overview

+* **Feature Name:** Platform Payload

+* **PI Phase(s) Supported:** SMM DXE

+

+## Purpose

+This package provides a common platform payload which is expected to work on most

+Intel platforms with a bootloader.

+

+# High-Level Theory of Operation

+Bootloader initialize memory/silicon/platform and payload focus on boot media initializaiton

+and OS boot. Payload is expected to be re-used on different Platforms.

+

+In the reality, some payload modules have platform dependency (e.g. only for Intel PCH)

+or bootloader dependency (only for coreboot). These modules would be located in

+edk2-platform repo.

+

+The generic UEFI payload could be built from EDK2 UefiPayloadPkg in ELF format following

+universal payload specification. And a Platform Payload could be built from PlatformPayloadPkg

+to provide Intel platform specific features (e.g. SPI module, PCH SMM) in FV/FD format.

+This platform payload could be inserted into universal UEFI payload as an ELF section

+to generate a full-feature payload.

+## Firmware Volumes

+* FvPlatformPayload

+

+## Build Flows

+use windows host as example to generate a full-feature payload:

+

+** Setup the build env

+set WORKSPACE=c:\payload

+set PACKAGES_PATH=%WORKSPACE%\edk2;%WORKSPACE%\edk2-platforms\Features\Intel;

+ %WORKSPACE%\edk2-platforms\Platform\Intel

+edk2\edksetup.bat

+

+** Build universal UEFI payload with platform Payload

+python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg.py -t VS2019

+ -D SMM_SUPPORT=TRUE -DVARIABLE_SUPPORT=NONE -D SMM_VARIABLE=TRUE

+or

+python edk2\UefiPayloadPkg\UniversalPayloadBuild.py -t VS2019 -D SMM_SUPPORT=TRUE -DVARIABLE_SUPPORT=NONE

+python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg.py -t VS2019 -D SMM_VARIABLE=TRUE -s

+

+ If build success, the final UEFI payload is at Build\UefiPayloadPkgX64\UniversalPayload.elf.

+

+## Features

+

+1. Modules

+Currently only SMM veriable feature is available.

+Several build macros are used as below for SMM variable feature modules.

+!if $(SMM_VARIABLE) == TRUE

+ ## PchSmiDispatchSmm

+ ## FvbSmm

+ ## FaultTolerantWriteSmm

+ ## VariableSmm

+ ## VariableSmmRuntimeDxe

+!endif

+

+2. Data Flows

+SMM variable:

+The interface with bootloader are defined in PlatformPayloadPkg\Include\Guid

+SpiFlashInfoGuid.h -- SPI related information for SPI flash operation.

+NvVariableInfoGuid.h -- Variable related information for SPI NV variables.

+

+## Control Flows

+EDK2 DXE/SMM core from universal UEFI payload would dispatch all the modules

+from this platform payload.

+

+## Test Point Results

+*_TODO_*

+The test(s) that can verify porting is complete for the feature.

+

+Each feature must describe at least one test point to verify the feature is successful. If the test point is not

+implemented, this should be stated.

+

+## Functional Exit Criteria

+*_TODO_*

+The testable functionality for the feature.

+

+This section should provide an ordered list of criteria that a board integrator can reference to ensure the feature is

+functional on their board.

+

+## Feature Enabling Checklist

+*_TODO_*

+An ordered list of required activities to achieve desired functionality for the feature.

+

+## Performance Impact

+A general expectation for the impact on overall boot performance due to using this feature.

+

+This section is expected to provide guidance on:

+* How to estimate performance impact due to the feature

+* How to measure performance impact of the feature

+* How to manage performance impact of the feature

+

+## Common Optimizations

+*_TODO_*

+Common size or performance tuning options for this feature.

+

+This section is recommended but not required. If not used, the contents should be left empty.

--
2.35.1.windows.2


Guo Dong
 

Any comments for this patch?

Thanks,
Guo

-----Original Message-----
From: Oram, Isaac W <isaac.w.oram@...>
Sent: Tuesday, May 10, 2022 4:41 PM
To: Dong, Guo <guo.dong@...>; devel@edk2.groups.io
Cc: Kinney, Michael D <michael.d.kinney@...>; Ni, Ray <ray.ni@...>; Rhodes, Sean <sean@...>; Desimone, Nathaniel L <nathaniel.l.desimone@...>; Chaganty, Rangasai V <rangasai.v.chaganty@...>; Gao, Liming <gaoliming@...>; Oram, Isaac W <isaac.w.oram@...>
Subject: RE: [edk2-devel][edk2-platforms][PATCH V2 1/1] Features/Intel/PlatformPayloadPkg: add platform payload FV

Added Features/Intel maintainers for review.

-----Original Message-----
From: Dong, Guo <guo.dong@...>
Sent: Friday, May 6, 2022 5:49 PM
To: devel@edk2.groups.io
Cc: Dong, Guo <guo.dong@...>; Kinney, Michael D <michael.d.kinney@...>; Ni, Ray <ray.ni@...>; Rhodes, Sean <sean@...>; Oram, Isaac W <isaac.w.oram@...>
Subject: [edk2-devel][edk2-platforms][PATCH V2 1/1] Features/Intel/PlatformPayloadPkg: add platform payload FV

From: Guo Dong <guo.dong@...>

UefiPayloadPkg in EDK2 repo was added SMM variable support for Intel
platform with SPI flash. But some of the modules for SMM variable are
Intel PCH specific (e.g. SPI library, SMM PCH module), so move these
modules into edk2-platforms repo.

A platform payload FV could be built from PlatformPayloadPkg which works
on Intel platforms (e.g.. ICX, APL, CML, CFL, KBL, TGL, ADL, etc.) with
SMM variable. This platform payload FV could be added into universal UEFI
payload built from EDK2 UefiPayloadPkg.

The steps to build a complete payload (use windows host as example):

set WORKSPACE=c:\payload
set PACKAGES_PATH=C:\payload\edk2;C:\payload\edk2-platforms\Platform\Intel;
C:\payload\edk2-platforms\Features\Intel;
edk2\edksetup.bat

python edk2\UefiPayloadPkg\UniversalPayloadBuild.py -t VS2019
-D SMM_SUPPORT=TRUE -DVARIABLE_SUPPORT=NONE

python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg.py
-t VS2019 -D SMM_VARIABLE=TRUE -s

The final UEFI payload generated at Build\UefiPayloadPkgX64\UniversalPayload.elf
if build success.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Ray Ni <ray.ni@...>
Cc: Sean Rhodes <sean@...>
Signed-off-by: Guo Dong <guo.dong@...>
Signed-off-by: Isaac Oram <isaac.w.oram@...>
---
Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc | 5 +++++
Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf | 7 ++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c | 1088 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h | 185 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c | 139 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h | 24 +++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h | 38 ++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h | 213 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc | 112 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf | 20 +++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf | 8 +++++++
Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c | 160 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf | 38 ++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf | 50 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c | 170 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h | 120 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h | 203 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c | 874 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf | 48 +++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c | 455 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h | 36 +++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf | 51 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec | 49 ++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc | 110 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf | 50 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py | 113 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Readme.md | 96 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
35 files changed, 4887 insertions(+)

diff --git a/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc b/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
index 28530b8c67..17cc3224b7 100644
--- a/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
@@ -80,6 +80,11 @@
gUserAuthFeaturePkgTokenSpaceGuid.PcdUserAuthenticationFeatureEnable |TRUE

gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable |TRUE



+ #

+ # Individual features

+ #

+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable |TRUE

+

#

# PCD that are required to be set by the build target should be configured here for test purposes

# These settings are only for the purposes of buildings, boards should follow instructions in Readme files.

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
index 2b36938df6..2a93ca1ec7 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
@@ -75,3 +75,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/VirtualKeyboardFeature.dsc

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc

+!endif

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
index e214175eda..8e98154f3e 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
@@ -53,6 +53,11 @@
UserAuthFeaturePkg/UserAuthFeaturePkg.dec

VirtualKeyboardFeaturePkg/VirtualKeyboardFeaturePkg.dec



+ #

+ # Individual features

+ #

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

#

# The section below sets all PCDs to FALSE in this DSC file so the feature is not enabled by default.

# Board can set PCDs to TRUE in its DSC file to enable a subset of advanced features

@@ -76,6 +81,8 @@
gUserAuthFeaturePkgTokenSpaceGuid.PcdUserAuthenticationFeatureEnable |FALSE

gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable |FALSE



+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable |FALSE

+

#

# There seems to be some build parsing odd behavior that requires this PCD to be specified even though

# the *.fdf that consumes it is dependent on the feature flag.

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf b/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
index 99089f9a7b..a0975d4d43 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
+++ b/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
@@ -76,3 +76,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/PostMemory.fdf

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PostMemory.fdf

+!endif

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf b/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
index 1db258446a..b2b821c9c4 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
+++ b/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
@@ -76,3 +76,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/PreMemory.fdf

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PreMemory.fdf

+!endif

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c b/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c
new file mode 100644
index 0000000000..d6dcfeb4e1
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c
@@ -0,0 +1,77 @@
+/** @file

+

+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiDxe.h>

+#include <Protocol/FirmwareVolumeBlock.h>

+#include <Library/PcdLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseLib.h>

+#include <Guid/FirmwareFileSystem2.h>

+#include <Guid/SystemNvDataGuid.h>

+

+#define FVB_MEDIA_BLOCK_SIZE 0x1000

+

+typedef struct {

+ EFI_FIRMWARE_VOLUME_HEADER FvInfo;

+ EFI_FV_BLOCK_MAP_ENTRY End[1];

+} EFI_FVB2_MEDIA_INFO;

+

+//

+// This data structure contains a template of FV header which is used to restore

+// Fv header if it's corrupted.

+//

+EFI_FVB2_MEDIA_INFO mFvbMediaInfo = {

+ {

+ { 0, }, // ZeroVector[16]

+ EFI_SYSTEM_NV_DATA_FV_GUID,

+ 0,

+ EFI_FVH_SIGNATURE,

+ 0x0004feff, // check PiFirmwareVolume.h for details on EFI_FVB_ATTRIBUTES_2

+ sizeof (EFI_FIRMWARE_VOLUME_HEADER) + sizeof (EFI_FV_BLOCK_MAP_ENTRY),

+ 0, // CheckSum which will be calucated dynamically.

+ 0, // ExtHeaderOffset

+ { 0, },

+ EFI_FVH_REVISION,

+ {

+ {

+ 0,

+ FVB_MEDIA_BLOCK_SIZE,

+ }

+ }

+ },

+ {

+ {

+ 0,

+ 0

+ }

+ }

+};

+

+

+/**

+ Get a heathy FV header used for variable store recovery

+

+ @retval The FV header.

+

+**/

+EFI_FIRMWARE_VOLUME_HEADER *

+GetFvHeaderTemplate (

+ VOID

+ )

+{

+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;

+ UINTN FvSize;

+

+ FvSize = PcdGet32 (PcdFlashNvStorageFtwSpareSize) * 2;

+ FvHeader = &mFvbMediaInfo.FvInfo;

+ FvHeader->FvLength = FvSize;

+ FvHeader->BlockMap[0].NumBlocks = (UINT32)(FvSize / FvHeader->BlockMap[0].Length);

+ FvHeader->Checksum = 0;

+ FvHeader->Checksum = CalculateCheckSum16 ((UINT16 *)FvHeader, FvHeader->HeaderLength);

+

+ return FvHeader;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c
new file mode 100644
index 0000000000..1d19f3726b
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c
@@ -0,0 +1,1088 @@
+/** @file

+Firmware Volume Block Driver to provide FVB service.

+

+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include "FvbService.h"

+

+//

+// Global variable for this FVB driver which contains

+// the private data of all firmware volume block instances

+//

+FWB_GLOBAL mFvbModuleGlobal;

+

+FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate = {

+ {

+ {

+ HARDWARE_DEVICE_PATH,

+ HW_MEMMAP_DP,

+ {

+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH)),

+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH) >> 8)

+ }

+ },

+ EfiMemoryMappedIO,

+ (EFI_PHYSICAL_ADDRESS)0,

+ (EFI_PHYSICAL_ADDRESS)0,

+ },

+ {

+ END_DEVICE_PATH_TYPE,

+ END_ENTIRE_DEVICE_PATH_SUBTYPE,

+ {

+ END_DEVICE_PATH_LENGTH,

+ 0

+ }

+ }

+};

+

+FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate = {

+ {

+ {

+ MEDIA_DEVICE_PATH,

+ MEDIA_PIWG_FW_VOL_DP,

+ {

+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH)),

+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH) >> 8)

+ }

+ },

+ { 0 }

+ },

+ {

+ END_DEVICE_PATH_TYPE,

+ END_ENTIRE_DEVICE_PATH_SUBTYPE,

+ {

+ END_DEVICE_PATH_LENGTH,

+ 0

+ }

+ }

+};

+

+EFI_FW_VOL_BLOCK_DEVICE mFvbDeviceTemplate = {

+ FVB_DEVICE_SIGNATURE,

+ NULL,

+ 0, // Instance

+ {

+ FvbProtocolGetAttributes,

+ FvbProtocolSetAttributes,

+ FvbProtocolGetPhysicalAddress,

+ FvbProtocolGetBlockSize,

+ FvbProtocolRead,

+ FvbProtocolWrite,

+ FvbProtocolEraseBlocks,

+ NULL

+ } // FwVolBlockInstance

+};

+

+/**

+ Get the pointer to EFI_FW_VOL_INSTANCE from the buffer pointed

+ by mFvbModuleGlobal.FvInstance based on a index.

+ Each EFI_FW_VOL_INSTANCE is with variable length as

+ we have a block map at the end of the EFI_FIRMWARE_VOLUME_HEADER.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+

+ @return A pointer to EFI_FW_VOL_INSTANCE.

+

+**/

+EFI_FW_VOL_INSTANCE *

+GetFvbInstance (

+ IN UINTN Instance

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwhRecord;

+

+ if ( Instance >= mFvbModuleGlobal.NumFv ) {

+ ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER);

+ return NULL;

+ }

+

+ //

+ // Find the right instance of the FVB private data

+ //

+ FwhRecord = mFvbModuleGlobal.FvInstance;

+ while ( Instance > 0 ) {

+ FwhRecord = (EFI_FW_VOL_INSTANCE *)((UINTN)((UINT8 *)FwhRecord) +

+ FwhRecord->VolumeHeader.HeaderLength +

+ (sizeof (EFI_FW_VOL_INSTANCE) - sizeof (EFI_FIRMWARE_VOLUME_HEADER)));

+ Instance--;

+ }

+

+ return FwhRecord;

+}

+

+/**

+ Get the EFI_FVB_ATTRIBUTES_2 of a FV.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+

+ @retval EFI_FVB_ATTRIBUTES_2 of the FV identified by Instance.

+

+**/

+STATIC

+EFI_FVB_ATTRIBUTES_2

+FvbGetVolumeAttributes (

+ IN UINTN Instance

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwInstance;

+

+ FwInstance = GetFvbInstance (Instance);

+ ASSERT (FwInstance != NULL);

+

+ if (FwInstance == NULL) {

+ return 0;

+ }

+

+ return FwInstance->VolumeHeader.Attributes;

+}

+

+/**

+ Retrieves the starting address of an LBA in an FV. It also

+ return a few other attribut of the FV.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+ @param[in] Lba The logical block address

+ @param[out] LbaAddress On output, contains the physical starting address

+ of the Lba

+ @param[out] LbaLength On output, contains the length of the block

+ @param[out] NumOfBlocks A pointer to a caller allocated UINTN in which the

+ number of consecutive blocks starting with Lba is

+ returned. All blocks in this range have a size of

+ BlockSize

+

+ @retval EFI_SUCCESS Successfully returns

+ @retval EFI_INVALID_PARAMETER Instance not found

+

+**/

+STATIC

+EFI_STATUS

+FvbGetLbaAddress (

+ IN UINTN Instance,

+ IN EFI_LBA Lba,

+ OUT UINTN *LbaAddress,

+ OUT UINTN *LbaLength,

+ OUT UINTN *NumOfBlocks

+ )

+{

+ UINT32 NumBlocks;

+ UINT32 BlockLength;

+ UINTN Offset;

+ EFI_LBA StartLba;

+ EFI_LBA NextLba;

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;

+

+ //

+ // Find the right instance of the FVB private data

+ //

+ FwhInstance = GetFvbInstance (Instance);

+ if (FwhInstance == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ StartLba = 0;

+ Offset = 0;

+ BlockMap = &FwhInstance->VolumeHeader.BlockMap[0];

+ ASSERT (BlockMap != NULL);

+

+ //

+ // Parse the blockmap of the FV to find which map entry the Lba belongs to

+ //

+ while (TRUE) {

+ if ( BlockMap != NULL) {

+ NumBlocks = BlockMap->NumBlocks;

+ BlockLength = BlockMap->Length;

+ }

+

+ if ((NumBlocks == 0) || (BlockLength == 0)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ NextLba = StartLba + NumBlocks;

+

+ //

+ // The map entry found

+ //

+ if ((Lba >= StartLba) && (Lba < NextLba)) {

+ Offset = Offset + (UINTN)MultU64x32 ((Lba - StartLba), BlockLength);

+ if (LbaAddress != NULL) {

+ *LbaAddress = FwhInstance->FvBase + Offset;

+ }

+

+ if (LbaLength != NULL) {

+ *LbaLength = BlockLength;

+ }

+

+ if (NumOfBlocks != NULL) {

+ *NumOfBlocks = (UINTN)(NextLba - Lba);

+ }

+

+ return EFI_SUCCESS;

+ }

+

+ StartLba = NextLba;

+ Offset = Offset + NumBlocks * BlockLength;

+ BlockMap++;

+ }

+}

+

+/**

+ Reads specified number of bytes into a buffer from the specified block

+

+ @param[in] Instance The FV instance to be read from

+ @param[in] Lba The logical block address to be read from

+ @param[in] BlockOffset Offset into the block at which to begin reading

+ @param[in, out] NumBytes Pointer that on input contains the total size of

+ the buffer. On output, it contains the total number

+ of bytes read

+ @param[in] Buffer Pointer to a caller allocated buffer that will be

+ used to hold the data read

+

+

+ @retval EFI_SUCCESS The firmware volume was read successfully and

+ contents are in Buffer

+ @retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes returned

+ in Buffer

+ @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be read

+ @retval EFI_INVALID_PARAMETER Instance not found, or NumBytes, Buffer are NULL

+

+**/

+STATIC

+EFI_STATUS

+FvbReadBlock (

+ IN UINTN Instance,

+ IN EFI_LBA Lba,

+ IN UINTN BlockOffset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+ UINTN LbaAddress;

+ UINTN LbaLength;

+ EFI_STATUS Status;

+ EFI_STATUS ReadStatus;

+

+ if ((NumBytes == NULL) || (Buffer == NULL)) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ if (*NumBytes == 0) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ Attributes = FvbGetVolumeAttributes (Instance);

+

+ if ((Attributes & EFI_FVB2_READ_STATUS) == 0) {

+ return (EFI_ACCESS_DENIED);

+ }

+

+ if (BlockOffset > LbaLength) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ if (LbaLength < (*NumBytes + BlockOffset)) {

+ *NumBytes = (UINT32)(LbaLength - BlockOffset);

+ Status = EFI_BAD_BUFFER_SIZE;

+ }

+

+ ReadStatus = LibFvbFlashDeviceRead (LbaAddress + BlockOffset, NumBytes, Buffer);

+ if (EFI_ERROR (ReadStatus)) {

+ return ReadStatus;

+ }

+

+ return Status;

+}

+

+/**

+ Writes specified number of bytes from the input buffer to the block

+

+ @param[in] Instance The FV instance to be written to

+ @param[in] Lba The starting logical block index to write to

+ @param[in] BlockOffset Offset into the block at which to begin writing

+ @param[in, out] NumBytes Pointer that on input contains the total size of

+ the buffer. On output, it contains the total number

+ of bytes actually written

+ @param[in] Buffer Pointer to a caller allocated buffer that contains

+ the source for the write

+ @retval EFI_SUCCESS The firmware volume was written successfully

+ @retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes

+ actually written

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written

+ @retval EFI_INVALID_PARAMETER Instance not found, or NumBytes, Buffer are NULL

+

+**/

+EFI_STATUS

+FvbWriteBlock (

+ IN UINTN Instance,

+ IN EFI_LBA Lba,

+ IN UINTN BlockOffset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+ UINTN LbaAddress;

+ UINTN LbaLength;

+ EFI_STATUS Status;

+

+ if ((NumBytes == NULL) || (Buffer == NULL)) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ if (*NumBytes == 0) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ //

+ // Check if the FV is write enabled

+ //

+ Attributes = FvbGetVolumeAttributes (Instance);

+ if ((Attributes & EFI_FVB2_WRITE_STATUS) == 0) {

+ return EFI_ACCESS_DENIED;

+ }

+

+ //

+ // Perform boundary checks and adjust NumBytes

+ //

+ if (BlockOffset > LbaLength) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ if ( LbaLength < (*NumBytes + BlockOffset)) {

+ DEBUG ((

+ DEBUG_ERROR,

+ "FvWriteBlock: Reducing Numbytes from 0x%x to 0x%x\n",

+ *NumBytes,

+ (UINT32)(LbaLength - BlockOffset)

+ ));

+ *NumBytes = (UINT32)(LbaLength - BlockOffset);

+ return EFI_BAD_BUFFER_SIZE;

+ }

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, FALSE);

+ Status = LibFvbFlashDeviceWrite (LbaAddress + BlockOffset, NumBytes, Buffer);

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, TRUE);

+ WriteBackInvalidateDataCacheRange ((VOID *)(LbaAddress + BlockOffset), *NumBytes);

+ return Status;

+}

+

+/**

+ Erases and initializes a firmware volume block

+

+ @param[in] Instance The FV instance to be erased

+ @param[in] Lba The logical block index to be erased

+

+ @retval EFI_SUCCESS The erase request was successfully completed

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written. Firmware device may have been

+ partially erased

+ @retval EFI_INVALID_PARAMETER Instance not found

+

+**/

+EFI_STATUS

+FvbEraseBlock (

+ IN UINTN Instance,

+ IN EFI_LBA Lba

+ )

+{

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+ UINTN LbaAddress;

+ UINTN LbaLength;

+ EFI_STATUS Status;

+

+ //

+ // Check if the FV is write enabled

+ //

+ Attributes = FvbGetVolumeAttributes (Instance);

+

+ if ((Attributes & EFI_FVB2_WRITE_STATUS) == 0) {

+ return (EFI_ACCESS_DENIED);

+ }

+

+ //

+ // Get the starting address of the block for erase.

+ //

+ Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, FALSE);

+

+ Status = LibFvbFlashDeviceBlockErase (LbaAddress, LbaLength);

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, TRUE);

+

+ WriteBackInvalidateDataCacheRange ((VOID *)LbaAddress, LbaLength);

+

+ return Status;

+}

+

+/**

+ Modifies the current settings of the firmware volume according to the

+ input parameter, and returns the new setting of the volume

+

+ @param[in] Instance The FV instance whose attributes is going to be

+ modified

+ @param[in, out] Attributes On input, it is a pointer to EFI_FVB_ATTRIBUTES_2

+ containing the desired firmware volume settings.

+ On successful return, it contains the new settings

+ of the firmware volume

+

+ @retval EFI_SUCCESS Successfully returns

+ @retval EFI_ACCESS_DENIED The volume setting is locked and cannot be modified

+ @retval EFI_INVALID_PARAMETER Instance not found, or The attributes requested are

+ in conflict with the capabilities as declared in the

+ firmware volume header

+

+**/

+STATIC

+EFI_STATUS

+FvbSetVolumeAttributes (

+ IN UINTN Instance,

+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+ EFI_FVB_ATTRIBUTES_2 OldAttributes;

+ EFI_FVB_ATTRIBUTES_2 *AttribPtr;

+ EFI_FVB_ATTRIBUTES_2 UnchangedAttributes;

+ UINT32 Capabilities;

+ UINT32 OldStatus;

+ UINT32 NewStatus;

+

+ //

+ // Find the right instance of the FVB private data

+ //

+ FwhInstance = GetFvbInstance (Instance);

+ if (FwhInstance == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ AttribPtr = (EFI_FVB_ATTRIBUTES_2 *)&(FwhInstance->VolumeHeader.Attributes);

+ ASSERT (AttribPtr != NULL);

+ if ( AttribPtr == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ OldAttributes = *AttribPtr;

+ Capabilities = OldAttributes & EFI_FVB2_CAPABILITIES;

+ OldStatus = OldAttributes & EFI_FVB2_STATUS;

+ NewStatus = *Attributes & EFI_FVB2_STATUS;

+

+ UnchangedAttributes = EFI_FVB2_READ_DISABLED_CAP | \

+ EFI_FVB2_READ_ENABLED_CAP | \

+ EFI_FVB2_WRITE_DISABLED_CAP | \

+ EFI_FVB2_WRITE_ENABLED_CAP | \

+ EFI_FVB2_LOCK_CAP | \

+ EFI_FVB2_STICKY_WRITE | \

+ EFI_FVB2_MEMORY_MAPPED | \

+ EFI_FVB2_ERASE_POLARITY | \

+ EFI_FVB2_READ_LOCK_CAP | \

+ EFI_FVB2_WRITE_LOCK_CAP | \

+ EFI_FVB2_ALIGNMENT;

+

+ //

+ // Some attributes of FV is read only can *not* be set

+ //

+ if ((OldAttributes & UnchangedAttributes) ^ (*Attributes & UnchangedAttributes)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ //

+ // If firmware volume is locked, no status bit can be updated

+ //

+ if ((OldAttributes & EFI_FVB2_LOCK_STATUS) != 0) {

+ if ((OldStatus ^ NewStatus) != 0) {

+ return EFI_ACCESS_DENIED;

+ }

+ }

+

+ //

+ // Test read disable

+ //

+ if ((Capabilities & EFI_FVB2_READ_DISABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_READ_STATUS) == 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test read enable

+ //

+ if ((Capabilities & EFI_FVB2_READ_ENABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_READ_STATUS) != 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test write disable

+ //

+ if ((Capabilities & EFI_FVB2_WRITE_DISABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_WRITE_STATUS) == 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test write enable

+ //

+ if ((Capabilities & EFI_FVB2_WRITE_ENABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_WRITE_STATUS) != 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test lock

+ //

+ if ((Capabilities & EFI_FVB2_LOCK_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_LOCK_STATUS) != 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ *AttribPtr = (*AttribPtr) & (0xFFFFFFFF & (~EFI_FVB2_STATUS));

+ *AttribPtr = (*AttribPtr) | NewStatus;

+ *Attributes = *AttribPtr;

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Retrieves the physical address of the device.

+

+ @param[in] This A pointer to EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL.

+ @param[out] Address Output buffer containing the address.

+

+ @retval EFI_SUCCESS The function always return successfully.

+ @retval EFI_INVALID_PARAMETER Instance not found.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolGetPhysicalAddress (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_PHYSICAL_ADDRESS *Address

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ FwhInstance = GetFvbInstance (FvbDevice->Instance);

+ if (FwhInstance == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ *Address = FwhInstance->FvBase;

+ return EFI_SUCCESS;

+}

+

+/**

+ Retrieve the size of a logical block

+

+ @param[in] This Calling context

+ @param[in] Lba Indicates which block to return the size for.

+ @param[out] BlockSize A pointer to a caller allocated UINTN in which

+ the size of the block is returned

+ @param[out] NumOfBlocks A pointer to a caller allocated UINTN in which the

+ number of consecutive blocks starting with Lba is

+ returned. All blocks in this range have a size of

+ BlockSize

+

+ @retval EFI_SUCCESS The function always return successfully.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolGetBlockSize (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ OUT UINTN *BlockSize,

+ OUT UINTN *NumOfBlocks

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ return FvbGetLbaAddress (FvbDevice->Instance, Lba, NULL, BlockSize, NumOfBlocks);

+}

+

+/**

+ Retrieves Volume attributes. No polarity translations are done.

+

+ @param[in] This Calling context

+ @param[out] Attributes Output buffer which contains attributes

+

+ @retval EFI_SUCCESS The function always return successfully.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolGetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ *Attributes = FvbGetVolumeAttributes (FvbDevice->Instance);

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Sets Volume attributes. No polarity translations are done.

+

+ @param[in] This Calling context

+ @param[in, out] Attributes Output buffer which contains attributes

+

+ @retval EFI_SUCCESS The function always return successfully.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolSetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ )

+{

+ EFI_STATUS Status;

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ Status = FvbSetVolumeAttributes (FvbDevice->Instance, Attributes);

+ return Status;

+}

+

+/**

+ This function erases one or more blocks as denoted by the

+ variable argument list. The entire parameter list of blocks must be verified

+ prior to erasing any blocks. If a block is requested that does not exist

+ within the associated firmware volume (it has a larger index than the last

+ block of the firmware volume), the EraseBlock() function must return

+ EFI_INVALID_PARAMETER without modifying the contents of the firmware volume.

+

+ @param[in] This Calling context

+ @param[in] ... Starting LBA followed by Number of Lba to erase.

+ a -1 to terminate the list.

+

+ @retval EFI_SUCCESS The erase request was successfully completed

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written. Firmware device may have been

+ partially erased

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolEraseBlocks (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ ...

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+ UINTN NumOfBlocks;

+ VA_LIST args;

+ EFI_LBA StartingLba;

+ UINTN NumOfLba;

+ EFI_STATUS Status;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ FwhInstance = GetFvbInstance (FvbDevice->Instance);

+ if (FwhInstance == NULL) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ NumOfBlocks = FwhInstance->NumOfBlocks;

+ VA_START (args, This);

+

+ do {

+ StartingLba = VA_ARG (args, EFI_LBA);

+ if ( StartingLba == EFI_LBA_LIST_TERMINATOR ) {

+ break;

+ }

+

+ NumOfLba = VA_ARG (args, UINT32);

+

+ //

+ // Check input parameters

+ //

+ if (NumOfLba == 0) {

+ VA_END (args);

+ return EFI_INVALID_PARAMETER;

+ }

+

+ if ((StartingLba + NumOfLba) > NumOfBlocks ) {

+ return EFI_INVALID_PARAMETER;

+ }

+ } while (1);

+

+ VA_END (args);

+

+ VA_START (args, This);

+ do {

+ StartingLba = VA_ARG (args, EFI_LBA);

+ if (StartingLba == EFI_LBA_LIST_TERMINATOR) {

+ break;

+ }

+

+ NumOfLba = VA_ARG (args, UINT32);

+

+ while ( NumOfLba > 0 ) {

+ Status = FvbEraseBlock (FvbDevice->Instance, StartingLba);

+ if ( EFI_ERROR (Status)) {

+ VA_END (args);

+ return Status;

+ }

+

+ StartingLba++;

+ NumOfLba--;

+ }

+ } while (1);

+

+ VA_END (args);

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Writes data beginning at Lba:Offset from FV. The write terminates either

+ when *NumBytes of data have been written, or when a block boundary is

+ reached. *NumBytes is updated to reflect the actual number of bytes

+ written. The write opertion does not include erase. This routine will

+ attempt to write only the specified bytes. If the writes do not stick,

+ it will return an error.

+

+ @param[in] This Calling context

+ @param[in] Lba Block in which to begin write

+ @param[in] Offset Offset in the block at which to begin write

+ @param[in,out] NumBytes On input, indicates the requested write size. On

+ output, indicates the actual number of bytes written

+ @param[in] Buffer Buffer containing source data for the write.

+

+ @retval EFI_SUCCESS The firmware volume was written successfully

+ @retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes

+ actually written

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written

+ @retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolWrite (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_STATUS Status;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ Status = FvbWriteBlock (FvbDevice->Instance, Lba, Offset, NumBytes, Buffer);

+ DEBUG ((

+ DEBUG_VERBOSE,

+ "FvbWrite: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0x%x Status:%r\n",

+ Lba,

+ Offset,

+ *NumBytes,

+ Buffer,

+ Status

+ ));

+

+ return Status;

+}

+

+/**

+ Reads data beginning at Lba:Offset from FV. The Read terminates either

+ when *NumBytes of data have been read, or when a block boundary is

+ reached. *NumBytes is updated to reflect the actual number of bytes

+ written. The write opertion does not include erase. This routine will

+ attempt to write only the specified bytes. If the writes do not stick,

+ it will return an error.

+

+ @param[in] This Calling context

+ @param[in] Lba Block in which to begin write

+ @param[in] Offset Offset in the block at which to begin write

+ @param[in,out] NumBytes On input, indicates the requested write size. On

+ output, indicates the actual number of bytes written

+ @param[out] Buffer Buffer containing source data for the write.

+

+

+Returns:

+ @retval EFI_SUCCESS The firmware volume was read successfully and

+ contents are in Buffer

+ @retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes returned

+ in Buffer

+ @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be read

+ @retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolRead (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_STATUS Status;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ Status = FvbReadBlock (FvbDevice->Instance, Lba, Offset, NumBytes, Buffer);

+ DEBUG ((

+ DEBUG_VERBOSE,

+ "FvbRead: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0x%x, Status:%r\n",

+ Lba,

+ Offset,

+ *NumBytes,

+ Buffer,

+ Status

+ ));

+

+ return Status;

+}

+

+/**

+ Check the integrity of firmware volume header in FvBase

+

+ @param[in] FvBase A pointer to firmware volume base address.

+

+ @retval TRUE The firmware volume is consistent

+ @retval FALSE The firmware volume has corrupted.

+

+**/

+BOOLEAN

+IsFvHeaderValid (

+ IN EFI_PHYSICAL_ADDRESS FvBase

+ )

+{

+ UINT16 Sum;

+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;

+

+ FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvBase;

+ if (FvBase == PcdGet32 (PcdFlashNvStorageVariableBase)) {

+ if (CompareMem (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid, sizeof (EFI_GUID)) != 0 ) {

+ DEBUG ((DEBUG_INFO, " --FileSystemGuid not match: %g\n", &FwVolHeader->FileSystemGuid));

+ return FALSE;

+ }

+ } else {

+ if (CompareMem (&FwVolHeader->FileSystemGuid, &gEfiFirmwareFileSystem2Guid, sizeof (EFI_GUID)) != 0 ) {

+ DEBUG ((DEBUG_INFO, " --not expected guid.\n"));

+ return FALSE;

+ }

+ }

+

+ if ((FwVolHeader->Revision != EFI_FVH_REVISION) ||

+ (FwVolHeader->Signature != EFI_FVH_SIGNATURE) ||

+ (FwVolHeader->FvLength == ((UINTN)-1)) ||

+ ((FwVolHeader->HeaderLength & 0x01) != 0))

+ {

+ DEBUG ((DEBUG_INFO, " -- >Revision = 0x%x, Signature = 0x%x\n", FwVolHeader->Revision, FwVolHeader->Signature));

+ DEBUG ((DEBUG_INFO, " -- >FvLength = 0x%lx, HeaderLength = 0x%x\n", FwVolHeader->FvLength, FwVolHeader->HeaderLength));

+ return FALSE;

+ }

+

+ Sum = CalculateSum16 ((UINT16 *)FwVolHeader, FwVolHeader->HeaderLength);

+ if (Sum != 0) {

+ DEBUG ((DEBUG_INFO, "error: checksum: 0x%04X (expect 0x0)\n", Sum));

+ return FALSE;

+ }

+

+ return TRUE;

+}

+

+/**

+ Get intial variable data.

+

+ @param[out] VarData Valid variable data.

+ @param[out] VarSize Valid variable size.

+

+ @retval RETURN_SUCCESS Successfully found initial variable data.

+ @retval RETURN_NOT_FOUND Failed to find the variable data file from FV.

+ @retval EFI_INVALID_PARAMETER VarData or VarSize is null.

+

+**/

+EFI_STATUS

+GetInitialVariableData (

+ OUT VOID **VarData,

+ OUT UINTN *VarSize

+ )

+{

+ EFI_STATUS Status;

+ VOID *ImageData;

+ UINTN ImageSize;

+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;

+ VARIABLE_STORE_HEADER *VariableStore;

+ AUTHENTICATED_VARIABLE_HEADER *Variable;

+ UINTN VariableSize;

+ UINTN VarEndAddr;

+

+ if ((VarData == NULL) || (VarSize == NULL)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Status = GetSectionFromAnyFv (PcdGetPtr (PcdNvsDataFile), EFI_SECTION_RAW, 0, &ImageData, &ImageSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)ImageData;

+ VariableStore = (VARIABLE_STORE_HEADER *)((UINT8 *)ImageData + FvHeader->HeaderLength);

+ VarEndAddr = (UINTN)VariableStore + VariableStore->Size;

+ Variable = (AUTHENTICATED_VARIABLE_HEADER *)HEADER_ALIGN (VariableStore + 1);

+ *VarData = (VOID *)Variable;

+ while (((UINTN)Variable < VarEndAddr)) {

+ if (Variable->StartId != VARIABLE_DATA) {

+ break;

+ }

+

+ VariableSize = sizeof (AUTHENTICATED_VARIABLE_HEADER) + Variable->DataSize + Variable->NameSize;

+ Variable = (AUTHENTICATED_VARIABLE_HEADER *)HEADER_ALIGN ((UINTN)Variable + VariableSize);

+ }

+

+ *VarSize = (UINTN)Variable - HEADER_ALIGN (VariableStore + 1);

+

+ return EFI_SUCCESS;

+}

+

+/**

+ The function does the necessary initialization work for

+ Firmware Volume Block Driver.

+

+ @retval EFI_SUCCESS This funtion always return EFI_SUCCESS.

+ It will ASSERT on errors.

+

+**/

+EFI_STATUS

+FvbInitialize (

+ VOID

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwVolInstance;

+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;

+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;

+ EFI_PHYSICAL_ADDRESS BaseAddress;

+ UINTN WriteAddr;

+ EFI_STATUS Status;

+ UINTN BufferSize;

+ UINTN Length;

+ VARIABLE_STORE_HEADER VariableStore;

+ VOID *VarData;

+

+ BaseAddress = PcdGet32 (PcdFlashNvStorageVariableBase);

+ FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)BaseAddress;

+

+ //

+ // Check FV header and variable store header

+ //

+ if (!IsFvHeaderValid (BaseAddress)) {

+ //

+ // Write back a healthy FV header

+ //

+ DEBUG ((DEBUG_ERROR, "Fvb: Writing back a healthy FV header: 0x%lx\n", BaseAddress));

+ FvHeader = GetFvHeaderTemplate ();

+ LibFvbFlashDeviceBlockLock ((UINTN)BaseAddress, FvHeader->BlockMap->Length, FALSE);

+

+ Status = LibFvbFlashDeviceBlockErase ((UINTN)BaseAddress, FvHeader->BlockMap->Length);

+ ASSERT_EFI_ERROR (Status);

+

+ Length = FvHeader->HeaderLength;

+ WriteAddr = (UINTN)BaseAddress;

+ Status = LibFvbFlashDeviceWrite (WriteAddr, &Length, (UINT8 *)FvHeader);

+ WriteAddr += Length;

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Write back variable store header

+ //

+ VariableStore.Size = PcdGet32 (PcdFlashNvStorageVariableSize) - FvHeader->HeaderLength;

+ VariableStore.Format = VARIABLE_STORE_FORMATTED;

+ VariableStore.State = VARIABLE_STORE_HEALTHY;

+ CopyGuid (&VariableStore.Signature, &gEfiAuthenticatedVariableGuid);

+ BufferSize = sizeof (VARIABLE_STORE_HEADER);

+ Status = LibFvbFlashDeviceWrite (WriteAddr, &BufferSize, (UINT8 *)&VariableStore);

+ WriteAddr += BufferSize;

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Write initial variable data if found

+ //

+ Status = GetInitialVariableData (&VarData, &Length);

+ if (!EFI_ERROR (Status)) {

+ Status = LibFvbFlashDeviceWrite (WriteAddr, &Length, (UINT8 *)VarData);

+ ASSERT_EFI_ERROR (Status);

+ }

+

+ LibFvbFlashDeviceBlockLock ((UINTN)BaseAddress, FvHeader->BlockMap->Length, TRUE);

+ WriteBackInvalidateDataCacheRange ((VOID *)(UINTN)BaseAddress, FvHeader->BlockMap->Length);

+ }

+

+ //

+ // Create a new FW volume instance for NVS variable

+ //

+ BufferSize = FvHeader->HeaderLength + sizeof (EFI_FW_VOL_INSTANCE) - sizeof (EFI_FIRMWARE_VOLUME_HEADER);

+ FwVolInstance = (EFI_FW_VOL_INSTANCE *)AllocateRuntimeZeroPool (BufferSize);

+ if (FwVolInstance == NULL) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ FwVolInstance->FvBase = (UINTN)BaseAddress;

+ CopyMem (&FwVolInstance->VolumeHeader, FvHeader, FvHeader->HeaderLength);

+

+ //

+ // Process the block map for each FV. Assume it has same block size.

+ //

+ FwVolInstance->NumOfBlocks = 0;

+ FvHeader = &FwVolInstance->VolumeHeader;

+ for (BlockMap = FvHeader->BlockMap; BlockMap->NumBlocks != 0; BlockMap++) {

+ FwVolInstance->NumOfBlocks += BlockMap->NumBlocks;

+ }

+

+ //

+ // Add a FVB Protocol Instance

+ //

+ Status = InstallFvbProtocol (FwVolInstance, mFvbModuleGlobal.NumFv);

+ mFvbModuleGlobal.NumFv++;

+ mFvbModuleGlobal.FvInstance = FwVolInstance;

+

+ return Status;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h
new file mode 100644
index 0000000000..54428d8391
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h
@@ -0,0 +1,185 @@
+/** @file

+The header file for Firmware volume block driver.

+

+Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef FW_BLOCK_SERVICE_H_

+#define FW_BLOCK_SERVICE_H_

+

+#include <Guid/EventGroup.h>

+#include <Guid/FirmwareFileSystem2.h>

+#include <Guid/SystemNvDataGuid.h>

+#include <Guid/VariableFormat.h>

+#include <Protocol/DevicePath.h>

+#include <Protocol/FirmwareVolumeBlock.h>

+#include <Library/UefiDriverEntryPoint.h>

+#include <Library/UefiBootServicesTableLib.h>

+#include <Library/UefiLib.h>

+#include <Library/BaseLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseMemoryLib.h>

+#include <Library/IoLib.h>

+#include <Library/CacheMaintenanceLib.h>

+#include <Library/MemoryAllocationLib.h>

+#include <Library/PcdLib.h>

+#include <Library/FlashDeviceLib.h>

+#include <Library/DevicePathLib.h>

+#include <Library/HobLib.h>

+#include <Library/DxeServicesLib.h>

+#include <Guid/NvVariableInfoGuid.h>

+#include <Register/ArchitecturalMsr.h>

+

+//

+// Define two helper macro to extract the Capability field or Status field in FVB

+// bit fields

+//

+#define EFI_FVB2_CAPABILITIES (EFI_FVB2_READ_DISABLED_CAP |\

+ EFI_FVB2_READ_ENABLED_CAP | \

+ EFI_FVB2_WRITE_DISABLED_CAP | \

+ EFI_FVB2_WRITE_ENABLED_CAP | \

+ EFI_FVB2_LOCK_CAP \

+ )

+

+#define EFI_FVB2_STATUS (EFI_FVB2_READ_STATUS | EFI_FVB2_WRITE_STATUS | EFI_FVB2_LOCK_STATUS)

+

+typedef struct {

+ UINTN FvBase;

+ UINTN NumOfBlocks;

+ //

+ // Note!!!: VolumeHeader must be the last element

+ // of the structure.

+ //

+ EFI_FIRMWARE_VOLUME_HEADER VolumeHeader;

+} EFI_FW_VOL_INSTANCE;

+

+typedef struct {

+ EFI_FW_VOL_INSTANCE *FvInstance;

+ UINT32 NumFv;

+ UINT32 Flags;

+} FWB_GLOBAL;

+

+//

+// Fvb Protocol instance data

+//

+#define FVB_DEVICE_FROM_THIS(a) CR(a, EFI_FW_VOL_BLOCK_DEVICE, FwVolBlockInstance, FVB_DEVICE_SIGNATURE)

+#define FVB_EXTEND_DEVICE_FROM_THIS(a) CR(a, EFI_FW_VOL_BLOCK_DEVICE, FvbExtension, FVB_DEVICE_SIGNATURE)

+#define FVB_DEVICE_SIGNATURE SIGNATURE_32('F','V','B','C')

+

+typedef struct {

+ MEDIA_FW_VOL_DEVICE_PATH FvDevPath;

+ EFI_DEVICE_PATH_PROTOCOL EndDevPath;

+} FV_PIWG_DEVICE_PATH;

+

+typedef struct {

+ MEMMAP_DEVICE_PATH MemMapDevPath;

+ EFI_DEVICE_PATH_PROTOCOL EndDevPath;

+} FV_MEMMAP_DEVICE_PATH;

+

+typedef struct {

+ UINT32 Signature;

+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;

+ UINTN Instance;

+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL FwVolBlockInstance;

+} EFI_FW_VOL_BLOCK_DEVICE;

+

+/**

+ Get a heathy FV header used for variable store recovery

+

+ @retval The FV header.

+

+**/

+EFI_FIRMWARE_VOLUME_HEADER *

+GetFvHeaderTemplate (

+ VOID

+ );

+

+EFI_STATUS

+InitVariableStore (

+ VOID

+ );

+

+//

+// Protocol APIs

+//

+EFI_STATUS

+EFIAPI

+FvbProtocolGetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolSetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolGetPhysicalAddress (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_PHYSICAL_ADDRESS *Address

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolGetBlockSize (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ OUT UINTN *BlockSize,

+ OUT UINTN *NumOfBlocks

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolRead (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolWrite (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolEraseBlocks (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ ...

+ );

+

+EFI_FW_VOL_INSTANCE *

+GetFvbInstance (

+ IN UINTN Instance

+ );

+

+EFI_STATUS

+InstallFvbProtocol (

+ IN EFI_FW_VOL_INSTANCE *FwhInstance,

+ IN UINTN InstanceNum

+ );

+

+EFI_STATUS

+FvbInitialize (

+ VOID

+ );

+

+extern FWB_GLOBAL mFvbModuleGlobal;

+extern EFI_FW_VOL_BLOCK_DEVICE mFvbDeviceTemplate;

+extern FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate;

+extern FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c b/Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c
new file mode 100644
index 0000000000..e2b87a74d2
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c
@@ -0,0 +1,139 @@
+/** @file

+ SMM Firmware Volume Block Driver.

+

+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiSmm.h>

+#include <Library/SmmServicesTableLib.h>

+#include "FvbSmmCommon.h"

+#include "FvbService.h"

+

+/**

+ The function installs EFI_SMM_FIRMWARE_VOLUME_BLOCK protocol

+ for each FV in the system.

+

+ @param[in] FwhInstance The pointer to a FW volume instance structure,

+ which contains the information about one FV.

+ @param[in] InstanceNum The instance number which can be used as a ID

+ to locate this FwhInstance in other functions.

+

+ @retval EFI_SUCESS Installed successfully.

+ @retval Else Did not install successfully.

+

+**/

+EFI_STATUS

+InstallFvbProtocol (

+ IN EFI_FW_VOL_INSTANCE *FwhInstance,

+ IN UINTN InstanceNum

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;

+ EFI_STATUS Status;

+ EFI_HANDLE FvbHandle;

+ FV_MEMMAP_DEVICE_PATH *FvDevicePath;

+ VOID *TempPtr;

+

+ FvbDevice = (EFI_FW_VOL_BLOCK_DEVICE *)AllocateRuntimeCopyPool (

+ sizeof (EFI_FW_VOL_BLOCK_DEVICE),

+ &mFvbDeviceTemplate

+ );

+ if (FvbDevice == NULL) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ FvbDevice->Instance = InstanceNum;

+ FwVolHeader = &FwhInstance->VolumeHeader;

+

+ //

+ // Set up the devicepath

+ //

+ if (FwVolHeader->ExtHeaderOffset == 0) {

+ //

+ // FV does not contains extension header, then produce MEMMAP_DEVICE_PATH

+ //

+ TempPtr = AllocateRuntimeCopyPool (sizeof (FV_MEMMAP_DEVICE_PATH), &mFvMemmapDevicePathTemplate);

+ FvbDevice->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)TempPtr;

+ if (FvbDevice->DevicePath == NULL) {

+ ASSERT (FALSE);

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ FvDevicePath = (FV_MEMMAP_DEVICE_PATH *)FvbDevice->DevicePath;

+ FvDevicePath->MemMapDevPath.StartingAddress = FwhInstance->FvBase;

+ FvDevicePath->MemMapDevPath.EndingAddress = FwhInstance->FvBase + FwVolHeader->FvLength - 1;

+ } else {

+ TempPtr = AllocateRuntimeCopyPool (sizeof (FV_PIWG_DEVICE_PATH), &mFvPIWGDevicePathTemplate);

+ FvbDevice->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)TempPtr;

+ if (FvbDevice->DevicePath == NULL) {

+ ASSERT (FALSE);

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ CopyGuid (

+ &((FV_PIWG_DEVICE_PATH *)FvbDevice->DevicePath)->FvDevPath.FvName,

+ (GUID *)(UINTN)(FwhInstance->FvBase + FwVolHeader->ExtHeaderOffset)

+ );

+ }

+

+ //

+ // Install the SMM Firmware Volume Block Protocol and Device Path Protocol

+ //

+ FvbHandle = NULL;

+ Status = gSmst->SmmInstallProtocolInterface (

+ &FvbHandle,

+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ &FvbDevice->FwVolBlockInstance

+ );

+ ASSERT_EFI_ERROR (Status);

+

+ Status = gSmst->SmmInstallProtocolInterface (

+ &FvbHandle,

+ &gEfiDevicePathProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ FvbDevice->DevicePath

+ );

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Notify the Fvb wrapper driver SMM fvb is ready

+ //

+ FvbHandle = NULL;

+ Status = gBS->InstallProtocolInterface (

+ &FvbHandle,

+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ &FvbDevice->FwVolBlockInstance

+ );

+

+ return Status;

+}

+

+/**

+ The driver entry point for SMM Firmware Volume Block Driver.

+

+ The function does the necessary initialization work

+ Firmware Volume Block Driver.

+

+ @param[in] ImageHandle The firmware allocated handle for the UEFI image.

+ @param[in] SystemTable A pointer to the EFI system table.

+

+ @retval EFI_SUCCESS This funtion always return EFI_SUCCESS.

+ It will ASSERT on errors.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbSmmInitialize (

+ IN EFI_HANDLE ImageHandle,

+ IN EFI_SYSTEM_TABLE *SystemTable

+ )

+{

+ FvbInitialize ();

+

+ return EFI_SUCCESS;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf
new file mode 100644
index 0000000000..a56654ba09
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf
@@ -0,0 +1,66 @@
+## @file

+# This driver installs the EFI_SMM_FIRMWARE_VOLUMEN_PROTOCOL.

+#

+#

+# Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = FvbSmm

+ FILE_GUID = A4EC8ADB-B7A8-47d1-8E52-EC820D0ACF6F

+ MODULE_TYPE = DXE_SMM_DRIVER

+ VERSION_STRING = 1.0

+ PI_SPECIFICATION_VERSION = 0x0001000A

+ ENTRY_POINT = FvbSmmInitialize

+

+[Sources]

+ FvbInfo.c

+ FvbService.h

+ FvbService.c

+ FvbServiceSmm.c

+ FvbSmmCommon.h

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ UefiCpuPkg/UefiCpuPkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ FlashDeviceLib

+ PcdLib

+ MemoryAllocationLib

+ CacheMaintenanceLib

+ IoLib

+ BaseMemoryLib

+ DebugLib

+ BaseLib

+ UefiLib

+ SmmServicesTableLib

+ UefiBootServicesTableLib

+ UefiDriverEntryPoint

+ HobLib

+ DxeServicesLib

+

+[Guids]

+ gEfiFirmwareFileSystem2Guid # ALWAYS_CONSUMED

+ gEfiSystemNvDataFvGuid # ALWAYS_CONSUMED

+ gEfiAuthenticatedVariableGuid

+ gNvVariableInfoGuid

+

+ [Protocols]

+ gEfiDevicePathProtocolGuid # PROTOCOL ALWAYS_PRODUCED

+ gEfiSmmFirmwareVolumeBlockProtocolGuid # PROTOCOL ALWAYS_PRODUCED

+

+[Pcd]

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize

+ gPlatformPayloadPkgTokenSpaceGuid.PcdNvsDataFile

+

+[Depex]

+ TRUE

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h
new file mode 100644
index 0000000000..0eadabe13f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h
@@ -0,0 +1,68 @@
+/** @file

+ The common header file for SMM FVB module.

+

+Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SMM_FVB_COMMON_H_

+#define SMM_FVB_COMMON_H_

+

+#include <Protocol/SmmFirmwareVolumeBlock.h>

+

+#define EFI_FUNCTION_GET_ATTRIBUTES 1

+#define EFI_FUNCTION_SET_ATTRIBUTES 2

+#define EFI_FUNCTION_GET_PHYSICAL_ADDRESS 3

+#define EFI_FUNCTION_GET_BLOCK_SIZE 4

+#define EFI_FUNCTION_READ 5

+#define EFI_FUNCTION_WRITE 6

+#define EFI_FUNCTION_ERASE_BLOCKS 7

+

+typedef struct {

+ UINTN Function;

+ EFI_STATUS ReturnStatus;

+ UINT8 Data[1];

+} SMM_FVB_COMMUNICATE_FUNCTION_HEADER;

+

+///

+/// Size of SMM communicate header, without including the payload.

+///

+#define SMM_COMMUNICATE_HEADER_SIZE (OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data))

+

+///

+/// Size of SMM FVB communicate function header, without including the payload.

+///

+#define SMM_FVB_COMMUNICATE_HEADER_SIZE (OFFSET_OF (SMM_FVB_COMMUNICATE_FUNCTION_HEADER, Data))

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+} SMM_FVB_ATTRIBUTES_HEADER;

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_PHYSICAL_ADDRESS Address;

+} SMM_FVB_PHYSICAL_ADDRESS_HEADER;

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_LBA Lba;

+ UINTN BlockSize;

+ UINTN NumOfBlocks;

+} SMM_FVB_BLOCK_SIZE_HEADER;

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_LBA Lba;

+ UINTN Offset;

+ UINTN NumBytes;

+} SMM_FVB_READ_WRITE_HEADER;

+

+typedef struct {

+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_LBA StartLba;

+ UINTN NumOfLba;

+} SMM_FVB_BLOCKS_HEADER;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h b/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h
new file mode 100644
index 0000000000..fd0bd73529
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h
@@ -0,0 +1,24 @@
+/** @file

+ This file defines the hob structure for the SPI flash variable info.

+

+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef NV_VARIABLE_INFO_GUID_H_

+#define NV_VARIABLE_INFO_GUID_H_

+

+//

+// NV variable hob info GUID

+//

+extern EFI_GUID gNvVariableInfoGuid;

+

+typedef struct {

+ UINT8 Revision;

+ UINT8 Reserved[3];

+ UINT32 VariableStoreBase;

+ UINT32 VariableStoreSize;

+} NV_VARIABLE_INFO;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h b/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h
new file mode 100644
index 0000000000..59b81851d5
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h
@@ -0,0 +1,38 @@
+/** @file

+ This file defines the hob structure for the SPI flash variable info.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SPI_FLASH_INFO_GUID_H_

+#define SPI_FLASH_INFO_GUID_H_

+

+#include <IndustryStandard/Acpi.h>

+//

+// SPI Flash infor hob GUID

+//

+extern EFI_GUID gSpiFlashInfoGuid;

+

+//

+// Set this bit if platform need disable SMM write protection when writing flash

+// in SMM mode using this method: -- AsmWriteMsr32 (0x1FE, MmioRead32 (0xFED30880) | BIT0);

+//

+#define FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT BIT0

+

+//

+// Reuse ACPI definition

+//

+typedef EFI_ACPI_3_0_GENERIC_ADDRESS_STRUCTURE PLD_GENERIC_ADDRESS;

+#define SPACE_ID_PCI_CONFIGURATION EFI_ACPI_3_0_PCI_CONFIGURATION_SPACE

+#define REGISTER_BIT_WIDTH_DWORD EFI_ACPI_3_0_DWORD

+

+typedef struct {

+ UINT8 Revision;

+ UINT8 Reserved;

+ UINT16 Flags;

+ PLD_GENERIC_ADDRESS SpiAddress;

+} SPI_FLASH_INFO;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h b/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h
new file mode 100644
index 0000000000..b5e8be225e
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h
@@ -0,0 +1,104 @@
+/** @file

+ Flash device library class header file.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef FLASHDEVICE_LIB_H_

+#define FLASHDEVICE_LIB_H_

+

+/**

+ Read NumBytes bytes of data from the address specified by

+ PAddress into Buffer.

+

+ @param[in] PAddress The starting physical address of the read.

+ @param[in,out] NumBytes On input, the number of bytes to read. On output, the number

+ of bytes actually read.

+ @param[out] Buffer The destination data buffer for the read.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceRead (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ );

+

+/**

+ Write NumBytes bytes of data from Buffer to the address specified by

+ PAddresss.

+

+ @param[in] PAddress The starting physical address of the write.

+ @param[in,out] NumBytes On input, the number of bytes to write. On output,

+ the actual number of bytes written.

+ @param[in] Buffer The source data buffer for the write.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceWrite (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ );

+

+/**

+ Erase the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of the region to be erased.

+ @param[in] LbaLength The length of the region to be erased. This parameter is necessary

+ as the physical block size on a flash device could be different than

+ the logical block size of Firmware Volume Block protocol. Erase on

+ flash chip is always performed block by block. Therefore, the ERASE

+ operation to a logical block is converted a number of ERASE operation

+ (or a partial erase) on the hardware.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockErase (

+ IN UINTN PAddress,

+ IN UINTN LbaLength

+ );

+

+/**

+ Lock or unlock the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of region to be (un)locked.

+ @param[in] LbaLength The length of the region to be (un)locked. This parameter is necessary

+ as the physical block size on a flash device could be different than

+ the logical block size of Firmware Volume Block protocol. (Un)Lock on

+ flash chip is always performed block by block. Therefore, the (Un)Lock

+ operation to a logical block is converted a number of (Un)Lock operation

+ (or a partial erase) on the hardware.

+ @param[in] Lock TRUE to lock. FALSE to unlock.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockLock (

+ IN UINTN PAddress,

+ IN UINTN LbaLength,

+ IN BOOLEAN Lock

+ );

+

+PHYSICAL_ADDRESS

+EFIAPI

+LibFvbFlashDeviceMemoryMap (

+ );

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h b/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h
new file mode 100644
index 0000000000..07f40502f2
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h
@@ -0,0 +1,213 @@
+/** @file

+ PCH SPI Common Driver implements the SPI Host Controller Compatibility Interface.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SPI_FLASH_LIB_H_

+#define SPI_FLASH_LIB_H_

+

+/**

+ Flash Region Type

+**/

+typedef enum {

+ FlashRegionDescriptor,

+ FlashRegionBios,

+ FlashRegionMe,

+ FlashRegionGbE,

+ FlashRegionPlatformData,

+ FlashRegionDer,

+ FlashRegionAll,

+ FlashRegionMax

+} FLASH_REGION_TYPE;

+

+/**

+ Read SFDP data from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in SFDP data portion of the SPI cycle, the max number is 64

+ @param[out] SfdpData The Pointer to caller-allocated buffer containing the SFDP data received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadSfdp (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SfdpData

+ );

+

+/**

+ Read Jedec Id from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in JedecId data portion of the SPI cycle, the data size is 3 typically

+ @param[out] JedecId The Pointer to caller-allocated buffer containing JEDEC ID received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadJedecId (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *JedecId

+ );

+

+/**

+ Write the status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[in] StatusValue The Pointer to caller-allocated buffer containing the value of Status register writing

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWriteStatus (

+ IN UINT32 ByteCount,

+ IN UINT8 *StatusValue

+ );

+

+/**

+ Read status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[out] StatusValue The Pointer to caller-allocated buffer containing the value of Status register received.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadStatus (

+ IN UINT32 ByteCount,

+ OUT UINT8 *StatusValue

+ );

+

+/**

+ Read SC Soft Strap Values

+

+ @param[in] SoftStrapAddr SC Soft Strap address offset from FPSBA.

+ @param[in] ByteCount Number of bytes in SoftStrap data portion of the SPI cycle

+ @param[out] SoftStrapValue The Pointer to caller-allocated buffer containing SC Soft Strap Value.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiReadPchSoftStrap (

+ IN UINT32 SoftStrapAddr,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SoftStrapValue

+ );

+

+/**

+ Read data from the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[out] Buffer The Pointer to caller-allocated buffer containing the dada received.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashRead (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ OUT UINT8 *Buffer

+ );

+

+/**

+ Erase some area on the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashErase (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount

+ );

+

+/**

+ Write data to the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in] Buffer Pointer to caller-allocated buffer containing the data sent during the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWrite (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN UINT8 *Buffer

+ );

+

+/**

+ Initialize an SPI library.

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_NOT_FOUND The expected SPI info could not be found

+**/

+EFI_STATUS

+EFIAPI

+SpiConstructor (

+ VOID

+ );

+

+/**

+ Get the SPI region base and size, based on the enum type

+

+ @param[in] FlashRegionType The Flash Region type for for the base address which is listed in the Descriptor.

+ @param[out] BaseAddress The Flash Linear Address for the Region 'n' Base

+ @param[out] RegionSize The size for the Region 'n'

+

+ @retval EFI_SUCCESS Read success

+ @retval EFI_INVALID_PARAMETER Invalid region type given

+ @retval EFI_DEVICE_ERROR The region is not used

+**/

+EFI_STATUS

+EFIAPI

+SpiGetRegionAddress (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ OUT UINT32 *BaseAddress OPTIONAL,

+ OUT UINT32 *RegionSize OPTIONAL

+ );

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc b/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc
new file mode 100644
index 0000000000..3003c563c9
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc
@@ -0,0 +1,112 @@
+## @file

+# This is a build description file for the Payload Platform advanced feature.

+# This file should be included into another package DSC file to build this feature.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+################################################################################

+#

+# Defines Section - statements that will be processed to create a Makefile.

+#

+################################################################################

+

+[Defines]

+ !ifndef $(DXE_ARCH)

+ !error "DXE_ARCH must be specified to build this feature!"

+ !endif

+

+ DEFINE SMM_VARIABLE = TRUE

+

+

+################################################################################

+#

+# PCD definitions section - list of all PCD definitions needed by this Platform.

+#

+################################################################################

+

+[PcdsPatchableInModule.X64]

+!if $(SMM_VARIABLE) == TRUE

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase |0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize |0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize |0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase |0

+!endif

+

+################################################################################

+#

+# Library Class section - list of all Library Classes needed by this feature.

+#

+################################################################################

+

+[LibraryClasses]

+ !if $(SMM_VARIABLE) == TRUE

+ PciLib|MdePkg/Library/BasePciLibPciExpress/BasePciLibPciExpress.inf

+ PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf

+ # (Optional for variable modules debug output

+ PlatformHookLib|UefiPayloadPkg/Library/PlatformHookLib/PlatformHookLib.inf

+ DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf

+ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf

+ DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf

+ !endif

+

+[LibraryClasses.common.DXE_SMM_DRIVER,LibraryClasses.common.DXE_RUNTIME_DRIVER]

+ !if $(SMM_VARIABLE) == TRUE

+ SpiFlashLib|PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf

+ FlashDeviceLib|PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf

+ DxeHobListLib|UefiPayloadPkg/Library/DxeHobListLib/DxeHobListLib.inf

+ HobLib|UefiPayloadPkg/Library/DxeHobLib/DxeHobLib.inf

+ TimerLib|UefiCpuPkg/Library/CpuTimerLib/BaseCpuTimerLib.inf

+ !endif

+

+################################################################################

+#

+# Component section - list of all components that need built for this feature.

+#

+# Note: The EDK II DSC file is not used to specify how compiled binary images get placed

+# into firmware volume images. This section is just a list of modules to compile from

+# source into UEFI-compliant binaries.

+# It is the FDF file that contains information on combining binary files into firmware

+# volume images, whose concept is beyond UEFI and is described in PI specification.

+# There may also be modules listed in this section that are not required in the FDF file,

+# When a module listed here is excluded from FDF file, then UEFI-compliant binary will be

+# generated for it, but the binary will not be put into any firmware volume.

+#

+################################################################################

+#

+# Feature DXE Components

+#

+

+# @todo: Change below line to [Components.$(DXE_ARCH)] after https://bugzilla.tianocore.org/show_bug.cgi?id=2308

+# is completed.

+[Components.X64]

+ #

+ # SMM Variable Support

+ #

+ !if $(SMM_VARIABLE) == TRUE

+ PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf

+ PlatformPayloadPkg/Fvb/FvbSmm.inf {

+ <LibraryClasses>

+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf

+ }

+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf {

+ <LibraryClasses>

+ NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf

+ NULL|MdeModulePkg/Library/VarCheckHiiLib/VarCheckHiiLib.inf

+ NULL|MdeModulePkg/Library/VarCheckPcdLib/VarCheckPcdLib.inf

+ NULL|MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.inf

+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf

+ }

+

+ MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf {

+ <LibraryClasses>

+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf

+ }

+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf

+ !endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf b/Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf
new file mode 100644
index 0000000000..54800b972c
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf
@@ -0,0 +1,20 @@
+## @file

+# FDF file for post-memory ACPI Debug advanced feature modules.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+#

+# SMM Support

+#

+!if $(SMM_VARIABLE) == TRUE

+ INF PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf

+ INF PlatformPayloadPkg/Fvb/FvbSmm.inf

+ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf

+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf

+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf

+

+!endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf b/Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf
new file mode 100644
index 0000000000..003b7a3e56
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf
@@ -0,0 +1,8 @@
+## @file

+# FDF file for pre-memory payload platform advanced feature modules.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

diff --git a/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c
new file mode 100644
index 0000000000..5a27043285
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c
@@ -0,0 +1,160 @@
+/** @file

+ Flash Device Library based on SPI Flash library.

+

+Copyright (c) 2018 - 2021, Intel Corporation. All rights reserved. <BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiDxe.h>

+#include <Library/BaseMemoryLib.h>

+#include <Library/DebugLib.h>

+#include <Library/SpiFlashLib.h>

+

+/**

+ Initialize spi flash device.

+

+ @retval EFI_SUCCESS The tested spi flash device is supported.

+ @retval EFI_UNSUPPORTED The tested spi flash device is not supported.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceInit (

+ VOID

+ )

+{

+ return SpiConstructor ();

+}

+

+/**

+ Read NumBytes bytes of data from the address specified by

+ PAddress into Buffer.

+

+ @param[in] PAddress The starting physical address of the read.

+ @param[in,out] NumBytes On input, the number of bytes to read. On output, the number

+ of bytes actually read.

+ @param[out] Buffer The destination data buffer for the read.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceRead (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+ UINT32 ByteCount;

+ UINT32 RgnSize;

+ UINT32 AddrOffset;

+

+ Status = SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - RgnSize))

+ // which equal (PAddress + RgnSize) here.

+ AddrOffset = (UINT32)((UINT32)PAddress + RgnSize);

+ ByteCount = (UINT32)*NumBytes;

+ return SpiFlashRead (FlashRegionBios, AddrOffset, ByteCount, Buffer);

+}

+

+/**

+ Write NumBytes bytes of data from Buffer to the address specified by

+ PAddresss.

+

+ @param[in] PAddress The starting physical address of the write.

+ @param[in,out] NumBytes On input, the number of bytes to write. On output,

+ the actual number of bytes written.

+ @param[in] Buffer The source data buffer for the write.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceWrite (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+ UINT32 ByteCount;

+ UINT32 RgnSize;

+ UINT32 AddrOffset;

+

+ Status = SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - RgnSize))

+ // which equal (PAddress + RgnSize) here.

+ AddrOffset = (UINT32)((UINT32)PAddress + RgnSize);

+ ByteCount = (UINT32)*NumBytes;

+ return SpiFlashWrite (FlashRegionBios, AddrOffset, ByteCount, Buffer);

+}

+

+/**

+ Erase the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of the block to be erased.

+ This library assume that caller garantee that the PAddress

+ is at the starting address of this block.

+ @param[in] LbaLength The length of the logical block to be erased.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockErase (

+ IN UINTN PAddress,

+ IN UINTN LbaLength

+ )

+{

+ EFI_STATUS Status;

+ UINT32 RgnSize;

+ UINT32 AddrOffset;

+

+ Status = SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - RgnSize))

+ // which equal (PAddress + RgnSize) here.

+ AddrOffset = (UINT32)((UINT32)PAddress + RgnSize);

+ return SpiFlashErase (FlashRegionBios, AddrOffset, (UINT32)LbaLength);

+}

+

+/**

+ Lock or unlock the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of region to be (un)locked.

+ @param[in] LbaLength The length of the logical block to be erased.

+ @param[in] Lock TRUE to lock. FALSE to unlock.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockLock (

+ IN UINTN PAddress,

+ IN UINTN LbaLength,

+ IN BOOLEAN Lock

+ )

+{

+ return EFI_SUCCESS;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf
new file mode 100644
index 0000000000..7285a37944
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf
@@ -0,0 +1,38 @@
+## @file

+# Library instace of Flash Device Library Class

+#

+# This library implement the flash device library class for the lakeport platform.

+#@copyright

+# Copyright (c) 2014 - 2021 Intel Corporation. All rights reserved

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = FlashDeviceLib

+ FILE_GUID = BA7CA537-1C65-4a90-9379-622A24A08141

+ MODULE_TYPE = DXE_DRIVER

+ VERSION_STRING = 1.0

+ LIBRARY_CLASS = FlashDeviceLib | DXE_SMM_DRIVER DXE_RUNTIME_DRIVER

+

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ FlashDeviceLib.c

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ DebugLib

+ BaseMemoryLib

+ SpiFlashLib

+

diff --git a/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c
new file mode 100644
index 0000000000..4ea89582f3
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c
@@ -0,0 +1,89 @@
+/** @file

+

+ Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiDxe.h>

+#include <Library/PcdLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseLib.h>

+#include <Guid/SystemNvDataGuid.h>

+#include <Guid/NvVariableInfoGuid.h>

+#include <Library/HobLib.h>

+

+

+/**

+ Initialize the variable store

+

+ @retval EFI_SUCCESS if initialize the store success.

+

+**/

+EFI_STATUS

+PcdInitConstructor (

+ VOID

+ )

+{

+ EFI_STATUS Status;

+ UINT32 NvStorageBase;

+ UINT32 NvStorageSize;

+ UINT32 NvVariableSize;

+ UINT32 FtwWorkingSize;

+ UINT32 FtwSpareSize;

+ EFI_HOB_GUID_TYPE *GuidHob;

+ NV_VARIABLE_INFO *NvVariableInfo;

+

+ //

+ // Find SPI flash variable hob

+ //

+ GuidHob = GetFirstGuidHob (&gNvVariableInfoGuid);

+ if (GuidHob == NULL) {

+ ASSERT (FALSE);

+ return EFI_NOT_FOUND;

+ }

+

+ NvVariableInfo = (NV_VARIABLE_INFO *)GET_GUID_HOB_DATA (GuidHob);

+

+ //

+ // Get variable region base and size.

+ //

+ NvStorageSize = NvVariableInfo->VariableStoreSize;

+ NvStorageBase = NvVariableInfo->VariableStoreBase;

+

+ //

+ // NvStorageBase needs to be 4KB aligned, NvStorageSize needs to be 8KB * n

+ //

+ if (((NvStorageBase & (SIZE_4KB - 1)) != 0) || ((NvStorageSize & (SIZE_8KB - 1)) != 0)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ FtwSpareSize = NvStorageSize / 2;

+ FtwWorkingSize = 0x2000;

+ NvVariableSize = NvStorageSize / 2 - FtwWorkingSize;

+ DEBUG ((DEBUG_INFO, "NvStorageBase:0x%x, NvStorageSize:0x%x\n", NvStorageBase, NvStorageSize));

+

+ if (NvVariableSize >= 0x80000000) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Status = PcdSet32S (PcdFlashNvStorageVariableSize, NvVariableSize);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet32S (PcdFlashNvStorageVariableBase, NvStorageBase);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet64S (PcdFlashNvStorageVariableBase64, NvStorageBase);

+ ASSERT_EFI_ERROR (Status);

+

+ Status = PcdSet32S (PcdFlashNvStorageFtwWorkingSize, FtwWorkingSize);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet32S (PcdFlashNvStorageFtwWorkingBase, NvStorageBase + NvVariableSize);

+ ASSERT_EFI_ERROR (Status);

+

+ Status = PcdSet32S (PcdFlashNvStorageFtwSpareSize, FtwSpareSize);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet32S (PcdFlashNvStorageFtwSpareBase, NvStorageBase + FtwSpareSize);

+ ASSERT_EFI_ERROR (Status);

+

+ return EFI_SUCCESS;

+}

+

diff --git a/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf
new file mode 100644
index 0000000000..05411b00d8
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf
@@ -0,0 +1,50 @@
+## @file

+# Initialize patchable PCDs using HOB info

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = PcdInitLib

+ FILE_GUID = 2C4A8902-B55A-472E-9845-3B931CE68071

+ MODULE_TYPE = BASE

+ VERSION_STRING = 1.0

+ LIBRARY_CLASS = NULL

+ CONSTRUCTOR = PcdInitConstructor

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ PcdInitLib.c

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ BaseLib

+ PcdLib

+ PciLib

+ HobLib

+ BaseLib

+

+[Guids]

+ gNvVariableInfoGuid

+

+[Pcd]

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase

+

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c
new file mode 100644
index 0000000000..18f4a0ba3f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c
@@ -0,0 +1,170 @@
+/** @file

+

+ Copyright (c) 2017-2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+#include "SpiCommon.h"

+

+/**

+ Acquire SPI MMIO BAR.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Return SPI BAR Address

+

+**/

+UINT32

+AcquireSpiBar0 (

+ IN UINTN PchSpiBase

+ )

+{

+ return MmioRead32 (PchSpiBase + R_SPI_BASE) & ~(B_SPI_BAR0_MASK);

+}

+

+/**

+ Release SPI MMIO BAR. Do nothing.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+**/

+VOID

+ReleaseSpiBar0 (

+ IN UINTN PchSpiBase

+ )

+{

+}

+

+/**

+ This function is to enable/disable BIOS Write Protect in SMM phase.

+

+ @param[in] EnableSmmSts Flag to Enable/disable Bios write protect

+

+**/

+VOID

+CpuSmmDisableBiosWriteProtect (

+ IN BOOLEAN EnableSmmSts

+ )

+{

+ UINT32 Data32;

+

+ if (EnableSmmSts) {

+ //

+ // Disable BIOS Write Protect in SMM phase.

+ //

+ Data32 = MmioRead32 ((UINTN)(0xFED30880)) | (UINT32)(BIT0);

+ AsmWriteMsr32 (0x000001FE, Data32);

+ } else {

+ //

+ // Enable BIOS Write Protect in SMM phase

+ //

+ Data32 = MmioRead32 ((UINTN)(0xFED30880)) & (UINT32)(~BIT0);

+ AsmWriteMsr32 (0x000001FE, Data32);

+ }

+

+ //

+ // Read FED30880h back to ensure the setting went through.

+ //

+ Data32 = MmioRead32 (0xFED30880);

+}

+

+/**

+ This function is a hook for Spi to disable BIOS Write Protect.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_ACCESS_DENIED The BIOS Region can only be updated in SMM phase

+

+**/

+EFI_STATUS

+EFIAPI

+DisableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ )

+{

+ //

+ // Write clear BC_SYNC_SS prior to change WPD from 0 to 1.

+ //

+ MmioOr8 (PchSpiBase + R_SPI_BCR + 1, (B_SPI_BCR_SYNC_SS >> 8));

+

+ //

+ // Enable the access to the BIOS space for both read and write cycles

+ //

+ MmioOr8 (PchSpiBase + R_SPI_BCR, B_SPI_BCR_BIOSWE);

+

+ if (CpuSmmBwp != 0) {

+ CpuSmmDisableBiosWriteProtect (TRUE);

+ }

+

+ return EFI_SUCCESS;

+}

+

+/**

+ This function is a hook for Spi to enable BIOS Write Protect.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+**/

+VOID

+EFIAPI

+EnableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ )

+{

+ //

+ // Disable the access to the BIOS space for write cycles

+ //

+ MmioAnd8 (PchSpiBase + R_SPI_BCR, (UINT8)(~B_SPI_BCR_BIOSWE));

+

+ if (CpuSmmBwp != 0) {

+ CpuSmmDisableBiosWriteProtect (FALSE);

+ }

+}

+

+/**

+ This function disables SPI Prefetching and caching,

+ and returns previous BIOS Control Register value before disabling.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Previous BIOS Control Register value

+

+**/

+UINT8

+SaveAndDisableSpiPrefetchCache (

+ IN UINTN PchSpiBase

+ )

+{

+ UINT8 BiosCtlSave;

+

+ BiosCtlSave = MmioRead8 (PchSpiBase + R_SPI_BCR) & B_SPI_BCR_SRC;

+

+ MmioAndThenOr32 (

+ PchSpiBase + R_SPI_BCR, \

+ (UINT32)(~B_SPI_BCR_SRC), \

+ (UINT32)(V_SPI_BCR_SRC_PREF_DIS_CACHE_DIS << B_SPI_BCR_SRC)

+ );

+

+ return BiosCtlSave;

+}

+

+/**

+ This function updates BIOS Control Register with the given value.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] BiosCtlValue BIOS Control Register Value to be updated

+

+**/

+VOID

+SetSpiBiosControlRegister (

+ IN UINTN PchSpiBase,

+ IN UINT8 BiosCtlValue

+ )

+{

+ MmioAndThenOr8 (PchSpiBase + R_SPI_BCR, (UINT8) ~B_SPI_BCR_SRC, BiosCtlValue);

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h
new file mode 100644
index 0000000000..b741904143
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h
@@ -0,0 +1,120 @@
+/** @file

+ Register names for SPI device.

+

+ Copyright (c) 2017 - 2019, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef REGS_SPI_H_

+#define REGS_SPI_H_

+

+#define R_SPI_BASE 0x10 ///< 32-bit Memory Base Address Register

+#define B_SPI_BAR0_MASK 0x0FFF

+#define R_SPI_BCR 0xDC ///< BIOS Control Register

+#define B_SPI_BCR_SRC (BIT3 | BIT2) ///< SPI Read Configuration (SRC)

+#define V_SPI_BCR_SRC_PREF_DIS_CACHE_DIS 0x04 ///< Prefetch Disable, Cache Disable

+#define B_SPI_BCR_SYNC_SS BIT8

+#define B_SPI_BCR_BIOSWE BIT0 ///< Write Protect Disable (WPD)

+

+///

+/// SPI Host Interface Registers

+#define R_SPI_HSFS 0x04 ///< Hardware Sequencing Flash Status and Control Register(32bits)

+#define B_SPI_HSFS_FDBC_MASK 0x3F000000 ///< Flash Data Byte Count ( <= 64), Count = (Value in this field) + 1.

+#define N_SPI_HSFS_FDBC 24

+#define B_SPI_HSFS_CYCLE_MASK 0x001E0000 ///< Flash Cycle.

+#define N_SPI_HSFS_CYCLE 17

+#define V_SPI_HSFS_CYCLE_READ 0 ///< Flash Cycle Read

+#define V_SPI_HSFS_CYCLE_WRITE 2 ///< Flash Cycle Write

+#define V_SPI_HSFS_CYCLE_4K_ERASE 3 ///< Flash Cycle 4K Block Erase

+#define V_SPI_HSFS_CYCLE_64K_ERASE 4 ///< Flash Cycle 64K Sector Erase

+#define V_SPI_HSFS_CYCLE_READ_SFDP 5 ///< Flash Cycle Read SFDP

+#define V_SPI_HSFS_CYCLE_READ_JEDEC_ID 6 ///< Flash Cycle Read JEDEC ID

+#define V_SPI_HSFS_CYCLE_WRITE_STATUS 7 ///< Flash Cycle Write Status

+#define V_SPI_HSFS_CYCLE_READ_STATUS 8 ///< Flash Cycle Read Status

+#define B_SPI_HSFS_CYCLE_FGO BIT16 ///< Flash Cycle Go.

+#define B_SPI_HSFS_FDV BIT14 ///< Flash Descriptor Valid

+#define B_SPI_HSFS_SCIP BIT5 ///< SPI Cycle in Progress

+#define B_SPI_HSFS_FCERR BIT1 ///< Flash Cycle Error

+#define B_SPI_HSFS_FDONE BIT0 ///< Flash Cycle Done

+

+#define R_SPI_FADDR 0x08 ///< SPI Flash Address

+#define B_SPI_FADDR_MASK 0x07FFFFFF ///< SPI Flash Address Mask (0~26bit)

+

+#define R_SPI_FDATA00 0x10 ///< SPI Data 00 (32 bits)

+

+#define R_SPI_FRAP 0x50 ///< SPI Flash Regions Access Permissions Register

+#define B_SPI_FRAP_BRWA_PLATFORM BIT12 // < Region write access for Region4 PlatformData

+#define B_SPI_FRAP_BRWA_GBE BIT11 // < Region write access for Region3 GbE

+#define B_SPI_FRAP_BRWA_SEC BIT10 ///< Region Write Access for Region2 SEC

+#define B_SPI_FRAP_BRWA_BIOS BIT9 ///< Region Write Access for Region1 BIOS

+#define B_SPI_FRAP_BRWA_FLASHD BIT8 ///< Region Write Access for Region0 Flash Descriptor

+#define B_SPI_FRAP_BRRA_PLATFORM BIT4 ///< Region read access for Region4 PlatformData

+#define B_SPI_FRAP_BRRA_GBE BIT3 ///< Region read access for Region3 GbE

+#define B_SPI_FRAP_BRRA_SEC BIT2 ///< Region Read Access for Region2 SEC

+#define B_SPI_FRAP_BRRA_BIOS BIT1 ///< Region Read Access for Region1 BIOS

+#define B_SPI_FRAP_BRRA_FLASHD BIT0 ///< Region Read Access for Region0 Flash Descriptor

+

+#define R_SPI_FREG0_FLASHD 0x54 ///< Flash Region 0 (Flash Descriptor) (32bits)

+#define B_SPI_FREG0_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG0_LIMIT 4 ///< Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG0_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG0_BASE 12 ///< Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG1_BIOS 0x58 ///< Flash Region 1 (BIOS) (32bits)

+#define B_SPI_FREG1_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG1_LIMIT 4 ///< Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG1_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG1_BASE 12 ///< Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG2_SEC 0x5C ///< Flash Region 2 (SEC) (32bits)

+#define B_SPI_FREG2_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG2_LIMIT 4 // < Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG2_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG2_BASE 12 // < Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG3_GBE 0x60 // < Flash Region 3(GbE)(32bits)

+#define B_SPI_FREG3_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG3_LIMIT 4 // < Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG3_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG3_BASE 12 // < Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG4_PLATFORM_DATA 0x64 ///< Flash Region 4 (Platform Data) (32bits)

+#define B_SPI_FREG4_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG4_LIMIT 4 ///< Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG4_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG4_BASE 12 ///< Bit 14:0 identifies address bits [26:2]

+

+#define S_SPI_FREGX 4 ///< Size of Flash Region register

+#define B_SPI_FREGX_LIMIT_MASK 0x7FFF0000 ///< Flash Region Limit [30:16] represents [26:12], [11:0] are assumed to be FFFh

+#define N_SPI_FREGX_LIMIT 16 ///< Region limit bit position

+#define N_SPI_FREGX_LIMIT_REPR 12 ///< Region limit bit represents position

+#define B_SPI_FREGX_BASE_MASK 0x00007FFF ///< Flash Region Base, [14:0] represents [26:12]

+

+#define R_SPI_FDOC 0xB4 ///< Flash Descriptor Observability Control Register (32 bits)

+#define B_SPI_FDOC_FDSS_MASK (BIT14 | BIT13 | BIT12) ///< Flash Descriptor Section Select

+#define V_SPI_FDOC_FDSS_FSDM 0x0000 ///< Flash Signature and Descriptor Map

+#define V_SPI_FDOC_FDSS_COMP 0x1000 ///< Component

+#define B_SPI_FDOC_FDSI_MASK 0x0FFC ///< Flash Descriptor Section Index

+

+#define R_SPI_FDOD 0xB8 ///< Flash Descriptor Observability Data Register (32 bits)

+

+#define R_SPI_LVSCC 0xC4 ///< Vendor Specific Component Capabilities for Component 0 (32 bits)

+#define B_SPI_LVSCC_EO_64K BIT29 ///< < 64k Erase valid (EO_64k_valid)

+

+#define R_SPI_UVSCC 0xC8 ///< Vendor Specific Component Capabilities for Component 1 (32 bits)

+

+#define R_SPI_FDBAR_FLASH_MAP0 0x14 ///< Flash MAP 0

+#define N_SPI_FDBAR_NC 8 ///< < Number Of Components

+#define B_SPI_FDBAR_NC 0x00000300 ///< Number Of Components

+

+#define R_SPI_FDBAR_FLASH_MAP1 0x18 ///< Flash MAP 1

+#define B_SPI_FDBAR_FPSBA 0x00FF0000 ///< Flash Strap Base Address

+

+//

+// Flash Component Base Address (FCBA) from Flash Region 0

+//

+#define R_SPI_FCBA_FLCOMP 0x00 ///< Flash Components Register

+#define B_SPI_FLCOMP_COMP1_MASK 0x0F ///< Flash Component 1 Density

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h
new file mode 100644
index 0000000000..95e9b9b1e7
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h
@@ -0,0 +1,203 @@
+/** @file

+ Header file for the SPI flash module.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SPI_COMMON_LIB_H_

+#define SPI_COMMON_LIB_H_

+

+#include <PiDxe.h>

+#include <Uefi/UefiBaseType.h>

+#include <IndustryStandard/Pci30.h>

+#include <Library/IoLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseMemoryLib.h>

+#include <Library/SpiFlashLib.h>

+#include <Library/MemoryAllocationLib.h>

+#include <Library/BaseLib.h>

+#include <Library/HobLib.h>

+#include <Library/TimerLib.h>

+#include <Guid/SpiFlashInfoGuid.h>

+#include "RegsSpi.h"

+

+///

+/// Maximum time allowed while waiting the SPI cycle to complete

+/// Wait Time = 6 seconds = 6000000 microseconds

+/// Wait Period = 10 microseconds

+///

+#define WAIT_TIME 6000000 ///< Wait Time = 6 seconds = 6000000 microseconds

+#define WAIT_PERIOD 10 ///< Wait Period = 10 microseconds

+

+///

+/// Flash cycle Type

+///

+typedef enum {

+ FlashCycleRead,

+ FlashCycleWrite,

+ FlashCycleErase,

+ FlashCycleReadSfdp,

+ FlashCycleReadJedecId,

+ FlashCycleWriteStatus,

+ FlashCycleReadStatus,

+ FlashCycleMax

+} FLASH_CYCLE_TYPE;

+

+///

+/// Flash Component Number

+///

+typedef enum {

+ FlashComponent0,

+ FlashComponent1,

+ FlashComponentMax

+} FLASH_COMPONENT_NUM;

+

+///

+/// Private data structure definitions for the driver

+///

+#define SC_SPI_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('P', 'S', 'P', 'I')

+

+typedef struct {

+ UINTN Signature;

+ EFI_HANDLE Handle;

+ UINT32 AcpiTmrReg;

+ UINTN PchSpiBase;

+ UINT16 RegionPermission;

+ UINT32 SfdpVscc0Value;

+ UINT32 SfdpVscc1Value;

+ UINT32 StrapBaseAddress;

+ UINT8 NumberOfComponents;

+ UINT16 Flags;

+ UINT32 Component1StartAddr;

+} SPI_INSTANCE;

+

+/**

+ Acquire SPI MMIO BAR

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Return SPI BAR Address

+

+**/

+UINT32

+AcquireSpiBar0 (

+ IN UINTN PchSpiBase

+ );

+

+/**

+ Release SPI MMIO BAR. Do nothing.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval None

+

+**/

+VOID

+ReleaseSpiBar0 (

+ IN UINTN PchSpiBase

+ );

+

+/**

+ This function is a hook for Spi to disable BIOS Write Protect

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_ACCESS_DENIED The BIOS Region can only be updated in SMM phase

+

+**/

+EFI_STATUS

+EFIAPI

+DisableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ );

+

+/**

+ This function is a hook for Spi to enable BIOS Write Protect

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+ @retval None

+

+**/

+VOID

+EFIAPI

+EnableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ );

+

+/**

+ This function disables SPI Prefetching and caching,

+ and returns previous BIOS Control Register value before disabling.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Previous BIOS Control Register value

+

+**/

+UINT8

+SaveAndDisableSpiPrefetchCache (

+ IN UINTN PchSpiBase

+ );

+

+/**

+ This function updates BIOS Control Register with the given value.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] BiosCtlValue BIOS Control Register Value to be updated

+

+ @retval None

+

+**/

+VOID

+SetSpiBiosControlRegister (

+ IN UINTN PchSpiBase,

+ IN UINT8 BiosCtlValue

+ );

+

+/**

+ This function sends the programmed SPI command to the slave device.

+

+ @param[in] SpiRegionType The SPI Region type for flash cycle which is listed in the Descriptor

+ @param[in] FlashCycleType The Flash SPI cycle type list in HSFC (Hardware Sequencing Flash Control Register) register

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in,out] Buffer Pointer to caller-allocated buffer containing the data received or sent during the SPI cycle.

+

+ @retval EFI_SUCCESS SPI command completes successfully.

+ @retval EFI_DEVICE_ERROR Device error, the command aborts abnormally.

+ @retval EFI_ACCESS_DENIED Some unrecognized command encountered in hardware sequencing mode

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+**/

+EFI_STATUS

+SendSpiCmd (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN FLASH_CYCLE_TYPE FlashCycleType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN OUT UINT8 *Buffer

+ );

+

+/**

+ Wait execution cycle to complete on the SPI interface.

+

+ @param[in] PchSpiBar0 Spi MMIO base address

+ @param[in] ErrorCheck TRUE if the SpiCycle needs to do the error check

+

+ @retval TRUE SPI cycle completed on the interface.

+ @retval FALSE Time out while waiting the SPI cycle to complete.

+ It's not safe to program the next command on the SPI interface.

+**/

+BOOLEAN

+WaitForSpiCycleComplete (

+ IN UINT32 PchSpiBar0,

+ IN BOOLEAN ErrorCheck

+ );

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c
new file mode 100644
index 0000000000..22639a748c
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c
@@ -0,0 +1,874 @@
+/** @file

+ Generic driver using Hardware Sequencing registers.

+

+ Copyright (c) 2017-2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+#include "SpiCommon.h"

+

+SPI_INSTANCE *mSpiInstance = NULL;

+

+/**

+ Get SPI Instance from library global data..

+

+ @retval SpiInstance Return SPI instance

+**/

+SPI_INSTANCE *

+GetSpiInstance (

+ VOID

+ )

+{

+ if (mSpiInstance == NULL) {

+ mSpiInstance = AllocatePool (sizeof (SPI_INSTANCE));

+ if (mSpiInstance == NULL) {

+ return NULL;

+ }

+

+ ZeroMem (mSpiInstance, sizeof (SPI_INSTANCE));

+ }

+

+ return mSpiInstance;

+}

+

+/**

+ Initialize an SPI library.

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_NOT_FOUND The expected SPI info could not be found

+**/

+EFI_STATUS

+EFIAPI

+SpiConstructor (

+ VOID

+ )

+{

+ UINT32 ScSpiBar0;

+ UINT8 Comp0Density;

+ SPI_INSTANCE *SpiInstance;

+ EFI_HOB_GUID_TYPE *GuidHob;

+ SPI_FLASH_INFO *SpiFlashInfo;

+

+ //

+ // Find SPI flash hob

+ //

+ GuidHob = GetFirstGuidHob (&gSpiFlashInfoGuid);

+ if (GuidHob == NULL) {

+ ASSERT (FALSE);

+ return EFI_NOT_FOUND;

+ }

+

+ SpiFlashInfo = (SPI_FLASH_INFO *)GET_GUID_HOB_DATA (GuidHob);

+

+ //

+ // Initialize the SPI instance

+ //

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_NOT_FOUND;

+ }

+

+ DEBUG ((DEBUG_INFO, "SpiInstance = %08X\n", SpiInstance));

+

+ SpiInstance->Signature = SC_SPI_PRIVATE_DATA_SIGNATURE;

+ SpiInstance->Handle = NULL;

+

+ //

+ // Check the SPI address

+ //

+ if ((SpiFlashInfo->SpiAddress.AddressSpaceId != EFI_ACPI_3_0_PCI_CONFIGURATION_SPACE) ||

+ (SpiFlashInfo->SpiAddress.RegisterBitWidth != 32) ||

+ (SpiFlashInfo->SpiAddress.RegisterBitOffset != 0) ||

+ (SpiFlashInfo->SpiAddress.AccessSize != EFI_ACPI_3_0_DWORD))

+ {

+ DEBUG ((DEBUG_ERROR, "SPI FLASH HOB is not expected. need check the hob or enhance SPI flash driver.\n"));

+ }

+

+ SpiInstance->PchSpiBase = (UINT32)(UINTN)SpiFlashInfo->SpiAddress.Address;

+ SpiInstance->Flags = SpiFlashInfo->Flags;

+ DEBUG ((DEBUG_INFO, "PchSpiBase at 0x%x\n", SpiInstance->PchSpiBase));

+

+ ScSpiBar0 = AcquireSpiBar0 (SpiInstance->PchSpiBase);

+ DEBUG ((DEBUG_INFO, "ScSpiBar0 at 0x%08X\n", ScSpiBar0));

+

+ if (ScSpiBar0 == 0) {

+ ASSERT (FALSE);

+ }

+

+ if ((MmioRead32 (ScSpiBar0 + R_SPI_HSFS) & B_SPI_HSFS_FDV) == 0) {

+ DEBUG ((DEBUG_ERROR, "SPI Flash descriptor invalid, cannot use Hardware Sequencing registers!\n"));

+ ASSERT (FALSE);

+ }

+

+ MmioOr32 (SpiInstance->PchSpiBase + PCI_COMMAND_OFFSET, EFI_PCI_COMMAND_MEMORY_SPACE);

+ SpiInstance->RegionPermission = MmioRead16 (ScSpiBar0 + R_SPI_FRAP);

+ SpiInstance->SfdpVscc0Value = MmioRead32 (ScSpiBar0 + R_SPI_LVSCC);

+ SpiInstance->SfdpVscc1Value = MmioRead32 (ScSpiBar0 + R_SPI_UVSCC);

+

+ //

+ // Select to Flash Map 0 Register to get the number of flash Component

+ //

+ MmioAndThenOr32 (

+ ScSpiBar0 + R_SPI_FDOC,

+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),

+ (UINT32)(V_SPI_FDOC_FDSS_FSDM | R_SPI_FDBAR_FLASH_MAP0)

+ );

+

+ //

+ // Copy Zero based Number Of Components

+ //

+ SpiInstance->NumberOfComponents = (UINT8)((MmioRead16 (ScSpiBar0 + R_SPI_FDOD) & B_SPI_FDBAR_NC) >> N_SPI_FDBAR_NC);

+

+ MmioAndThenOr32 (

+ ScSpiBar0 + R_SPI_FDOC,

+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),

+ (UINT32)(V_SPI_FDOC_FDSS_COMP | R_SPI_FCBA_FLCOMP)

+ );

+

+ //

+ // Copy Component 0 Density

+ //

+ Comp0Density = (UINT8)MmioRead32 (ScSpiBar0 + R_SPI_FDOD) & B_SPI_FLCOMP_COMP1_MASK;

+ SpiInstance->Component1StartAddr = (UINT32)(SIZE_512KB << Comp0Density);

+

+ //

+ // Select FLASH_MAP1 to get Flash SC Strap Base Address

+ //

+ MmioAndThenOr32 (

+ (ScSpiBar0 + R_SPI_FDOC),

+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),

+ (UINT32)(V_SPI_FDOC_FDSS_FSDM | R_SPI_FDBAR_FLASH_MAP1)

+ );

+

+ SpiInstance->StrapBaseAddress = MmioRead32 (ScSpiBar0 + R_SPI_FDOD) & B_SPI_FDBAR_FPSBA;

+

+ //

+ // Align FPSBA with address bits for the SC Strap portion of flash descriptor

+ //

+ SpiInstance->StrapBaseAddress &= B_SPI_FDBAR_FPSBA;

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Read data from the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[out] Buffer The Pointer to caller-allocated buffer containing the data received.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashRead (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ OUT UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (FlashRegionType, FlashCycleRead, Address, ByteCount, Buffer);

+ return Status;

+}

+

+/**

+ Write data to the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in] Buffer Pointer to caller-allocated buffer containing the data sent during the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWrite (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (FlashRegionType, FlashCycleWrite, Address, ByteCount, Buffer);

+ return Status;

+}

+

+/**

+ Erase some area on the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashErase (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (FlashRegionType, FlashCycleErase, Address, ByteCount, NULL);

+ return Status;

+}

+

+/**

+ Read SFDP data from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in SFDP data portion of the SPI cycle, the max number is 64

+ @param[out] SfdpData The Pointer to caller-allocated buffer containing the SFDP data received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadSfdp (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SfdpData

+ )

+{

+ EFI_STATUS Status;

+ UINT32 Address;

+ SPI_INSTANCE *SpiInstance;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ if ((ByteCount > 64) || (ComponentNumber > SpiInstance->NumberOfComponents)) {

+ ASSERT (FALSE);

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Address = 0;

+ if (ComponentNumber == FlashComponent1) {

+ Address = SpiInstance->Component1StartAddr;

+ }

+

+ Status = SendSpiCmd (0, FlashCycleReadSfdp, Address, ByteCount, SfdpData);

+ return Status;

+}

+

+/**

+ Read Jedec Id from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in JedecId data portion of the SPI cycle, the data size is 3 typically

+ @param[out] JedecId The Pointer to caller-allocated buffer containing JEDEC ID received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadJedecId (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *JedecId

+ )

+{

+ EFI_STATUS Status;

+ UINT32 Address;

+ SPI_INSTANCE *SpiInstance;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ if (ComponentNumber > SpiInstance->NumberOfComponents) {

+ ASSERT (FALSE);

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Address = 0;

+ if (ComponentNumber == FlashComponent1) {

+ Address = SpiInstance->Component1StartAddr;

+ }

+

+ Status = SendSpiCmd (0, FlashCycleReadJedecId, Address, ByteCount, JedecId);

+ return Status;

+}

+

+/**

+ Write the status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[in] StatusValue The Pointer to caller-allocated buffer containing the value of Status register writing

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWriteStatus (

+ IN UINT32 ByteCount,

+ IN UINT8 *StatusValue

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (0, FlashCycleWriteStatus, 0, ByteCount, StatusValue);

+ return Status;

+}

+

+/**

+ Read status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[out] StatusValue The Pointer to caller-allocated buffer containing the value of Status register received.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadStatus (

+ IN UINT32 ByteCount,

+ OUT UINT8 *StatusValue

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (0, FlashCycleReadStatus, 0, ByteCount, StatusValue);

+ return Status;

+}

+

+/**

+ Read SC Soft Strap Values

+

+ @param[in] SoftStrapAddr SC Soft Strap address offset from FPSBA.

+ @param[in] ByteCount Number of bytes in SoftStrap data portion of the SPI cycle

+ @param[out] SoftStrapValue The Pointer to caller-allocated buffer containing SC Soft Strap Value.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiReadPchSoftStrap (

+ IN UINT32 SoftStrapAddr,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SoftStrapValue

+ )

+{

+ UINT32 StrapFlashAddr;

+ EFI_STATUS Status;

+ SPI_INSTANCE *SpiInstance;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ ASSERT (SpiInstance->StrapBaseAddress != 0);

+ //

+ // SC Strap Flash Address = FPSBA + RamAddr

+ //

+ StrapFlashAddr = SpiInstance->StrapBaseAddress + SoftStrapAddr;

+

+ Status = SendSpiCmd (FlashRegionDescriptor, FlashCycleRead, StrapFlashAddr, ByteCount, SoftStrapValue);

+ return Status;

+}

+

+/**

+ This function sends the programmed SPI command to the slave device.

+

+ @param[in] FlashRegionType The SPI Region type for flash cycle which is listed in the Descriptor

+ @param[in] FlashCycleType The Flash SPI cycle type list in HSFC (Hardware Sequencing Flash Control Register) register

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in,out] Buffer Pointer to caller-allocated buffer containing the data received or sent during the SPI cycle.

+

+ @retval EFI_SUCCESS SPI command completes successfully.

+ @retval EFI_DEVICE_ERROR Device error, the command aborts abnormally.

+ @retval EFI_ACCESS_DENIED Some unrecognized command encountered in hardware sequencing mode

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+**/

+EFI_STATUS

+SendSpiCmd (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN FLASH_CYCLE_TYPE FlashCycleType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN OUT UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+ UINT32 Index;

+ UINTN SpiBaseAddress;

+ UINT32 ScSpiBar0;

+ UINT32 LimitAddress;

+ UINT32 HardwareSpiAddr;

+ UINT16 PermissionBit;

+ UINT32 SpiDataCount;

+ UINT32 FlashCycle;

+ UINT8 BiosCtlSave;

+ SPI_INSTANCE *SpiInstance;

+ UINT32 Data32;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ Status = EFI_SUCCESS;

+ SpiBaseAddress = SpiInstance->PchSpiBase;

+ ScSpiBar0 = AcquireSpiBar0 (SpiBaseAddress);

+ BiosCtlSave = 0;

+ SpiInstance->RegionPermission = MmioRead16 (ScSpiBar0 + R_SPI_FRAP);

+

+ //

+ // If it's write cycle, disable Prefetching, Caching and disable BIOS Write Protect

+ //

+ if ((FlashCycleType == FlashCycleWrite) || (FlashCycleType == FlashCycleErase)) {

+ Status = DisableBiosWriteProtect (SpiBaseAddress, mSpiInstance->Flags & FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT);

+ if (EFI_ERROR (Status)) {

+ goto SendSpiCmdEnd;

+ }

+

+ BiosCtlSave = SaveAndDisableSpiPrefetchCache (SpiBaseAddress);

+ }

+

+ //

+ // Make sure it's safe to program the command.

+ //

+ if (!WaitForSpiCycleComplete (ScSpiBar0, FALSE)) {

+ Status = EFI_DEVICE_ERROR;

+ goto SendSpiCmdEnd;

+ }

+

+ HardwareSpiAddr = Address;

+ if ((FlashCycleType == FlashCycleRead) ||

+ (FlashCycleType == FlashCycleWrite) ||

+ (FlashCycleType == FlashCycleErase))

+ {

+ switch (FlashRegionType) {

+ case FlashRegionDescriptor:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_FLASHD;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_FLASHD;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG0_FLASHD);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG0_BASE_MASK) << N_SPI_FREG0_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG0_LIMIT_MASK) >> N_SPI_FREG0_LIMIT;

+ break;

+

+ case FlashRegionBios:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_BIOS;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_BIOS;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG1_BIOS);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG1_BASE_MASK) << N_SPI_FREG1_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG1_LIMIT_MASK) >> N_SPI_FREG1_LIMIT;

+ break;

+

+ case FlashRegionMe:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_SEC;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_SEC;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG2_SEC);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG2_BASE_MASK) << N_SPI_FREG2_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG2_LIMIT_MASK) >> N_SPI_FREG2_LIMIT;

+ break;

+

+ case FlashRegionGbE:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_GBE;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_GBE;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG3_GBE);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG3_BASE_MASK) << N_SPI_FREG3_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG3_LIMIT_MASK) >> N_SPI_FREG3_LIMIT;

+ break;

+

+ case FlashRegionPlatformData:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_PLATFORM;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_PLATFORM;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG4_PLATFORM_DATA);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG4_BASE_MASK) << N_SPI_FREG4_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG4_LIMIT_MASK) >> N_SPI_FREG4_LIMIT;

+ break;

+

+ case FlashRegionAll:

+ //

+ // FlashRegionAll indicates address is relative to flash device

+ // No error checking for this case

+ //

+ LimitAddress = 0;

+ PermissionBit = 0;

+ break;

+

+ default:

+ Status = EFI_UNSUPPORTED;

+ goto SendSpiCmdEnd;

+ }

+

+ if ((LimitAddress != 0) && (Address > LimitAddress)) {

+ Status = EFI_INVALID_PARAMETER;

+ goto SendSpiCmdEnd;

+ }

+

+ //

+ // If the operation is read, but the region attribute is not read allowed, return error.

+ // If the operation is write, but the region attribute is not write allowed, return error.

+ //

+ if ((PermissionBit != 0) && ((SpiInstance->RegionPermission & PermissionBit) == 0)) {

+ Status = EFI_ACCESS_DENIED;

+ goto SendSpiCmdEnd;

+ }

+ }

+

+ //

+ // Check for SC SPI hardware sequencing required commands

+ //

+ FlashCycle = 0;

+ switch (FlashCycleType) {

+ case FlashCycleRead:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleWrite:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_WRITE << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleErase:

+ if (((ByteCount % SIZE_4KB) != 0) || ((HardwareSpiAddr % SIZE_4KB) != 0)) {

+ DEBUG ((DEBUG_ERROR, "Erase and erase size must be 4KB aligned. \n"));

+ ASSERT (FALSE);

+ Status = EFI_INVALID_PARAMETER;

+ goto SendSpiCmdEnd;

+ }

+

+ break;

+

+ case FlashCycleReadSfdp:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ_SFDP << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleReadJedecId:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ_JEDEC_ID << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleWriteStatus:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_WRITE_STATUS << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleReadStatus:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ_STATUS << N_SPI_HSFS_CYCLE);

+ break;

+

+ default:

+ //

+ // Unrecognized Operation

+ //

+ ASSERT (FALSE);

+ Status = EFI_INVALID_PARAMETER;

+ goto SendSpiCmdEnd;

+ break;

+ }

+

+ do {

+ SpiDataCount = ByteCount;

+ if ((FlashCycleType == FlashCycleRead) || (FlashCycleType == FlashCycleWrite)) {

+ //

+ // Trim at 256 byte boundary per operation,

+ // - SC SPI controller requires trimming at 4KB boundary

+ // - Some SPI chips require trimming at 256 byte boundary for write operation

+ // - Trimming has limited performance impact as we can read / write at most 64 byte

+ // per operation

+ //

+ if (HardwareSpiAddr + ByteCount > ((HardwareSpiAddr + BIT8) &~(BIT8 - 1))) {

+ SpiDataCount = (((UINT32)(HardwareSpiAddr) + BIT8) &~(BIT8 - 1)) - (UINT32)(HardwareSpiAddr);

+ }

+

+ //

+ // Calculate the number of bytes to shift in/out during the SPI data cycle.

+ // Valid settings for the number of bytes during each data portion of the

+ // SC SPI cycles are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 24, 32, 40, 48, 56, 64

+ //

+ if (SpiDataCount >= 64) {

+ SpiDataCount = 64;

+ } else if ((SpiDataCount &~0x07) != 0) {

+ SpiDataCount = SpiDataCount &~0x07;

+ }

+ }

+

+ if (FlashCycleType == FlashCycleErase) {

+ if (((ByteCount / SIZE_64KB) != 0) &&

+ ((ByteCount % SIZE_64KB) == 0) &&

+ ((HardwareSpiAddr % SIZE_64KB) == 0))

+ {

+ if (HardwareSpiAddr < SpiInstance->Component1StartAddr) {

+ //

+ // Check whether Component0 support 64k Erase

+ //

+ if ((SpiInstance->SfdpVscc0Value & B_SPI_LVSCC_EO_64K) != 0) {

+ SpiDataCount = SIZE_64KB;

+ } else {

+ SpiDataCount = SIZE_4KB;

+ }

+ } else {

+ //

+ // Check whether Component1 support 64k Erase

+ //

+ if ((SpiInstance->SfdpVscc1Value & B_SPI_LVSCC_EO_64K) != 0) {

+ SpiDataCount = SIZE_64KB;

+ } else {

+ SpiDataCount = SIZE_4KB;

+ }

+ }

+ } else {

+ SpiDataCount = SIZE_4KB;

+ }

+

+ if (SpiDataCount == SIZE_4KB) {

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_4K_ERASE << N_SPI_HSFS_CYCLE);

+ } else {

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_64K_ERASE << N_SPI_HSFS_CYCLE);

+ }

+ }

+

+ //

+ // If it's write cycle, load data into the SPI data buffer.

+ //

+ if ((FlashCycleType == FlashCycleWrite) || (FlashCycleType == FlashCycleWriteStatus)) {

+ if ((SpiDataCount & 0x07) != 0) {

+ //

+ // Use Byte write if Data Count is 0, 1, 2, 3, 4, 5, 6, 7

+ //

+ for (Index = 0; Index < SpiDataCount; Index++) {

+ MmioWrite8 (ScSpiBar0 + R_SPI_FDATA00 + Index, Buffer[Index]);

+ }

+ } else {

+ //

+ // Use Dword write if Data Count is 8, 16, 24, 32, 40, 48, 56, 64

+ //

+ for (Index = 0; Index < SpiDataCount; Index += sizeof (UINT32)) {

+ MmioWrite32 (ScSpiBar0 + R_SPI_FDATA00 + Index, *(UINT32 *)(Buffer + Index));

+ }

+ }

+ }

+

+ //

+ // Set the Flash Address

+ //

+ MmioWrite32 (ScSpiBar0 + R_SPI_FADDR, (UINT32)(HardwareSpiAddr & B_SPI_FADDR_MASK));

+

+ //

+ // Set Data count, Flash cycle, and Set Go bit to start a cycle

+ //

+ MmioAndThenOr32 (

+ ScSpiBar0 + R_SPI_HSFS,

+ (UINT32)(~(B_SPI_HSFS_FDBC_MASK | B_SPI_HSFS_CYCLE_MASK)),

+ (UINT32)(((SpiDataCount - 1) << N_SPI_HSFS_FDBC) | FlashCycle | B_SPI_HSFS_CYCLE_FGO)

+ );

+

+ //

+ // Wait for command execution complete.

+ //

+ if (!WaitForSpiCycleComplete (ScSpiBar0, TRUE)) {

+ Status = EFI_DEVICE_ERROR;

+ goto SendSpiCmdEnd;

+ }

+

+ //

+ // If it's read cycle, load data into the caller's buffer.

+ //

+ if ((FlashCycleType == FlashCycleRead) ||

+ (FlashCycleType == FlashCycleReadSfdp) ||

+ (FlashCycleType == FlashCycleReadJedecId) ||

+ (FlashCycleType == FlashCycleReadStatus))

+ {

+ if ((SpiDataCount & 0x07) != 0) {

+ //

+ // Use Byte read if Data Count is 0, 1, 2, 3, 4, 5, 6, 7

+ //

+ for (Index = 0; Index < SpiDataCount; Index++) {

+ Buffer[Index] = MmioRead8 (ScSpiBar0 + R_SPI_FDATA00 + Index);

+ }

+ } else {

+ //

+ // Use Dword read if Data Count is 8, 16, 24, 32, 40, 48, 56, 64

+ //

+ for (Index = 0; Index < SpiDataCount; Index += sizeof (UINT32)) {

+ *(UINT32 *)(Buffer + Index) = MmioRead32 (ScSpiBar0 + R_SPI_FDATA00 + Index);

+ }

+ }

+ }

+

+ HardwareSpiAddr += SpiDataCount;

+ Buffer += SpiDataCount;

+ ByteCount -= SpiDataCount;

+ } while (ByteCount > 0);

+

+SendSpiCmdEnd:

+ ///

+ /// Restore the settings for SPI Prefetching and Caching and enable BIOS Write Protect

+ ///

+ if ((FlashCycleType == FlashCycleWrite) || (FlashCycleType == FlashCycleErase)) {

+ EnableBiosWriteProtect (SpiBaseAddress, mSpiInstance->Flags & FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT);

+ SetSpiBiosControlRegister (SpiBaseAddress, BiosCtlSave);

+ }

+

+ ReleaseSpiBar0 (SpiBaseAddress);

+

+ return Status;

+}

+

+/**

+ Wait execution cycle to complete on the SPI interface.

+

+ @param[in] ScSpiBar0 Spi MMIO base address

+ @param[in] ErrorCheck TRUE if the SpiCycle needs to do the error check

+

+ @retval TRUE SPI cycle completed on the interface.

+ @retval FALSE Time out while waiting the SPI cycle to complete.

+ It's not safe to program the next command on the SPI interface.

+**/

+BOOLEAN

+WaitForSpiCycleComplete (

+ IN UINT32 ScSpiBar0,

+ IN BOOLEAN ErrorCheck

+ )

+{

+ UINT64 WaitTicks;

+ UINT64 WaitCount;

+ UINT32 Data32;

+

+ //

+ // Convert the wait period allowed into to tick count

+ //

+ WaitCount = WAIT_TIME / WAIT_PERIOD;

+ //

+ // Wait for the SPI cycle to complete.

+ //

+ for (WaitTicks = 0; WaitTicks < WaitCount; WaitTicks++) {

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_HSFS);

+ if ((Data32 & B_SPI_HSFS_SCIP) == 0) {

+ MmioWrite32 (ScSpiBar0 + R_SPI_HSFS, B_SPI_HSFS_FCERR | B_SPI_HSFS_FDONE);

+ if (((Data32 & B_SPI_HSFS_FCERR) != 0) && ErrorCheck) {

+ return FALSE;

+ } else {

+ return TRUE;

+ }

+ }

+

+ MicroSecondDelay (WAIT_PERIOD);

+ }

+

+ return FALSE;

+}

+

+/**

+ Get the SPI region base and size, based on the enum type

+

+ @param[in] FlashRegionType The Flash Region type for for the base address which is listed in the Descriptor.

+ @param[out] BaseAddress The Flash Linear Address for the Region 'n' Base

+ @param[out] RegionSize The size for the Region 'n'

+

+ @retval EFI_SUCCESS Read success

+ @retval EFI_INVALID_PARAMETER Invalid region type given

+ @retval EFI_DEVICE_ERROR The region is not used

+**/

+EFI_STATUS

+EFIAPI

+SpiGetRegionAddress (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ OUT UINT32 *BaseAddress OPTIONAL,

+ OUT UINT32 *RegionSize OPTIONAL

+ )

+{

+ UINT32 ScSpiBar0;

+ UINT32 ReadValue;

+ UINT32 Base;

+ SPI_INSTANCE *SpiInstance;

+

+ if (FlashRegionType >= FlashRegionMax) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ if (FlashRegionType == FlashRegionAll) {

+ if (BaseAddress != NULL) {

+ *BaseAddress = 0;

+ }

+

+ if (RegionSize != NULL) {

+ *RegionSize = SpiInstance->Component1StartAddr;

+ }

+

+ return EFI_SUCCESS;

+ }

+

+ ScSpiBar0 = AcquireSpiBar0 (SpiInstance->PchSpiBase);

+ ReadValue = MmioRead32 (ScSpiBar0 + R_SPI_FREG0_FLASHD + S_SPI_FREGX * (UINT32)FlashRegionType);

+ ReleaseSpiBar0 (SpiInstance->PchSpiBase);

+

+ //

+ // If the region is not used, the Region Base is 7FFFh and Region Limit is 0000h

+ //

+ if (ReadValue == B_SPI_FREGX_BASE_MASK) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ Base = (ReadValue & B_SPI_FREG1_BASE_MASK) << N_SPI_FREG1_BASE;

+ if (BaseAddress != NULL) {

+ *BaseAddress = Base;

+ }

+

+ if (RegionSize != NULL) {

+ *RegionSize = ((((ReadValue & B_SPI_FREGX_LIMIT_MASK) >> N_SPI_FREGX_LIMIT) + 1) <<

+ N_SPI_FREGX_LIMIT_REPR) - Base;

+ }

+

+ return EFI_SUCCESS;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf
new file mode 100644
index 0000000000..fae851c12f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf
@@ -0,0 +1,48 @@
+## @file

+# Library instance for SPI flash library using SPI hardware sequence

+#

+# Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = SpiFlashLib

+ FILE_GUID = 6F96AFCB-DE89-4ca1-A63F-8703EE8FDE50

+ MODULE_TYPE = BASE

+ VERSION_STRING = 1.0

+ LIBRARY_CLASS = SpiFlashLib

+ CONSTRUCTOR = SpiConstructor

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ RegsSpi.h

+ SpiCommon.h

+ PchSpi.c

+ SpiFlashLib.c

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ BaseLib

+ PcdLib

+ IoLib

+ PciLib

+ HobLib

+ TimerLib

+ BaseLib

+

+[Guids]

+ gSpiFlashInfoGuid

+

+[Pcd]

+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress

diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c
new file mode 100644
index 0000000000..7fc589303e
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c
@@ -0,0 +1,455 @@
+/** @file

+ SMM SwDispatch2 Protocol.

+

+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+

+

+**/

+

+#include "PchSmiDispatchSmm.h"

+

+typedef struct {

+ UINT8 EosBitOffset;

+ UINT8 ApmBitOffset;

+ UINT32 SmiEosAddr;

+ UINT32 SmiApmStsAddr;

+} SMM_PCH_REGISTER;

+

+SMM_PCH_REGISTER mSmiPchReg;

+

+EFI_SMM_CPU_PROTOCOL *mSmmCpuProtocol;

+LIST_ENTRY mSmmSwDispatch2Queue = INITIALIZE_LIST_HEAD_VARIABLE (mSmmSwDispatch2Queue);

+

+/**

+ Find SmmSwDispatch2Context by SwSmiInputValue.

+

+ @param[in] SwSmiInputValue The value to indentify the SmmSwDispatch2 context

+

+ @return Pointer to EFI_SMM_SW_DISPATCH2_CONTEXT context

+**/

+EFI_SMM_SW_DISPATCH2_CONTEXT *

+FindContextBySwSmiInputValue (

+ IN UINTN SwSmiInputValue

+ )

+{

+ LIST_ENTRY *Node;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;

+

+ Node = mSmmSwDispatch2Queue.ForwardLink;

+ for ( ; Node != &mSmmSwDispatch2Queue; Node = Node->ForwardLink) {

+ Dispatch2Context = BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link);

+ if (Dispatch2Context->SwSmiInputValue == SwSmiInputValue) {

+ return Dispatch2Context;

+ }

+ }

+

+ return NULL;

+}

+

+/**

+ Find SmmSwDispatch2Context by DispatchHandle.

+

+ @param DispatchHandle The handle to indentify the SmmSwDispatch2 context

+

+ @return Pointer to EFI_SMM_SW_DISPATCH2_CONTEXT context

+**/

+EFI_SMM_SW_DISPATCH2_CONTEXT *

+FindContextByDispatchHandle (

+ IN EFI_HANDLE DispatchHandle

+ )

+{

+ LIST_ENTRY *Node;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;

+

+ Node = mSmmSwDispatch2Queue.ForwardLink;

+ for ( ; Node != &mSmmSwDispatch2Queue; Node = Node->ForwardLink) {

+ Dispatch2Context = BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link);

+ if (Dispatch2Context->DispatchHandle == DispatchHandle) {

+ return Dispatch2Context;

+ }

+ }

+

+ return NULL;

+}

+

+/**

+ Dispatch registered SMM handlers

+

+ @param DispatchHandle The unique handle assigned to this handler by SmiHandlerRegister().

+ @param RegisterContext Points to an optional handler context which was specified when the handler was registered.

+ @param CommBuffer A pointer to a collection of data in memory that will

+ be conveyed from a non-SMM environment into an SMM environment.

+ @param CommBufferSize The size of the CommBuffer.

+

+ @return Status Code

+

+**/

+EFI_STATUS

+SmmSwDispatcher (

+ IN EFI_HANDLE DispatchHandle,

+ IN CONST VOID *RegisterContext,

+ IN OUT VOID *CommBuffer,

+ IN OUT UINTN *CommBufferSize

+ )

+{

+ EFI_STATUS Status;

+ EFI_SMM_SW_CONTEXT SwContext;

+ UINTN Index;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;

+ EFI_SMM_HANDLER_ENTRY_POINT2 DispatchFunction;

+ EFI_SMM_SW_REGISTER_CONTEXT DispatchContext;

+ UINTN Size;

+ EFI_SMM_SAVE_STATE_IO_INFO IoInfo;

+

+ //

+ // Construct new context

+ //

+ SwContext.SwSmiCpuIndex = 0;

+ SwContext.CommandPort = IoRead8 (SMM_CONTROL_PORT);

+ SwContext.DataPort = IoRead8 (SMM_DATA_PORT);

+

+ //

+ // Try to find which CPU trigger SWSMI

+ //

+ for (Index = 0; Index < gSmst->NumberOfCpus; Index++) {

+ Status = mSmmCpuProtocol->ReadSaveState (

+ mSmmCpuProtocol,

+ sizeof (IoInfo),

+ EFI_SMM_SAVE_STATE_REGISTER_IO,

+ Index,

+ &IoInfo

+ );

+ if (EFI_ERROR (Status)) {

+ continue;

+ }

+

+ if (IoInfo.IoPort == SMM_CONTROL_PORT) {

+ //

+ // Great! Find it.

+ //

+ SwContext.SwSmiCpuIndex = Index;

+ DEBUG ((DEBUG_VERBOSE, "CPU index = 0x%x/0x%x\n", Index, gSmst->NumberOfCpus));

+ break;

+ }

+ }

+

+ if (SwContext.CommandPort == 0) {

+ DEBUG ((DEBUG_VERBOSE, "NOT SW SMI\n"));

+ Status = EFI_SUCCESS;

+ goto End;

+ }

+

+ //

+ // Search context

+ //

+ Context = FindContextBySwSmiInputValue (SwContext.CommandPort);

+ if (Context == NULL) {

+ DEBUG ((DEBUG_INFO, "No handler for SMI value 0x%x\n", SwContext.CommandPort));

+ Status = EFI_SUCCESS;

+ goto End;

+ }

+

+ DEBUG ((DEBUG_VERBOSE, "Prepare to call handler for 0x%x\n", SwContext.CommandPort));

+

+ //

+ // Dispatch

+ //

+ DispatchContext.SwSmiInputValue = SwContext.CommandPort;

+ Size = sizeof (SwContext);

+ DispatchFunction = (EFI_SMM_HANDLER_ENTRY_POINT2)Context->DispatchFunction;

+ Status = DispatchFunction (DispatchHandle, &DispatchContext, &SwContext, &Size);

+

+End:

+ //

+ // Clear SMI APM status

+ //

+ IoOr32 (mSmiPchReg.SmiApmStsAddr, 1 << mSmiPchReg.ApmBitOffset);

+

+ //

+ // Set EOS bit

+ //

+ IoOr32 (mSmiPchReg.SmiEosAddr, 1 << mSmiPchReg.EosBitOffset);

+

+ return Status;

+}

+

+/**

+Check the SwSmiInputValue is already used

+

+@param[in] SwSmiInputValue To indentify the SmmSwDispatch2 context

+

+@retval EFI_SUCCESS SwSmiInputValue could be used.

+@retval EFI_INVALID_PARAMETER SwSmiInputValue is already be used.

+

+**/

+EFI_STATUS

+SmiInputValueCheck (

+ IN UINTN SwSmiInputValue

+ )

+{

+ LIST_ENTRY *Node;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;

+

+ Node = mSmmSwDispatch2Queue.ForwardLink;

+ for ( ; Node != &mSmmSwDispatch2Queue; Node = Node->ForwardLink) {

+ Dispatch2Context = BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link);

+ if (Dispatch2Context->SwSmiInputValue == SwSmiInputValue) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Register a child SMI source dispatch function for the specified software SMI.

+

+ This service registers a function (DispatchFunction) which will be called when the software

+ SMI source specified by RegContext->SwSmiCpuIndex is detected. On return, DispatchHandle

+ contains a unique handle which may be used later to unregister the function using UnRegister().

+

+ @param[in] This Pointer to the EFI_SMM_SW_DISPATCH2_PROTOCOL instance.

+ @param[in] DispatchFunction Function to register for handler when the specified software

+ SMI is generated.

+ @param[in, out] RegContext Pointer to the dispatch function's context.

+ The caller fills this context in before calling

+ the register function to indicate to the register

+ function which Software SMI input value the

+ dispatch function should be invoked for.

+ @param[out] DispatchHandle Handle generated by the dispatcher to track the

+ function instance.

+

+ @retval EFI_SUCCESS The dispatch function has been successfully

+ registered and the SMI source has been enabled.

+ @retval EFI_DEVICE_ERROR The SW driver was unable to enable the SMI source.

+ @retval EFI_INVALID_PARAMETER RegisterContext is invalid. The SW SMI input value

+ is not within valid range.

+ @retval EFI_OUT_OF_RESOURCES There is not enough memory (system or SMM) to manage this

+ child.

+ @retval EFI_OUT_OF_RESOURCES A unique software SMI value could not be assigned

+ for this dispatch.

+**/

+EFI_STATUS

+EFIAPI

+SmmSwDispatch2Register (

+ IN CONST EFI_SMM_SW_DISPATCH2_PROTOCOL *This,

+ IN EFI_SMM_HANDLER_ENTRY_POINT2 DispatchFunction,

+ IN OUT EFI_SMM_SW_REGISTER_CONTEXT *RegContext,

+ OUT EFI_HANDLE *DispatchHandle

+ )

+{

+ EFI_STATUS Status;

+ UINTN Index;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;

+

+ if (RegContext->SwSmiInputValue == (UINTN)-1) {

+ //

+ // If SwSmiInputValue is set to (UINTN) -1 then a unique value

+ // will be assigned and returned in the structure.

+ //

+ Status = EFI_NOT_FOUND;

+ for (Index = 1; Index < MAXIMUM_SWI_VALUE; Index++) {

+ Status = SmiInputValueCheck (Index);

+ if (!EFI_ERROR (Status)) {

+ RegContext->SwSmiInputValue = Index;

+ break;

+ }

+ }

+

+ if (RegContext->SwSmiInputValue == (UINTN)-1) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+ }

+

+ if ((RegContext->SwSmiInputValue > MAXIMUM_SWI_VALUE) || (RegContext->SwSmiInputValue == 0)) {

+ DEBUG ((DEBUG_ERROR, "ERROR: SMI value range (1 ~ 0x%x)\n", MAXIMUM_SWI_VALUE));

+ return EFI_INVALID_PARAMETER;

+ }

+

+ //

+ // Register

+ //

+ Status = gSmst->SmmAllocatePool (EfiRuntimeServicesData, sizeof (*Context), (VOID **)&Context);

+ ASSERT_EFI_ERROR (Status);

+ if (EFI_ERROR (Status)) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ *DispatchHandle = (EFI_HANDLE)Context;

+ Context->Signature = SMI_SW_HANDLER_SIGNATURE;

+ Context->SwSmiInputValue = RegContext->SwSmiInputValue;

+ Context->DispatchFunction = (UINTN)DispatchFunction;

+ Context->DispatchHandle = *DispatchHandle;

+ InsertTailList (&mSmmSwDispatch2Queue, &Context->Link);

+

+ return Status;

+}

+

+/**

+ Unregister a child SMI source dispatch function for the specified software SMI.

+

+ This service removes the handler associated with DispatchHandle so that it will no longer be

+ called in response to a software SMI.

+

+ @param[in] This Pointer to the EFI_SMM_SW_DISPATCH2_PROTOCOL instance.

+ @param[in] DispatchHandle Handle of dispatch function to deregister.

+

+ @retval EFI_SUCCESS The dispatch function has been successfully unregistered.

+ @retval EFI_INVALID_PARAMETER The DispatchHandle was not valid.

+**/

+EFI_STATUS

+EFIAPI

+SmmSwDispatch2UnRegister (

+ IN CONST EFI_SMM_SW_DISPATCH2_PROTOCOL *This,

+ IN EFI_HANDLE DispatchHandle

+ )

+{

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;

+

+ //

+ // Unregister

+ //

+ Context = FindContextByDispatchHandle (DispatchHandle);

+ ASSERT (Context != NULL);

+ if (Context != NULL) {

+ RemoveEntryList (&Context->Link);

+ gSmst->SmmFreePool (Context);

+ }

+

+ return EFI_SUCCESS;

+}

+

+EFI_SMM_SW_DISPATCH2_PROTOCOL gSmmSwDispatch2 = {

+ SmmSwDispatch2Register,

+ SmmSwDispatch2UnRegister,

+ MAXIMUM_SWI_VALUE

+};

+

+/**

+ Get specified SMI register based on given register ID

+

+ @param[in] SmmRegister SMI related register array from bootloader

+ @param[in] Id The register ID to get.

+

+ @retval NULL The register is not found or the format is not expected.

+ @return smi register

+

+**/

+PLD_GENERIC_REGISTER *

+GetSmmCtrlRegById (

+ IN PLD_SMM_REGISTERS *SmmRegister,

+ IN UINT32 Id

+ )

+{

+ UINT32 Index;

+ PLD_GENERIC_REGISTER *PldReg;

+

+ PldReg = NULL;

+ for (Index = 0; Index < SmmRegister->Count; Index++) {

+ if (SmmRegister->Registers[Index].Id == Id) {

+ PldReg = &SmmRegister->Registers[Index];

+ break;

+ }

+ }

+

+ if (PldReg == NULL) {

+ DEBUG ((DEBUG_INFO, "Register %d not found.\n", Id));

+ return NULL;

+ }

+

+ //

+ // Checking the register if it is expected.

+ //

+ if ((PldReg->Address.AccessSize != EFI_ACPI_3_0_DWORD) ||

+ (PldReg->Address.Address == 0) ||

+ (PldReg->Address.RegisterBitWidth != 1) ||

+ (PldReg->Address.AddressSpaceId != EFI_ACPI_3_0_SYSTEM_IO) ||

+ (PldReg->Value != 1))

+ {

+ DEBUG ((DEBUG_INFO, "Unexpected SMM register.\n"));

+ DEBUG ((DEBUG_INFO, "AddressSpaceId= 0x%x\n", PldReg->Address.AddressSpaceId));

+ DEBUG ((DEBUG_INFO, "RegBitWidth = 0x%x\n", PldReg->Address.RegisterBitWidth));

+ DEBUG ((DEBUG_INFO, "RegBitOffset = 0x%x\n", PldReg->Address.RegisterBitOffset));

+ DEBUG ((DEBUG_INFO, "AccessSize = 0x%x\n", PldReg->Address.AccessSize));

+ DEBUG ((DEBUG_INFO, "Address = 0x%lx\n", PldReg->Address.Address));

+ return NULL;

+ }

+

+ return PldReg;

+}

+

+/**

+ Entry Point for this driver.

+

+ @param[in] ImageHandle Image handle of this driver.

+ @param[in] SystemTable A Pointer to the EFI System Table.

+

+ @retval EFI_SUCCESS The entry point is executed successfully.

+ @retval other Some error occurred when executing this entry point.

+**/

+EFI_STATUS

+EFIAPI

+PchSmiDispatchEntryPoint (

+ IN EFI_HANDLE ImageHandle,

+ IN EFI_SYSTEM_TABLE *SystemTable

+ )

+{

+ EFI_STATUS Status;

+ EFI_HANDLE DispatchHandle;

+ EFI_HOB_GUID_TYPE *GuidHob;

+ PLD_SMM_REGISTERS *SmmRegister;

+ PLD_GENERIC_REGISTER *SmiEosReg;

+ PLD_GENERIC_REGISTER *SmiApmStsReg;

+

+ GuidHob = GetFirstGuidHob (&gSmmRegisterInfoGuid);

+ if (GuidHob == NULL) {

+ return EFI_UNSUPPORTED;

+ }

+

+ SmmRegister = (PLD_SMM_REGISTERS *)GET_GUID_HOB_DATA (GuidHob);

+ SmiEosReg = GetSmmCtrlRegById (SmmRegister, REGISTER_ID_SMI_EOS);

+ if (SmiEosReg == NULL) {

+ DEBUG ((DEBUG_ERROR, "SMI EOS reg not found.\n"));

+ return EFI_NOT_FOUND;

+ }

+

+ mSmiPchReg.SmiEosAddr = (UINT32)SmiEosReg->Address.Address;

+ mSmiPchReg.EosBitOffset = SmiEosReg->Address.RegisterBitOffset;

+

+ SmiApmStsReg = GetSmmCtrlRegById (SmmRegister, REGISTER_ID_SMI_APM_STS);

+ if (SmiApmStsReg == NULL) {

+ DEBUG ((DEBUG_ERROR, "SMI APM status reg not found.\n"));

+ return EFI_NOT_FOUND;

+ }

+

+ mSmiPchReg.SmiApmStsAddr = (UINT32)SmiApmStsReg->Address.Address;

+ mSmiPchReg.ApmBitOffset = SmiApmStsReg->Address.RegisterBitOffset;

+

+ //

+ // Locate PI SMM CPU protocol

+ //

+ Status = gSmst->SmmLocateProtocol (&gEfiSmmCpuProtocolGuid, NULL, (VOID **)&mSmmCpuProtocol);

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Register a SMM handler to handle subsequent SW SMIs.

+ //

+ Status = gSmst->SmiHandlerRegister ((EFI_MM_HANDLER_ENTRY_POINT)SmmSwDispatcher, NULL, &DispatchHandle);

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Publish PI SMM SwDispatch2 Protocol

+ //

+ ImageHandle = NULL;

+ Status = gSmst->SmmInstallProtocolInterface (

+ &ImageHandle,

+ &gEfiSmmSwDispatch2ProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ &gSmmSwDispatch2

+ );

+ ASSERT_EFI_ERROR (Status);

+

+ return Status;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h
new file mode 100644
index 0000000000..c14fe99929
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h
@@ -0,0 +1,36 @@
+/** @file

+ The header file for SMM SwDispatch2 module.

+

+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SMM_SW_DISPATCH2_H_

+#define SMM_SW_DISPATCH2_H_

+

+#include <PiDxe.h>

+#include <Protocol/SmmSwDispatch2.h>

+#include <Protocol/SmmCpu.h>

+#include <Library/UefiDriverEntryPoint.h>

+#include <Library/SmmServicesTableLib.h>

+#include <Library/BaseLib.h>

+#include <Library/IoLib.h>

+#include <Library/DebugLib.h>

+#include <Guid/SmmRegisterInfoGuid.h>

+#include <Library/HobLib.h>

+

+#define SMI_SW_HANDLER_SIGNATURE SIGNATURE_32('s','s','w','h')

+#define MAXIMUM_SWI_VALUE 0xFF

+#define SMM_CONTROL_PORT 0xB2

+#define SMM_DATA_PORT 0xB3

+

+typedef struct {

+ UINTN Signature;

+ LIST_ENTRY Link;

+ EFI_HANDLE DispatchHandle;

+ UINTN SwSmiInputValue;

+ UINTN DispatchFunction;

+} EFI_SMM_SW_DISPATCH2_CONTEXT;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf
new file mode 100644
index 0000000000..96a154e888
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf
@@ -0,0 +1,51 @@
+## @file

+# PCH SMM SMI Software dispatch module.

+#

+# Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = PchSmiDispatchSmm

+ FILE_GUID = 60F343E3-2AE2-4AA7-B01E-BF9BD5C04A3B

+ MODULE_TYPE = DXE_SMM_DRIVER

+ VERSION_STRING = 1.0

+ PI_SPECIFICATION_VERSION = 0x0001000A

+ ENTRY_POINT = PchSmiDispatchEntryPoint

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ PchSmiDispatchSmm.c

+ PchSmiDispatchSmm.h

+

+[Packages]

+ MdePkg/MdePkg.dec

+ UefiPayloadPkg/UefiPayloadPkg.dec

+

+[LibraryClasses]

+ UefiDriverEntryPoint

+ MemoryAllocationLib

+ DebugLib

+ UefiBootServicesTableLib

+ SmmServicesTableLib

+ BaseLib

+ IoLib

+ HobLib

+

+[Protocols]

+ gEfiSmmCpuProtocolGuid # PROTOCOL ALWAYS_CONSUMED

+ gEfiSmmSwDispatch2ProtocolGuid # PROTOCOL ALWAYS_PRODUCED

+

+[Guids]

+ gSmmRegisterInfoGuid

+

+[Depex]

+ gEfiSmmCpuProtocolGuid

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec
new file mode 100644
index 0000000000..549f96d85f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec
@@ -0,0 +1,49 @@
+## @file

+# Payload Platform Package

+#

+# Provides drivers and definitions to create payload platform FV.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ DEC_SPECIFICATION = 0x00010005

+ PACKAGE_NAME = PlatformPayloadPkg

+ PACKAGE_GUID = 17F3ACAC-079D-4518-9EBF-E33289733E8C

+ PACKAGE_VERSION = 0.1

+

+[Includes]

+ Include

+

+[Guids]

+ #

+ ## Defines the token space for the Payload platform Package PCDs.

+ #

+ gPlatformPayloadPkgTokenSpaceGuid = {0xa375ddc6, 0x74fb, 0x4de1, {0x82, 0x6d, 0xa3, 0x10, 0xa3, 0x3b, 0x89, 0x77}}

+

+ #

+ # SPI variable support

+ #

+ gNvVariableInfoGuid = { 0x7a345dca, 0xc26, 0x4f2a, { 0xa8, 0x9a, 0x57, 0xc0, 0x8d, 0xdd, 0x22, 0xee } }

+ gSpiFlashInfoGuid = { 0x2d4aac1b, 0x91a5, 0x4cd5, { 0x9b, 0x5c, 0xb4, 0x0f, 0x5d, 0x28, 0x51, 0xa1 } }

+

+

+################################################################################

+#

+# PCD Declarations section - list of all PCDs Declared by this Package

+# Only this package should be providing the

+# declaration, other packages should not.

+#

+################################################################################

+

+[PcdsFeatureFlag]

+ ## Feature enabling control

+ # @Prompt Enable payload platform FV common for most Intel platforms

+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable|FALSE|BOOLEAN|0x00000001

+

+[PcdsFixedAtBuild, PcdsPatchableInModule]

+ ## FFS filename to find the default variable initial data file.

+ # @Prompt FFS Name of variable initial data file

+ gPlatformPayloadPkgTokenSpaceGuid.PcdNvsDataFile |{ 0x1a, 0xf1, 0xb1, 0xae, 0x42, 0xcc, 0xcf, 0x4e, 0xac, 0x60, 0xdb, 0xab, 0xf6, 0xca, 0x69, 0xe6 }|VOID*|0x00000025

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc
new file mode 100644
index 0000000000..adf028c511
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc
@@ -0,0 +1,110 @@
+## @file

+# platform Payload Package

+#

+# Provides platform specific drivers and definitions to create a platform FV

+# to work with universal UEFI payload to provide support for common Intel platforms.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+################################################################################

+#

+# Defines Section - statements that will be processed to create a Makefile.

+#

+################################################################################

+[Defines]

+ PLATFORM_NAME = PlatformPayloadPkg

+ PLATFORM_GUID = D3C551BE-9BC6-48F5-AA8A-F49425C28CA9

+ PLATFORM_VERSION = 0.1

+ DSC_SPECIFICATION = 0x00010005

+ SUPPORTED_ARCHITECTURES = X64

+ BUILD_TARGETS = DEBUG|RELEASE|NOOPT

+ SKUID_IDENTIFIER = DEFAULT

+ OUTPUT_DIRECTORY = Build/$(PLATFORM_NAME)

+ FLASH_DEFINITION = $(PLATFORM_NAME)/PlatformPayloadPkg.fdf

+ PCD_DYNAMIC_AS_DYNAMICEX = TRUE

+ DXE_ARCH = X64

+

+[Packages]

+ MinPlatformPkg/MinPlatformPkg.dec

+

+################################################################################

+#

+# SKU Identification section - list of all SKU IDs supported by this Platform.

+#

+################################################################################

+[SkuIds]

+ 0|DEFAULT

+

+################################################################################

+#

+# Library Class section - list of all Library Classes needed by this Platform.

+#

+################################################################################

+

+#

+# Since there are no 32b libraries or components in this package, these PCD are specified for 64b only

+#

+[PcdsFeatureFlag]

+ #

+ # PCD needed for MinPlatform build includes

+ #

+ gMinPlatformPkgTokenSpaceGuid.PcdSmiHandlerProfileEnable |FALSE

+ gMinPlatformPkgTokenSpaceGuid.PcdUefiSecureBootEnable |FALSE

+ gMinPlatformPkgTokenSpaceGuid.PcdPerformanceEnable |FALSE

+

+[PcdsPatchableInModule.X64]

+ gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x7

+ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000004F

+!if $(SOURCE_DEBUG_ENABLE)

+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x17

+!else

+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2F

+!endif

+

+ #

+ # The following parameters are set by Library/PlatformHookLib

+ #

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialUseMmio|FALSE

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterBase|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialBaudRate|115200

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterStride|1

+

+################################################################################

+#

+# Pcd DynamicEx Section - list of all EDK II PCD Entries defined by this Platform

+#

+################################################################################

+

+[PcdsDynamicExDefault]

+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0

+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseSize|0

+

+

+#

+# Include common libraries

+#

+!include MinPlatformPkg/Include/Dsc/CoreCommonLib.dsc

+!include MinPlatformPkg/Include/Dsc/CorePeiLib.dsc

+!include MinPlatformPkg/Include/Dsc/CoreDxeLib.dsc

+

+#

+# This package always builds the feature.

+#

+!include Include/PlatformPayloadFeature.dsc

+

+[BuildOptions]

+ *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES

+ GCC:*_UNIXGCC_*_CC_FLAGS = -DMDEPKG_NDEBUG

+ GCC:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG

+ INTEL:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG

+ MSFT:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG

+

+[BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER]

+ GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000

+ XCODE:*_*_*_DLINK_FLAGS = -seg1addr 0x1000 -segalign 0x1000

+ XCODE:*_*_*_MTOC_FLAGS = -align 0x1000

+ CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:4096

+ MSFT:*_*_*_DLINK_FLAGS = /ALIGN:4096

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf
new file mode 100644
index 0000000000..f781a364d7
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf
@@ -0,0 +1,50 @@
+## @file

+# Payload platform Package

+#

+# Provides platform specific drivers and definitions to create a platform FV

+# to work with universal UEF payload.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ DEFINE FD_BASE = 0x00800000

+ DEFINE FD_BLOCK_SIZE = 0x00001000

+

+ !if $(TARGET) == "NOOPT"

+ DEFINE FD_SIZE = 0x00090000

+ DEFINE NUM_BLOCKS = 0x90

+ !else

+ DEFINE FD_SIZE = 0x00050000

+ DEFINE NUM_BLOCKS = 0x50

+ !endif

+

+[FD.PlatformPayload]

+ BaseAddress = $(FD_BASE) | gUefiPayloadPkgTokenSpaceGuid.PcdPayloadFdMemBase

+ Size = $(FD_SIZE) | gUefiPayloadPkgTokenSpaceGuid.PcdPayloadFdMemSize

+ ErasePolarity = 1

+ BlockSize = $(FD_BLOCK_SIZE)

+ NumBlocks = $(NUM_BLOCKS)

+

+ 0x00000000 | $(FD_SIZE)

+ FV = PlatformPayload

+

+[FV.PlatformPayload]

+ !include MinPlatformPkg/Include/Fdf/CommonSpiFvHeaderInfo.fdf

+ FvNameGuid = 96E75986-6FDD-491E-9FD5-35E21AC45B45

+ FvForceRebase = FALSE

+

+ !include Include/PostMemory.fdf

+

+################################################################################

+#

+# Rules are use with the [FV] section's module INF type to define

+# how an FFS file is created for a given INF file. The following Rule are the default

+# rules for the different module type. User can add the customized rules to define the

+# content of the FFS file.

+#

+################################################################################

+

+!include MinPlatformPkg/Include/Fdf/RuleInclude.fdf

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py
new file mode 100644
index 0000000000..1e3e1cce21
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py
@@ -0,0 +1,113 @@
+## @file

+# This file contains the script to build UniversalPayload with platform payload

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+##

+

+import argparse

+import subprocess

+import os

+import shutil

+import sys

+from ctypes import *

+

+sys.dont_write_bytecode = True

+

+def RunCommand(cmd):

+ print(cmd)

+ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,cwd=os.environ['WORKSPACE'])

+ while True:

+ line = p.stdout.readline()

+ if not line:

+ break

+ print(line.strip().decode(errors='ignore'))

+

+ p.communicate()

+ if p.returncode != 0:

+ print("- Failed - error happened when run command: %s"%cmd)

+ raise Exception("ERROR: when run command: %s"%cmd)

+

+def BuildUniversalPayload(Args, MacroList):

+ BuildTarget = Args.Target

+ ToolChain = Args.ToolChain

+ ElfToolChain = 'CLANGDWARF'

+ ObjCopyFlag = "elf64-x86-64" if Args.Arch == 'X64' else "elf32-i386"

+

+ #

+ # Find universal UEFI payload build build script

+ #

+ Edk2PayloadBuildScript = os.path.normpath("UefiPayloadPkg/UniversalPayloadBuild.py")

+ for package_path in os.environ['PACKAGES_PATH'].split(';'):

+ if os.path.exists (os.path.join (package_path, Edk2PayloadBuildScript)):

+ Edk2PayloadBuildScript = os.path.join (package_path, Edk2PayloadBuildScript)

+ break

+ if not os.path.exists (Edk2PayloadBuildScript):

+ raise Exception("Could not find universal UEFI payload build script UniversalPayloadBuild.py")

+

+ PlatformFvDscPath = os.path.normpath("PlatformPayloadPkg/PlatformPayloadPkg.dsc")

+ BuildDir = os.path.join(os.environ['WORKSPACE'], os.path.normpath("Build/UefiPayloadPkgX64"))

+ PlatformFvReportPath = os.path.join(BuildDir, "PlatformPayloadReport.txt")

+ UniversalUefiPld = os.path.join(BuildDir, 'UniversalPayload.elf')

+ PlatformFv = os.path.join(os.environ['WORKSPACE'], os.path.normpath("Build/PlatformPayloadPkg"), f"{BuildTarget}_{ToolChain}", os.path.normpath("FV/PlatformPayload.Fv"))

+

+ if "CLANG_BIN" in os.environ:

+ LlvmObjcopyPath = os.path.join(os.environ["CLANG_BIN"], "llvm-objcopy")

+ else:

+ LlvmObjcopyPath = "llvm-objcopy"

+ try:

+ RunCommand('"%s" --version'%LlvmObjcopyPath)

+ except:

+ print("- Failed - Please check if LLVM is installed or if CLANG_BIN is set correctly")

+ sys.exit(1)

+

+ Defines = ""

+ for key in MacroList:

+ Defines +=" -D {0}={1}".format(key, MacroList[key])

+

+ #

+ # Building Universal Payload entry.

+ #

+ if not Args.Skip:

+ BuildPayload = f"python {Edk2PayloadBuildScript} -b {BuildTarget} -t {ToolChain} -a {Args.Arch} {Defines}"

+ RunCommand(BuildPayload)

+

+ #

+ # Building Platform Payload.

+ #

+ BuildPayload = f"build -p {PlatformFvDscPath} -b {BuildTarget} -a X64 -t {ToolChain} -y {PlatformFvReportPath}"

+ BuildPayload += Defines

+ RunCommand(BuildPayload)

+

+ #

+ # Copy the Platform Payload as a section in elf format Universal Payload.

+ #

+ remove_section = f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyFlag} --remove-section .upld.platform_fv {UniversalUefiPld}'

+ add_section = f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyFlag} --add-section .upld.platform_fv={PlatformFv} {UniversalUefiPld}'

+ set_section = f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyFlag} --set-section-alignment .upld.platform_fv=16 {UniversalUefiPld}'

+ RunCommand(remove_section)

+ RunCommand(add_section)

+ RunCommand(set_section)

+

+

+def main():

+ parser = argparse.ArgumentParser(description='Build Platform Payload FV and add it to Universal UEFI Payload')

+ parser.add_argument('-t', '--ToolChain')

+ parser.add_argument('-b', '--Target', default='DEBUG')

+ parser.add_argument('-a', '--Arch', choices=['IA32', 'X64'], help='Specify the ARCH for payload entry module. Default build X64 image.', default ='X64')

+ parser.add_argument("-D", "--Macro", action="append")

+ parser.add_argument('-s', '--Skip', action='store_true', help='Skip Universal UEFI payload build (just build platform FV and add to Universal UEFI payload.')

+ MacroList = {}

+ args = parser.parse_args()

+ if args.Macro is not None:

+ for Argument in args.Macro:

+ if Argument.count('=') != 1:

+ print("Unknown variable passed in: %s"%Argument)

+ raise Exception("ERROR: Unknown variable passed in: %s"%Argument)

+ tokens = Argument.strip().split('=')

+ MacroList[tokens[0].upper()] = tokens[1]

+ BuildUniversalPayload(args, MacroList)

+ print ("Successfully build Universal Payload with platform FV")

+

+if __name__ == '__main__':

+ main()

diff --git a/Features/Intel/PlatformPayloadPkg/Readme.md b/Features/Intel/PlatformPayloadPkg/Readme.md
new file mode 100644
index 0000000000..10e863b5e0
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Readme.md
@@ -0,0 +1,96 @@
+# Overview

+* **Feature Name:** Platform Payload

+* **PI Phase(s) Supported:** SMM DXE

+

+## Purpose

+This package provides a common platform payload which is expected to work on most

+Intel platforms with a bootloader.

+

+# High-Level Theory of Operation

+Bootloader initialize memory/silicon/platform and payload focus on boot media initializaiton

+and OS boot. Payload is expected to be re-used on different Platforms.

+

+In the reality, some payload modules have platform dependency (e.g. only for Intel PCH)

+or bootloader dependency (only for coreboot). These modules would be located in

+edk2-platform repo.

+

+The generic UEFI payload could be built from EDK2 UefiPayloadPkg in ELF format following

+universal payload specification. And a Platform Payload could be built from PlatformPayloadPkg

+to provide Intel platform specific features (e.g. SPI module, PCH SMM) in FV/FD format.

+This platform payload could be inserted into universal UEFI payload as an ELF section

+to generate a full-feature payload.

+## Firmware Volumes

+* FvPlatformPayload

+

+## Build Flows

+use windows host as example to generate a full-feature payload:

+

+** Setup the build env

+set WORKSPACE=c:\payload

+set PACKAGES_PATH=%WORKSPACE%\edk2;%WORKSPACE%\edk2-platforms\Features\Intel;

+ %WORKSPACE%\edk2-platforms\Platform\Intel

+edk2\edksetup.bat

+

+** Build universal UEFI payload with platform Payload

+python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg.py -t VS2019

+ -D SMM_SUPPORT=TRUE -DVARIABLE_SUPPORT=NONE -D SMM_VARIABLE=TRUE

+or

+python edk2\UefiPayloadPkg\UniversalPayloadBuild.py -t VS2019 -D SMM_SUPPORT=TRUE -DVARIABLE_SUPPORT=NONE

+python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg.py -t VS2019 -D SMM_VARIABLE=TRUE -s

+

+ If build success, the final UEFI payload is at Build\UefiPayloadPkgX64\UniversalPayload.elf.

+

+## Features

+

+1. Modules

+Currently only SMM veriable feature is available.

+Several build macros are used as below for SMM variable feature modules.

+!if $(SMM_VARIABLE) == TRUE

+ ## PchSmiDispatchSmm

+ ## FvbSmm

+ ## FaultTolerantWriteSmm

+ ## VariableSmm

+ ## VariableSmmRuntimeDxe

+!endif

+

+2. Data Flows

+SMM variable:

+The interface with bootloader are defined in PlatformPayloadPkg\Include\Guid

+SpiFlashInfoGuid.h -- SPI related information for SPI flash operation.

+NvVariableInfoGuid.h -- Variable related information for SPI NV variables.

+

+## Control Flows

+EDK2 DXE/SMM core from universal UEFI payload would dispatch all the modules

+from this platform payload.

+

+## Test Point Results

+*_TODO_*

+The test(s) that can verify porting is complete for the feature.

+

+Each feature must describe at least one test point to verify the feature is successful. If the test point is not

+implemented, this should be stated.

+

+## Functional Exit Criteria

+*_TODO_*

+The testable functionality for the feature.

+

+This section should provide an ordered list of criteria that a board integrator can reference to ensure the feature is

+functional on their board.

+

+## Feature Enabling Checklist

+*_TODO_*

+An ordered list of required activities to achieve desired functionality for the feature.

+

+## Performance Impact

+A general expectation for the impact on overall boot performance due to using this feature.

+

+This section is expected to provide guidance on:

+* How to estimate performance impact due to the feature

+* How to measure performance impact of the feature

+* How to manage performance impact of the feature

+

+## Common Optimizations

+*_TODO_*

+Common size or performance tuning options for this feature.

+

+This section is recommended but not required. If not used, the contents should be left empty.

--
2.35.1.windows.2


Chaganty, Rangasai V
 

Reviewed-by: Sai Chaganty <rangasai.v.chaganty@...>

-----Original Message-----
From: Oram, Isaac W <isaac.w.oram@...>
Sent: Tuesday, May 10, 2022 4:41 PM
To: Dong, Guo <guo.dong@...>; devel@edk2.groups.io
Cc: Kinney, Michael D <michael.d.kinney@...>; Ni, Ray <ray.ni@...>; Rhodes, Sean <sean@...>; Desimone, Nathaniel L <nathaniel.l.desimone@...>; Chaganty, Rangasai V <rangasai.v.chaganty@...>; Gao, Liming <gaoliming@...>; Oram, Isaac W <isaac.w.oram@...>
Subject: RE: [edk2-devel][edk2-platforms][PATCH V2 1/1] Features/Intel/PlatformPayloadPkg: add platform payload FV

Added Features/Intel maintainers for review.

-----Original Message-----
From: Dong, Guo <guo.dong@...>
Sent: Friday, May 6, 2022 5:49 PM
To: devel@edk2.groups.io
Cc: Dong, Guo <guo.dong@...>; Kinney, Michael D <michael.d.kinney@...>; Ni, Ray <ray.ni@...>; Rhodes, Sean <sean@...>; Oram, Isaac W <isaac.w.oram@...>
Subject: [edk2-devel][edk2-platforms][PATCH V2 1/1] Features/Intel/PlatformPayloadPkg: add platform payload FV

From: Guo Dong <guo.dong@...>

UefiPayloadPkg in EDK2 repo was added SMM variable support for Intel
platform with SPI flash. But some of the modules for SMM variable are
Intel PCH specific (e.g. SPI library, SMM PCH module), so move these
modules into edk2-platforms repo.

A platform payload FV could be built from PlatformPayloadPkg which works
on Intel platforms (e.g.. ICX, APL, CML, CFL, KBL, TGL, ADL, etc.) with
SMM variable. This platform payload FV could be added into universal UEFI
payload built from EDK2 UefiPayloadPkg.

The steps to build a complete payload (use windows host as example):

set WORKSPACE=c:\payload
set PACKAGES_PATH=C:\payload\edk2;C:\payload\edk2-platforms\Platform\Intel;
C:\payload\edk2-platforms\Features\Intel;
edk2\edksetup.bat

python edk2\UefiPayloadPkg\UniversalPayloadBuild.py -t VS2019
-D SMM_SUPPORT=TRUE -DVARIABLE_SUPPORT=NONE

python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg.py
-t VS2019 -D SMM_VARIABLE=TRUE -s

The final UEFI payload generated at Build\UefiPayloadPkgX64\UniversalPayload.elf
if build success.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Ray Ni <ray.ni@...>
Cc: Sean Rhodes <sean@...>
Signed-off-by: Guo Dong <guo.dong@...>
Signed-off-by: Isaac Oram <isaac.w.oram@...>
---
Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc | 5 +++++
Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf | 7 ++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c | 1088 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h | 185 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c | 139 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h | 24 +++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h | 38 ++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h | 213 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc | 112 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf | 20 +++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf | 8 +++++++
Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c | 160 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf | 38 ++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf | 50 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c | 170 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h | 120 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h | 203 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c | 874 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf | 48 +++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c | 455 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h | 36 +++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf | 51 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec | 49 ++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc | 110 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf | 50 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py | 113 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Readme.md | 96 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
35 files changed, 4887 insertions(+)

diff --git a/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc b/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
index 28530b8c67..17cc3224b7 100644
--- a/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
@@ -80,6 +80,11 @@
gUserAuthFeaturePkgTokenSpaceGuid.PcdUserAuthenticationFeatureEnable |TRUE

gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable |TRUE



+ #

+ # Individual features

+ #

+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable |TRUE

+

#

# PCD that are required to be set by the build target should be configured here for test purposes

# These settings are only for the purposes of buildings, boards should follow instructions in Readme files.

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
index 2b36938df6..2a93ca1ec7 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
@@ -75,3 +75,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/VirtualKeyboardFeature.dsc

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc

+!endif

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
index e214175eda..8e98154f3e 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
@@ -53,6 +53,11 @@
UserAuthFeaturePkg/UserAuthFeaturePkg.dec

VirtualKeyboardFeaturePkg/VirtualKeyboardFeaturePkg.dec



+ #

+ # Individual features

+ #

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

#

# The section below sets all PCDs to FALSE in this DSC file so the feature is not enabled by default.

# Board can set PCDs to TRUE in its DSC file to enable a subset of advanced features

@@ -76,6 +81,8 @@
gUserAuthFeaturePkgTokenSpaceGuid.PcdUserAuthenticationFeatureEnable |FALSE

gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable |FALSE



+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable |FALSE

+

#

# There seems to be some build parsing odd behavior that requires this PCD to be specified even though

# the *.fdf that consumes it is dependent on the feature flag.

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf b/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
index 99089f9a7b..a0975d4d43 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
+++ b/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
@@ -76,3 +76,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/PostMemory.fdf

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PostMemory.fdf

+!endif

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf b/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
index 1db258446a..b2b821c9c4 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
+++ b/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
@@ -76,3 +76,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/PreMemory.fdf

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PreMemory.fdf

+!endif

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c b/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c
new file mode 100644
index 0000000000..d6dcfeb4e1
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c
@@ -0,0 +1,77 @@
+/** @file

+

+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiDxe.h>

+#include <Protocol/FirmwareVolumeBlock.h>

+#include <Library/PcdLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseLib.h>

+#include <Guid/FirmwareFileSystem2.h>

+#include <Guid/SystemNvDataGuid.h>

+

+#define FVB_MEDIA_BLOCK_SIZE 0x1000

+

+typedef struct {

+ EFI_FIRMWARE_VOLUME_HEADER FvInfo;

+ EFI_FV_BLOCK_MAP_ENTRY End[1];

+} EFI_FVB2_MEDIA_INFO;

+

+//

+// This data structure contains a template of FV header which is used to restore

+// Fv header if it's corrupted.

+//

+EFI_FVB2_MEDIA_INFO mFvbMediaInfo = {

+ {

+ { 0, }, // ZeroVector[16]

+ EFI_SYSTEM_NV_DATA_FV_GUID,

+ 0,

+ EFI_FVH_SIGNATURE,

+ 0x0004feff, // check PiFirmwareVolume.h for details on EFI_FVB_ATTRIBUTES_2

+ sizeof (EFI_FIRMWARE_VOLUME_HEADER) + sizeof (EFI_FV_BLOCK_MAP_ENTRY),

+ 0, // CheckSum which will be calucated dynamically.

+ 0, // ExtHeaderOffset

+ { 0, },

+ EFI_FVH_REVISION,

+ {

+ {

+ 0,

+ FVB_MEDIA_BLOCK_SIZE,

+ }

+ }

+ },

+ {

+ {

+ 0,

+ 0

+ }

+ }

+};

+

+

+/**

+ Get a heathy FV header used for variable store recovery

+

+ @retval The FV header.

+

+**/

+EFI_FIRMWARE_VOLUME_HEADER *

+GetFvHeaderTemplate (

+ VOID

+ )

+{

+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;

+ UINTN FvSize;

+

+ FvSize = PcdGet32 (PcdFlashNvStorageFtwSpareSize) * 2;

+ FvHeader = &mFvbMediaInfo.FvInfo;

+ FvHeader->FvLength = FvSize;

+ FvHeader->BlockMap[0].NumBlocks = (UINT32)(FvSize / FvHeader->BlockMap[0].Length);

+ FvHeader->Checksum = 0;

+ FvHeader->Checksum = CalculateCheckSum16 ((UINT16 *)FvHeader, FvHeader->HeaderLength);

+

+ return FvHeader;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c
new file mode 100644
index 0000000000..1d19f3726b
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c
@@ -0,0 +1,1088 @@
+/** @file

+Firmware Volume Block Driver to provide FVB service.

+

+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include "FvbService.h"

+

+//

+// Global variable for this FVB driver which contains

+// the private data of all firmware volume block instances

+//

+FWB_GLOBAL mFvbModuleGlobal;

+

+FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate = {

+ {

+ {

+ HARDWARE_DEVICE_PATH,

+ HW_MEMMAP_DP,

+ {

+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH)),

+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH) >> 8)

+ }

+ },

+ EfiMemoryMappedIO,

+ (EFI_PHYSICAL_ADDRESS)0,

+ (EFI_PHYSICAL_ADDRESS)0,

+ },

+ {

+ END_DEVICE_PATH_TYPE,

+ END_ENTIRE_DEVICE_PATH_SUBTYPE,

+ {

+ END_DEVICE_PATH_LENGTH,

+ 0

+ }

+ }

+};

+

+FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate = {

+ {

+ {

+ MEDIA_DEVICE_PATH,

+ MEDIA_PIWG_FW_VOL_DP,

+ {

+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH)),

+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH) >> 8)

+ }

+ },

+ { 0 }

+ },

+ {

+ END_DEVICE_PATH_TYPE,

+ END_ENTIRE_DEVICE_PATH_SUBTYPE,

+ {

+ END_DEVICE_PATH_LENGTH,

+ 0

+ }

+ }

+};

+

+EFI_FW_VOL_BLOCK_DEVICE mFvbDeviceTemplate = {

+ FVB_DEVICE_SIGNATURE,

+ NULL,

+ 0, // Instance

+ {

+ FvbProtocolGetAttributes,

+ FvbProtocolSetAttributes,

+ FvbProtocolGetPhysicalAddress,

+ FvbProtocolGetBlockSize,

+ FvbProtocolRead,

+ FvbProtocolWrite,

+ FvbProtocolEraseBlocks,

+ NULL

+ } // FwVolBlockInstance

+};

+

+/**

+ Get the pointer to EFI_FW_VOL_INSTANCE from the buffer pointed

+ by mFvbModuleGlobal.FvInstance based on a index.

+ Each EFI_FW_VOL_INSTANCE is with variable length as

+ we have a block map at the end of the EFI_FIRMWARE_VOLUME_HEADER.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+

+ @return A pointer to EFI_FW_VOL_INSTANCE.

+

+**/

+EFI_FW_VOL_INSTANCE *

+GetFvbInstance (

+ IN UINTN Instance

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwhRecord;

+

+ if ( Instance >= mFvbModuleGlobal.NumFv ) {

+ ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER);

+ return NULL;

+ }

+

+ //

+ // Find the right instance of the FVB private data

+ //

+ FwhRecord = mFvbModuleGlobal.FvInstance;

+ while ( Instance > 0 ) {

+ FwhRecord = (EFI_FW_VOL_INSTANCE *)((UINTN)((UINT8 *)FwhRecord) +

+ FwhRecord->VolumeHeader.HeaderLength +

+ (sizeof (EFI_FW_VOL_INSTANCE) - sizeof (EFI_FIRMWARE_VOLUME_HEADER)));

+ Instance--;

+ }

+

+ return FwhRecord;

+}

+

+/**

+ Get the EFI_FVB_ATTRIBUTES_2 of a FV.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+

+ @retval EFI_FVB_ATTRIBUTES_2 of the FV identified by Instance.

+

+**/

+STATIC

+EFI_FVB_ATTRIBUTES_2

+FvbGetVolumeAttributes (

+ IN UINTN Instance

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwInstance;

+

+ FwInstance = GetFvbInstance (Instance);

+ ASSERT (FwInstance != NULL);

+

+ if (FwInstance == NULL) {

+ return 0;

+ }

+

+ return FwInstance->VolumeHeader.Attributes;

+}

+

+/**

+ Retrieves the starting address of an LBA in an FV. It also

+ return a few other attribut of the FV.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+ @param[in] Lba The logical block address

+ @param[out] LbaAddress On output, contains the physical starting address

+ of the Lba

+ @param[out] LbaLength On output, contains the length of the block

+ @param[out] NumOfBlocks A pointer to a caller allocated UINTN in which the

+ number of consecutive blocks starting with Lba is

+ returned. All blocks in this range have a size of

+ BlockSize

+

+ @retval EFI_SUCCESS Successfully returns

+ @retval EFI_INVALID_PARAMETER Instance not found

+

+**/

+STATIC

+EFI_STATUS

+FvbGetLbaAddress (

+ IN UINTN Instance,

+ IN EFI_LBA Lba,

+ OUT UINTN *LbaAddress,

+ OUT UINTN *LbaLength,

+ OUT UINTN *NumOfBlocks

+ )

+{

+ UINT32 NumBlocks;

+ UINT32 BlockLength;

+ UINTN Offset;

+ EFI_LBA StartLba;

+ EFI_LBA NextLba;

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;

+

+ //

+ // Find the right instance of the FVB private data

+ //

+ FwhInstance = GetFvbInstance (Instance);

+ if (FwhInstance == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ StartLba = 0;

+ Offset = 0;

+ BlockMap = &FwhInstance->VolumeHeader.BlockMap[0];

+ ASSERT (BlockMap != NULL);

+

+ //

+ // Parse the blockmap of the FV to find which map entry the Lba belongs to

+ //

+ while (TRUE) {

+ if ( BlockMap != NULL) {

+ NumBlocks = BlockMap->NumBlocks;

+ BlockLength = BlockMap->Length;

+ }

+

+ if ((NumBlocks == 0) || (BlockLength == 0)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ NextLba = StartLba + NumBlocks;

+

+ //

+ // The map entry found

+ //

+ if ((Lba >= StartLba) && (Lba < NextLba)) {

+ Offset = Offset + (UINTN)MultU64x32 ((Lba - StartLba), BlockLength);

+ if (LbaAddress != NULL) {

+ *LbaAddress = FwhInstance->FvBase + Offset;

+ }

+

+ if (LbaLength != NULL) {

+ *LbaLength = BlockLength;

+ }

+

+ if (NumOfBlocks != NULL) {

+ *NumOfBlocks = (UINTN)(NextLba - Lba);

+ }

+

+ return EFI_SUCCESS;

+ }

+

+ StartLba = NextLba;

+ Offset = Offset + NumBlocks * BlockLength;

+ BlockMap++;

+ }

+}

+

+/**

+ Reads specified number of bytes into a buffer from the specified block

+

+ @param[in] Instance The FV instance to be read from

+ @param[in] Lba The logical block address to be read from

+ @param[in] BlockOffset Offset into the block at which to begin reading

+ @param[in, out] NumBytes Pointer that on input contains the total size of

+ the buffer. On output, it contains the total number

+ of bytes read

+ @param[in] Buffer Pointer to a caller allocated buffer that will be

+ used to hold the data read

+

+

+ @retval EFI_SUCCESS The firmware volume was read successfully and

+ contents are in Buffer

+ @retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes returned

+ in Buffer

+ @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be read

+ @retval EFI_INVALID_PARAMETER Instance not found, or NumBytes, Buffer are NULL

+

+**/

+STATIC

+EFI_STATUS

+FvbReadBlock (

+ IN UINTN Instance,

+ IN EFI_LBA Lba,

+ IN UINTN BlockOffset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+ UINTN LbaAddress;

+ UINTN LbaLength;

+ EFI_STATUS Status;

+ EFI_STATUS ReadStatus;

+

+ if ((NumBytes == NULL) || (Buffer == NULL)) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ if (*NumBytes == 0) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ Attributes = FvbGetVolumeAttributes (Instance);

+

+ if ((Attributes & EFI_FVB2_READ_STATUS) == 0) {

+ return (EFI_ACCESS_DENIED);

+ }

+

+ if (BlockOffset > LbaLength) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ if (LbaLength < (*NumBytes + BlockOffset)) {

+ *NumBytes = (UINT32)(LbaLength - BlockOffset);

+ Status = EFI_BAD_BUFFER_SIZE;

+ }

+

+ ReadStatus = LibFvbFlashDeviceRead (LbaAddress + BlockOffset, NumBytes, Buffer);

+ if (EFI_ERROR (ReadStatus)) {

+ return ReadStatus;

+ }

+

+ return Status;

+}

+

+/**

+ Writes specified number of bytes from the input buffer to the block

+

+ @param[in] Instance The FV instance to be written to

+ @param[in] Lba The starting logical block index to write to

+ @param[in] BlockOffset Offset into the block at which to begin writing

+ @param[in, out] NumBytes Pointer that on input contains the total size of

+ the buffer. On output, it contains the total number

+ of bytes actually written

+ @param[in] Buffer Pointer to a caller allocated buffer that contains

+ the source for the write

+ @retval EFI_SUCCESS The firmware volume was written successfully

+ @retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes

+ actually written

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written

+ @retval EFI_INVALID_PARAMETER Instance not found, or NumBytes, Buffer are NULL

+

+**/

+EFI_STATUS

+FvbWriteBlock (

+ IN UINTN Instance,

+ IN EFI_LBA Lba,

+ IN UINTN BlockOffset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+ UINTN LbaAddress;

+ UINTN LbaLength;

+ EFI_STATUS Status;

+

+ if ((NumBytes == NULL) || (Buffer == NULL)) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ if (*NumBytes == 0) {

+ return (EFI_INVALID_PARAMETER);

+ }

+

+ Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ //

+ // Check if the FV is write enabled

+ //

+ Attributes = FvbGetVolumeAttributes (Instance);

+ if ((Attributes & EFI_FVB2_WRITE_STATUS) == 0) {

+ return EFI_ACCESS_DENIED;

+ }

+

+ //

+ // Perform boundary checks and adjust NumBytes

+ //

+ if (BlockOffset > LbaLength) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ if ( LbaLength < (*NumBytes + BlockOffset)) {

+ DEBUG ((

+ DEBUG_ERROR,

+ "FvWriteBlock: Reducing Numbytes from 0x%x to 0x%x\n",

+ *NumBytes,

+ (UINT32)(LbaLength - BlockOffset)

+ ));

+ *NumBytes = (UINT32)(LbaLength - BlockOffset);

+ return EFI_BAD_BUFFER_SIZE;

+ }

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, FALSE);

+ Status = LibFvbFlashDeviceWrite (LbaAddress + BlockOffset, NumBytes, Buffer);

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, TRUE);

+ WriteBackInvalidateDataCacheRange ((VOID *)(LbaAddress + BlockOffset), *NumBytes);

+ return Status;

+}

+

+/**

+ Erases and initializes a firmware volume block

+

+ @param[in] Instance The FV instance to be erased

+ @param[in] Lba The logical block index to be erased

+

+ @retval EFI_SUCCESS The erase request was successfully completed

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written. Firmware device may have been

+ partially erased

+ @retval EFI_INVALID_PARAMETER Instance not found

+

+**/

+EFI_STATUS

+FvbEraseBlock (

+ IN UINTN Instance,

+ IN EFI_LBA Lba

+ )

+{

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+ UINTN LbaAddress;

+ UINTN LbaLength;

+ EFI_STATUS Status;

+

+ //

+ // Check if the FV is write enabled

+ //

+ Attributes = FvbGetVolumeAttributes (Instance);

+

+ if ((Attributes & EFI_FVB2_WRITE_STATUS) == 0) {

+ return (EFI_ACCESS_DENIED);

+ }

+

+ //

+ // Get the starting address of the block for erase.

+ //

+ Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, FALSE);

+

+ Status = LibFvbFlashDeviceBlockErase (LbaAddress, LbaLength);

+

+ LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, TRUE);

+

+ WriteBackInvalidateDataCacheRange ((VOID *)LbaAddress, LbaLength);

+

+ return Status;

+}

+

+/**

+ Modifies the current settings of the firmware volume according to the

+ input parameter, and returns the new setting of the volume

+

+ @param[in] Instance The FV instance whose attributes is going to be

+ modified

+ @param[in, out] Attributes On input, it is a pointer to EFI_FVB_ATTRIBUTES_2

+ containing the desired firmware volume settings.

+ On successful return, it contains the new settings

+ of the firmware volume

+

+ @retval EFI_SUCCESS Successfully returns

+ @retval EFI_ACCESS_DENIED The volume setting is locked and cannot be modified

+ @retval EFI_INVALID_PARAMETER Instance not found, or The attributes requested are

+ in conflict with the capabilities as declared in the

+ firmware volume header

+

+**/

+STATIC

+EFI_STATUS

+FvbSetVolumeAttributes (

+ IN UINTN Instance,

+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+ EFI_FVB_ATTRIBUTES_2 OldAttributes;

+ EFI_FVB_ATTRIBUTES_2 *AttribPtr;

+ EFI_FVB_ATTRIBUTES_2 UnchangedAttributes;

+ UINT32 Capabilities;

+ UINT32 OldStatus;

+ UINT32 NewStatus;

+

+ //

+ // Find the right instance of the FVB private data

+ //

+ FwhInstance = GetFvbInstance (Instance);

+ if (FwhInstance == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ AttribPtr = (EFI_FVB_ATTRIBUTES_2 *)&(FwhInstance->VolumeHeader.Attributes);

+ ASSERT (AttribPtr != NULL);

+ if ( AttribPtr == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ OldAttributes = *AttribPtr;

+ Capabilities = OldAttributes & EFI_FVB2_CAPABILITIES;

+ OldStatus = OldAttributes & EFI_FVB2_STATUS;

+ NewStatus = *Attributes & EFI_FVB2_STATUS;

+

+ UnchangedAttributes = EFI_FVB2_READ_DISABLED_CAP | \

+ EFI_FVB2_READ_ENABLED_CAP | \

+ EFI_FVB2_WRITE_DISABLED_CAP | \

+ EFI_FVB2_WRITE_ENABLED_CAP | \

+ EFI_FVB2_LOCK_CAP | \

+ EFI_FVB2_STICKY_WRITE | \

+ EFI_FVB2_MEMORY_MAPPED | \

+ EFI_FVB2_ERASE_POLARITY | \

+ EFI_FVB2_READ_LOCK_CAP | \

+ EFI_FVB2_WRITE_LOCK_CAP | \

+ EFI_FVB2_ALIGNMENT;

+

+ //

+ // Some attributes of FV is read only can *not* be set

+ //

+ if ((OldAttributes & UnchangedAttributes) ^ (*Attributes & UnchangedAttributes)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ //

+ // If firmware volume is locked, no status bit can be updated

+ //

+ if ((OldAttributes & EFI_FVB2_LOCK_STATUS) != 0) {

+ if ((OldStatus ^ NewStatus) != 0) {

+ return EFI_ACCESS_DENIED;

+ }

+ }

+

+ //

+ // Test read disable

+ //

+ if ((Capabilities & EFI_FVB2_READ_DISABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_READ_STATUS) == 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test read enable

+ //

+ if ((Capabilities & EFI_FVB2_READ_ENABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_READ_STATUS) != 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test write disable

+ //

+ if ((Capabilities & EFI_FVB2_WRITE_DISABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_WRITE_STATUS) == 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test write enable

+ //

+ if ((Capabilities & EFI_FVB2_WRITE_ENABLED_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_WRITE_STATUS) != 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ //

+ // Test lock

+ //

+ if ((Capabilities & EFI_FVB2_LOCK_CAP) == 0) {

+ if ((NewStatus & EFI_FVB2_LOCK_STATUS) != 0) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ *AttribPtr = (*AttribPtr) & (0xFFFFFFFF & (~EFI_FVB2_STATUS));

+ *AttribPtr = (*AttribPtr) | NewStatus;

+ *Attributes = *AttribPtr;

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Retrieves the physical address of the device.

+

+ @param[in] This A pointer to EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL.

+ @param[out] Address Output buffer containing the address.

+

+ @retval EFI_SUCCESS The function always return successfully.

+ @retval EFI_INVALID_PARAMETER Instance not found.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolGetPhysicalAddress (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_PHYSICAL_ADDRESS *Address

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ FwhInstance = GetFvbInstance (FvbDevice->Instance);

+ if (FwhInstance == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ *Address = FwhInstance->FvBase;

+ return EFI_SUCCESS;

+}

+

+/**

+ Retrieve the size of a logical block

+

+ @param[in] This Calling context

+ @param[in] Lba Indicates which block to return the size for.

+ @param[out] BlockSize A pointer to a caller allocated UINTN in which

+ the size of the block is returned

+ @param[out] NumOfBlocks A pointer to a caller allocated UINTN in which the

+ number of consecutive blocks starting with Lba is

+ returned. All blocks in this range have a size of

+ BlockSize

+

+ @retval EFI_SUCCESS The function always return successfully.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolGetBlockSize (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ OUT UINTN *BlockSize,

+ OUT UINTN *NumOfBlocks

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ return FvbGetLbaAddress (FvbDevice->Instance, Lba, NULL, BlockSize, NumOfBlocks);

+}

+

+/**

+ Retrieves Volume attributes. No polarity translations are done.

+

+ @param[in] This Calling context

+ @param[out] Attributes Output buffer which contains attributes

+

+ @retval EFI_SUCCESS The function always return successfully.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolGetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ *Attributes = FvbGetVolumeAttributes (FvbDevice->Instance);

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Sets Volume attributes. No polarity translations are done.

+

+ @param[in] This Calling context

+ @param[in, out] Attributes Output buffer which contains attributes

+

+ @retval EFI_SUCCESS The function always return successfully.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolSetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ )

+{

+ EFI_STATUS Status;

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ Status = FvbSetVolumeAttributes (FvbDevice->Instance, Attributes);

+ return Status;

+}

+

+/**

+ This function erases one or more blocks as denoted by the

+ variable argument list. The entire parameter list of blocks must be verified

+ prior to erasing any blocks. If a block is requested that does not exist

+ within the associated firmware volume (it has a larger index than the last

+ block of the firmware volume), the EraseBlock() function must return

+ EFI_INVALID_PARAMETER without modifying the contents of the firmware volume.

+

+ @param[in] This Calling context

+ @param[in] ... Starting LBA followed by Number of Lba to erase.

+ a -1 to terminate the list.

+

+ @retval EFI_SUCCESS The erase request was successfully completed

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written. Firmware device may have been

+ partially erased

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolEraseBlocks (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ ...

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+ UINTN NumOfBlocks;

+ VA_LIST args;

+ EFI_LBA StartingLba;

+ UINTN NumOfLba;

+ EFI_STATUS Status;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ FwhInstance = GetFvbInstance (FvbDevice->Instance);

+ if (FwhInstance == NULL) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ NumOfBlocks = FwhInstance->NumOfBlocks;

+ VA_START (args, This);

+

+ do {

+ StartingLba = VA_ARG (args, EFI_LBA);

+ if ( StartingLba == EFI_LBA_LIST_TERMINATOR ) {

+ break;

+ }

+

+ NumOfLba = VA_ARG (args, UINT32);

+

+ //

+ // Check input parameters

+ //

+ if (NumOfLba == 0) {

+ VA_END (args);

+ return EFI_INVALID_PARAMETER;

+ }

+

+ if ((StartingLba + NumOfLba) > NumOfBlocks ) {

+ return EFI_INVALID_PARAMETER;

+ }

+ } while (1);

+

+ VA_END (args);

+

+ VA_START (args, This);

+ do {

+ StartingLba = VA_ARG (args, EFI_LBA);

+ if (StartingLba == EFI_LBA_LIST_TERMINATOR) {

+ break;

+ }

+

+ NumOfLba = VA_ARG (args, UINT32);

+

+ while ( NumOfLba > 0 ) {

+ Status = FvbEraseBlock (FvbDevice->Instance, StartingLba);

+ if ( EFI_ERROR (Status)) {

+ VA_END (args);

+ return Status;

+ }

+

+ StartingLba++;

+ NumOfLba--;

+ }

+ } while (1);

+

+ VA_END (args);

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Writes data beginning at Lba:Offset from FV. The write terminates either

+ when *NumBytes of data have been written, or when a block boundary is

+ reached. *NumBytes is updated to reflect the actual number of bytes

+ written. The write opertion does not include erase. This routine will

+ attempt to write only the specified bytes. If the writes do not stick,

+ it will return an error.

+

+ @param[in] This Calling context

+ @param[in] Lba Block in which to begin write

+ @param[in] Offset Offset in the block at which to begin write

+ @param[in,out] NumBytes On input, indicates the requested write size. On

+ output, indicates the actual number of bytes written

+ @param[in] Buffer Buffer containing source data for the write.

+

+ @retval EFI_SUCCESS The firmware volume was written successfully

+ @retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes

+ actually written

+ @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be written

+ @retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolWrite (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_STATUS Status;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ Status = FvbWriteBlock (FvbDevice->Instance, Lba, Offset, NumBytes, Buffer);

+ DEBUG ((

+ DEBUG_VERBOSE,

+ "FvbWrite: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0x%x Status:%r\n",

+ Lba,

+ Offset,

+ *NumBytes,

+ Buffer,

+ Status

+ ));

+

+ return Status;

+}

+

+/**

+ Reads data beginning at Lba:Offset from FV. The Read terminates either

+ when *NumBytes of data have been read, or when a block boundary is

+ reached. *NumBytes is updated to reflect the actual number of bytes

+ written. The write opertion does not include erase. This routine will

+ attempt to write only the specified bytes. If the writes do not stick,

+ it will return an error.

+

+ @param[in] This Calling context

+ @param[in] Lba Block in which to begin write

+ @param[in] Offset Offset in the block at which to begin write

+ @param[in,out] NumBytes On input, indicates the requested write size. On

+ output, indicates the actual number of bytes written

+ @param[out] Buffer Buffer containing source data for the write.

+

+

+Returns:

+ @retval EFI_SUCCESS The firmware volume was read successfully and

+ contents are in Buffer

+ @retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boundary. On output,

+ NumBytes contains the total number of bytes returned

+ in Buffer

+ @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state

+ @retval EFI_DEVICE_ERROR The block device is not functioning correctly and

+ could not be read

+ @retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL

+

+**/

+EFI_STATUS

+EFIAPI

+FvbProtocolRead (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_STATUS Status;

+

+ FvbDevice = FVB_DEVICE_FROM_THIS (This);

+ Status = FvbReadBlock (FvbDevice->Instance, Lba, Offset, NumBytes, Buffer);

+ DEBUG ((

+ DEBUG_VERBOSE,

+ "FvbRead: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0x%x, Status:%r\n",

+ Lba,

+ Offset,

+ *NumBytes,

+ Buffer,

+ Status

+ ));

+

+ return Status;

+}

+

+/**

+ Check the integrity of firmware volume header in FvBase

+

+ @param[in] FvBase A pointer to firmware volume base address.

+

+ @retval TRUE The firmware volume is consistent

+ @retval FALSE The firmware volume has corrupted.

+

+**/

+BOOLEAN

+IsFvHeaderValid (

+ IN EFI_PHYSICAL_ADDRESS FvBase

+ )

+{

+ UINT16 Sum;

+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;

+

+ FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvBase;

+ if (FvBase == PcdGet32 (PcdFlashNvStorageVariableBase)) {

+ if (CompareMem (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid, sizeof (EFI_GUID)) != 0 ) {

+ DEBUG ((DEBUG_INFO, " --FileSystemGuid not match: %g\n", &FwVolHeader->FileSystemGuid));

+ return FALSE;

+ }

+ } else {

+ if (CompareMem (&FwVolHeader->FileSystemGuid, &gEfiFirmwareFileSystem2Guid, sizeof (EFI_GUID)) != 0 ) {

+ DEBUG ((DEBUG_INFO, " --not expected guid.\n"));

+ return FALSE;

+ }

+ }

+

+ if ((FwVolHeader->Revision != EFI_FVH_REVISION) ||

+ (FwVolHeader->Signature != EFI_FVH_SIGNATURE) ||

+ (FwVolHeader->FvLength == ((UINTN)-1)) ||

+ ((FwVolHeader->HeaderLength & 0x01) != 0))

+ {

+ DEBUG ((DEBUG_INFO, " -- >Revision = 0x%x, Signature = 0x%x\n", FwVolHeader->Revision, FwVolHeader->Signature));

+ DEBUG ((DEBUG_INFO, " -- >FvLength = 0x%lx, HeaderLength = 0x%x\n", FwVolHeader->FvLength, FwVolHeader->HeaderLength));

+ return FALSE;

+ }

+

+ Sum = CalculateSum16 ((UINT16 *)FwVolHeader, FwVolHeader->HeaderLength);

+ if (Sum != 0) {

+ DEBUG ((DEBUG_INFO, "error: checksum: 0x%04X (expect 0x0)\n", Sum));

+ return FALSE;

+ }

+

+ return TRUE;

+}

+

+/**

+ Get intial variable data.

+

+ @param[out] VarData Valid variable data.

+ @param[out] VarSize Valid variable size.

+

+ @retval RETURN_SUCCESS Successfully found initial variable data.

+ @retval RETURN_NOT_FOUND Failed to find the variable data file from FV.

+ @retval EFI_INVALID_PARAMETER VarData or VarSize is null.

+

+**/

+EFI_STATUS

+GetInitialVariableData (

+ OUT VOID **VarData,

+ OUT UINTN *VarSize

+ )

+{

+ EFI_STATUS Status;

+ VOID *ImageData;

+ UINTN ImageSize;

+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;

+ VARIABLE_STORE_HEADER *VariableStore;

+ AUTHENTICATED_VARIABLE_HEADER *Variable;

+ UINTN VariableSize;

+ UINTN VarEndAddr;

+

+ if ((VarData == NULL) || (VarSize == NULL)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Status = GetSectionFromAnyFv (PcdGetPtr (PcdNvsDataFile), EFI_SECTION_RAW, 0, &ImageData, &ImageSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)ImageData;

+ VariableStore = (VARIABLE_STORE_HEADER *)((UINT8 *)ImageData + FvHeader->HeaderLength);

+ VarEndAddr = (UINTN)VariableStore + VariableStore->Size;

+ Variable = (AUTHENTICATED_VARIABLE_HEADER *)HEADER_ALIGN (VariableStore + 1);

+ *VarData = (VOID *)Variable;

+ while (((UINTN)Variable < VarEndAddr)) {

+ if (Variable->StartId != VARIABLE_DATA) {

+ break;

+ }

+

+ VariableSize = sizeof (AUTHENTICATED_VARIABLE_HEADER) + Variable->DataSize + Variable->NameSize;

+ Variable = (AUTHENTICATED_VARIABLE_HEADER *)HEADER_ALIGN ((UINTN)Variable + VariableSize);

+ }

+

+ *VarSize = (UINTN)Variable - HEADER_ALIGN (VariableStore + 1);

+

+ return EFI_SUCCESS;

+}

+

+/**

+ The function does the necessary initialization work for

+ Firmware Volume Block Driver.

+

+ @retval EFI_SUCCESS This funtion always return EFI_SUCCESS.

+ It will ASSERT on errors.

+

+**/

+EFI_STATUS

+FvbInitialize (

+ VOID

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwVolInstance;

+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;

+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;

+ EFI_PHYSICAL_ADDRESS BaseAddress;

+ UINTN WriteAddr;

+ EFI_STATUS Status;

+ UINTN BufferSize;

+ UINTN Length;

+ VARIABLE_STORE_HEADER VariableStore;

+ VOID *VarData;

+

+ BaseAddress = PcdGet32 (PcdFlashNvStorageVariableBase);

+ FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)BaseAddress;

+

+ //

+ // Check FV header and variable store header

+ //

+ if (!IsFvHeaderValid (BaseAddress)) {

+ //

+ // Write back a healthy FV header

+ //

+ DEBUG ((DEBUG_ERROR, "Fvb: Writing back a healthy FV header: 0x%lx\n", BaseAddress));

+ FvHeader = GetFvHeaderTemplate ();

+ LibFvbFlashDeviceBlockLock ((UINTN)BaseAddress, FvHeader->BlockMap->Length, FALSE);

+

+ Status = LibFvbFlashDeviceBlockErase ((UINTN)BaseAddress, FvHeader->BlockMap->Length);

+ ASSERT_EFI_ERROR (Status);

+

+ Length = FvHeader->HeaderLength;

+ WriteAddr = (UINTN)BaseAddress;

+ Status = LibFvbFlashDeviceWrite (WriteAddr, &Length, (UINT8 *)FvHeader);

+ WriteAddr += Length;

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Write back variable store header

+ //

+ VariableStore.Size = PcdGet32 (PcdFlashNvStorageVariableSize) - FvHeader->HeaderLength;

+ VariableStore.Format = VARIABLE_STORE_FORMATTED;

+ VariableStore.State = VARIABLE_STORE_HEALTHY;

+ CopyGuid (&VariableStore.Signature, &gEfiAuthenticatedVariableGuid);

+ BufferSize = sizeof (VARIABLE_STORE_HEADER);

+ Status = LibFvbFlashDeviceWrite (WriteAddr, &BufferSize, (UINT8 *)&VariableStore);

+ WriteAddr += BufferSize;

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Write initial variable data if found

+ //

+ Status = GetInitialVariableData (&VarData, &Length);

+ if (!EFI_ERROR (Status)) {

+ Status = LibFvbFlashDeviceWrite (WriteAddr, &Length, (UINT8 *)VarData);

+ ASSERT_EFI_ERROR (Status);

+ }

+

+ LibFvbFlashDeviceBlockLock ((UINTN)BaseAddress, FvHeader->BlockMap->Length, TRUE);

+ WriteBackInvalidateDataCacheRange ((VOID *)(UINTN)BaseAddress, FvHeader->BlockMap->Length);

+ }

+

+ //

+ // Create a new FW volume instance for NVS variable

+ //

+ BufferSize = FvHeader->HeaderLength + sizeof (EFI_FW_VOL_INSTANCE) - sizeof (EFI_FIRMWARE_VOLUME_HEADER);

+ FwVolInstance = (EFI_FW_VOL_INSTANCE *)AllocateRuntimeZeroPool (BufferSize);

+ if (FwVolInstance == NULL) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ FwVolInstance->FvBase = (UINTN)BaseAddress;

+ CopyMem (&FwVolInstance->VolumeHeader, FvHeader, FvHeader->HeaderLength);

+

+ //

+ // Process the block map for each FV. Assume it has same block size.

+ //

+ FwVolInstance->NumOfBlocks = 0;

+ FvHeader = &FwVolInstance->VolumeHeader;

+ for (BlockMap = FvHeader->BlockMap; BlockMap->NumBlocks != 0; BlockMap++) {

+ FwVolInstance->NumOfBlocks += BlockMap->NumBlocks;

+ }

+

+ //

+ // Add a FVB Protocol Instance

+ //

+ Status = InstallFvbProtocol (FwVolInstance, mFvbModuleGlobal.NumFv);

+ mFvbModuleGlobal.NumFv++;

+ mFvbModuleGlobal.FvInstance = FwVolInstance;

+

+ return Status;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h
new file mode 100644
index 0000000000..54428d8391
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h
@@ -0,0 +1,185 @@
+/** @file

+The header file for Firmware volume block driver.

+

+Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef FW_BLOCK_SERVICE_H_

+#define FW_BLOCK_SERVICE_H_

+

+#include <Guid/EventGroup.h>

+#include <Guid/FirmwareFileSystem2.h>

+#include <Guid/SystemNvDataGuid.h>

+#include <Guid/VariableFormat.h>

+#include <Protocol/DevicePath.h>

+#include <Protocol/FirmwareVolumeBlock.h>

+#include <Library/UefiDriverEntryPoint.h>

+#include <Library/UefiBootServicesTableLib.h>

+#include <Library/UefiLib.h>

+#include <Library/BaseLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseMemoryLib.h>

+#include <Library/IoLib.h>

+#include <Library/CacheMaintenanceLib.h>

+#include <Library/MemoryAllocationLib.h>

+#include <Library/PcdLib.h>

+#include <Library/FlashDeviceLib.h>

+#include <Library/DevicePathLib.h>

+#include <Library/HobLib.h>

+#include <Library/DxeServicesLib.h>

+#include <Guid/NvVariableInfoGuid.h>

+#include <Register/ArchitecturalMsr.h>

+

+//

+// Define two helper macro to extract the Capability field or Status field in FVB

+// bit fields

+//

+#define EFI_FVB2_CAPABILITIES (EFI_FVB2_READ_DISABLED_CAP |\

+ EFI_FVB2_READ_ENABLED_CAP | \

+ EFI_FVB2_WRITE_DISABLED_CAP | \

+ EFI_FVB2_WRITE_ENABLED_CAP | \

+ EFI_FVB2_LOCK_CAP \

+ )

+

+#define EFI_FVB2_STATUS (EFI_FVB2_READ_STATUS | EFI_FVB2_WRITE_STATUS | EFI_FVB2_LOCK_STATUS)

+

+typedef struct {

+ UINTN FvBase;

+ UINTN NumOfBlocks;

+ //

+ // Note!!!: VolumeHeader must be the last element

+ // of the structure.

+ //

+ EFI_FIRMWARE_VOLUME_HEADER VolumeHeader;

+} EFI_FW_VOL_INSTANCE;

+

+typedef struct {

+ EFI_FW_VOL_INSTANCE *FvInstance;

+ UINT32 NumFv;

+ UINT32 Flags;

+} FWB_GLOBAL;

+

+//

+// Fvb Protocol instance data

+//

+#define FVB_DEVICE_FROM_THIS(a) CR(a, EFI_FW_VOL_BLOCK_DEVICE, FwVolBlockInstance, FVB_DEVICE_SIGNATURE)

+#define FVB_EXTEND_DEVICE_FROM_THIS(a) CR(a, EFI_FW_VOL_BLOCK_DEVICE, FvbExtension, FVB_DEVICE_SIGNATURE)

+#define FVB_DEVICE_SIGNATURE SIGNATURE_32('F','V','B','C')

+

+typedef struct {

+ MEDIA_FW_VOL_DEVICE_PATH FvDevPath;

+ EFI_DEVICE_PATH_PROTOCOL EndDevPath;

+} FV_PIWG_DEVICE_PATH;

+

+typedef struct {

+ MEMMAP_DEVICE_PATH MemMapDevPath;

+ EFI_DEVICE_PATH_PROTOCOL EndDevPath;

+} FV_MEMMAP_DEVICE_PATH;

+

+typedef struct {

+ UINT32 Signature;

+ EFI_DEVICE_PATH_PROTOCOL *DevicePath;

+ UINTN Instance;

+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL FwVolBlockInstance;

+} EFI_FW_VOL_BLOCK_DEVICE;

+

+/**

+ Get a heathy FV header used for variable store recovery

+

+ @retval The FV header.

+

+**/

+EFI_FIRMWARE_VOLUME_HEADER *

+GetFvHeaderTemplate (

+ VOID

+ );

+

+EFI_STATUS

+InitVariableStore (

+ VOID

+ );

+

+//

+// Protocol APIs

+//

+EFI_STATUS

+EFIAPI

+FvbProtocolGetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolSetAttributes (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolGetPhysicalAddress (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ OUT EFI_PHYSICAL_ADDRESS *Address

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolGetBlockSize (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ OUT UINTN *BlockSize,

+ OUT UINTN *NumOfBlocks

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolRead (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolWrite (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ IN EFI_LBA Lba,

+ IN UINTN Offset,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ );

+

+EFI_STATUS

+EFIAPI

+FvbProtocolEraseBlocks (

+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+ ...

+ );

+

+EFI_FW_VOL_INSTANCE *

+GetFvbInstance (

+ IN UINTN Instance

+ );

+

+EFI_STATUS

+InstallFvbProtocol (

+ IN EFI_FW_VOL_INSTANCE *FwhInstance,

+ IN UINTN InstanceNum

+ );

+

+EFI_STATUS

+FvbInitialize (

+ VOID

+ );

+

+extern FWB_GLOBAL mFvbModuleGlobal;

+extern EFI_FW_VOL_BLOCK_DEVICE mFvbDeviceTemplate;

+extern FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate;

+extern FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c b/Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c
new file mode 100644
index 0000000000..e2b87a74d2
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c
@@ -0,0 +1,139 @@
+/** @file

+ SMM Firmware Volume Block Driver.

+

+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiSmm.h>

+#include <Library/SmmServicesTableLib.h>

+#include "FvbSmmCommon.h"

+#include "FvbService.h"

+

+/**

+ The function installs EFI_SMM_FIRMWARE_VOLUME_BLOCK protocol

+ for each FV in the system.

+

+ @param[in] FwhInstance The pointer to a FW volume instance structure,

+ which contains the information about one FV.

+ @param[in] InstanceNum The instance number which can be used as a ID

+ to locate this FwhInstance in other functions.

+

+ @retval EFI_SUCESS Installed successfully.

+ @retval Else Did not install successfully.

+

+**/

+EFI_STATUS

+InstallFvbProtocol (

+ IN EFI_FW_VOL_INSTANCE *FwhInstance,

+ IN UINTN InstanceNum

+ )

+{

+ EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;

+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;

+ EFI_STATUS Status;

+ EFI_HANDLE FvbHandle;

+ FV_MEMMAP_DEVICE_PATH *FvDevicePath;

+ VOID *TempPtr;

+

+ FvbDevice = (EFI_FW_VOL_BLOCK_DEVICE *)AllocateRuntimeCopyPool (

+ sizeof (EFI_FW_VOL_BLOCK_DEVICE),

+ &mFvbDeviceTemplate

+ );

+ if (FvbDevice == NULL) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ FvbDevice->Instance = InstanceNum;

+ FwVolHeader = &FwhInstance->VolumeHeader;

+

+ //

+ // Set up the devicepath

+ //

+ if (FwVolHeader->ExtHeaderOffset == 0) {

+ //

+ // FV does not contains extension header, then produce MEMMAP_DEVICE_PATH

+ //

+ TempPtr = AllocateRuntimeCopyPool (sizeof (FV_MEMMAP_DEVICE_PATH), &mFvMemmapDevicePathTemplate);

+ FvbDevice->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)TempPtr;

+ if (FvbDevice->DevicePath == NULL) {

+ ASSERT (FALSE);

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ FvDevicePath = (FV_MEMMAP_DEVICE_PATH *)FvbDevice->DevicePath;

+ FvDevicePath->MemMapDevPath.StartingAddress = FwhInstance->FvBase;

+ FvDevicePath->MemMapDevPath.EndingAddress = FwhInstance->FvBase + FwVolHeader->FvLength - 1;

+ } else {

+ TempPtr = AllocateRuntimeCopyPool (sizeof (FV_PIWG_DEVICE_PATH), &mFvPIWGDevicePathTemplate);

+ FvbDevice->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)TempPtr;

+ if (FvbDevice->DevicePath == NULL) {

+ ASSERT (FALSE);

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ CopyGuid (

+ &((FV_PIWG_DEVICE_PATH *)FvbDevice->DevicePath)->FvDevPath.FvName,

+ (GUID *)(UINTN)(FwhInstance->FvBase + FwVolHeader->ExtHeaderOffset)

+ );

+ }

+

+ //

+ // Install the SMM Firmware Volume Block Protocol and Device Path Protocol

+ //

+ FvbHandle = NULL;

+ Status = gSmst->SmmInstallProtocolInterface (

+ &FvbHandle,

+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ &FvbDevice->FwVolBlockInstance

+ );

+ ASSERT_EFI_ERROR (Status);

+

+ Status = gSmst->SmmInstallProtocolInterface (

+ &FvbHandle,

+ &gEfiDevicePathProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ FvbDevice->DevicePath

+ );

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Notify the Fvb wrapper driver SMM fvb is ready

+ //

+ FvbHandle = NULL;

+ Status = gBS->InstallProtocolInterface (

+ &FvbHandle,

+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ &FvbDevice->FwVolBlockInstance

+ );

+

+ return Status;

+}

+

+/**

+ The driver entry point for SMM Firmware Volume Block Driver.

+

+ The function does the necessary initialization work

+ Firmware Volume Block Driver.

+

+ @param[in] ImageHandle The firmware allocated handle for the UEFI image.

+ @param[in] SystemTable A pointer to the EFI system table.

+

+ @retval EFI_SUCCESS This funtion always return EFI_SUCCESS.

+ It will ASSERT on errors.

+

+**/

+EFI_STATUS

+EFIAPI

+FvbSmmInitialize (

+ IN EFI_HANDLE ImageHandle,

+ IN EFI_SYSTEM_TABLE *SystemTable

+ )

+{

+ FvbInitialize ();

+

+ return EFI_SUCCESS;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf
new file mode 100644
index 0000000000..a56654ba09
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf
@@ -0,0 +1,66 @@
+## @file

+# This driver installs the EFI_SMM_FIRMWARE_VOLUMEN_PROTOCOL.

+#

+#

+# Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = FvbSmm

+ FILE_GUID = A4EC8ADB-B7A8-47d1-8E52-EC820D0ACF6F

+ MODULE_TYPE = DXE_SMM_DRIVER

+ VERSION_STRING = 1.0

+ PI_SPECIFICATION_VERSION = 0x0001000A

+ ENTRY_POINT = FvbSmmInitialize

+

+[Sources]

+ FvbInfo.c

+ FvbService.h

+ FvbService.c

+ FvbServiceSmm.c

+ FvbSmmCommon.h

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ UefiCpuPkg/UefiCpuPkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ FlashDeviceLib

+ PcdLib

+ MemoryAllocationLib

+ CacheMaintenanceLib

+ IoLib

+ BaseMemoryLib

+ DebugLib

+ BaseLib

+ UefiLib

+ SmmServicesTableLib

+ UefiBootServicesTableLib

+ UefiDriverEntryPoint

+ HobLib

+ DxeServicesLib

+

+[Guids]

+ gEfiFirmwareFileSystem2Guid # ALWAYS_CONSUMED

+ gEfiSystemNvDataFvGuid # ALWAYS_CONSUMED

+ gEfiAuthenticatedVariableGuid

+ gNvVariableInfoGuid

+

+ [Protocols]

+ gEfiDevicePathProtocolGuid # PROTOCOL ALWAYS_PRODUCED

+ gEfiSmmFirmwareVolumeBlockProtocolGuid # PROTOCOL ALWAYS_PRODUCED

+

+[Pcd]

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize

+ gPlatformPayloadPkgTokenSpaceGuid.PcdNvsDataFile

+

+[Depex]

+ TRUE

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h
new file mode 100644
index 0000000000..0eadabe13f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h
@@ -0,0 +1,68 @@
+/** @file

+ The common header file for SMM FVB module.

+

+Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SMM_FVB_COMMON_H_

+#define SMM_FVB_COMMON_H_

+

+#include <Protocol/SmmFirmwareVolumeBlock.h>

+

+#define EFI_FUNCTION_GET_ATTRIBUTES 1

+#define EFI_FUNCTION_SET_ATTRIBUTES 2

+#define EFI_FUNCTION_GET_PHYSICAL_ADDRESS 3

+#define EFI_FUNCTION_GET_BLOCK_SIZE 4

+#define EFI_FUNCTION_READ 5

+#define EFI_FUNCTION_WRITE 6

+#define EFI_FUNCTION_ERASE_BLOCKS 7

+

+typedef struct {

+ UINTN Function;

+ EFI_STATUS ReturnStatus;

+ UINT8 Data[1];

+} SMM_FVB_COMMUNICATE_FUNCTION_HEADER;

+

+///

+/// Size of SMM communicate header, without including the payload.

+///

+#define SMM_COMMUNICATE_HEADER_SIZE (OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data))

+

+///

+/// Size of SMM FVB communicate function header, without including the payload.

+///

+#define SMM_FVB_COMMUNICATE_HEADER_SIZE (OFFSET_OF (SMM_FVB_COMMUNICATE_FUNCTION_HEADER, Data))

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_FVB_ATTRIBUTES_2 Attributes;

+} SMM_FVB_ATTRIBUTES_HEADER;

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_PHYSICAL_ADDRESS Address;

+} SMM_FVB_PHYSICAL_ADDRESS_HEADER;

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_LBA Lba;

+ UINTN BlockSize;

+ UINTN NumOfBlocks;

+} SMM_FVB_BLOCK_SIZE_HEADER;

+

+typedef struct {

+ EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_LBA Lba;

+ UINTN Offset;

+ UINTN NumBytes;

+} SMM_FVB_READ_WRITE_HEADER;

+

+typedef struct {

+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *SmmFvb;

+ EFI_LBA StartLba;

+ UINTN NumOfLba;

+} SMM_FVB_BLOCKS_HEADER;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h b/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h
new file mode 100644
index 0000000000..fd0bd73529
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h
@@ -0,0 +1,24 @@
+/** @file

+ This file defines the hob structure for the SPI flash variable info.

+

+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef NV_VARIABLE_INFO_GUID_H_

+#define NV_VARIABLE_INFO_GUID_H_

+

+//

+// NV variable hob info GUID

+//

+extern EFI_GUID gNvVariableInfoGuid;

+

+typedef struct {

+ UINT8 Revision;

+ UINT8 Reserved[3];

+ UINT32 VariableStoreBase;

+ UINT32 VariableStoreSize;

+} NV_VARIABLE_INFO;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h b/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h
new file mode 100644
index 0000000000..59b81851d5
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h
@@ -0,0 +1,38 @@
+/** @file

+ This file defines the hob structure for the SPI flash variable info.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SPI_FLASH_INFO_GUID_H_

+#define SPI_FLASH_INFO_GUID_H_

+

+#include <IndustryStandard/Acpi.h>

+//

+// SPI Flash infor hob GUID

+//

+extern EFI_GUID gSpiFlashInfoGuid;

+

+//

+// Set this bit if platform need disable SMM write protection when writing flash

+// in SMM mode using this method: -- AsmWriteMsr32 (0x1FE, MmioRead32 (0xFED30880) | BIT0);

+//

+#define FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT BIT0

+

+//

+// Reuse ACPI definition

+//

+typedef EFI_ACPI_3_0_GENERIC_ADDRESS_STRUCTURE PLD_GENERIC_ADDRESS;

+#define SPACE_ID_PCI_CONFIGURATION EFI_ACPI_3_0_PCI_CONFIGURATION_SPACE

+#define REGISTER_BIT_WIDTH_DWORD EFI_ACPI_3_0_DWORD

+

+typedef struct {

+ UINT8 Revision;

+ UINT8 Reserved;

+ UINT16 Flags;

+ PLD_GENERIC_ADDRESS SpiAddress;

+} SPI_FLASH_INFO;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h b/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h
new file mode 100644
index 0000000000..b5e8be225e
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h
@@ -0,0 +1,104 @@
+/** @file

+ Flash device library class header file.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef FLASHDEVICE_LIB_H_

+#define FLASHDEVICE_LIB_H_

+

+/**

+ Read NumBytes bytes of data from the address specified by

+ PAddress into Buffer.

+

+ @param[in] PAddress The starting physical address of the read.

+ @param[in,out] NumBytes On input, the number of bytes to read. On output, the number

+ of bytes actually read.

+ @param[out] Buffer The destination data buffer for the read.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceRead (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ );

+

+/**

+ Write NumBytes bytes of data from Buffer to the address specified by

+ PAddresss.

+

+ @param[in] PAddress The starting physical address of the write.

+ @param[in,out] NumBytes On input, the number of bytes to write. On output,

+ the actual number of bytes written.

+ @param[in] Buffer The source data buffer for the write.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceWrite (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ );

+

+/**

+ Erase the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of the region to be erased.

+ @param[in] LbaLength The length of the region to be erased. This parameter is necessary

+ as the physical block size on a flash device could be different than

+ the logical block size of Firmware Volume Block protocol. Erase on

+ flash chip is always performed block by block. Therefore, the ERASE

+ operation to a logical block is converted a number of ERASE operation

+ (or a partial erase) on the hardware.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockErase (

+ IN UINTN PAddress,

+ IN UINTN LbaLength

+ );

+

+/**

+ Lock or unlock the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of region to be (un)locked.

+ @param[in] LbaLength The length of the region to be (un)locked. This parameter is necessary

+ as the physical block size on a flash device could be different than

+ the logical block size of Firmware Volume Block protocol. (Un)Lock on

+ flash chip is always performed block by block. Therefore, the (Un)Lock

+ operation to a logical block is converted a number of (Un)Lock operation

+ (or a partial erase) on the hardware.

+ @param[in] Lock TRUE to lock. FALSE to unlock.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockLock (

+ IN UINTN PAddress,

+ IN UINTN LbaLength,

+ IN BOOLEAN Lock

+ );

+

+PHYSICAL_ADDRESS

+EFIAPI

+LibFvbFlashDeviceMemoryMap (

+ );

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h b/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h
new file mode 100644
index 0000000000..07f40502f2
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h
@@ -0,0 +1,213 @@
+/** @file

+ PCH SPI Common Driver implements the SPI Host Controller Compatibility Interface.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SPI_FLASH_LIB_H_

+#define SPI_FLASH_LIB_H_

+

+/**

+ Flash Region Type

+**/

+typedef enum {

+ FlashRegionDescriptor,

+ FlashRegionBios,

+ FlashRegionMe,

+ FlashRegionGbE,

+ FlashRegionPlatformData,

+ FlashRegionDer,

+ FlashRegionAll,

+ FlashRegionMax

+} FLASH_REGION_TYPE;

+

+/**

+ Read SFDP data from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in SFDP data portion of the SPI cycle, the max number is 64

+ @param[out] SfdpData The Pointer to caller-allocated buffer containing the SFDP data received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadSfdp (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SfdpData

+ );

+

+/**

+ Read Jedec Id from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in JedecId data portion of the SPI cycle, the data size is 3 typically

+ @param[out] JedecId The Pointer to caller-allocated buffer containing JEDEC ID received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadJedecId (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *JedecId

+ );

+

+/**

+ Write the status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[in] StatusValue The Pointer to caller-allocated buffer containing the value of Status register writing

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWriteStatus (

+ IN UINT32 ByteCount,

+ IN UINT8 *StatusValue

+ );

+

+/**

+ Read status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[out] StatusValue The Pointer to caller-allocated buffer containing the value of Status register received.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadStatus (

+ IN UINT32 ByteCount,

+ OUT UINT8 *StatusValue

+ );

+

+/**

+ Read SC Soft Strap Values

+

+ @param[in] SoftStrapAddr SC Soft Strap address offset from FPSBA.

+ @param[in] ByteCount Number of bytes in SoftStrap data portion of the SPI cycle

+ @param[out] SoftStrapValue The Pointer to caller-allocated buffer containing SC Soft Strap Value.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiReadPchSoftStrap (

+ IN UINT32 SoftStrapAddr,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SoftStrapValue

+ );

+

+/**

+ Read data from the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[out] Buffer The Pointer to caller-allocated buffer containing the dada received.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashRead (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ OUT UINT8 *Buffer

+ );

+

+/**

+ Erase some area on the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashErase (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount

+ );

+

+/**

+ Write data to the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in] Buffer Pointer to caller-allocated buffer containing the data sent during the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWrite (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN UINT8 *Buffer

+ );

+

+/**

+ Initialize an SPI library.

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_NOT_FOUND The expected SPI info could not be found

+**/

+EFI_STATUS

+EFIAPI

+SpiConstructor (

+ VOID

+ );

+

+/**

+ Get the SPI region base and size, based on the enum type

+

+ @param[in] FlashRegionType The Flash Region type for for the base address which is listed in the Descriptor.

+ @param[out] BaseAddress The Flash Linear Address for the Region 'n' Base

+ @param[out] RegionSize The size for the Region 'n'

+

+ @retval EFI_SUCCESS Read success

+ @retval EFI_INVALID_PARAMETER Invalid region type given

+ @retval EFI_DEVICE_ERROR The region is not used

+**/

+EFI_STATUS

+EFIAPI

+SpiGetRegionAddress (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ OUT UINT32 *BaseAddress OPTIONAL,

+ OUT UINT32 *RegionSize OPTIONAL

+ );

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc b/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc
new file mode 100644
index 0000000000..3003c563c9
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc
@@ -0,0 +1,112 @@
+## @file

+# This is a build description file for the Payload Platform advanced feature.

+# This file should be included into another package DSC file to build this feature.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+################################################################################

+#

+# Defines Section - statements that will be processed to create a Makefile.

+#

+################################################################################

+

+[Defines]

+ !ifndef $(DXE_ARCH)

+ !error "DXE_ARCH must be specified to build this feature!"

+ !endif

+

+ DEFINE SMM_VARIABLE = TRUE

+

+

+################################################################################

+#

+# PCD definitions section - list of all PCD definitions needed by this Platform.

+#

+################################################################################

+

+[PcdsPatchableInModule.X64]

+!if $(SMM_VARIABLE) == TRUE

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase |0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize |0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize |0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase |0

+!endif

+

+################################################################################

+#

+# Library Class section - list of all Library Classes needed by this feature.

+#

+################################################################################

+

+[LibraryClasses]

+ !if $(SMM_VARIABLE) == TRUE

+ PciLib|MdePkg/Library/BasePciLibPciExpress/BasePciLibPciExpress.inf

+ PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf

+ # (Optional for variable modules debug output

+ PlatformHookLib|UefiPayloadPkg/Library/PlatformHookLib/PlatformHookLib.inf

+ DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf

+ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf

+ DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf

+ !endif

+

+[LibraryClasses.common.DXE_SMM_DRIVER,LibraryClasses.common.DXE_RUNTIME_DRIVER]

+ !if $(SMM_VARIABLE) == TRUE

+ SpiFlashLib|PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf

+ FlashDeviceLib|PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf

+ DxeHobListLib|UefiPayloadPkg/Library/DxeHobListLib/DxeHobListLib.inf

+ HobLib|UefiPayloadPkg/Library/DxeHobLib/DxeHobLib.inf

+ TimerLib|UefiCpuPkg/Library/CpuTimerLib/BaseCpuTimerLib.inf

+ !endif

+

+################################################################################

+#

+# Component section - list of all components that need built for this feature.

+#

+# Note: The EDK II DSC file is not used to specify how compiled binary images get placed

+# into firmware volume images. This section is just a list of modules to compile from

+# source into UEFI-compliant binaries.

+# It is the FDF file that contains information on combining binary files into firmware

+# volume images, whose concept is beyond UEFI and is described in PI specification.

+# There may also be modules listed in this section that are not required in the FDF file,

+# When a module listed here is excluded from FDF file, then UEFI-compliant binary will be

+# generated for it, but the binary will not be put into any firmware volume.

+#

+################################################################################

+#

+# Feature DXE Components

+#

+

+# @todo: Change below line to [Components.$(DXE_ARCH)] after https://bugzilla.tianocore.org/show_bug.cgi?id=2308

+# is completed.

+[Components.X64]

+ #

+ # SMM Variable Support

+ #

+ !if $(SMM_VARIABLE) == TRUE

+ PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf

+ PlatformPayloadPkg/Fvb/FvbSmm.inf {

+ <LibraryClasses>

+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf

+ }

+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf {

+ <LibraryClasses>

+ NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf

+ NULL|MdeModulePkg/Library/VarCheckHiiLib/VarCheckHiiLib.inf

+ NULL|MdeModulePkg/Library/VarCheckPcdLib/VarCheckPcdLib.inf

+ NULL|MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.inf

+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf

+ }

+

+ MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf {

+ <LibraryClasses>

+ NULL|PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf

+ }

+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf

+ !endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf b/Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf
new file mode 100644
index 0000000000..54800b972c
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf
@@ -0,0 +1,20 @@
+## @file

+# FDF file for post-memory ACPI Debug advanced feature modules.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+#

+# SMM Support

+#

+!if $(SMM_VARIABLE) == TRUE

+ INF PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf

+ INF PlatformPayloadPkg/Fvb/FvbSmm.inf

+ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf

+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf

+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf

+

+!endif

diff --git a/Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf b/Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf
new file mode 100644
index 0000000000..003b7a3e56
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf
@@ -0,0 +1,8 @@
+## @file

+# FDF file for pre-memory payload platform advanced feature modules.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

diff --git a/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c
new file mode 100644
index 0000000000..5a27043285
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c
@@ -0,0 +1,160 @@
+/** @file

+ Flash Device Library based on SPI Flash library.

+

+Copyright (c) 2018 - 2021, Intel Corporation. All rights reserved. <BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiDxe.h>

+#include <Library/BaseMemoryLib.h>

+#include <Library/DebugLib.h>

+#include <Library/SpiFlashLib.h>

+

+/**

+ Initialize spi flash device.

+

+ @retval EFI_SUCCESS The tested spi flash device is supported.

+ @retval EFI_UNSUPPORTED The tested spi flash device is not supported.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceInit (

+ VOID

+ )

+{

+ return SpiConstructor ();

+}

+

+/**

+ Read NumBytes bytes of data from the address specified by

+ PAddress into Buffer.

+

+ @param[in] PAddress The starting physical address of the read.

+ @param[in,out] NumBytes On input, the number of bytes to read. On output, the number

+ of bytes actually read.

+ @param[out] Buffer The destination data buffer for the read.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceRead (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ OUT UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+ UINT32 ByteCount;

+ UINT32 RgnSize;

+ UINT32 AddrOffset;

+

+ Status = SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - RgnSize))

+ // which equal (PAddress + RgnSize) here.

+ AddrOffset = (UINT32)((UINT32)PAddress + RgnSize);

+ ByteCount = (UINT32)*NumBytes;

+ return SpiFlashRead (FlashRegionBios, AddrOffset, ByteCount, Buffer);

+}

+

+/**

+ Write NumBytes bytes of data from Buffer to the address specified by

+ PAddresss.

+

+ @param[in] PAddress The starting physical address of the write.

+ @param[in,out] NumBytes On input, the number of bytes to write. On output,

+ the actual number of bytes written.

+ @param[in] Buffer The source data buffer for the write.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceWrite (

+ IN UINTN PAddress,

+ IN OUT UINTN *NumBytes,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+ UINT32 ByteCount;

+ UINT32 RgnSize;

+ UINT32 AddrOffset;

+

+ Status = SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - RgnSize))

+ // which equal (PAddress + RgnSize) here.

+ AddrOffset = (UINT32)((UINT32)PAddress + RgnSize);

+ ByteCount = (UINT32)*NumBytes;

+ return SpiFlashWrite (FlashRegionBios, AddrOffset, ByteCount, Buffer);

+}

+

+/**

+ Erase the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of the block to be erased.

+ This library assume that caller garantee that the PAddress

+ is at the starting address of this block.

+ @param[in] LbaLength The length of the logical block to be erased.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockErase (

+ IN UINTN PAddress,

+ IN UINTN LbaLength

+ )

+{

+ EFI_STATUS Status;

+ UINT32 RgnSize;

+ UINT32 AddrOffset;

+

+ Status = SpiGetRegionAddress (FlashRegionBios, NULL, &RgnSize);

+ if (EFI_ERROR (Status)) {

+ return Status;

+ }

+

+ // BIOS region offset can be calculated by (PAddress - (0x100000000 - RgnSize))

+ // which equal (PAddress + RgnSize) here.

+ AddrOffset = (UINT32)((UINT32)PAddress + RgnSize);

+ return SpiFlashErase (FlashRegionBios, AddrOffset, (UINT32)LbaLength);

+}

+

+/**

+ Lock or unlock the block starting at PAddress.

+

+ @param[in] PAddress The starting physical address of region to be (un)locked.

+ @param[in] LbaLength The length of the logical block to be erased.

+ @param[in] Lock TRUE to lock. FALSE to unlock.

+

+ @retval EFI_SUCCESS. Opertion is successful.

+ @retval EFI_DEVICE_ERROR If there is any device errors.

+

+**/

+EFI_STATUS

+EFIAPI

+LibFvbFlashDeviceBlockLock (

+ IN UINTN PAddress,

+ IN UINTN LbaLength,

+ IN BOOLEAN Lock

+ )

+{

+ return EFI_SUCCESS;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf
new file mode 100644
index 0000000000..7285a37944
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf
@@ -0,0 +1,38 @@
+## @file

+# Library instace of Flash Device Library Class

+#

+# This library implement the flash device library class for the lakeport platform.

+#@copyright

+# Copyright (c) 2014 - 2021 Intel Corporation. All rights reserved

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = FlashDeviceLib

+ FILE_GUID = BA7CA537-1C65-4a90-9379-622A24A08141

+ MODULE_TYPE = DXE_DRIVER

+ VERSION_STRING = 1.0

+ LIBRARY_CLASS = FlashDeviceLib | DXE_SMM_DRIVER DXE_RUNTIME_DRIVER

+

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ FlashDeviceLib.c

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ DebugLib

+ BaseMemoryLib

+ SpiFlashLib

+

diff --git a/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c
new file mode 100644
index 0000000000..4ea89582f3
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c
@@ -0,0 +1,89 @@
+/** @file

+

+ Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiDxe.h>

+#include <Library/PcdLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseLib.h>

+#include <Guid/SystemNvDataGuid.h>

+#include <Guid/NvVariableInfoGuid.h>

+#include <Library/HobLib.h>

+

+

+/**

+ Initialize the variable store

+

+ @retval EFI_SUCCESS if initialize the store success.

+

+**/

+EFI_STATUS

+PcdInitConstructor (

+ VOID

+ )

+{

+ EFI_STATUS Status;

+ UINT32 NvStorageBase;

+ UINT32 NvStorageSize;

+ UINT32 NvVariableSize;

+ UINT32 FtwWorkingSize;

+ UINT32 FtwSpareSize;

+ EFI_HOB_GUID_TYPE *GuidHob;

+ NV_VARIABLE_INFO *NvVariableInfo;

+

+ //

+ // Find SPI flash variable hob

+ //

+ GuidHob = GetFirstGuidHob (&gNvVariableInfoGuid);

+ if (GuidHob == NULL) {

+ ASSERT (FALSE);

+ return EFI_NOT_FOUND;

+ }

+

+ NvVariableInfo = (NV_VARIABLE_INFO *)GET_GUID_HOB_DATA (GuidHob);

+

+ //

+ // Get variable region base and size.

+ //

+ NvStorageSize = NvVariableInfo->VariableStoreSize;

+ NvStorageBase = NvVariableInfo->VariableStoreBase;

+

+ //

+ // NvStorageBase needs to be 4KB aligned, NvStorageSize needs to be 8KB * n

+ //

+ if (((NvStorageBase & (SIZE_4KB - 1)) != 0) || ((NvStorageSize & (SIZE_8KB - 1)) != 0)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ FtwSpareSize = NvStorageSize / 2;

+ FtwWorkingSize = 0x2000;

+ NvVariableSize = NvStorageSize / 2 - FtwWorkingSize;

+ DEBUG ((DEBUG_INFO, "NvStorageBase:0x%x, NvStorageSize:0x%x\n", NvStorageBase, NvStorageSize));

+

+ if (NvVariableSize >= 0x80000000) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Status = PcdSet32S (PcdFlashNvStorageVariableSize, NvVariableSize);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet32S (PcdFlashNvStorageVariableBase, NvStorageBase);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet64S (PcdFlashNvStorageVariableBase64, NvStorageBase);

+ ASSERT_EFI_ERROR (Status);

+

+ Status = PcdSet32S (PcdFlashNvStorageFtwWorkingSize, FtwWorkingSize);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet32S (PcdFlashNvStorageFtwWorkingBase, NvStorageBase + NvVariableSize);

+ ASSERT_EFI_ERROR (Status);

+

+ Status = PcdSet32S (PcdFlashNvStorageFtwSpareSize, FtwSpareSize);

+ ASSERT_EFI_ERROR (Status);

+ Status = PcdSet32S (PcdFlashNvStorageFtwSpareBase, NvStorageBase + FtwSpareSize);

+ ASSERT_EFI_ERROR (Status);

+

+ return EFI_SUCCESS;

+}

+

diff --git a/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf
new file mode 100644
index 0000000000..05411b00d8
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf
@@ -0,0 +1,50 @@
+## @file

+# Initialize patchable PCDs using HOB info

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = PcdInitLib

+ FILE_GUID = 2C4A8902-B55A-472E-9845-3B931CE68071

+ MODULE_TYPE = BASE

+ VERSION_STRING = 1.0

+ LIBRARY_CLASS = NULL

+ CONSTRUCTOR = PcdInitConstructor

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ PcdInitLib.c

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ BaseLib

+ PcdLib

+ PciLib

+ HobLib

+ BaseLib

+

+[Guids]

+ gNvVariableInfoGuid

+

+[Pcd]

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase

+

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c
new file mode 100644
index 0000000000..18f4a0ba3f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c
@@ -0,0 +1,170 @@
+/** @file

+

+ Copyright (c) 2017-2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+#include "SpiCommon.h"

+

+/**

+ Acquire SPI MMIO BAR.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Return SPI BAR Address

+

+**/

+UINT32

+AcquireSpiBar0 (

+ IN UINTN PchSpiBase

+ )

+{

+ return MmioRead32 (PchSpiBase + R_SPI_BASE) & ~(B_SPI_BAR0_MASK);

+}

+

+/**

+ Release SPI MMIO BAR. Do nothing.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+**/

+VOID

+ReleaseSpiBar0 (

+ IN UINTN PchSpiBase

+ )

+{

+}

+

+/**

+ This function is to enable/disable BIOS Write Protect in SMM phase.

+

+ @param[in] EnableSmmSts Flag to Enable/disable Bios write protect

+

+**/

+VOID

+CpuSmmDisableBiosWriteProtect (

+ IN BOOLEAN EnableSmmSts

+ )

+{

+ UINT32 Data32;

+

+ if (EnableSmmSts) {

+ //

+ // Disable BIOS Write Protect in SMM phase.

+ //

+ Data32 = MmioRead32 ((UINTN)(0xFED30880)) | (UINT32)(BIT0);

+ AsmWriteMsr32 (0x000001FE, Data32);

+ } else {

+ //

+ // Enable BIOS Write Protect in SMM phase

+ //

+ Data32 = MmioRead32 ((UINTN)(0xFED30880)) & (UINT32)(~BIT0);

+ AsmWriteMsr32 (0x000001FE, Data32);

+ }

+

+ //

+ // Read FED30880h back to ensure the setting went through.

+ //

+ Data32 = MmioRead32 (0xFED30880);

+}

+

+/**

+ This function is a hook for Spi to disable BIOS Write Protect.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_ACCESS_DENIED The BIOS Region can only be updated in SMM phase

+

+**/

+EFI_STATUS

+EFIAPI

+DisableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ )

+{

+ //

+ // Write clear BC_SYNC_SS prior to change WPD from 0 to 1.

+ //

+ MmioOr8 (PchSpiBase + R_SPI_BCR + 1, (B_SPI_BCR_SYNC_SS >> 8));

+

+ //

+ // Enable the access to the BIOS space for both read and write cycles

+ //

+ MmioOr8 (PchSpiBase + R_SPI_BCR, B_SPI_BCR_BIOSWE);

+

+ if (CpuSmmBwp != 0) {

+ CpuSmmDisableBiosWriteProtect (TRUE);

+ }

+

+ return EFI_SUCCESS;

+}

+

+/**

+ This function is a hook for Spi to enable BIOS Write Protect.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+**/

+VOID

+EFIAPI

+EnableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ )

+{

+ //

+ // Disable the access to the BIOS space for write cycles

+ //

+ MmioAnd8 (PchSpiBase + R_SPI_BCR, (UINT8)(~B_SPI_BCR_BIOSWE));

+

+ if (CpuSmmBwp != 0) {

+ CpuSmmDisableBiosWriteProtect (FALSE);

+ }

+}

+

+/**

+ This function disables SPI Prefetching and caching,

+ and returns previous BIOS Control Register value before disabling.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Previous BIOS Control Register value

+

+**/

+UINT8

+SaveAndDisableSpiPrefetchCache (

+ IN UINTN PchSpiBase

+ )

+{

+ UINT8 BiosCtlSave;

+

+ BiosCtlSave = MmioRead8 (PchSpiBase + R_SPI_BCR) & B_SPI_BCR_SRC;

+

+ MmioAndThenOr32 (

+ PchSpiBase + R_SPI_BCR, \

+ (UINT32)(~B_SPI_BCR_SRC), \

+ (UINT32)(V_SPI_BCR_SRC_PREF_DIS_CACHE_DIS << B_SPI_BCR_SRC)

+ );

+

+ return BiosCtlSave;

+}

+

+/**

+ This function updates BIOS Control Register with the given value.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] BiosCtlValue BIOS Control Register Value to be updated

+

+**/

+VOID

+SetSpiBiosControlRegister (

+ IN UINTN PchSpiBase,

+ IN UINT8 BiosCtlValue

+ )

+{

+ MmioAndThenOr8 (PchSpiBase + R_SPI_BCR, (UINT8) ~B_SPI_BCR_SRC, BiosCtlValue);

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h
new file mode 100644
index 0000000000..b741904143
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h
@@ -0,0 +1,120 @@
+/** @file

+ Register names for SPI device.

+

+ Copyright (c) 2017 - 2019, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef REGS_SPI_H_

+#define REGS_SPI_H_

+

+#define R_SPI_BASE 0x10 ///< 32-bit Memory Base Address Register

+#define B_SPI_BAR0_MASK 0x0FFF

+#define R_SPI_BCR 0xDC ///< BIOS Control Register

+#define B_SPI_BCR_SRC (BIT3 | BIT2) ///< SPI Read Configuration (SRC)

+#define V_SPI_BCR_SRC_PREF_DIS_CACHE_DIS 0x04 ///< Prefetch Disable, Cache Disable

+#define B_SPI_BCR_SYNC_SS BIT8

+#define B_SPI_BCR_BIOSWE BIT0 ///< Write Protect Disable (WPD)

+

+///

+/// SPI Host Interface Registers

+#define R_SPI_HSFS 0x04 ///< Hardware Sequencing Flash Status and Control Register(32bits)

+#define B_SPI_HSFS_FDBC_MASK 0x3F000000 ///< Flash Data Byte Count ( <= 64), Count = (Value in this field) + 1.

+#define N_SPI_HSFS_FDBC 24

+#define B_SPI_HSFS_CYCLE_MASK 0x001E0000 ///< Flash Cycle.

+#define N_SPI_HSFS_CYCLE 17

+#define V_SPI_HSFS_CYCLE_READ 0 ///< Flash Cycle Read

+#define V_SPI_HSFS_CYCLE_WRITE 2 ///< Flash Cycle Write

+#define V_SPI_HSFS_CYCLE_4K_ERASE 3 ///< Flash Cycle 4K Block Erase

+#define V_SPI_HSFS_CYCLE_64K_ERASE 4 ///< Flash Cycle 64K Sector Erase

+#define V_SPI_HSFS_CYCLE_READ_SFDP 5 ///< Flash Cycle Read SFDP

+#define V_SPI_HSFS_CYCLE_READ_JEDEC_ID 6 ///< Flash Cycle Read JEDEC ID

+#define V_SPI_HSFS_CYCLE_WRITE_STATUS 7 ///< Flash Cycle Write Status

+#define V_SPI_HSFS_CYCLE_READ_STATUS 8 ///< Flash Cycle Read Status

+#define B_SPI_HSFS_CYCLE_FGO BIT16 ///< Flash Cycle Go.

+#define B_SPI_HSFS_FDV BIT14 ///< Flash Descriptor Valid

+#define B_SPI_HSFS_SCIP BIT5 ///< SPI Cycle in Progress

+#define B_SPI_HSFS_FCERR BIT1 ///< Flash Cycle Error

+#define B_SPI_HSFS_FDONE BIT0 ///< Flash Cycle Done

+

+#define R_SPI_FADDR 0x08 ///< SPI Flash Address

+#define B_SPI_FADDR_MASK 0x07FFFFFF ///< SPI Flash Address Mask (0~26bit)

+

+#define R_SPI_FDATA00 0x10 ///< SPI Data 00 (32 bits)

+

+#define R_SPI_FRAP 0x50 ///< SPI Flash Regions Access Permissions Register

+#define B_SPI_FRAP_BRWA_PLATFORM BIT12 // < Region write access for Region4 PlatformData

+#define B_SPI_FRAP_BRWA_GBE BIT11 // < Region write access for Region3 GbE

+#define B_SPI_FRAP_BRWA_SEC BIT10 ///< Region Write Access for Region2 SEC

+#define B_SPI_FRAP_BRWA_BIOS BIT9 ///< Region Write Access for Region1 BIOS

+#define B_SPI_FRAP_BRWA_FLASHD BIT8 ///< Region Write Access for Region0 Flash Descriptor

+#define B_SPI_FRAP_BRRA_PLATFORM BIT4 ///< Region read access for Region4 PlatformData

+#define B_SPI_FRAP_BRRA_GBE BIT3 ///< Region read access for Region3 GbE

+#define B_SPI_FRAP_BRRA_SEC BIT2 ///< Region Read Access for Region2 SEC

+#define B_SPI_FRAP_BRRA_BIOS BIT1 ///< Region Read Access for Region1 BIOS

+#define B_SPI_FRAP_BRRA_FLASHD BIT0 ///< Region Read Access for Region0 Flash Descriptor

+

+#define R_SPI_FREG0_FLASHD 0x54 ///< Flash Region 0 (Flash Descriptor) (32bits)

+#define B_SPI_FREG0_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG0_LIMIT 4 ///< Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG0_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG0_BASE 12 ///< Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG1_BIOS 0x58 ///< Flash Region 1 (BIOS) (32bits)

+#define B_SPI_FREG1_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG1_LIMIT 4 ///< Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG1_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG1_BASE 12 ///< Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG2_SEC 0x5C ///< Flash Region 2 (SEC) (32bits)

+#define B_SPI_FREG2_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG2_LIMIT 4 // < Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG2_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG2_BASE 12 // < Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG3_GBE 0x60 // < Flash Region 3(GbE)(32bits)

+#define B_SPI_FREG3_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG3_LIMIT 4 // < Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG3_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG3_BASE 12 // < Bit 14:0 identifies address bits [26:2]

+

+#define R_SPI_FREG4_PLATFORM_DATA 0x64 ///< Flash Region 4 (Platform Data) (32bits)

+#define B_SPI_FREG4_LIMIT_MASK 0x7FFF0000 ///< Size, [30:16] here represents limit[26:12]

+#define N_SPI_FREG4_LIMIT 4 ///< Bit 30:16 identifies address bits [26:12]

+#define B_SPI_FREG4_BASE_MASK 0x00007FFF ///< Base, [14:0] here represents base [26:12]

+#define N_SPI_FREG4_BASE 12 ///< Bit 14:0 identifies address bits [26:2]

+

+#define S_SPI_FREGX 4 ///< Size of Flash Region register

+#define B_SPI_FREGX_LIMIT_MASK 0x7FFF0000 ///< Flash Region Limit [30:16] represents [26:12], [11:0] are assumed to be FFFh

+#define N_SPI_FREGX_LIMIT 16 ///< Region limit bit position

+#define N_SPI_FREGX_LIMIT_REPR 12 ///< Region limit bit represents position

+#define B_SPI_FREGX_BASE_MASK 0x00007FFF ///< Flash Region Base, [14:0] represents [26:12]

+

+#define R_SPI_FDOC 0xB4 ///< Flash Descriptor Observability Control Register (32 bits)

+#define B_SPI_FDOC_FDSS_MASK (BIT14 | BIT13 | BIT12) ///< Flash Descriptor Section Select

+#define V_SPI_FDOC_FDSS_FSDM 0x0000 ///< Flash Signature and Descriptor Map

+#define V_SPI_FDOC_FDSS_COMP 0x1000 ///< Component

+#define B_SPI_FDOC_FDSI_MASK 0x0FFC ///< Flash Descriptor Section Index

+

+#define R_SPI_FDOD 0xB8 ///< Flash Descriptor Observability Data Register (32 bits)

+

+#define R_SPI_LVSCC 0xC4 ///< Vendor Specific Component Capabilities for Component 0 (32 bits)

+#define B_SPI_LVSCC_EO_64K BIT29 ///< < 64k Erase valid (EO_64k_valid)

+

+#define R_SPI_UVSCC 0xC8 ///< Vendor Specific Component Capabilities for Component 1 (32 bits)

+

+#define R_SPI_FDBAR_FLASH_MAP0 0x14 ///< Flash MAP 0

+#define N_SPI_FDBAR_NC 8 ///< < Number Of Components

+#define B_SPI_FDBAR_NC 0x00000300 ///< Number Of Components

+

+#define R_SPI_FDBAR_FLASH_MAP1 0x18 ///< Flash MAP 1

+#define B_SPI_FDBAR_FPSBA 0x00FF0000 ///< Flash Strap Base Address

+

+//

+// Flash Component Base Address (FCBA) from Flash Region 0

+//

+#define R_SPI_FCBA_FLCOMP 0x00 ///< Flash Components Register

+#define B_SPI_FLCOMP_COMP1_MASK 0x0F ///< Flash Component 1 Density

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h
new file mode 100644
index 0000000000..95e9b9b1e7
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h
@@ -0,0 +1,203 @@
+/** @file

+ Header file for the SPI flash module.

+

+ Copyright (c) 2017 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SPI_COMMON_LIB_H_

+#define SPI_COMMON_LIB_H_

+

+#include <PiDxe.h>

+#include <Uefi/UefiBaseType.h>

+#include <IndustryStandard/Pci30.h>

+#include <Library/IoLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseMemoryLib.h>

+#include <Library/SpiFlashLib.h>

+#include <Library/MemoryAllocationLib.h>

+#include <Library/BaseLib.h>

+#include <Library/HobLib.h>

+#include <Library/TimerLib.h>

+#include <Guid/SpiFlashInfoGuid.h>

+#include "RegsSpi.h"

+

+///

+/// Maximum time allowed while waiting the SPI cycle to complete

+/// Wait Time = 6 seconds = 6000000 microseconds

+/// Wait Period = 10 microseconds

+///

+#define WAIT_TIME 6000000 ///< Wait Time = 6 seconds = 6000000 microseconds

+#define WAIT_PERIOD 10 ///< Wait Period = 10 microseconds

+

+///

+/// Flash cycle Type

+///

+typedef enum {

+ FlashCycleRead,

+ FlashCycleWrite,

+ FlashCycleErase,

+ FlashCycleReadSfdp,

+ FlashCycleReadJedecId,

+ FlashCycleWriteStatus,

+ FlashCycleReadStatus,

+ FlashCycleMax

+} FLASH_CYCLE_TYPE;

+

+///

+/// Flash Component Number

+///

+typedef enum {

+ FlashComponent0,

+ FlashComponent1,

+ FlashComponentMax

+} FLASH_COMPONENT_NUM;

+

+///

+/// Private data structure definitions for the driver

+///

+#define SC_SPI_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('P', 'S', 'P', 'I')

+

+typedef struct {

+ UINTN Signature;

+ EFI_HANDLE Handle;

+ UINT32 AcpiTmrReg;

+ UINTN PchSpiBase;

+ UINT16 RegionPermission;

+ UINT32 SfdpVscc0Value;

+ UINT32 SfdpVscc1Value;

+ UINT32 StrapBaseAddress;

+ UINT8 NumberOfComponents;

+ UINT16 Flags;

+ UINT32 Component1StartAddr;

+} SPI_INSTANCE;

+

+/**

+ Acquire SPI MMIO BAR

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Return SPI BAR Address

+

+**/

+UINT32

+AcquireSpiBar0 (

+ IN UINTN PchSpiBase

+ );

+

+/**

+ Release SPI MMIO BAR. Do nothing.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval None

+

+**/

+VOID

+ReleaseSpiBar0 (

+ IN UINTN PchSpiBase

+ );

+

+/**

+ This function is a hook for Spi to disable BIOS Write Protect

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_ACCESS_DENIED The BIOS Region can only be updated in SMM phase

+

+**/

+EFI_STATUS

+EFIAPI

+DisableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ );

+

+/**

+ This function is a hook for Spi to enable BIOS Write Protect

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] CpuSmmBwp Need to disable CPU SMM Bios write protection or not

+

+ @retval None

+

+**/

+VOID

+EFIAPI

+EnableBiosWriteProtect (

+ IN UINTN PchSpiBase,

+ IN UINT8 CpuSmmBwp

+ );

+

+/**

+ This function disables SPI Prefetching and caching,

+ and returns previous BIOS Control Register value before disabling.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+

+ @retval Previous BIOS Control Register value

+

+**/

+UINT8

+SaveAndDisableSpiPrefetchCache (

+ IN UINTN PchSpiBase

+ );

+

+/**

+ This function updates BIOS Control Register with the given value.

+

+ @param[in] PchSpiBase PCH SPI PCI Base Address

+ @param[in] BiosCtlValue BIOS Control Register Value to be updated

+

+ @retval None

+

+**/

+VOID

+SetSpiBiosControlRegister (

+ IN UINTN PchSpiBase,

+ IN UINT8 BiosCtlValue

+ );

+

+/**

+ This function sends the programmed SPI command to the slave device.

+

+ @param[in] SpiRegionType The SPI Region type for flash cycle which is listed in the Descriptor

+ @param[in] FlashCycleType The Flash SPI cycle type list in HSFC (Hardware Sequencing Flash Control Register) register

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in,out] Buffer Pointer to caller-allocated buffer containing the data received or sent during the SPI cycle.

+

+ @retval EFI_SUCCESS SPI command completes successfully.

+ @retval EFI_DEVICE_ERROR Device error, the command aborts abnormally.

+ @retval EFI_ACCESS_DENIED Some unrecognized command encountered in hardware sequencing mode

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+**/

+EFI_STATUS

+SendSpiCmd (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN FLASH_CYCLE_TYPE FlashCycleType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN OUT UINT8 *Buffer

+ );

+

+/**

+ Wait execution cycle to complete on the SPI interface.

+

+ @param[in] PchSpiBar0 Spi MMIO base address

+ @param[in] ErrorCheck TRUE if the SpiCycle needs to do the error check

+

+ @retval TRUE SPI cycle completed on the interface.

+ @retval FALSE Time out while waiting the SPI cycle to complete.

+ It's not safe to program the next command on the SPI interface.

+**/

+BOOLEAN

+WaitForSpiCycleComplete (

+ IN UINT32 PchSpiBar0,

+ IN BOOLEAN ErrorCheck

+ );

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c
new file mode 100644
index 0000000000..22639a748c
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c
@@ -0,0 +1,874 @@
+/** @file

+ Generic driver using Hardware Sequencing registers.

+

+ Copyright (c) 2017-2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+#include "SpiCommon.h"

+

+SPI_INSTANCE *mSpiInstance = NULL;

+

+/**

+ Get SPI Instance from library global data..

+

+ @retval SpiInstance Return SPI instance

+**/

+SPI_INSTANCE *

+GetSpiInstance (

+ VOID

+ )

+{

+ if (mSpiInstance == NULL) {

+ mSpiInstance = AllocatePool (sizeof (SPI_INSTANCE));

+ if (mSpiInstance == NULL) {

+ return NULL;

+ }

+

+ ZeroMem (mSpiInstance, sizeof (SPI_INSTANCE));

+ }

+

+ return mSpiInstance;

+}

+

+/**

+ Initialize an SPI library.

+

+ @retval EFI_SUCCESS The protocol instance was properly initialized

+ @retval EFI_NOT_FOUND The expected SPI info could not be found

+**/

+EFI_STATUS

+EFIAPI

+SpiConstructor (

+ VOID

+ )

+{

+ UINT32 ScSpiBar0;

+ UINT8 Comp0Density;

+ SPI_INSTANCE *SpiInstance;

+ EFI_HOB_GUID_TYPE *GuidHob;

+ SPI_FLASH_INFO *SpiFlashInfo;

+

+ //

+ // Find SPI flash hob

+ //

+ GuidHob = GetFirstGuidHob (&gSpiFlashInfoGuid);

+ if (GuidHob == NULL) {

+ ASSERT (FALSE);

+ return EFI_NOT_FOUND;

+ }

+

+ SpiFlashInfo = (SPI_FLASH_INFO *)GET_GUID_HOB_DATA (GuidHob);

+

+ //

+ // Initialize the SPI instance

+ //

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_NOT_FOUND;

+ }

+

+ DEBUG ((DEBUG_INFO, "SpiInstance = %08X\n", SpiInstance));

+

+ SpiInstance->Signature = SC_SPI_PRIVATE_DATA_SIGNATURE;

+ SpiInstance->Handle = NULL;

+

+ //

+ // Check the SPI address

+ //

+ if ((SpiFlashInfo->SpiAddress.AddressSpaceId != EFI_ACPI_3_0_PCI_CONFIGURATION_SPACE) ||

+ (SpiFlashInfo->SpiAddress.RegisterBitWidth != 32) ||

+ (SpiFlashInfo->SpiAddress.RegisterBitOffset != 0) ||

+ (SpiFlashInfo->SpiAddress.AccessSize != EFI_ACPI_3_0_DWORD))

+ {

+ DEBUG ((DEBUG_ERROR, "SPI FLASH HOB is not expected. need check the hob or enhance SPI flash driver.\n"));

+ }

+

+ SpiInstance->PchSpiBase = (UINT32)(UINTN)SpiFlashInfo->SpiAddress.Address;

+ SpiInstance->Flags = SpiFlashInfo->Flags;

+ DEBUG ((DEBUG_INFO, "PchSpiBase at 0x%x\n", SpiInstance->PchSpiBase));

+

+ ScSpiBar0 = AcquireSpiBar0 (SpiInstance->PchSpiBase);

+ DEBUG ((DEBUG_INFO, "ScSpiBar0 at 0x%08X\n", ScSpiBar0));

+

+ if (ScSpiBar0 == 0) {

+ ASSERT (FALSE);

+ }

+

+ if ((MmioRead32 (ScSpiBar0 + R_SPI_HSFS) & B_SPI_HSFS_FDV) == 0) {

+ DEBUG ((DEBUG_ERROR, "SPI Flash descriptor invalid, cannot use Hardware Sequencing registers!\n"));

+ ASSERT (FALSE);

+ }

+

+ MmioOr32 (SpiInstance->PchSpiBase + PCI_COMMAND_OFFSET, EFI_PCI_COMMAND_MEMORY_SPACE);

+ SpiInstance->RegionPermission = MmioRead16 (ScSpiBar0 + R_SPI_FRAP);

+ SpiInstance->SfdpVscc0Value = MmioRead32 (ScSpiBar0 + R_SPI_LVSCC);

+ SpiInstance->SfdpVscc1Value = MmioRead32 (ScSpiBar0 + R_SPI_UVSCC);

+

+ //

+ // Select to Flash Map 0 Register to get the number of flash Component

+ //

+ MmioAndThenOr32 (

+ ScSpiBar0 + R_SPI_FDOC,

+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),

+ (UINT32)(V_SPI_FDOC_FDSS_FSDM | R_SPI_FDBAR_FLASH_MAP0)

+ );

+

+ //

+ // Copy Zero based Number Of Components

+ //

+ SpiInstance->NumberOfComponents = (UINT8)((MmioRead16 (ScSpiBar0 + R_SPI_FDOD) & B_SPI_FDBAR_NC) >> N_SPI_FDBAR_NC);

+

+ MmioAndThenOr32 (

+ ScSpiBar0 + R_SPI_FDOC,

+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),

+ (UINT32)(V_SPI_FDOC_FDSS_COMP | R_SPI_FCBA_FLCOMP)

+ );

+

+ //

+ // Copy Component 0 Density

+ //

+ Comp0Density = (UINT8)MmioRead32 (ScSpiBar0 + R_SPI_FDOD) & B_SPI_FLCOMP_COMP1_MASK;

+ SpiInstance->Component1StartAddr = (UINT32)(SIZE_512KB << Comp0Density);

+

+ //

+ // Select FLASH_MAP1 to get Flash SC Strap Base Address

+ //

+ MmioAndThenOr32 (

+ (ScSpiBar0 + R_SPI_FDOC),

+ (UINT32)(~(B_SPI_FDOC_FDSS_MASK | B_SPI_FDOC_FDSI_MASK)),

+ (UINT32)(V_SPI_FDOC_FDSS_FSDM | R_SPI_FDBAR_FLASH_MAP1)

+ );

+

+ SpiInstance->StrapBaseAddress = MmioRead32 (ScSpiBar0 + R_SPI_FDOD) & B_SPI_FDBAR_FPSBA;

+

+ //

+ // Align FPSBA with address bits for the SC Strap portion of flash descriptor

+ //

+ SpiInstance->StrapBaseAddress &= B_SPI_FDBAR_FPSBA;

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Read data from the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[out] Buffer The Pointer to caller-allocated buffer containing the data received.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashRead (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ OUT UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (FlashRegionType, FlashCycleRead, Address, ByteCount, Buffer);

+ return Status;

+}

+

+/**

+ Write data to the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in] Buffer Pointer to caller-allocated buffer containing the data sent during the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWrite (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (FlashRegionType, FlashCycleWrite, Address, ByteCount, Buffer);

+ return Status;

+}

+

+/**

+ Erase some area on the flash part.

+

+ @param[in] FlashRegionType The Flash Region type for flash cycle which is listed in the Descriptor.

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashErase (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (FlashRegionType, FlashCycleErase, Address, ByteCount, NULL);

+ return Status;

+}

+

+/**

+ Read SFDP data from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in SFDP data portion of the SPI cycle, the max number is 64

+ @param[out] SfdpData The Pointer to caller-allocated buffer containing the SFDP data received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadSfdp (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SfdpData

+ )

+{

+ EFI_STATUS Status;

+ UINT32 Address;

+ SPI_INSTANCE *SpiInstance;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ if ((ByteCount > 64) || (ComponentNumber > SpiInstance->NumberOfComponents)) {

+ ASSERT (FALSE);

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Address = 0;

+ if (ComponentNumber == FlashComponent1) {

+ Address = SpiInstance->Component1StartAddr;

+ }

+

+ Status = SendSpiCmd (0, FlashCycleReadSfdp, Address, ByteCount, SfdpData);

+ return Status;

+}

+

+/**

+ Read Jedec Id from the flash part.

+

+ @param[in] ComponentNumber The Component Number for chip select

+ @param[in] ByteCount Number of bytes in JedecId data portion of the SPI cycle, the data size is 3 typically

+ @param[out] JedecId The Pointer to caller-allocated buffer containing JEDEC ID received

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadJedecId (

+ IN UINT8 ComponentNumber,

+ IN UINT32 ByteCount,

+ OUT UINT8 *JedecId

+ )

+{

+ EFI_STATUS Status;

+ UINT32 Address;

+ SPI_INSTANCE *SpiInstance;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ if (ComponentNumber > SpiInstance->NumberOfComponents) {

+ ASSERT (FALSE);

+ return EFI_INVALID_PARAMETER;

+ }

+

+ Address = 0;

+ if (ComponentNumber == FlashComponent1) {

+ Address = SpiInstance->Component1StartAddr;

+ }

+

+ Status = SendSpiCmd (0, FlashCycleReadJedecId, Address, ByteCount, JedecId);

+ return Status;

+}

+

+/**

+ Write the status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[in] StatusValue The Pointer to caller-allocated buffer containing the value of Status register writing

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashWriteStatus (

+ IN UINT32 ByteCount,

+ IN UINT8 *StatusValue

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (0, FlashCycleWriteStatus, 0, ByteCount, StatusValue);

+ return Status;

+}

+

+/**

+ Read status register in the flash part.

+

+ @param[in] ByteCount Number of bytes in Status data portion of the SPI cycle, the data size is 1 typically

+ @param[out] StatusValue The Pointer to caller-allocated buffer containing the value of Status register received.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiFlashReadStatus (

+ IN UINT32 ByteCount,

+ OUT UINT8 *StatusValue

+ )

+{

+ EFI_STATUS Status;

+

+ Status = SendSpiCmd (0, FlashCycleReadStatus, 0, ByteCount, StatusValue);

+ return Status;

+}

+

+/**

+ Read SC Soft Strap Values

+

+ @param[in] SoftStrapAddr SC Soft Strap address offset from FPSBA.

+ @param[in] ByteCount Number of bytes in SoftStrap data portion of the SPI cycle

+ @param[out] SoftStrapValue The Pointer to caller-allocated buffer containing SC Soft Strap Value.

+ It is the caller's responsibility to make sure Buffer is large enough for the total number of bytes read.

+

+ @retval EFI_SUCCESS Command succeed.

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+ @retval EFI_DEVICE_ERROR Device error, command aborts abnormally.

+**/

+EFI_STATUS

+EFIAPI

+SpiReadPchSoftStrap (

+ IN UINT32 SoftStrapAddr,

+ IN UINT32 ByteCount,

+ OUT UINT8 *SoftStrapValue

+ )

+{

+ UINT32 StrapFlashAddr;

+ EFI_STATUS Status;

+ SPI_INSTANCE *SpiInstance;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ ASSERT (SpiInstance->StrapBaseAddress != 0);

+ //

+ // SC Strap Flash Address = FPSBA + RamAddr

+ //

+ StrapFlashAddr = SpiInstance->StrapBaseAddress + SoftStrapAddr;

+

+ Status = SendSpiCmd (FlashRegionDescriptor, FlashCycleRead, StrapFlashAddr, ByteCount, SoftStrapValue);

+ return Status;

+}

+

+/**

+ This function sends the programmed SPI command to the slave device.

+

+ @param[in] FlashRegionType The SPI Region type for flash cycle which is listed in the Descriptor

+ @param[in] FlashCycleType The Flash SPI cycle type list in HSFC (Hardware Sequencing Flash Control Register) register

+ @param[in] Address The Flash Linear Address must fall within a region for which BIOS has access permissions.

+ @param[in] ByteCount Number of bytes in the data portion of the SPI cycle.

+ @param[in,out] Buffer Pointer to caller-allocated buffer containing the data received or sent during the SPI cycle.

+

+ @retval EFI_SUCCESS SPI command completes successfully.

+ @retval EFI_DEVICE_ERROR Device error, the command aborts abnormally.

+ @retval EFI_ACCESS_DENIED Some unrecognized command encountered in hardware sequencing mode

+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.

+**/

+EFI_STATUS

+SendSpiCmd (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ IN FLASH_CYCLE_TYPE FlashCycleType,

+ IN UINT32 Address,

+ IN UINT32 ByteCount,

+ IN OUT UINT8 *Buffer

+ )

+{

+ EFI_STATUS Status;

+ UINT32 Index;

+ UINTN SpiBaseAddress;

+ UINT32 ScSpiBar0;

+ UINT32 LimitAddress;

+ UINT32 HardwareSpiAddr;

+ UINT16 PermissionBit;

+ UINT32 SpiDataCount;

+ UINT32 FlashCycle;

+ UINT8 BiosCtlSave;

+ SPI_INSTANCE *SpiInstance;

+ UINT32 Data32;

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ Status = EFI_SUCCESS;

+ SpiBaseAddress = SpiInstance->PchSpiBase;

+ ScSpiBar0 = AcquireSpiBar0 (SpiBaseAddress);

+ BiosCtlSave = 0;

+ SpiInstance->RegionPermission = MmioRead16 (ScSpiBar0 + R_SPI_FRAP);

+

+ //

+ // If it's write cycle, disable Prefetching, Caching and disable BIOS Write Protect

+ //

+ if ((FlashCycleType == FlashCycleWrite) || (FlashCycleType == FlashCycleErase)) {

+ Status = DisableBiosWriteProtect (SpiBaseAddress, mSpiInstance->Flags & FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT);

+ if (EFI_ERROR (Status)) {

+ goto SendSpiCmdEnd;

+ }

+

+ BiosCtlSave = SaveAndDisableSpiPrefetchCache (SpiBaseAddress);

+ }

+

+ //

+ // Make sure it's safe to program the command.

+ //

+ if (!WaitForSpiCycleComplete (ScSpiBar0, FALSE)) {

+ Status = EFI_DEVICE_ERROR;

+ goto SendSpiCmdEnd;

+ }

+

+ HardwareSpiAddr = Address;

+ if ((FlashCycleType == FlashCycleRead) ||

+ (FlashCycleType == FlashCycleWrite) ||

+ (FlashCycleType == FlashCycleErase))

+ {

+ switch (FlashRegionType) {

+ case FlashRegionDescriptor:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_FLASHD;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_FLASHD;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG0_FLASHD);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG0_BASE_MASK) << N_SPI_FREG0_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG0_LIMIT_MASK) >> N_SPI_FREG0_LIMIT;

+ break;

+

+ case FlashRegionBios:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_BIOS;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_BIOS;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG1_BIOS);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG1_BASE_MASK) << N_SPI_FREG1_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG1_LIMIT_MASK) >> N_SPI_FREG1_LIMIT;

+ break;

+

+ case FlashRegionMe:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_SEC;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_SEC;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG2_SEC);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG2_BASE_MASK) << N_SPI_FREG2_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG2_LIMIT_MASK) >> N_SPI_FREG2_LIMIT;

+ break;

+

+ case FlashRegionGbE:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_GBE;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_GBE;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG3_GBE);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG3_BASE_MASK) << N_SPI_FREG3_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG3_LIMIT_MASK) >> N_SPI_FREG3_LIMIT;

+ break;

+

+ case FlashRegionPlatformData:

+ if (FlashCycleType == FlashCycleRead) {

+ PermissionBit = B_SPI_FRAP_BRRA_PLATFORM;

+ } else {

+ PermissionBit = B_SPI_FRAP_BRWA_PLATFORM;

+ }

+

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_FREG4_PLATFORM_DATA);

+ HardwareSpiAddr += (Data32 & B_SPI_FREG4_BASE_MASK) << N_SPI_FREG4_BASE;

+ LimitAddress = (Data32 & B_SPI_FREG4_LIMIT_MASK) >> N_SPI_FREG4_LIMIT;

+ break;

+

+ case FlashRegionAll:

+ //

+ // FlashRegionAll indicates address is relative to flash device

+ // No error checking for this case

+ //

+ LimitAddress = 0;

+ PermissionBit = 0;

+ break;

+

+ default:

+ Status = EFI_UNSUPPORTED;

+ goto SendSpiCmdEnd;

+ }

+

+ if ((LimitAddress != 0) && (Address > LimitAddress)) {

+ Status = EFI_INVALID_PARAMETER;

+ goto SendSpiCmdEnd;

+ }

+

+ //

+ // If the operation is read, but the region attribute is not read allowed, return error.

+ // If the operation is write, but the region attribute is not write allowed, return error.

+ //

+ if ((PermissionBit != 0) && ((SpiInstance->RegionPermission & PermissionBit) == 0)) {

+ Status = EFI_ACCESS_DENIED;

+ goto SendSpiCmdEnd;

+ }

+ }

+

+ //

+ // Check for SC SPI hardware sequencing required commands

+ //

+ FlashCycle = 0;

+ switch (FlashCycleType) {

+ case FlashCycleRead:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleWrite:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_WRITE << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleErase:

+ if (((ByteCount % SIZE_4KB) != 0) || ((HardwareSpiAddr % SIZE_4KB) != 0)) {

+ DEBUG ((DEBUG_ERROR, "Erase and erase size must be 4KB aligned. \n"));

+ ASSERT (FALSE);

+ Status = EFI_INVALID_PARAMETER;

+ goto SendSpiCmdEnd;

+ }

+

+ break;

+

+ case FlashCycleReadSfdp:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ_SFDP << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleReadJedecId:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ_JEDEC_ID << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleWriteStatus:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_WRITE_STATUS << N_SPI_HSFS_CYCLE);

+ break;

+

+ case FlashCycleReadStatus:

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_READ_STATUS << N_SPI_HSFS_CYCLE);

+ break;

+

+ default:

+ //

+ // Unrecognized Operation

+ //

+ ASSERT (FALSE);

+ Status = EFI_INVALID_PARAMETER;

+ goto SendSpiCmdEnd;

+ break;

+ }

+

+ do {

+ SpiDataCount = ByteCount;

+ if ((FlashCycleType == FlashCycleRead) || (FlashCycleType == FlashCycleWrite)) {

+ //

+ // Trim at 256 byte boundary per operation,

+ // - SC SPI controller requires trimming at 4KB boundary

+ // - Some SPI chips require trimming at 256 byte boundary for write operation

+ // - Trimming has limited performance impact as we can read / write at most 64 byte

+ // per operation

+ //

+ if (HardwareSpiAddr + ByteCount > ((HardwareSpiAddr + BIT8) &~(BIT8 - 1))) {

+ SpiDataCount = (((UINT32)(HardwareSpiAddr) + BIT8) &~(BIT8 - 1)) - (UINT32)(HardwareSpiAddr);

+ }

+

+ //

+ // Calculate the number of bytes to shift in/out during the SPI data cycle.

+ // Valid settings for the number of bytes during each data portion of the

+ // SC SPI cycles are: 0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 24, 32, 40, 48, 56, 64

+ //

+ if (SpiDataCount >= 64) {

+ SpiDataCount = 64;

+ } else if ((SpiDataCount &~0x07) != 0) {

+ SpiDataCount = SpiDataCount &~0x07;

+ }

+ }

+

+ if (FlashCycleType == FlashCycleErase) {

+ if (((ByteCount / SIZE_64KB) != 0) &&

+ ((ByteCount % SIZE_64KB) == 0) &&

+ ((HardwareSpiAddr % SIZE_64KB) == 0))

+ {

+ if (HardwareSpiAddr < SpiInstance->Component1StartAddr) {

+ //

+ // Check whether Component0 support 64k Erase

+ //

+ if ((SpiInstance->SfdpVscc0Value & B_SPI_LVSCC_EO_64K) != 0) {

+ SpiDataCount = SIZE_64KB;

+ } else {

+ SpiDataCount = SIZE_4KB;

+ }

+ } else {

+ //

+ // Check whether Component1 support 64k Erase

+ //

+ if ((SpiInstance->SfdpVscc1Value & B_SPI_LVSCC_EO_64K) != 0) {

+ SpiDataCount = SIZE_64KB;

+ } else {

+ SpiDataCount = SIZE_4KB;

+ }

+ }

+ } else {

+ SpiDataCount = SIZE_4KB;

+ }

+

+ if (SpiDataCount == SIZE_4KB) {

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_4K_ERASE << N_SPI_HSFS_CYCLE);

+ } else {

+ FlashCycle = (UINT32)(V_SPI_HSFS_CYCLE_64K_ERASE << N_SPI_HSFS_CYCLE);

+ }

+ }

+

+ //

+ // If it's write cycle, load data into the SPI data buffer.

+ //

+ if ((FlashCycleType == FlashCycleWrite) || (FlashCycleType == FlashCycleWriteStatus)) {

+ if ((SpiDataCount & 0x07) != 0) {

+ //

+ // Use Byte write if Data Count is 0, 1, 2, 3, 4, 5, 6, 7

+ //

+ for (Index = 0; Index < SpiDataCount; Index++) {

+ MmioWrite8 (ScSpiBar0 + R_SPI_FDATA00 + Index, Buffer[Index]);

+ }

+ } else {

+ //

+ // Use Dword write if Data Count is 8, 16, 24, 32, 40, 48, 56, 64

+ //

+ for (Index = 0; Index < SpiDataCount; Index += sizeof (UINT32)) {

+ MmioWrite32 (ScSpiBar0 + R_SPI_FDATA00 + Index, *(UINT32 *)(Buffer + Index));

+ }

+ }

+ }

+

+ //

+ // Set the Flash Address

+ //

+ MmioWrite32 (ScSpiBar0 + R_SPI_FADDR, (UINT32)(HardwareSpiAddr & B_SPI_FADDR_MASK));

+

+ //

+ // Set Data count, Flash cycle, and Set Go bit to start a cycle

+ //

+ MmioAndThenOr32 (

+ ScSpiBar0 + R_SPI_HSFS,

+ (UINT32)(~(B_SPI_HSFS_FDBC_MASK | B_SPI_HSFS_CYCLE_MASK)),

+ (UINT32)(((SpiDataCount - 1) << N_SPI_HSFS_FDBC) | FlashCycle | B_SPI_HSFS_CYCLE_FGO)

+ );

+

+ //

+ // Wait for command execution complete.

+ //

+ if (!WaitForSpiCycleComplete (ScSpiBar0, TRUE)) {

+ Status = EFI_DEVICE_ERROR;

+ goto SendSpiCmdEnd;

+ }

+

+ //

+ // If it's read cycle, load data into the caller's buffer.

+ //

+ if ((FlashCycleType == FlashCycleRead) ||

+ (FlashCycleType == FlashCycleReadSfdp) ||

+ (FlashCycleType == FlashCycleReadJedecId) ||

+ (FlashCycleType == FlashCycleReadStatus))

+ {

+ if ((SpiDataCount & 0x07) != 0) {

+ //

+ // Use Byte read if Data Count is 0, 1, 2, 3, 4, 5, 6, 7

+ //

+ for (Index = 0; Index < SpiDataCount; Index++) {

+ Buffer[Index] = MmioRead8 (ScSpiBar0 + R_SPI_FDATA00 + Index);

+ }

+ } else {

+ //

+ // Use Dword read if Data Count is 8, 16, 24, 32, 40, 48, 56, 64

+ //

+ for (Index = 0; Index < SpiDataCount; Index += sizeof (UINT32)) {

+ *(UINT32 *)(Buffer + Index) = MmioRead32 (ScSpiBar0 + R_SPI_FDATA00 + Index);

+ }

+ }

+ }

+

+ HardwareSpiAddr += SpiDataCount;

+ Buffer += SpiDataCount;

+ ByteCount -= SpiDataCount;

+ } while (ByteCount > 0);

+

+SendSpiCmdEnd:

+ ///

+ /// Restore the settings for SPI Prefetching and Caching and enable BIOS Write Protect

+ ///

+ if ((FlashCycleType == FlashCycleWrite) || (FlashCycleType == FlashCycleErase)) {

+ EnableBiosWriteProtect (SpiBaseAddress, mSpiInstance->Flags & FLAGS_SPI_DISABLE_SMM_WRITE_PROTECT);

+ SetSpiBiosControlRegister (SpiBaseAddress, BiosCtlSave);

+ }

+

+ ReleaseSpiBar0 (SpiBaseAddress);

+

+ return Status;

+}

+

+/**

+ Wait execution cycle to complete on the SPI interface.

+

+ @param[in] ScSpiBar0 Spi MMIO base address

+ @param[in] ErrorCheck TRUE if the SpiCycle needs to do the error check

+

+ @retval TRUE SPI cycle completed on the interface.

+ @retval FALSE Time out while waiting the SPI cycle to complete.

+ It's not safe to program the next command on the SPI interface.

+**/

+BOOLEAN

+WaitForSpiCycleComplete (

+ IN UINT32 ScSpiBar0,

+ IN BOOLEAN ErrorCheck

+ )

+{

+ UINT64 WaitTicks;

+ UINT64 WaitCount;

+ UINT32 Data32;

+

+ //

+ // Convert the wait period allowed into to tick count

+ //

+ WaitCount = WAIT_TIME / WAIT_PERIOD;

+ //

+ // Wait for the SPI cycle to complete.

+ //

+ for (WaitTicks = 0; WaitTicks < WaitCount; WaitTicks++) {

+ Data32 = MmioRead32 (ScSpiBar0 + R_SPI_HSFS);

+ if ((Data32 & B_SPI_HSFS_SCIP) == 0) {

+ MmioWrite32 (ScSpiBar0 + R_SPI_HSFS, B_SPI_HSFS_FCERR | B_SPI_HSFS_FDONE);

+ if (((Data32 & B_SPI_HSFS_FCERR) != 0) && ErrorCheck) {

+ return FALSE;

+ } else {

+ return TRUE;

+ }

+ }

+

+ MicroSecondDelay (WAIT_PERIOD);

+ }

+

+ return FALSE;

+}

+

+/**

+ Get the SPI region base and size, based on the enum type

+

+ @param[in] FlashRegionType The Flash Region type for for the base address which is listed in the Descriptor.

+ @param[out] BaseAddress The Flash Linear Address for the Region 'n' Base

+ @param[out] RegionSize The size for the Region 'n'

+

+ @retval EFI_SUCCESS Read success

+ @retval EFI_INVALID_PARAMETER Invalid region type given

+ @retval EFI_DEVICE_ERROR The region is not used

+**/

+EFI_STATUS

+EFIAPI

+SpiGetRegionAddress (

+ IN FLASH_REGION_TYPE FlashRegionType,

+ OUT UINT32 *BaseAddress OPTIONAL,

+ OUT UINT32 *RegionSize OPTIONAL

+ )

+{

+ UINT32 ScSpiBar0;

+ UINT32 ReadValue;

+ UINT32 Base;

+ SPI_INSTANCE *SpiInstance;

+

+ if (FlashRegionType >= FlashRegionMax) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ SpiInstance = GetSpiInstance ();

+ if (SpiInstance == NULL) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ if (FlashRegionType == FlashRegionAll) {

+ if (BaseAddress != NULL) {

+ *BaseAddress = 0;

+ }

+

+ if (RegionSize != NULL) {

+ *RegionSize = SpiInstance->Component1StartAddr;

+ }

+

+ return EFI_SUCCESS;

+ }

+

+ ScSpiBar0 = AcquireSpiBar0 (SpiInstance->PchSpiBase);

+ ReadValue = MmioRead32 (ScSpiBar0 + R_SPI_FREG0_FLASHD + S_SPI_FREGX * (UINT32)FlashRegionType);

+ ReleaseSpiBar0 (SpiInstance->PchSpiBase);

+

+ //

+ // If the region is not used, the Region Base is 7FFFh and Region Limit is 0000h

+ //

+ if (ReadValue == B_SPI_FREGX_BASE_MASK) {

+ return EFI_DEVICE_ERROR;

+ }

+

+ Base = (ReadValue & B_SPI_FREG1_BASE_MASK) << N_SPI_FREG1_BASE;

+ if (BaseAddress != NULL) {

+ *BaseAddress = Base;

+ }

+

+ if (RegionSize != NULL) {

+ *RegionSize = ((((ReadValue & B_SPI_FREGX_LIMIT_MASK) >> N_SPI_FREGX_LIMIT) + 1) <<

+ N_SPI_FREGX_LIMIT_REPR) - Base;

+ }

+

+ return EFI_SUCCESS;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf
new file mode 100644
index 0000000000..fae851c12f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf
@@ -0,0 +1,48 @@
+## @file

+# Library instance for SPI flash library using SPI hardware sequence

+#

+# Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = SpiFlashLib

+ FILE_GUID = 6F96AFCB-DE89-4ca1-A63F-8703EE8FDE50

+ MODULE_TYPE = BASE

+ VERSION_STRING = 1.0

+ LIBRARY_CLASS = SpiFlashLib

+ CONSTRUCTOR = SpiConstructor

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ RegsSpi.h

+ SpiCommon.h

+ PchSpi.c

+ SpiFlashLib.c

+

+[Packages]

+ MdePkg/MdePkg.dec

+ MdeModulePkg/MdeModulePkg.dec

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

+[LibraryClasses]

+ BaseLib

+ PcdLib

+ IoLib

+ PciLib

+ HobLib

+ TimerLib

+ BaseLib

+

+[Guids]

+ gSpiFlashInfoGuid

+

+[Pcd]

+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress

diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c
new file mode 100644
index 0000000000..7fc589303e
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c
@@ -0,0 +1,455 @@
+/** @file

+ SMM SwDispatch2 Protocol.

+

+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+

+

+**/

+

+#include "PchSmiDispatchSmm.h"

+

+typedef struct {

+ UINT8 EosBitOffset;

+ UINT8 ApmBitOffset;

+ UINT32 SmiEosAddr;

+ UINT32 SmiApmStsAddr;

+} SMM_PCH_REGISTER;

+

+SMM_PCH_REGISTER mSmiPchReg;

+

+EFI_SMM_CPU_PROTOCOL *mSmmCpuProtocol;

+LIST_ENTRY mSmmSwDispatch2Queue = INITIALIZE_LIST_HEAD_VARIABLE (mSmmSwDispatch2Queue);

+

+/**

+ Find SmmSwDispatch2Context by SwSmiInputValue.

+

+ @param[in] SwSmiInputValue The value to indentify the SmmSwDispatch2 context

+

+ @return Pointer to EFI_SMM_SW_DISPATCH2_CONTEXT context

+**/

+EFI_SMM_SW_DISPATCH2_CONTEXT *

+FindContextBySwSmiInputValue (

+ IN UINTN SwSmiInputValue

+ )

+{

+ LIST_ENTRY *Node;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;

+

+ Node = mSmmSwDispatch2Queue.ForwardLink;

+ for ( ; Node != &mSmmSwDispatch2Queue; Node = Node->ForwardLink) {

+ Dispatch2Context = BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link);

+ if (Dispatch2Context->SwSmiInputValue == SwSmiInputValue) {

+ return Dispatch2Context;

+ }

+ }

+

+ return NULL;

+}

+

+/**

+ Find SmmSwDispatch2Context by DispatchHandle.

+

+ @param DispatchHandle The handle to indentify the SmmSwDispatch2 context

+

+ @return Pointer to EFI_SMM_SW_DISPATCH2_CONTEXT context

+**/

+EFI_SMM_SW_DISPATCH2_CONTEXT *

+FindContextByDispatchHandle (

+ IN EFI_HANDLE DispatchHandle

+ )

+{

+ LIST_ENTRY *Node;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;

+

+ Node = mSmmSwDispatch2Queue.ForwardLink;

+ for ( ; Node != &mSmmSwDispatch2Queue; Node = Node->ForwardLink) {

+ Dispatch2Context = BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link);

+ if (Dispatch2Context->DispatchHandle == DispatchHandle) {

+ return Dispatch2Context;

+ }

+ }

+

+ return NULL;

+}

+

+/**

+ Dispatch registered SMM handlers

+

+ @param DispatchHandle The unique handle assigned to this handler by SmiHandlerRegister().

+ @param RegisterContext Points to an optional handler context which was specified when the handler was registered.

+ @param CommBuffer A pointer to a collection of data in memory that will

+ be conveyed from a non-SMM environment into an SMM environment.

+ @param CommBufferSize The size of the CommBuffer.

+

+ @return Status Code

+

+**/

+EFI_STATUS

+SmmSwDispatcher (

+ IN EFI_HANDLE DispatchHandle,

+ IN CONST VOID *RegisterContext,

+ IN OUT VOID *CommBuffer,

+ IN OUT UINTN *CommBufferSize

+ )

+{

+ EFI_STATUS Status;

+ EFI_SMM_SW_CONTEXT SwContext;

+ UINTN Index;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;

+ EFI_SMM_HANDLER_ENTRY_POINT2 DispatchFunction;

+ EFI_SMM_SW_REGISTER_CONTEXT DispatchContext;

+ UINTN Size;

+ EFI_SMM_SAVE_STATE_IO_INFO IoInfo;

+

+ //

+ // Construct new context

+ //

+ SwContext.SwSmiCpuIndex = 0;

+ SwContext.CommandPort = IoRead8 (SMM_CONTROL_PORT);

+ SwContext.DataPort = IoRead8 (SMM_DATA_PORT);

+

+ //

+ // Try to find which CPU trigger SWSMI

+ //

+ for (Index = 0; Index < gSmst->NumberOfCpus; Index++) {

+ Status = mSmmCpuProtocol->ReadSaveState (

+ mSmmCpuProtocol,

+ sizeof (IoInfo),

+ EFI_SMM_SAVE_STATE_REGISTER_IO,

+ Index,

+ &IoInfo

+ );

+ if (EFI_ERROR (Status)) {

+ continue;

+ }

+

+ if (IoInfo.IoPort == SMM_CONTROL_PORT) {

+ //

+ // Great! Find it.

+ //

+ SwContext.SwSmiCpuIndex = Index;

+ DEBUG ((DEBUG_VERBOSE, "CPU index = 0x%x/0x%x\n", Index, gSmst->NumberOfCpus));

+ break;

+ }

+ }

+

+ if (SwContext.CommandPort == 0) {

+ DEBUG ((DEBUG_VERBOSE, "NOT SW SMI\n"));

+ Status = EFI_SUCCESS;

+ goto End;

+ }

+

+ //

+ // Search context

+ //

+ Context = FindContextBySwSmiInputValue (SwContext.CommandPort);

+ if (Context == NULL) {

+ DEBUG ((DEBUG_INFO, "No handler for SMI value 0x%x\n", SwContext.CommandPort));

+ Status = EFI_SUCCESS;

+ goto End;

+ }

+

+ DEBUG ((DEBUG_VERBOSE, "Prepare to call handler for 0x%x\n", SwContext.CommandPort));

+

+ //

+ // Dispatch

+ //

+ DispatchContext.SwSmiInputValue = SwContext.CommandPort;

+ Size = sizeof (SwContext);

+ DispatchFunction = (EFI_SMM_HANDLER_ENTRY_POINT2)Context->DispatchFunction;

+ Status = DispatchFunction (DispatchHandle, &DispatchContext, &SwContext, &Size);

+

+End:

+ //

+ // Clear SMI APM status

+ //

+ IoOr32 (mSmiPchReg.SmiApmStsAddr, 1 << mSmiPchReg.ApmBitOffset);

+

+ //

+ // Set EOS bit

+ //

+ IoOr32 (mSmiPchReg.SmiEosAddr, 1 << mSmiPchReg.EosBitOffset);

+

+ return Status;

+}

+

+/**

+Check the SwSmiInputValue is already used

+

+@param[in] SwSmiInputValue To indentify the SmmSwDispatch2 context

+

+@retval EFI_SUCCESS SwSmiInputValue could be used.

+@retval EFI_INVALID_PARAMETER SwSmiInputValue is already be used.

+

+**/

+EFI_STATUS

+SmiInputValueCheck (

+ IN UINTN SwSmiInputValue

+ )

+{

+ LIST_ENTRY *Node;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Dispatch2Context;

+

+ Node = mSmmSwDispatch2Queue.ForwardLink;

+ for ( ; Node != &mSmmSwDispatch2Queue; Node = Node->ForwardLink) {

+ Dispatch2Context = BASE_CR (Node, EFI_SMM_SW_DISPATCH2_CONTEXT, Link);

+ if (Dispatch2Context->SwSmiInputValue == SwSmiInputValue) {

+ return EFI_INVALID_PARAMETER;

+ }

+ }

+

+ return EFI_SUCCESS;

+}

+

+/**

+ Register a child SMI source dispatch function for the specified software SMI.

+

+ This service registers a function (DispatchFunction) which will be called when the software

+ SMI source specified by RegContext->SwSmiCpuIndex is detected. On return, DispatchHandle

+ contains a unique handle which may be used later to unregister the function using UnRegister().

+

+ @param[in] This Pointer to the EFI_SMM_SW_DISPATCH2_PROTOCOL instance.

+ @param[in] DispatchFunction Function to register for handler when the specified software

+ SMI is generated.

+ @param[in, out] RegContext Pointer to the dispatch function's context.

+ The caller fills this context in before calling

+ the register function to indicate to the register

+ function which Software SMI input value the

+ dispatch function should be invoked for.

+ @param[out] DispatchHandle Handle generated by the dispatcher to track the

+ function instance.

+

+ @retval EFI_SUCCESS The dispatch function has been successfully

+ registered and the SMI source has been enabled.

+ @retval EFI_DEVICE_ERROR The SW driver was unable to enable the SMI source.

+ @retval EFI_INVALID_PARAMETER RegisterContext is invalid. The SW SMI input value

+ is not within valid range.

+ @retval EFI_OUT_OF_RESOURCES There is not enough memory (system or SMM) to manage this

+ child.

+ @retval EFI_OUT_OF_RESOURCES A unique software SMI value could not be assigned

+ for this dispatch.

+**/

+EFI_STATUS

+EFIAPI

+SmmSwDispatch2Register (

+ IN CONST EFI_SMM_SW_DISPATCH2_PROTOCOL *This,

+ IN EFI_SMM_HANDLER_ENTRY_POINT2 DispatchFunction,

+ IN OUT EFI_SMM_SW_REGISTER_CONTEXT *RegContext,

+ OUT EFI_HANDLE *DispatchHandle

+ )

+{

+ EFI_STATUS Status;

+ UINTN Index;

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;

+

+ if (RegContext->SwSmiInputValue == (UINTN)-1) {

+ //

+ // If SwSmiInputValue is set to (UINTN) -1 then a unique value

+ // will be assigned and returned in the structure.

+ //

+ Status = EFI_NOT_FOUND;

+ for (Index = 1; Index < MAXIMUM_SWI_VALUE; Index++) {

+ Status = SmiInputValueCheck (Index);

+ if (!EFI_ERROR (Status)) {

+ RegContext->SwSmiInputValue = Index;

+ break;

+ }

+ }

+

+ if (RegContext->SwSmiInputValue == (UINTN)-1) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+ }

+

+ if ((RegContext->SwSmiInputValue > MAXIMUM_SWI_VALUE) || (RegContext->SwSmiInputValue == 0)) {

+ DEBUG ((DEBUG_ERROR, "ERROR: SMI value range (1 ~ 0x%x)\n", MAXIMUM_SWI_VALUE));

+ return EFI_INVALID_PARAMETER;

+ }

+

+ //

+ // Register

+ //

+ Status = gSmst->SmmAllocatePool (EfiRuntimeServicesData, sizeof (*Context), (VOID **)&Context);

+ ASSERT_EFI_ERROR (Status);

+ if (EFI_ERROR (Status)) {

+ return EFI_OUT_OF_RESOURCES;

+ }

+

+ *DispatchHandle = (EFI_HANDLE)Context;

+ Context->Signature = SMI_SW_HANDLER_SIGNATURE;

+ Context->SwSmiInputValue = RegContext->SwSmiInputValue;

+ Context->DispatchFunction = (UINTN)DispatchFunction;

+ Context->DispatchHandle = *DispatchHandle;

+ InsertTailList (&mSmmSwDispatch2Queue, &Context->Link);

+

+ return Status;

+}

+

+/**

+ Unregister a child SMI source dispatch function for the specified software SMI.

+

+ This service removes the handler associated with DispatchHandle so that it will no longer be

+ called in response to a software SMI.

+

+ @param[in] This Pointer to the EFI_SMM_SW_DISPATCH2_PROTOCOL instance.

+ @param[in] DispatchHandle Handle of dispatch function to deregister.

+

+ @retval EFI_SUCCESS The dispatch function has been successfully unregistered.

+ @retval EFI_INVALID_PARAMETER The DispatchHandle was not valid.

+**/

+EFI_STATUS

+EFIAPI

+SmmSwDispatch2UnRegister (

+ IN CONST EFI_SMM_SW_DISPATCH2_PROTOCOL *This,

+ IN EFI_HANDLE DispatchHandle

+ )

+{

+ EFI_SMM_SW_DISPATCH2_CONTEXT *Context;

+

+ //

+ // Unregister

+ //

+ Context = FindContextByDispatchHandle (DispatchHandle);

+ ASSERT (Context != NULL);

+ if (Context != NULL) {

+ RemoveEntryList (&Context->Link);

+ gSmst->SmmFreePool (Context);

+ }

+

+ return EFI_SUCCESS;

+}

+

+EFI_SMM_SW_DISPATCH2_PROTOCOL gSmmSwDispatch2 = {

+ SmmSwDispatch2Register,

+ SmmSwDispatch2UnRegister,

+ MAXIMUM_SWI_VALUE

+};

+

+/**

+ Get specified SMI register based on given register ID

+

+ @param[in] SmmRegister SMI related register array from bootloader

+ @param[in] Id The register ID to get.

+

+ @retval NULL The register is not found or the format is not expected.

+ @return smi register

+

+**/

+PLD_GENERIC_REGISTER *

+GetSmmCtrlRegById (

+ IN PLD_SMM_REGISTERS *SmmRegister,

+ IN UINT32 Id

+ )

+{

+ UINT32 Index;

+ PLD_GENERIC_REGISTER *PldReg;

+

+ PldReg = NULL;

+ for (Index = 0; Index < SmmRegister->Count; Index++) {

+ if (SmmRegister->Registers[Index].Id == Id) {

+ PldReg = &SmmRegister->Registers[Index];

+ break;

+ }

+ }

+

+ if (PldReg == NULL) {

+ DEBUG ((DEBUG_INFO, "Register %d not found.\n", Id));

+ return NULL;

+ }

+

+ //

+ // Checking the register if it is expected.

+ //

+ if ((PldReg->Address.AccessSize != EFI_ACPI_3_0_DWORD) ||

+ (PldReg->Address.Address == 0) ||

+ (PldReg->Address.RegisterBitWidth != 1) ||

+ (PldReg->Address.AddressSpaceId != EFI_ACPI_3_0_SYSTEM_IO) ||

+ (PldReg->Value != 1))

+ {

+ DEBUG ((DEBUG_INFO, "Unexpected SMM register.\n"));

+ DEBUG ((DEBUG_INFO, "AddressSpaceId= 0x%x\n", PldReg->Address.AddressSpaceId));

+ DEBUG ((DEBUG_INFO, "RegBitWidth = 0x%x\n", PldReg->Address.RegisterBitWidth));

+ DEBUG ((DEBUG_INFO, "RegBitOffset = 0x%x\n", PldReg->Address.RegisterBitOffset));

+ DEBUG ((DEBUG_INFO, "AccessSize = 0x%x\n", PldReg->Address.AccessSize));

+ DEBUG ((DEBUG_INFO, "Address = 0x%lx\n", PldReg->Address.Address));

+ return NULL;

+ }

+

+ return PldReg;

+}

+

+/**

+ Entry Point for this driver.

+

+ @param[in] ImageHandle Image handle of this driver.

+ @param[in] SystemTable A Pointer to the EFI System Table.

+

+ @retval EFI_SUCCESS The entry point is executed successfully.

+ @retval other Some error occurred when executing this entry point.

+**/

+EFI_STATUS

+EFIAPI

+PchSmiDispatchEntryPoint (

+ IN EFI_HANDLE ImageHandle,

+ IN EFI_SYSTEM_TABLE *SystemTable

+ )

+{

+ EFI_STATUS Status;

+ EFI_HANDLE DispatchHandle;

+ EFI_HOB_GUID_TYPE *GuidHob;

+ PLD_SMM_REGISTERS *SmmRegister;

+ PLD_GENERIC_REGISTER *SmiEosReg;

+ PLD_GENERIC_REGISTER *SmiApmStsReg;

+

+ GuidHob = GetFirstGuidHob (&gSmmRegisterInfoGuid);

+ if (GuidHob == NULL) {

+ return EFI_UNSUPPORTED;

+ }

+

+ SmmRegister = (PLD_SMM_REGISTERS *)GET_GUID_HOB_DATA (GuidHob);

+ SmiEosReg = GetSmmCtrlRegById (SmmRegister, REGISTER_ID_SMI_EOS);

+ if (SmiEosReg == NULL) {

+ DEBUG ((DEBUG_ERROR, "SMI EOS reg not found.\n"));

+ return EFI_NOT_FOUND;

+ }

+

+ mSmiPchReg.SmiEosAddr = (UINT32)SmiEosReg->Address.Address;

+ mSmiPchReg.EosBitOffset = SmiEosReg->Address.RegisterBitOffset;

+

+ SmiApmStsReg = GetSmmCtrlRegById (SmmRegister, REGISTER_ID_SMI_APM_STS);

+ if (SmiApmStsReg == NULL) {

+ DEBUG ((DEBUG_ERROR, "SMI APM status reg not found.\n"));

+ return EFI_NOT_FOUND;

+ }

+

+ mSmiPchReg.SmiApmStsAddr = (UINT32)SmiApmStsReg->Address.Address;

+ mSmiPchReg.ApmBitOffset = SmiApmStsReg->Address.RegisterBitOffset;

+

+ //

+ // Locate PI SMM CPU protocol

+ //

+ Status = gSmst->SmmLocateProtocol (&gEfiSmmCpuProtocolGuid, NULL, (VOID **)&mSmmCpuProtocol);

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Register a SMM handler to handle subsequent SW SMIs.

+ //

+ Status = gSmst->SmiHandlerRegister ((EFI_MM_HANDLER_ENTRY_POINT)SmmSwDispatcher, NULL, &DispatchHandle);

+ ASSERT_EFI_ERROR (Status);

+

+ //

+ // Publish PI SMM SwDispatch2 Protocol

+ //

+ ImageHandle = NULL;

+ Status = gSmst->SmmInstallProtocolInterface (

+ &ImageHandle,

+ &gEfiSmmSwDispatch2ProtocolGuid,

+ EFI_NATIVE_INTERFACE,

+ &gSmmSwDispatch2

+ );

+ ASSERT_EFI_ERROR (Status);

+

+ return Status;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h
new file mode 100644
index 0000000000..c14fe99929
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h
@@ -0,0 +1,36 @@
+/** @file

+ The header file for SMM SwDispatch2 module.

+

+ Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#ifndef SMM_SW_DISPATCH2_H_

+#define SMM_SW_DISPATCH2_H_

+

+#include <PiDxe.h>

+#include <Protocol/SmmSwDispatch2.h>

+#include <Protocol/SmmCpu.h>

+#include <Library/UefiDriverEntryPoint.h>

+#include <Library/SmmServicesTableLib.h>

+#include <Library/BaseLib.h>

+#include <Library/IoLib.h>

+#include <Library/DebugLib.h>

+#include <Guid/SmmRegisterInfoGuid.h>

+#include <Library/HobLib.h>

+

+#define SMI_SW_HANDLER_SIGNATURE SIGNATURE_32('s','s','w','h')

+#define MAXIMUM_SWI_VALUE 0xFF

+#define SMM_CONTROL_PORT 0xB2

+#define SMM_DATA_PORT 0xB3

+

+typedef struct {

+ UINTN Signature;

+ LIST_ENTRY Link;

+ EFI_HANDLE DispatchHandle;

+ UINTN SwSmiInputValue;

+ UINTN DispatchFunction;

+} EFI_SMM_SW_DISPATCH2_CONTEXT;

+

+#endif

diff --git a/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf
new file mode 100644
index 0000000000..96a154e888
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf
@@ -0,0 +1,51 @@
+## @file

+# PCH SMM SMI Software dispatch module.

+#

+# Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>

+#

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ INF_VERSION = 0x00010005

+ BASE_NAME = PchSmiDispatchSmm

+ FILE_GUID = 60F343E3-2AE2-4AA7-B01E-BF9BD5C04A3B

+ MODULE_TYPE = DXE_SMM_DRIVER

+ VERSION_STRING = 1.0

+ PI_SPECIFICATION_VERSION = 0x0001000A

+ ENTRY_POINT = PchSmiDispatchEntryPoint

+

+#

+# The following information is for reference only and not required by the build tools.

+#

+# VALID_ARCHITECTURES = IA32 X64

+#

+

+[Sources]

+ PchSmiDispatchSmm.c

+ PchSmiDispatchSmm.h

+

+[Packages]

+ MdePkg/MdePkg.dec

+ UefiPayloadPkg/UefiPayloadPkg.dec

+

+[LibraryClasses]

+ UefiDriverEntryPoint

+ MemoryAllocationLib

+ DebugLib

+ UefiBootServicesTableLib

+ SmmServicesTableLib

+ BaseLib

+ IoLib

+ HobLib

+

+[Protocols]

+ gEfiSmmCpuProtocolGuid # PROTOCOL ALWAYS_CONSUMED

+ gEfiSmmSwDispatch2ProtocolGuid # PROTOCOL ALWAYS_PRODUCED

+

+[Guids]

+ gSmmRegisterInfoGuid

+

+[Depex]

+ gEfiSmmCpuProtocolGuid

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec
new file mode 100644
index 0000000000..549f96d85f
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec
@@ -0,0 +1,49 @@
+## @file

+# Payload Platform Package

+#

+# Provides drivers and definitions to create payload platform FV.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ DEC_SPECIFICATION = 0x00010005

+ PACKAGE_NAME = PlatformPayloadPkg

+ PACKAGE_GUID = 17F3ACAC-079D-4518-9EBF-E33289733E8C

+ PACKAGE_VERSION = 0.1

+

+[Includes]

+ Include

+

+[Guids]

+ #

+ ## Defines the token space for the Payload platform Package PCDs.

+ #

+ gPlatformPayloadPkgTokenSpaceGuid = {0xa375ddc6, 0x74fb, 0x4de1, {0x82, 0x6d, 0xa3, 0x10, 0xa3, 0x3b, 0x89, 0x77}}

+

+ #

+ # SPI variable support

+ #

+ gNvVariableInfoGuid = { 0x7a345dca, 0xc26, 0x4f2a, { 0xa8, 0x9a, 0x57, 0xc0, 0x8d, 0xdd, 0x22, 0xee } }

+ gSpiFlashInfoGuid = { 0x2d4aac1b, 0x91a5, 0x4cd5, { 0x9b, 0x5c, 0xb4, 0x0f, 0x5d, 0x28, 0x51, 0xa1 } }

+

+

+################################################################################

+#

+# PCD Declarations section - list of all PCDs Declared by this Package

+# Only this package should be providing the

+# declaration, other packages should not.

+#

+################################################################################

+

+[PcdsFeatureFlag]

+ ## Feature enabling control

+ # @Prompt Enable payload platform FV common for most Intel platforms

+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable|FALSE|BOOLEAN|0x00000001

+

+[PcdsFixedAtBuild, PcdsPatchableInModule]

+ ## FFS filename to find the default variable initial data file.

+ # @Prompt FFS Name of variable initial data file

+ gPlatformPayloadPkgTokenSpaceGuid.PcdNvsDataFile |{ 0x1a, 0xf1, 0xb1, 0xae, 0x42, 0xcc, 0xcf, 0x4e, 0xac, 0x60, 0xdb, 0xab, 0xf6, 0xca, 0x69, 0xe6 }|VOID*|0x00000025

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc
new file mode 100644
index 0000000000..adf028c511
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc
@@ -0,0 +1,110 @@
+## @file

+# platform Payload Package

+#

+# Provides platform specific drivers and definitions to create a platform FV

+# to work with universal UEFI payload to provide support for common Intel platforms.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+################################################################################

+#

+# Defines Section - statements that will be processed to create a Makefile.

+#

+################################################################################

+[Defines]

+ PLATFORM_NAME = PlatformPayloadPkg

+ PLATFORM_GUID = D3C551BE-9BC6-48F5-AA8A-F49425C28CA9

+ PLATFORM_VERSION = 0.1

+ DSC_SPECIFICATION = 0x00010005

+ SUPPORTED_ARCHITECTURES = X64

+ BUILD_TARGETS = DEBUG|RELEASE|NOOPT

+ SKUID_IDENTIFIER = DEFAULT

+ OUTPUT_DIRECTORY = Build/$(PLATFORM_NAME)

+ FLASH_DEFINITION = $(PLATFORM_NAME)/PlatformPayloadPkg.fdf

+ PCD_DYNAMIC_AS_DYNAMICEX = TRUE

+ DXE_ARCH = X64

+

+[Packages]

+ MinPlatformPkg/MinPlatformPkg.dec

+

+################################################################################

+#

+# SKU Identification section - list of all SKU IDs supported by this Platform.

+#

+################################################################################

+[SkuIds]

+ 0|DEFAULT

+

+################################################################################

+#

+# Library Class section - list of all Library Classes needed by this Platform.

+#

+################################################################################

+

+#

+# Since there are no 32b libraries or components in this package, these PCD are specified for 64b only

+#

+[PcdsFeatureFlag]

+ #

+ # PCD needed for MinPlatform build includes

+ #

+ gMinPlatformPkgTokenSpaceGuid.PcdSmiHandlerProfileEnable |FALSE

+ gMinPlatformPkgTokenSpaceGuid.PcdUefiSecureBootEnable |FALSE

+ gMinPlatformPkgTokenSpaceGuid.PcdPerformanceEnable |FALSE

+

+[PcdsPatchableInModule.X64]

+ gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x7

+ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000004F

+!if $(SOURCE_DEBUG_ENABLE)

+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x17

+!else

+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2F

+!endif

+

+ #

+ # The following parameters are set by Library/PlatformHookLib

+ #

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialUseMmio|FALSE

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterBase|0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialBaudRate|115200

+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterStride|1

+

+################################################################################

+#

+# Pcd DynamicEx Section - list of all EDK II PCD Entries defined by this Platform

+#

+################################################################################

+

+[PcdsDynamicExDefault]

+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0

+ gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseSize|0

+

+

+#

+# Include common libraries

+#

+!include MinPlatformPkg/Include/Dsc/CoreCommonLib.dsc

+!include MinPlatformPkg/Include/Dsc/CorePeiLib.dsc

+!include MinPlatformPkg/Include/Dsc/CoreDxeLib.dsc

+

+#

+# This package always builds the feature.

+#

+!include Include/PlatformPayloadFeature.dsc

+

+[BuildOptions]

+ *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES

+ GCC:*_UNIXGCC_*_CC_FLAGS = -DMDEPKG_NDEBUG

+ GCC:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG

+ INTEL:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG

+ MSFT:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG

+

+[BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER]

+ GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000

+ XCODE:*_*_*_DLINK_FLAGS = -seg1addr 0x1000 -segalign 0x1000

+ XCODE:*_*_*_MTOC_FLAGS = -align 0x1000

+ CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:4096

+ MSFT:*_*_*_DLINK_FLAGS = /ALIGN:4096

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf
new file mode 100644
index 0000000000..f781a364d7
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf
@@ -0,0 +1,50 @@
+## @file

+# Payload platform Package

+#

+# Provides platform specific drivers and definitions to create a platform FV

+# to work with universal UEF payload.

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+#

+##

+

+[Defines]

+ DEFINE FD_BASE = 0x00800000

+ DEFINE FD_BLOCK_SIZE = 0x00001000

+

+ !if $(TARGET) == "NOOPT"

+ DEFINE FD_SIZE = 0x00090000

+ DEFINE NUM_BLOCKS = 0x90

+ !else

+ DEFINE FD_SIZE = 0x00050000

+ DEFINE NUM_BLOCKS = 0x50

+ !endif

+

+[FD.PlatformPayload]

+ BaseAddress = $(FD_BASE) | gUefiPayloadPkgTokenSpaceGuid.PcdPayloadFdMemBase

+ Size = $(FD_SIZE) | gUefiPayloadPkgTokenSpaceGuid.PcdPayloadFdMemSize

+ ErasePolarity = 1

+ BlockSize = $(FD_BLOCK_SIZE)

+ NumBlocks = $(NUM_BLOCKS)

+

+ 0x00000000 | $(FD_SIZE)

+ FV = PlatformPayload

+

+[FV.PlatformPayload]

+ !include MinPlatformPkg/Include/Fdf/CommonSpiFvHeaderInfo.fdf

+ FvNameGuid = 96E75986-6FDD-491E-9FD5-35E21AC45B45

+ FvForceRebase = FALSE

+

+ !include Include/PostMemory.fdf

+

+################################################################################

+#

+# Rules are use with the [FV] section's module INF type to define

+# how an FFS file is created for a given INF file. The following Rule are the default

+# rules for the different module type. User can add the customized rules to define the

+# content of the FFS file.

+#

+################################################################################

+

+!include MinPlatformPkg/Include/Fdf/RuleInclude.fdf

diff --git a/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py
new file mode 100644
index 0000000000..1e3e1cce21
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py
@@ -0,0 +1,113 @@
+## @file

+# This file contains the script to build UniversalPayload with platform payload

+#

+# Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>

+# SPDX-License-Identifier: BSD-2-Clause-Patent

+##

+

+import argparse

+import subprocess

+import os

+import shutil

+import sys

+from ctypes import *

+

+sys.dont_write_bytecode = True

+

+def RunCommand(cmd):

+ print(cmd)

+ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,cwd=os.environ['WORKSPACE'])

+ while True:

+ line = p.stdout.readline()

+ if not line:

+ break

+ print(line.strip().decode(errors='ignore'))

+

+ p.communicate()

+ if p.returncode != 0:

+ print("- Failed - error happened when run command: %s"%cmd)

+ raise Exception("ERROR: when run command: %s"%cmd)

+

+def BuildUniversalPayload(Args, MacroList):

+ BuildTarget = Args.Target

+ ToolChain = Args.ToolChain

+ ElfToolChain = 'CLANGDWARF'

+ ObjCopyFlag = "elf64-x86-64" if Args.Arch == 'X64' else "elf32-i386"

+

+ #

+ # Find universal UEFI payload build build script

+ #

+ Edk2PayloadBuildScript = os.path.normpath("UefiPayloadPkg/UniversalPayloadBuild.py")

+ for package_path in os.environ['PACKAGES_PATH'].split(';'):

+ if os.path.exists (os.path.join (package_path, Edk2PayloadBuildScript)):

+ Edk2PayloadBuildScript = os.path.join (package_path, Edk2PayloadBuildScript)

+ break

+ if not os.path.exists (Edk2PayloadBuildScript):

+ raise Exception("Could not find universal UEFI payload build script UniversalPayloadBuild.py")

+

+ PlatformFvDscPath = os.path.normpath("PlatformPayloadPkg/PlatformPayloadPkg.dsc")

+ BuildDir = os.path.join(os.environ['WORKSPACE'], os.path.normpath("Build/UefiPayloadPkgX64"))

+ PlatformFvReportPath = os.path.join(BuildDir, "PlatformPayloadReport.txt")

+ UniversalUefiPld = os.path.join(BuildDir, 'UniversalPayload.elf')

+ PlatformFv = os.path.join(os.environ['WORKSPACE'], os.path.normpath("Build/PlatformPayloadPkg"), f"{BuildTarget}_{ToolChain}", os.path.normpath("FV/PlatformPayload.Fv"))

+

+ if "CLANG_BIN" in os.environ:

+ LlvmObjcopyPath = os.path.join(os.environ["CLANG_BIN"], "llvm-objcopy")

+ else:

+ LlvmObjcopyPath = "llvm-objcopy"

+ try:

+ RunCommand('"%s" --version'%LlvmObjcopyPath)

+ except:

+ print("- Failed - Please check if LLVM is installed or if CLANG_BIN is set correctly")

+ sys.exit(1)

+

+ Defines = ""

+ for key in MacroList:

+ Defines +=" -D {0}={1}".format(key, MacroList[key])

+

+ #

+ # Building Universal Payload entry.

+ #

+ if not Args.Skip:

+ BuildPayload = f"python {Edk2PayloadBuildScript} -b {BuildTarget} -t {ToolChain} -a {Args.Arch} {Defines}"

+ RunCommand(BuildPayload)

+

+ #

+ # Building Platform Payload.

+ #

+ BuildPayload = f"build -p {PlatformFvDscPath} -b {BuildTarget} -a X64 -t {ToolChain} -y {PlatformFvReportPath}"

+ BuildPayload += Defines

+ RunCommand(BuildPayload)

+

+ #

+ # Copy the Platform Payload as a section in elf format Universal Payload.

+ #

+ remove_section = f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyFlag} --remove-section .upld.platform_fv {UniversalUefiPld}'

+ add_section = f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyFlag} --add-section .upld.platform_fv={PlatformFv} {UniversalUefiPld}'

+ set_section = f'"{LlvmObjcopyPath}" -I {ObjCopyFlag} -O {ObjCopyFlag} --set-section-alignment .upld.platform_fv=16 {UniversalUefiPld}'

+ RunCommand(remove_section)

+ RunCommand(add_section)

+ RunCommand(set_section)

+

+

+def main():

+ parser = argparse.ArgumentParser(description='Build Platform Payload FV and add it to Universal UEFI Payload')

+ parser.add_argument('-t', '--ToolChain')

+ parser.add_argument('-b', '--Target', default='DEBUG')

+ parser.add_argument('-a', '--Arch', choices=['IA32', 'X64'], help='Specify the ARCH for payload entry module. Default build X64 image.', default ='X64')

+ parser.add_argument("-D", "--Macro", action="append")

+ parser.add_argument('-s', '--Skip', action='store_true', help='Skip Universal UEFI payload build (just build platform FV and add to Universal UEFI payload.')

+ MacroList = {}

+ args = parser.parse_args()

+ if args.Macro is not None:

+ for Argument in args.Macro:

+ if Argument.count('=') != 1:

+ print("Unknown variable passed in: %s"%Argument)

+ raise Exception("ERROR: Unknown variable passed in: %s"%Argument)

+ tokens = Argument.strip().split('=')

+ MacroList[tokens[0].upper()] = tokens[1]

+ BuildUniversalPayload(args, MacroList)

+ print ("Successfully build Universal Payload with platform FV")

+

+if __name__ == '__main__':

+ main()

diff --git a/Features/Intel/PlatformPayloadPkg/Readme.md b/Features/Intel/PlatformPayloadPkg/Readme.md
new file mode 100644
index 0000000000..10e863b5e0
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Readme.md
@@ -0,0 +1,96 @@
+# Overview

+* **Feature Name:** Platform Payload

+* **PI Phase(s) Supported:** SMM DXE

+

+## Purpose

+This package provides a common platform payload which is expected to work on most

+Intel platforms with a bootloader.

+

+# High-Level Theory of Operation

+Bootloader initialize memory/silicon/platform and payload focus on boot media initializaiton

+and OS boot. Payload is expected to be re-used on different Platforms.

+

+In the reality, some payload modules have platform dependency (e.g. only for Intel PCH)

+or bootloader dependency (only for coreboot). These modules would be located in

+edk2-platform repo.

+

+The generic UEFI payload could be built from EDK2 UefiPayloadPkg in ELF format following

+universal payload specification. And a Platform Payload could be built from PlatformPayloadPkg

+to provide Intel platform specific features (e.g. SPI module, PCH SMM) in FV/FD format.

+This platform payload could be inserted into universal UEFI payload as an ELF section

+to generate a full-feature payload.

+## Firmware Volumes

+* FvPlatformPayload

+

+## Build Flows

+use windows host as example to generate a full-feature payload:

+

+** Setup the build env

+set WORKSPACE=c:\payload

+set PACKAGES_PATH=%WORKSPACE%\edk2;%WORKSPACE%\edk2-platforms\Features\Intel;

+ %WORKSPACE%\edk2-platforms\Platform\Intel

+edk2\edksetup.bat

+

+** Build universal UEFI payload with platform Payload

+python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg.py -t VS2019

+ -D SMM_SUPPORT=TRUE -DVARIABLE_SUPPORT=NONE -D SMM_VARIABLE=TRUE

+or

+python edk2\UefiPayloadPkg\UniversalPayloadBuild.py -t VS2019 -D SMM_SUPPORT=TRUE -DVARIABLE_SUPPORT=NONE

+python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg.py -t VS2019 -D SMM_VARIABLE=TRUE -s

+

+ If build success, the final UEFI payload is at Build\UefiPayloadPkgX64\UniversalPayload.elf.

+

+## Features

+

+1. Modules

+Currently only SMM veriable feature is available.

+Several build macros are used as below for SMM variable feature modules.

+!if $(SMM_VARIABLE) == TRUE

+ ## PchSmiDispatchSmm

+ ## FvbSmm

+ ## FaultTolerantWriteSmm

+ ## VariableSmm

+ ## VariableSmmRuntimeDxe

+!endif

+

+2. Data Flows

+SMM variable:

+The interface with bootloader are defined in PlatformPayloadPkg\Include\Guid

+SpiFlashInfoGuid.h -- SPI related information for SPI flash operation.

+NvVariableInfoGuid.h -- Variable related information for SPI NV variables.

+

+## Control Flows

+EDK2 DXE/SMM core from universal UEFI payload would dispatch all the modules

+from this platform payload.

+

+## Test Point Results

+*_TODO_*

+The test(s) that can verify porting is complete for the feature.

+

+Each feature must describe at least one test point to verify the feature is successful. If the test point is not

+implemented, this should be stated.

+

+## Functional Exit Criteria

+*_TODO_*

+The testable functionality for the feature.

+

+This section should provide an ordered list of criteria that a board integrator can reference to ensure the feature is

+functional on their board.

+

+## Feature Enabling Checklist

+*_TODO_*

+An ordered list of required activities to achieve desired functionality for the feature.

+

+## Performance Impact

+A general expectation for the impact on overall boot performance due to using this feature.

+

+This section is expected to provide guidance on:

+* How to estimate performance impact due to the feature

+* How to measure performance impact of the feature

+* How to manage performance impact of the feature

+

+## Common Optimizations

+*_TODO_*

+Common size or performance tuning options for this feature.

+

+This section is recommended but not required. If not used, the contents should be left empty.

--
2.35.1.windows.2


Isaac Oram
 

Pushed as 60053f3077..edc718521e

-----Original Message-----
From: Chaganty, Rangasai V <rangasai.v.chaganty@...>
Sent: Wednesday, August 3, 2022 2:57 PM
To: Oram, Isaac W <isaac.w.oram@...>; Dong, Guo <guo.dong@...>; devel@edk2.groups.io
Cc: Kinney, Michael D <michael.d.kinney@...>; Ni, Ray <ray.ni@...>; Rhodes, Sean <sean@...>; Desimone, Nathaniel L <nathaniel.l.desimone@...>; Gao, Liming <gaoliming@...>
Subject: RE: [edk2-devel][edk2-platforms][PATCH V2 1/1] Features/Intel/PlatformPayloadPkg: add platform payload FV

Reviewed-by: Sai Chaganty <rangasai.v.chaganty@...>

-----Original Message-----
From: Oram, Isaac W <isaac.w.oram@...>
Sent: Tuesday, May 10, 2022 4:41 PM
To: Dong, Guo <guo.dong@...>; devel@edk2.groups.io
Cc: Kinney, Michael D <michael.d.kinney@...>; Ni, Ray <ray.ni@...>; Rhodes, Sean <sean@...>; Desimone, Nathaniel L <nathaniel.l.desimone@...>; Chaganty, Rangasai V <rangasai.v.chaganty@...>; Gao, Liming <gaoliming@...>; Oram, Isaac W <isaac.w.oram@...>
Subject: RE: [edk2-devel][edk2-platforms][PATCH V2 1/1] Features/Intel/PlatformPayloadPkg: add platform payload FV

Added Features/Intel maintainers for review.

-----Original Message-----
From: Dong, Guo <guo.dong@...>
Sent: Friday, May 6, 2022 5:49 PM
To: devel@edk2.groups.io
Cc: Dong, Guo <guo.dong@...>; Kinney, Michael D <michael.d.kinney@...>; Ni, Ray <ray.ni@...>; Rhodes, Sean <sean@...>; Oram, Isaac W <isaac.w.oram@...>
Subject: [edk2-devel][edk2-platforms][PATCH V2 1/1] Features/Intel/PlatformPayloadPkg: add platform payload FV

From: Guo Dong <guo.dong@...>

UefiPayloadPkg in EDK2 repo was added SMM variable support for Intel
platform with SPI flash. But some of the modules for SMM variable are
Intel PCH specific (e.g. SPI library, SMM PCH module), so move these
modules into edk2-platforms repo.

A platform payload FV could be built from PlatformPayloadPkg which works
on Intel platforms (e.g.. ICX, APL, CML, CFL, KBL, TGL, ADL, etc.) with
SMM variable. This platform payload FV could be added into universal UEFI
payload built from EDK2 UefiPayloadPkg.

The steps to build a complete payload (use windows host as example):

set WORKSPACE=c:\payload
set PACKAGES_PATH=C:\payload\edk2;C:\payload\edk2-platforms\Platform\Intel;
C:\payload\edk2-platforms\Features\Intel;
edk2\edksetup.bat

python edk2\UefiPayloadPkg\UniversalPayloadBuild.py -t VS2019
-D SMM_SUPPORT=TRUE -DVARIABLE_SUPPORT=NONE

python edk2-platforms\Features\Intel\PlatformPayloadPkg\PlatformPayloadPkg.py
-t VS2019 -D SMM_VARIABLE=TRUE -s

The final UEFI payload generated at Build\UefiPayloadPkgX64\UniversalPayload.elf
if build success.

Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Ray Ni <ray.ni@...>
Cc: Sean Rhodes <sean@...>
Signed-off-by: Guo Dong <guo.dong@...>
Signed-off-by: Isaac Oram <isaac.w.oram@...>
---
Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc | 5 +++++
Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf | 7 ++++++
Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf | 7 ++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c | 1088 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbService.h | 185 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbServiceSmm.c | 139 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbSmm.inf | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Fvb/FvbSmmCommon.h | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Guid/NvVariableInfoGuid.h | 24 +++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Guid/SpiFlashInfoGuid.h | 38 ++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Library/FlashDeviceLib.h | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/Library/SpiFlashLib.h | 213 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc | 112 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PostMemory.fdf | 20 +++++++++++++++++
Features/Intel/PlatformPayloadPkg/Include/PreMemory.fdf | 8 +++++++
Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.c | 160 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/FlashDeviceLib/FlashDeviceLib.inf | 38 ++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.c | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/PcdInitLib/PcdInitLib.inf | 50 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/PchSpi.c | 170 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/RegsSpi.h | 120 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiCommon.h | 203 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.c | 874 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Library/SpiFlashLib/SpiFlashLib.inf | 48 +++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.c | 455 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.h | 36 +++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PchSmiDispatchSmm/PchSmiDispatchSmm.inf | 51 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dec | 49 ++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.dsc | 110 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.fdf | 50 +++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/PlatformPayloadPkg.py | 113 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Features/Intel/PlatformPayloadPkg/Readme.md | 96 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
35 files changed, 4887 insertions(+)

diff --git a/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc b/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
index 28530b8c67..17cc3224b7 100644
--- a/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/AdvancedFeaturePkg.dsc
@@ -80,6 +80,11 @@
gUserAuthFeaturePkgTokenSpaceGuid.PcdUserAuthenticationFeatureEnable |TRUE

gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable |TRUE



+ #

+ # Individual features

+ #

+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable |TRUE

+

#

# PCD that are required to be set by the build target should be configured here for test purposes

# These settings are only for the purposes of buildings, boards should follow instructions in Readme files.

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
index 2b36938df6..2a93ca1ec7 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeatures.dsc
@@ -75,3 +75,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/VirtualKeyboardFeature.dsc

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PlatformPayloadFeature.dsc

+!endif

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
index e214175eda..8e98154f3e 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
+++ b/Features/Intel/AdvancedFeaturePkg/Include/AdvancedFeaturesPcd.dsc
@@ -53,6 +53,11 @@
UserAuthFeaturePkg/UserAuthFeaturePkg.dec

VirtualKeyboardFeaturePkg/VirtualKeyboardFeaturePkg.dec



+ #

+ # Individual features

+ #

+ PlatformPayloadPkg/PlatformPayloadPkg.dec

+

#

# The section below sets all PCDs to FALSE in this DSC file so the feature is not enabled by default.

# Board can set PCDs to TRUE in its DSC file to enable a subset of advanced features

@@ -76,6 +81,8 @@
gUserAuthFeaturePkgTokenSpaceGuid.PcdUserAuthenticationFeatureEnable |FALSE

gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable |FALSE



+ gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable |FALSE

+

#

# There seems to be some build parsing odd behavior that requires this PCD to be specified even though

# the *.fdf that consumes it is dependent on the feature flag.

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf b/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
index 99089f9a7b..a0975d4d43 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
+++ b/Features/Intel/AdvancedFeaturePkg/Include/PostMemory.fdf
@@ -76,3 +76,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/PostMemory.fdf

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PostMemory.fdf

+!endif

diff --git a/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf b/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
index 1db258446a..b2b821c9c4 100644
--- a/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
+++ b/Features/Intel/AdvancedFeaturePkg/Include/PreMemory.fdf
@@ -76,3 +76,10 @@
!if gVirtualKeyboardFeaturePkgTokenSpaceGuid.PcdVirtualKeyboardFeatureEnable == TRUE

!include VirtualKeyboardFeaturePkg/Include/PreMemory.fdf

!endif

+

+#

+# Individual features

+#

+!if gPlatformPayloadPkgTokenSpaceGuid.PcdPayloadPackageFeatureEnable == TRUE

+ !include PlatformPayloadPkg/Include/PreMemory.fdf

+!endif

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c b/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c
new file mode 100644
index 0000000000..d6dcfeb4e1
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbInfo.c
@@ -0,0 +1,77 @@
+/** @file

+

+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include <PiDxe.h>

+#include <Protocol/FirmwareVolumeBlock.h>

+#include <Library/PcdLib.h>

+#include <Library/DebugLib.h>

+#include <Library/BaseLib.h>

+#include <Guid/FirmwareFileSystem2.h>

+#include <Guid/SystemNvDataGuid.h>

+

+#define FVB_MEDIA_BLOCK_SIZE 0x1000

+

+typedef struct {

+ EFI_FIRMWARE_VOLUME_HEADER FvInfo;

+ EFI_FV_BLOCK_MAP_ENTRY End[1];

+} EFI_FVB2_MEDIA_INFO;

+

+//

+// This data structure contains a template of FV header which is used to restore

+// Fv header if it's corrupted.

+//

+EFI_FVB2_MEDIA_INFO mFvbMediaInfo = {

+ {

+ { 0, }, // ZeroVector[16]

+ EFI_SYSTEM_NV_DATA_FV_GUID,

+ 0,

+ EFI_FVH_SIGNATURE,

+ 0x0004feff, // check PiFirmwareVolume.h for details on EFI_FVB_ATTRIBUTES_2

+ sizeof (EFI_FIRMWARE_VOLUME_HEADER) + sizeof (EFI_FV_BLOCK_MAP_ENTRY),

+ 0, // CheckSum which will be calucated dynamically.

+ 0, // ExtHeaderOffset

+ { 0, },

+ EFI_FVH_REVISION,

+ {

+ {

+ 0,

+ FVB_MEDIA_BLOCK_SIZE,

+ }

+ }

+ },

+ {

+ {

+ 0,

+ 0

+ }

+ }

+};

+

+

+/**

+ Get a heathy FV header used for variable store recovery

+

+ @retval The FV header.

+

+**/

+EFI_FIRMWARE_VOLUME_HEADER *

+GetFvHeaderTemplate (

+ VOID

+ )

+{

+ EFI_FIRMWARE_VOLUME_HEADER *FvHeader;

+ UINTN FvSize;

+

+ FvSize = PcdGet32 (PcdFlashNvStorageFtwSpareSize) * 2;

+ FvHeader = &mFvbMediaInfo.FvInfo;

+ FvHeader->FvLength = FvSize;

+ FvHeader->BlockMap[0].NumBlocks = (UINT32)(FvSize / FvHeader->BlockMap[0].Length);

+ FvHeader->Checksum = 0;

+ FvHeader->Checksum = CalculateCheckSum16 ((UINT16 *)FvHeader, FvHeader->HeaderLength);

+

+ return FvHeader;

+}

diff --git a/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c
new file mode 100644
index 0000000000..1d19f3726b
--- /dev/null
+++ b/Features/Intel/PlatformPayloadPkg/Fvb/FvbService.c
@@ -0,0 +1,1088 @@
+/** @file

+Firmware Volume Block Driver to provide FVB service.

+

+ Copyright (c) 2014 - 2021, Intel Corporation. All rights reserved.<BR>

+ SPDX-License-Identifier: BSD-2-Clause-Patent

+

+**/

+

+#include "FvbService.h"

+

+//

+// Global variable for this FVB driver which contains

+// the private data of all firmware volume block instances

+//

+FWB_GLOBAL mFvbModuleGlobal;

+

+FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate = {

+ {

+ {

+ HARDWARE_DEVICE_PATH,

+ HW_MEMMAP_DP,

+ {

+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH)),

+ (UINT8)(sizeof (MEMMAP_DEVICE_PATH) >> 8)

+ }

+ },

+ EfiMemoryMappedIO,

+ (EFI_PHYSICAL_ADDRESS)0,

+ (EFI_PHYSICAL_ADDRESS)0,

+ },

+ {

+ END_DEVICE_PATH_TYPE,

+ END_ENTIRE_DEVICE_PATH_SUBTYPE,

+ {

+ END_DEVICE_PATH_LENGTH,

+ 0

+ }

+ }

+};

+

+FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate = {

+ {

+ {

+ MEDIA_DEVICE_PATH,

+ MEDIA_PIWG_FW_VOL_DP,

+ {

+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH)),

+ (UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH) >> 8)

+ }

+ },

+ { 0 }

+ },

+ {

+ END_DEVICE_PATH_TYPE,

+ END_ENTIRE_DEVICE_PATH_SUBTYPE,

+ {

+ END_DEVICE_PATH_LENGTH,

+ 0

+ }

+ }

+};

+

+EFI_FW_VOL_BLOCK_DEVICE mFvbDeviceTemplate = {

+ FVB_DEVICE_SIGNATURE,

+ NULL,

+ 0, // Instance

+ {

+ FvbProtocolGetAttributes,

+ FvbProtocolSetAttributes,

+ FvbProtocolGetPhysicalAddress,

+ FvbProtocolGetBlockSize,

+ FvbProtocolRead,

+ FvbProtocolWrite,

+ FvbProtocolEraseBlocks,

+ NULL

+ } // FwVolBlockInstance

+};

+

+/**

+ Get the pointer to EFI_FW_VOL_INSTANCE from the buffer pointed

+ by mFvbModuleGlobal.FvInstance based on a index.

+ Each EFI_FW_VOL_INSTANCE is with variable length as

+ we have a block map at the end of the EFI_FIRMWARE_VOLUME_HEADER.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+

+ @return A pointer to EFI_FW_VOL_INSTANCE.

+

+**/

+EFI_FW_VOL_INSTANCE *

+GetFvbInstance (

+ IN UINTN Instance

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwhRecord;

+

+ if ( Instance >= mFvbModuleGlobal.NumFv ) {

+ ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER);

+ return NULL;

+ }

+

+ //

+ // Find the right instance of the FVB private data

+ //

+ FwhRecord = mFvbModuleGlobal.FvInstance;

+ while ( Instance > 0 ) {

+ FwhRecord = (EFI_FW_VOL_INSTANCE *)((UINTN)((UINT8 *)FwhRecord) +

+ FwhRecord->VolumeHeader.HeaderLength +

+ (sizeof (EFI_FW_VOL_INSTANCE) - sizeof (EFI_FIRMWARE_VOLUME_HEADER)));

+ Instance--;

+ }

+

+ return FwhRecord;

+}

+

+/**

+ Get the EFI_FVB_ATTRIBUTES_2 of a FV.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+

+ @retval EFI_FVB_ATTRIBUTES_2 of the FV identified by Instance.

+

+**/

+STATIC

+EFI_FVB_ATTRIBUTES_2

+FvbGetVolumeAttributes (

+ IN UINTN Instance

+ )

+{

+ EFI_FW_VOL_INSTANCE *FwInstance;

+

+ FwInstance = GetFvbInstance (Instance);

+ ASSERT (FwInstance != NULL);

+

+ if (FwInstance == NULL) {

+ return 0;

+ }

+

+ return FwInstance->VolumeHeader.Attributes;

+}

+

+/**

+ Retrieves the starting address of an LBA in an FV. It also

+ return a few other attribut of the FV.

+

+ @param[in] Instance The index of the EFI_FW_VOL_INSTANCE.

+ @param[in] Lba The logical block address

+ @param[out] LbaAddress On output, contains the physical starting address

+ of the Lba

+ @param[out] LbaLength On output, contains the length of the block

+ @param[out] NumOfBlocks A pointer to a caller allocated UINTN in which the

+ number of consecutive blocks starting with Lba is

+ returned. All blocks in this range have a size of

+ BlockSize

+

+ @retval EFI_SUCCESS Successfully returns

+ @retval EFI_INVALID_PARAMETER Instance not found

+

+**/

+STATIC

+EFI_STATUS

+FvbGetLbaAddress (

+ IN UINTN Instance,

+ IN EFI_LBA Lba,

+ OUT UINTN *LbaAddress,

+ OUT UINTN *LbaLength,

+ OUT UINTN *NumOfBlocks

+ )

+{

+ UINT32 NumBlocks;

+ UINT32 BlockLength;

+ UINTN Offset;

+ EFI_LBA StartLba;

+ EFI_LBA NextLba;

+ EFI_FW_VOL_INSTANCE *FwhInstance;

+ EFI_FV_BLOCK_MAP_ENTRY *BlockMap;

+

+ //

+ // Find the right instance of the FVB private data

+ //

+ FwhInstance = GetFvbInstance (Instance);

+ if (FwhInstance == NULL) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ StartLba = 0;

+ Offset = 0;

+ BlockMap = &FwhInstance->VolumeHeader.BlockMap[0];

+ ASSERT (BlockMap != NULL);

+

+ //

+ // Parse the blockmap of the FV to find which map entry the Lba belongs to

+ //

+ while (TRUE) {

+ if ( BlockMap != NULL) {

+ NumBlocks = BlockMap->NumBlocks;

+ BlockLength = BlockMap->Length;

+ }

+

+ if ((NumBlocks == 0) || (BlockLength == 0)) {

+ return EFI_INVALID_PARAMETER;

+ }

+

+ NextLba = StartLba + NumBlocks;

+

+ //

+ // The map entry found

+ //

+ if ((Lba >= StartLba) && (Lba < NextLba)) {

+ Offset = Offset + (UINTN)MultU64x32 ((Lba - StartLba), BlockLength);

+ if (LbaAddress != NULL) {

+ *LbaAddress = FwhInstance->FvBase + Offset;

+ }

+

+