Topics

[PATCH 1/2 v5] Drivers/OpTeeRpmb: Add an OP-TEE backed RPMB driver


Ilias Apalodimas
 

A following patch is adding support for building StMM in order to run it
from OP-TEE.
OP-TEE in combination with a NS-world supplicant can use the RPMB
partition of an eMMC to store EFI variables. The supplicant
functionality is currently available in U-Boot only but can be ported
into EDK2. Assuming similar functionality is added in EDK2, this will
allow any hardware with an RPMB partition to store EFI variables
securely.

So let's add a driver that enables access of the RPMB partition through
OP-TEE. Since the upper layers expect a byte addressable interface,
the driver allocates memory and patches the PCDs, while syncing the
memory/hardware on read/write callbacks.

Signed-off-by: Ilias Apalodimas <ilias.apalodimas@linaro.org>
---
Drivers/OpTeeRpmb/FixupPcd.c | 89 +++
Drivers/OpTeeRpmb/FixupPcd.inf | 43 ++
Drivers/OpTeeRpmb/OpTeeRpmbFv.inf | 58 ++
Drivers/OpTeeRpmb/OpTeeRpmbFvb.c | 920 ++++++++++++++++++++++++++++++
Drivers/OpTeeRpmb/OpTeeRpmbFvb.h | 52 ++
5 files changed, 1162 insertions(+)
create mode 100644 Drivers/OpTeeRpmb/FixupPcd.c
create mode 100644 Drivers/OpTeeRpmb/FixupPcd.inf
create mode 100644 Drivers/OpTeeRpmb/OpTeeRpmbFv.inf
create mode 100644 Drivers/OpTeeRpmb/OpTeeRpmbFvb.c
create mode 100644 Drivers/OpTeeRpmb/OpTeeRpmbFvb.h

diff --git a/Drivers/OpTeeRpmb/FixupPcd.c b/Drivers/OpTeeRpmb/FixupPcd.c
new file mode 100644
index 000000000000..6cd503b71c6d
--- /dev/null
+++ b/Drivers/OpTeeRpmb/FixupPcd.c
@@ -0,0 +1,89 @@
+/** @file=0D
+=0D
+ Update the patched PCDs to their correct value=0D
+=0D
+ Copyright (c) 2020, Linaro Ltd. All rights reserved.<BR>=0D
+=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+/**=0D
+ * Patch the relevant PCDs of the RPMB driver with the correct address of =
the=0D
+ * allocated memory=0D
+ *=0D
+**/=0D
+#include <Library/BaseLib.h>=0D
+#include <Library/DebugLib.h>=0D
+#include <Library/MmServicesTableLib.h>=0D
+#include <Library/PcdLib.h>=0D
+=0D
+#include <Protocol/FirmwareVolumeBlock.h>=0D
+#include <Protocol/SmmFirmwareVolumeBlock.h>=0D
+=0D
+#include "OpTeeRpmbFvb.h"=0D
+=0D
+/**=0D
+ Fixup the Pcd values for variable storage=0D
+=0D
+ Since the upper layers of EDK2 expect a memory mapped interface and we c=
an't=0D
+ offer that from an RPMB, the driver allocates memory on init and passes =
that=0D
+ on the upper layers. Since the memory is dynamically allocated and we ca=
n't set the=0D
+ PCD is StMM context, we need to patch it correctly on each access=0D
+=0D
+ @retval EFI_SUCCESS Protocol was found and PCDs patched up=0D
+=0D
+ **/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FixPcdMemory (=0D
+ VOID=0D
+ )=0D
+{=0D
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol;=0D
+ MEM_INSTANCE *Instance;=0D
+ EFI_STATUS Status;=0D
+=0D
+ //=0D
+ // Locate SmmFirmwareVolumeBlockProtocol=0D
+ //=0D
+ Status =3D gMmst->MmLocateProtocol (=0D
+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,=0D
+ NULL,=0D
+ (VOID **) &FvbProtocol=0D
+ );=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ Instance =3D INSTANCE_FROM_FVB_THIS (FvbProtocol);=0D
+ // The Pcd is user defined, so make sure we don't overflow=0D
+ if (Instance->MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageV=
ariableSize)) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ if (Instance->MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageV=
ariableSize) -=0D
+ PcdGet32 (PcdFlashNvStorageFtwWorkingSize)) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ // Patch PCDs with the the correct values=0D
+ PatchPcdSet64 (PcdFlashNvStorageVariableBase64, Instance->MemBaseAddress=
);=0D
+ PatchPcdSet64 (=0D
+ PcdFlashNvStorageFtwWorkingBase64,=0D
+ Instance->MemBaseAddress + PcdGet32 (PcdFlashNvStorageVariableSize)=0D
+ );=0D
+ PatchPcdSet64 (=0D
+ PcdFlashNvStorageFtwSpareBase64,=0D
+ Instance->MemBaseAddress +=0D
+ PcdGet32 (PcdFlashNvStorageVariableSize) +=0D
+ PcdGet32 (PcdFlashNvStorageFtwWorkingSize)=0D
+ );=0D
+=0D
+ DEBUG ((DEBUG_INFO, "%a: Fixup PcdFlashNvStorageVariableBase64: 0x%lx\n"=
,=0D
+ __FUNCTION__, PcdGet64 (PcdFlashNvStorageVariableBase64)));=0D
+ DEBUG ((DEBUG_INFO, "%a: Fixup PcdFlashNvStorageFtwWorkingBase64: 0x%lx\=
n",=0D
+ __FUNCTION__, PcdGet64 (PcdFlashNvStorageFtwWorkingBase64)));=0D
+ DEBUG ((DEBUG_INFO, "%a: Fixup PcdFlashNvStorageFtwSpareBase64: 0x%lx\n"=
,=0D
+ __FUNCTION__, PcdGet64 (PcdFlashNvStorageFtwSpareBase64)));=0D
+=0D
+ return Status;=0D
+}=0D
diff --git a/Drivers/OpTeeRpmb/FixupPcd.inf b/Drivers/OpTeeRpmb/FixupPcd.inf
new file mode 100644
index 000000000000..5146257993ef
--- /dev/null
+++ b/Drivers/OpTeeRpmb/FixupPcd.inf
@@ -0,0 +1,43 @@
+## @file=0D
+# Instance of Base Memory Library without assembly.=0D
+#=0D
+# Copyright (c) 2020, Linaro Ltd. All rights reserved.<BR>=0D
+#=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+#=0D
+##=0D
+=0D
+[Defines]=0D
+ INF_VERSION =3D 0x0001001A=0D
+ BASE_NAME =3D FixupPcd=0D
+ FILE_GUID =3D a827c337-a9c6-301b-aeb7-acbc95d8da22=
=0D
+ MODULE_TYPE =3D BASE=0D
+ VERSION_STRING =3D 0.1=0D
+ LIBRARY_CLASS =3D RpmbPcdFixup|MM_STANDALONE=0D
+ CONSTRUCTOR =3D FixPcdMemory=0D
+=0D
+[Sources]=0D
+ FixupPcd.c=0D
+ OpTeeRpmbFvb.h=0D
+=0D
+[Packages]=0D
+ MdeModulePkg/MdeModulePkg.dec=0D
+ MdePkg/MdePkg.dec=0D
+=0D
+[LibraryClasses]=0D
+ BaseLib=0D
+ DebugLib=0D
+ MmServicesTableLib=0D
+ PcdLib=0D
+=0D
+[Pcd]=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize=0D
+=0D
+[Protocols]=0D
+ gEfiSmmFirmwareVolumeBlockProtocolGuid ## CONSUMES=0D
diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFv.inf b/Drivers/OpTeeRpmb/OpTeeRpm=
bFv.inf
new file mode 100644
index 000000000000..c3580859ffde
--- /dev/null
+++ b/Drivers/OpTeeRpmb/OpTeeRpmbFv.inf
@@ -0,0 +1,58 @@
+## @file=0D
+#=0D
+# Component description file for OpTeeRpmbFv module=0D
+#=0D
+# Copyright (c) 2020, Linaro Ltd. All rights reserved.<BR>=0D
+#=0D
+# SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+#=0D
+##=0D
+=0D
+[Defines]=0D
+ INF_VERSION =3D 0x0001001A=0D
+ BASE_NAME =3D OpTeeRpmbFv=0D
+ FILE_GUID =3D 4803FC20-E583-3BCD-8C60-141E85C9A2CF=
=0D
+ MODULE_TYPE =3D MM_STANDALONE=0D
+ VERSION_STRING =3D 0.1=0D
+ PI_SPECIFICATION_VERSION =3D 0x00010032=0D
+ ENTRY_POINT =3D OpTeeRpmbFvbInit=0D
+=0D
+[Sources]=0D
+ OpTeeRpmbFvb.c=0D
+ OpTeeRpmbFvb.h=0D
+=0D
+[Packages]=0D
+ ArmPkg/ArmPkg.dec=0D
+ ArmPlatformPkg/ArmPlatformPkg.dec=0D
+ MdeModulePkg/MdeModulePkg.dec=0D
+ MdePkg/MdePkg.dec=0D
+ StandaloneMmPkg/StandaloneMmPkg.dec=0D
+=0D
+[LibraryClasses]=0D
+ ArmSvcLib=0D
+ BaseLib=0D
+ BaseMemoryLib=0D
+ DebugLib=0D
+ MemoryAllocationLib=0D
+ MmServicesTableLib=0D
+ PcdLib=0D
+ StandaloneMmDriverEntryPoint=0D
+=0D
+[Guids]=0D
+ gEfiAuthenticatedVariableGuid=0D
+ gEfiSystemNvDataFvGuid=0D
+ gEfiVariableGuid=0D
+=0D
+[Pcd]=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64=0D
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize=0D
+=0D
+[Protocols]=0D
+ gEfiSmmFirmwareVolumeBlockProtocolGuid ## PRODUCES=0D
+=0D
+[Depex]=0D
+ TRUE=0D
diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFvb.c b/Drivers/OpTeeRpmb/OpTeeRpmb=
Fvb.c
new file mode 100644
index 000000000000..950082cf6df4
--- /dev/null
+++ b/Drivers/OpTeeRpmb/OpTeeRpmbFvb.c
@@ -0,0 +1,920 @@
+/** @file=0D
+=0D
+ FV block I/O protocol driver for RPMB eMMC accessed via OP-TEE=0D
+=0D
+ Copyright (c) 2020, Linaro Ltd. All rights reserved.<BR>=0D
+=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+#include <Library/ArmSvcLib.h>=0D
+#include <Library/BaseLib.h>=0D
+#include <Library/BaseMemoryLib.h>=0D
+#include <Library/DebugLib.h>=0D
+#include <Library/MemoryAllocationLib.h>=0D
+#include <Library/MmServicesTableLib.h>=0D
+#include <Library/PcdLib.h>=0D
+=0D
+#include <IndustryStandard/ArmFfaSvc.h>=0D
+#include <IndustryStandard/ArmMmSvc.h>=0D
+#include <Protocol/FirmwareVolumeBlock.h>=0D
+#include <Protocol/SmmFirmwareVolumeBlock.h>=0D
+#include <Guid/VariableFormat.h>=0D
+=0D
+#include "OpTeeRpmbFvb.h"=0D
+=0D
+// These are what OP-TEE expects in ./core/arch/arm/kernel/stmm_sp.c=0D
+// Since the FFA autodiscovery mechanism is not yet implemented we are=0D
+// hardcoding the ID values for the two operations OP-TEE currently suppor=
ts=0D
+//=0D
+// mMemMgrId is used to set the page permissions after relocating the exec=
utable=0D
+// mStorageId is used to access the RPMB partition via OP-TEE=0D
+// In both cases the return value is located in x3. Once the autodiscovery=
mechanism=0D
+// is in place, we'll have to account for an error value in x2 as well, ha=
ndling=0D
+// the autodiscovery failed scenario=0D
+STATIC CONST UINT16 mMemMgrId =3D 3U;=0D
+STATIC CONST UINT16 mStorageId =3D 4U;=0D
+=0D
+STATIC MEM_INSTANCE mInstance;=0D
+=0D
+/**=0D
+ Sends an SVC call to OP-TEE for reading/writing an RPMB partition=0D
+=0D
+ @param SvcAct SVC ID for read/write=0D
+ @param Addr Base address of the buffer. When reading contents will=
be=0D
+ copied to that buffer after reading them from the devi=
ce.=0D
+ When writing, the buffer holds the contents we want to=
=0D
+ write cwtoin the device=0D
+ @param NumBytes Number of bytes to read/write=0D
+ @param Offset Offset into the RPMB file=0D
+=0D
+ @retval EFI_SUCCESS read/write ok=0D
+=0D
+ @retval EFI_UNSUPPORTED SVC to op-tee not supported=0D
+=0D
+ @retval EFI_INVALID_PARAMETER SVC to op-tee had an invalid par=
am=0D
+=0D
+ @retval EFI_ACCESS_DENIED SVC to op-tee was denied=0D
+=0D
+ @retval EFI_OUT_OF_RESOURCES op-tee out of memory=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+ReadWriteRpmb (=0D
+ UINTN SvcAct,=0D
+ UINTN Addr,=0D
+ UINTN NumBytes,=0D
+ UINTN Offset=0D
+ )=0D
+{=0D
+ ARM_SVC_ARGS SvcArgs;=0D
+ EFI_STATUS Status;=0D
+=0D
+ ZeroMem (&SvcArgs, sizeof (SvcArgs));=0D
+=0D
+ SvcArgs.Arg0 =3D ARM_SVC_ID_FFA_MSG_SEND_DIRECT_REQ_AARCH64;=0D
+ SvcArgs.Arg1 =3D mStorageId;=0D
+ SvcArgs.Arg2 =3D 0;=0D
+ SvcArgs.Arg3 =3D SvcAct;=0D
+ SvcArgs.Arg4 =3D Addr;=0D
+ SvcArgs.Arg5 =3D NumBytes;=0D
+ SvcArgs.Arg6 =3D Offset;=0D
+=0D
+ ArmCallSvc (&SvcArgs);=0D
+ if (SvcArgs.Arg3) {=0D
+ DEBUG ((DEBUG_ERROR, "%a: Svc Call 0x%08x Addr: 0x%08x len: 0x%x Offse=
t: 0x%x failed with 0x%x\n",=0D
+ __func__, SvcAct, Addr, NumBytes, Offset, SvcArgs.Arg3));=0D
+ }=0D
+=0D
+ switch (SvcArgs.Arg3) {=0D
+ case ARM_SVC_SPM_RET_SUCCESS:=0D
+ Status =3D EFI_SUCCESS;=0D
+ break;=0D
+=0D
+ case ARM_SVC_SPM_RET_NOT_SUPPORTED:=0D
+ Status =3D EFI_UNSUPPORTED;=0D
+ break;=0D
+=0D
+ case ARM_SVC_SPM_RET_INVALID_PARAMS:=0D
+ Status =3D EFI_INVALID_PARAMETER;=0D
+ break;=0D
+=0D
+ case ARM_SVC_SPM_RET_DENIED:=0D
+ Status =3D EFI_ACCESS_DENIED;=0D
+ break;=0D
+=0D
+ case ARM_SVC_SPM_RET_NO_MEMORY:=0D
+ Status =3D EFI_OUT_OF_RESOURCES;=0D
+ break;=0D
+=0D
+ default:=0D
+ Status =3D EFI_ACCESS_DENIED;=0D
+ }=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ The GetAttributes() function retrieves the attributes and=0D
+ current settings of the block.=0D
+=0D
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL insta=
nce.=0D
+=0D
+ @param Attributes Pointer to EFI_FVB_ATTRIBUTES_2 in which the=0D
+ attributes and current settings are=0D
+ returned. Type EFI_FVB_ATTRIBUTES_2 is defined=0D
+ in EFI_FIRMWARE_VOLUME_HEADER.=0D
+=0D
+ @retval EFI_SUCCESS The firmware volume attributes were=0D
+ returned.=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+OpTeeRpmbFvbGetAttributes (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ OUT EFI_FVB_ATTRIBUTES_2 *Attributes=0D
+ )=0D
+{=0D
+ *Attributes =3D EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled=0D
+ EFI_FVB2_READ_STATUS | // Reads are currently enabl=
ed=0D
+ EFI_FVB2_WRITE_STATUS | // Writes are currently enab=
led=0D
+ EFI_FVB2_WRITE_ENABLED_CAP | // Writes may be enabled=0D
+ EFI_FVB2_STICKY_WRITE | // A block erase is required=
to flip bits into EFI_FVB2_ERASE_POLARITY=0D
+ EFI_FVB2_MEMORY_MAPPED | // It is memory mapped=0D
+ EFI_FVB2_ERASE_POLARITY; // After erasure all bits ta=
ke this value (i.e. '1')=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ The SetAttributes() function sets configurable firmware volume=0D
+ attributes and returns the new settings of the firmware volume.=0D
+=0D
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL ins=
tance.=0D
+=0D
+ @param Attributes On input, Attributes is a pointer to=0D
+ EFI_FVB_ATTRIBUTES_2 that contains the=0D
+ desired firmware volume settings. On=0D
+ successful return, it contains the new=0D
+ settings of the firmware volume. Type=0D
+ EFI_FVB_ATTRIBUTES_2 is defined in=0D
+ EFI_FIRMWARE_VOLUME_HEADER.=0D
+=0D
+ @retval EFI_UNSUPPORTED Set attributes not supported=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+OpTeeRpmbFvbSetAttributes (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes=0D
+ )=0D
+{=0D
+ DEBUG ((DEBUG_ERROR, "FvbSetAttributes(0x%X) is not supported\n", *Attri=
butes));=0D
+ return EFI_UNSUPPORTED;=0D
+}=0D
+=0D
+/**=0D
+ The GetPhysicalAddress() function retrieves the base address of=0D
+ a memory-mapped firmware volume. This function should be called=0D
+ only for memory-mapped firmware volumes.=0D
+=0D
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instanc=
e.=0D
+=0D
+ @param Address Pointer to a caller-allocated=0D
+ EFI_PHYSICAL_ADDRESS that, on successful=0D
+ return from GetPhysicalAddress(), contains the=0D
+ base address of the firmware volume.=0D
+=0D
+ @retval EFI_SUCCESS The firmware volume base address was returned.=
=0D
+=0D
+ @retval EFI_UNSUPPORTED The firmware volume is not memory mapped.=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+OpTeeRpmbFvbGetPhysicalAddress (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ OUT EFI_PHYSICAL_ADDRESS *Address=0D
+ )=0D
+{=0D
+ MEM_INSTANCE *Instance;=0D
+=0D
+ Instance =3D INSTANCE_FROM_FVB_THIS (This);=0D
+ *Address =3D Instance->MemBaseAddress;=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ The GetBlockSize() function retrieves the size of the requested=0D
+ block. It also returns the number of additional blocks with=0D
+ the identical size. The GetBlockSize() function is used to=0D
+ retrieve the block map (see EFI_FIRMWARE_VOLUME_HEADER).=0D
+=0D
+=0D
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL i=
nstance.=0D
+=0D
+ @param Lba Indicates the block for which to return the size.=
=0D
+=0D
+ @param BlockSize Pointer to a caller-allocated UINTN in which=0D
+ the size of the block is returned.=0D
+=0D
+ @param NumberOfBlocks Pointer to a caller-allocated UINTN in=0D
+ which the number of consecutive blocks,=0D
+ starting with Lba, is returned. All=0D
+ blocks in this range have a size of=0D
+ BlockSize.=0D
+=0D
+=0D
+ @retval EFI_SUCCESS The firmware volume base address was ret=
urned.=0D
+=0D
+ @retval EFI_INVALID_PARAMETER The requested LBA is out of range.=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+OpTeeRpmbFvbGetBlockSize (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ IN EFI_LBA Lba,=0D
+ OUT UINTN *BlockSize,=0D
+ OUT UINTN *NumberOfBlocks=0D
+ )=0D
+{=0D
+ MEM_INSTANCE *Instance;=0D
+=0D
+ Instance =3D INSTANCE_FROM_FVB_THIS (This);=0D
+ if (Lba > Instance->NBlocks) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ *NumberOfBlocks =3D Instance->NBlocks - (UINTN)Lba;=0D
+ *BlockSize =3D Instance->BlockSize;=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Reads the specified number of bytes into a buffer from the specified blo=
ck.=0D
+=0D
+ The Read() function reads the requested number of bytes from the=0D
+ requested block and stores them in the provided buffer.=0D
+ Implementations should be mindful that the firmware volume=0D
+ might be in the ReadDisabled state. If it is in this state,=0D
+ the Read() function must return the status code=0D
+ EFI_ACCESS_DENIED without modifying the contents of the=0D
+ buffer. The Read() function must also prevent spanning block=0D
+ boundaries. If a read is requested that would span a block=0D
+ boundary, the read must read up to the boundary but not=0D
+ beyond. The output parameter NumBytes must be set to correctly=0D
+ indicate the number of bytes actually read. The caller must be=0D
+ aware that a read may be partially completed.=0D
+=0D
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instanc=
e.=0D
+=0D
+ @param Lba The starting logical block index=0D
+ from which to read.=0D
+=0D
+ @param Offset Offset into the block at which to begin reading.=0D
+=0D
+ @param NumBytes Pointer to a UINTN. At entry, *NumBytes=0D
+ contains the total size of the buffer. At=0D
+ exit, *NumBytes contains the total number of=0D
+ bytes read.=0D
+=0D
+ @param Buffer Pointer to a caller-allocated buffer that will=0D
+ be used to hold the data that is read.=0D
+=0D
+ @retval EFI_SUCCESS The firmware volume was read successfully,=0D
+ and contents are in Buffer.=0D
+=0D
+ @retval EFI_BAD_BUFFER_SIZE Read attempted across an LBA=0D
+ boundary. On output, NumBytes=0D
+ contains the total number of bytes=0D
+ returned in Buffer.=0D
+=0D
+ @retval EFI_ACCESS_DENIED The firmware volume is in the=0D
+ ReadDisabled state.=0D
+=0D
+ @retval EFI_DEVICE_ERROR The block device is not=0D
+ functioning correctly and could=0D
+ not be read.=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+OpTeeRpmbFvbRead (=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 OUT UINT8 *Buffer=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ MEM_INSTANCE *Instance;=0D
+ VOID *Base;=0D
+=0D
+ Status =3D EFI_SUCCESS;=0D
+ Instance =3D INSTANCE_FROM_FVB_THIS (This);=0D
+ if (!Instance->Initialized) {=0D
+ Status =3D Instance->Initialize (Instance);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+ }=0D
+=0D
+ Base =3D (VOID *)Instance->MemBaseAddress + (Lba * Instance->BlockSize) =
+ Offset;=0D
+ // We could read the data from the RPMB instead of memory=0D
+ // The 2 copies should already be identical=0D
+ // Copy from memory image=0D
+ CopyMem (Buffer, Base, *NumBytes);=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Writes the specified number of bytes from the input buffer to the block.=
=0D
+=0D
+ The Write() function writes the specified number of bytes from=0D
+ the provided buffer to the specified block and offset. If the=0D
+ firmware volume is sticky write, the caller must ensure that=0D
+ all the bits of the specified range to write are in the=0D
+ EFI_FVB_ERASE_POLARITY state before calling the Write()=0D
+ function, or else the result will be unpredictable. This=0D
+ unpredictability arises because, for a sticky-write firmware=0D
+ volume, a write may negate a bit in the EFI_FVB_ERASE_POLARITY=0D
+ state but cannot flip it back again. Before calling the=0D
+ Write() function, it is recommended for the caller to first call=0D
+ the EraseBlocks() function to erase the specified block to=0D
+ write. A block erase cycle will transition bits from the=0D
+ (NOT)EFI_FVB_ERASE_POLARITY state back to the=0D
+ EFI_FVB_ERASE_POLARITY state. Implementations should be=0D
+ mindful that the firmware volume might be in the WriteDisabled=0D
+ state. If it is in this state, the Write() function must=0D
+ return the status code EFI_ACCESS_DENIED without modifying the=0D
+ contents of the firmware volume. The Write() function must=0D
+ also prevent spanning block boundaries. If a write is=0D
+ requested that spans a block boundary, the write must store up=0D
+ to the boundary but not beyond. The output parameter NumBytes=0D
+ must be set to correctly indicate the number of bytes actually=0D
+ written. The caller must be aware that a write may be=0D
+ partially completed. All writes, partial or otherwise, must be=0D
+ fully flushed to the hardware before the Write() service=0D
+ returns.=0D
+=0D
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instanc=
e.=0D
+=0D
+ @param Lba The starting logical block index to write to.=0D
+=0D
+ @param Offset Offset into the block at which to begin writing.=0D
+=0D
+ @param NumBytes The pointer to a UINTN. At entry, *NumBytes=0D
+ contains the total size of the buffer. At=0D
+ exit, *NumBytes contains the total number of=0D
+ bytes actually written.=0D
+=0D
+ @param Buffer The pointer to a caller-allocated buffer that=0D
+ contains the source for the write.=0D
+=0D
+ @retval EFI_SUCCESS The firmware volume was written successfully=
.=0D
+=0D
+ @retval EFI_BAD_BUFFER_SIZE The write was attempted across an=0D
+ LBA boundary. On output, NumBytes=0D
+ contains the total number of bytes=0D
+ actually written.=0D
+=0D
+ @retval EFI_ACCESS_DENIED The firmware volume is in the=0D
+ WriteDisabled state.=0D
+=0D
+ @retval EFI_DEVICE_ERROR The block device is malfunctioning=0D
+ and could not be written.=0D
+=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+OpTeeRpmbFvbWrite (=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
+ MEM_INSTANCE *Instance;=0D
+ EFI_STATUS Status;=0D
+ VOID *Base;=0D
+=0D
+ Instance =3D INSTANCE_FROM_FVB_THIS (This);=0D
+ if (!Instance->Initialized) {=0D
+ Status =3D Instance->Initialize (Instance);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+ }=0D
+ Base =3D (VOID *)Instance->MemBaseAddress + Lba * Instance->BlockSize + =
Offset;=0D
+ Status =3D ReadWriteRpmb (=0D
+ SP_SVC_RPMB_WRITE,=0D
+ (UINTN)Buffer,=0D
+ *NumBytes,=0D
+ (Lba * Instance->BlockSize) + Offset=0D
+ );=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+=0D
+ // Update the memory copy=0D
+ CopyMem (Base, Buffer, *NumBytes);=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Erases and initializes a firmware volume block.=0D
+=0D
+ The EraseBlocks() function erases one or more blocks as denoted=0D
+ by the variable argument list. The entire parameter list of=0D
+ blocks must be verified before erasing any blocks. If a block is=0D
+ requested that does not exist within the associated firmware=0D
+ volume (it has a larger index than the last block of the=0D
+ firmware volume), the EraseBlocks() function must return the=0D
+ status code EFI_INVALID_PARAMETER without modifying the contents=0D
+ of the firmware volume. Implementations should be mindful that=0D
+ the firmware volume might be in the WriteDisabled state. If it=0D
+ is in this state, the EraseBlocks() function must return the=0D
+ status code EFI_ACCESS_DENIED without modifying the contents of=0D
+ the firmware volume. All calls to EraseBlocks() must be fully=0D
+ flushed to the hardware before the EraseBlocks() service=0D
+ returns.=0D
+=0D
+ @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL=0D
+ instance.=0D
+=0D
+ @param ... The variable argument list is a list of tuples.=0D
+ Each tuple describes a range of LBAs to erase=0D
+ and consists of the following:=0D
+ - An EFI_LBA that indicates the starting LBA=0D
+ - A UINTN that indicates the number of blocks to=0D
+ erase.=0D
+=0D
+ The list is terminated with an=0D
+ EFI_LBA_LIST_TERMINATOR. For example, the=0D
+ following indicates that two ranges of blocks=0D
+ (5-7 and 10-11) are to be erased: EraseBlocks=0D
+ (This, 5, 3, 10, 2, EFI_LBA_LIST_TERMINATOR);=0D
+=0D
+ @retval EFI_SUCCESS The erase request successfully=0D
+ completed.=0D
+=0D
+ @retval EFI_ACCESS_DENIED The firmware volume is in the=0D
+ WriteDisabled state.=0D
+ @retval EFI_DEVICE_ERROR The block device is not functioning=0D
+ correctly and could not be written.=0D
+ The firmware device may have been=0D
+ partially erased.=0D
+ @retval EFI_INVALID_PARAMETER One or more of the LBAs listed=0D
+ in the variable argument list do=0D
+ not exist in the firmware volume.=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+OpTeeRpmbFvbErase (=0D
+ IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,=0D
+ ...=0D
+ )=0D
+{=0D
+ MEM_INSTANCE *Instance;=0D
+ UINTN NumBytes;=0D
+ UINTN NumLba;=0D
+ EFI_LBA Start;=0D
+ VOID *Base;=0D
+ VOID *Buf;=0D
+ VA_LIST Args;=0D
+ EFI_STATUS Status;=0D
+=0D
+ Instance =3D INSTANCE_FROM_FVB_THIS (This);=0D
+=0D
+ VA_START (Args, This);=0D
+ for (Start =3D VA_ARG (Args, EFI_LBA);=0D
+ Start !=3D EFI_LBA_LIST_TERMINATOR;=0D
+ Start =3D VA_ARG (Args, EFI_LBA)) {=0D
+ NumLba =3D VA_ARG (Args, UINTN);=0D
+ if (NumLba =3D=3D 0 || Start + NumLba > Instance->NBlocks) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+ NumBytes =3D NumLba * Instance->BlockSize;=0D
+ Base =3D (VOID *)Instance->MemBaseAddress + Start * Instance->BlockSiz=
e;=0D
+ Buf =3D AllocatePool (NumLba * Instance->BlockSize);=0D
+ if (Buf =3D=3D NULL) {=0D
+ return EFI_DEVICE_ERROR;=0D
+ }=0D
+ SetMem64 (Buf, NumLba * Instance->BlockSize, ~0UL);=0D
+ // Write the device=0D
+ Status =3D ReadWriteRpmb (=0D
+ SP_SVC_RPMB_WRITE,=0D
+ (UINTN)Buf,=0D
+ NumBytes,=0D
+ Start * Instance->BlockSize=0D
+ );=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+ // Update the in memory copy=0D
+ SetMem64 (Base, NumLba * Instance->BlockSize, ~0UL);=0D
+ FreePool (Buf);=0D
+ }=0D
+=0D
+ VA_END (Args);=0D
+=0D
+ return EFI_SUCCESS;=0D
+}=0D
+=0D
+/**=0D
+ Since we use a memory backed storage we need to restore the RPMB content=
s=0D
+ into memory before we register the Fvb protocol.=0D
+=0D
+ @param Instance Address to copy flash contents to=0D
+**/=0D
+STATIC=0D
+VOID=0D
+ReadEntireFlash (=0D
+ MEM_INSTANCE *Instance=0D
+ )=0D
+{=0D
+ UINTN ReadAddr;=0D
+ UINTN StorageFtwWorkingSize;=0D
+ UINTN StorageVariableSize;=0D
+ UINTN StorageFtwSpareSize;=0D
+=0D
+ StorageFtwWorkingSize =3D PcdGet32(PcdFlashNvStorageFtwWorkingSize);=0D
+ StorageVariableSize =3D PcdGet32(PcdFlashNvStorageVariableSize);=0D
+ StorageFtwSpareSize =3D PcdGet32(PcdFlashNvStorageFtwSpareSize);=0D
+=0D
+ ReadAddr =3D Instance->MemBaseAddress;=0D
+ // There's no need to check if the read failed here. The upper EDK2 laye=
rs=0D
+ // will initialize the flash correctly if the in-memory copy is wrong=0D
+ ReadWriteRpmb (=0D
+ SP_SVC_RPMB_READ,=0D
+ ReadAddr,=0D
+ StorageVariableSize + StorageFtwWorkingSize + StorageFtwSpareSize,=0D
+ 0=0D
+ );=0D
+}=0D
+=0D
+/**=0D
+ Validate the firmware volume header.=0D
+=0D
+ @param FwVolHeader Pointer to the firmware volume header for the RPMB=0D
+=0D
+ @retval EFI_SUCCESS The firmware volume header is correct=0D
+ @retval EFI_NOT_FOUND No header present=0D
+ @retval EFI_VOLUME_CORRUPTED The firmware volume header CRC was invalid=
=0D
+ or either one of GUID's, Signature and hea=
der=0D
+ length was invalid=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+EFIAPI=0D
+ValidateFvHeader (=0D
+ IN EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader=0D
+ )=0D
+{=0D
+ UINT16 Checksum;=0D
+ VARIABLE_STORE_HEADER *VariableStoreHeader;=0D
+ UINTN VariableStoreLength;=0D
+ UINTN FvLength;=0D
+=0D
+ FvLength =3D PcdGet32(PcdFlashNvStorageVariableSize) +=0D
+ PcdGet32(PcdFlashNvStorageFtwWorkingSize) +=0D
+ PcdGet32(PcdFlashNvStorageFtwSpareSize);=0D
+=0D
+ // Verify the header revision, header signature, length=0D
+ // Length of FvBlock cannot be 2**64-1=0D
+ // HeaderLength cannot be an odd number=0D
+ //=0D
+ if ( (FwVolHeader->Revision !=3D EFI_FVH_REVISION)=0D
+ || (FwVolHeader->Signature !=3D EFI_FVH_SIGNATURE)=0D
+ || (FwVolHeader->FvLength !=3D FvLength)=0D
+ )=0D
+ {=0D
+ DEBUG ((DEBUG_INFO, "%a: No Firmware Volume header present\n",=0D
+ __FUNCTION__));=0D
+ return EFI_NOT_FOUND;=0D
+ }=0D
+=0D
+ // Check the Firmware Volume Guid=0D
+ if (!CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid)=
) {=0D
+ DEBUG ((DEBUG_INFO, "%a: Firmware Volume Guid non-compatible\n",=0D
+ __FUNCTION__));=0D
+ return EFI_VOLUME_CORRUPTED;=0D
+ }=0D
+=0D
+ // Verify the header checksum=0D
+ Checksum =3D CalculateSum16((UINT16*)FwVolHeader, FwVolHeader->HeaderLen=
gth);=0D
+ if (Checksum !=3D 0) {=0D
+ DEBUG ((DEBUG_INFO, "%a: FV checksum is invalid (Checksum:0x%X)\n",=0D
+ __FUNCTION__, Checksum));=0D
+ return EFI_VOLUME_CORRUPTED;=0D
+ }=0D
+=0D
+ VariableStoreHeader =3D (VARIABLE_STORE_HEADER*)((UINTN)FwVolHeader +=0D
+ FwVolHeader->HeaderLength);=0D
+=0D
+ // Check the Variable Store Guid=0D
+ if (!CompareGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid) &&=
=0D
+ !CompareGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVar=
iableGuid)) {=0D
+ DEBUG ((DEBUG_INFO, "%a: Variable Store Guid non-compatible\n", __FUNC=
TION__));=0D
+ return EFI_VOLUME_CORRUPTED;=0D
+ }=0D
+=0D
+ VariableStoreLength =3D PcdGet32 (PcdFlashNvStorageVariableSize) -=0D
+ FwVolHeader->HeaderLength;=0D
+ if (VariableStoreHeader->Size !=3D VariableStoreLength) {=0D
+ DEBUG ((DEBUG_INFO, "%a: Variable Store Length does not match\n",=0D
+ __FUNCTION__));=0D
+ return EFI_VOLUME_CORRUPTED;=0D
+ }=0D
+=0D
+ return EFI_SUCCESS;=0D
+=0D
+}=0D
+=0D
+/**=0D
+ Initialize Fvb and variable storage headers for the RPMB storage.=0D
+=0D
+ @param Instance MEM_INSTANCE pointer describing the device and the=0D
+ Firmware Block Protocol=0D
+=0D
+ @retval EFI_SUCCESS read/write ok=0D
+=0D
+ @retval EFI_UNSUPPORTED SVC to op-tee not supported=0D
+=0D
+ @retval EFI_INVALID_PARAMETER SVC to op-tee had an invalid par=
am=0D
+=0D
+ @retval EFI_ACCESS_DENIED SVC to op-tee was denied=0D
+=0D
+ @retval EFI_OUT_OF_RESOURCES op-tee out of memory=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+InitializeFvAndVariableStoreHeaders (=0D
+ MEM_INSTANCE *Instance=0D
+ )=0D
+{=0D
+ EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader;=0D
+ VARIABLE_STORE_HEADER *VariableStoreHeader;=0D
+ EFI_STATUS Status;=0D
+ UINTN HeadersLength;=0D
+ VOID* Headers;=0D
+=0D
+ HeadersLength =3D sizeof (EFI_FIRMWARE_VOLUME_HEADER) +=0D
+ sizeof (EFI_FV_BLOCK_MAP_ENTRY) +=0D
+ sizeof (VARIABLE_STORE_HEADER);=0D
+ Headers =3D AllocateZeroPool (HeadersLength);=0D
+ if (Headers =3D=3D NULL) {=0D
+ return EFI_OUT_OF_RESOURCES;=0D
+ }=0D
+=0D
+ //=0D
+ // EFI_FIRMWARE_VOLUME_HEADER=0D
+ //=0D
+ FirmwareVolumeHeader =3D (EFI_FIRMWARE_VOLUME_HEADER*)Headers;=0D
+ CopyGuid (&FirmwareVolumeHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid=
);=0D
+ FirmwareVolumeHeader->FvLength =3D PcdGet32(PcdFlashNvStorageVariableSiz=
e) +=0D
+ PcdGet32(PcdFlashNvStorageFtwWorkingSiz=
e) +=0D
+ PcdGet32(PcdFlashNvStorageFtwSpareSize)=
;=0D
+ FirmwareVolumeHeader->Signature =3D EFI_FVH_SIGNATURE;=0D
+ FirmwareVolumeHeader->Attributes =3D EFI_FVB2_READ_ENABLED_CAP |=0D
+ EFI_FVB2_READ_STATUS |=0D
+ EFI_FVB2_STICKY_WRITE |=0D
+ EFI_FVB2_MEMORY_MAPPED |=0D
+ EFI_FVB2_ERASE_POLARITY |=0D
+ EFI_FVB2_WRITE_STATUS |=0D
+ EFI_FVB2_WRITE_ENABLED_CAP;=0D
+=0D
+ FirmwareVolumeHeader->HeaderLength =3D sizeof (EFI_FIRMWARE_VOLUME_HEADE=
R) +=0D
+ sizeof (EFI_FV_BLOCK_MAP_ENTRY);=0D
+ FirmwareVolumeHeader->Revision =3D EFI_FVH_REVISION;=0D
+ FirmwareVolumeHeader->BlockMap[0].NumBlocks =3D Instance->NBlocks;=0D
+ FirmwareVolumeHeader->BlockMap[0].Length =3D Instance->BlockSize;=0D
+ FirmwareVolumeHeader->BlockMap[1].NumBlocks =3D 0;=0D
+ FirmwareVolumeHeader->BlockMap[1].Length =3D 0;=0D
+ FirmwareVolumeHeader->Checksum =3D CalculateCheckSum16 (=0D
+ (UINT16*)FirmwareVolumeHeader,=0D
+ FirmwareVolumeHeader->HeaderLength=0D
+ );=0D
+=0D
+ //=0D
+ // VARIABLE_STORE_HEADER=0D
+ //=0D
+ VariableStoreHeader =3D (VARIABLE_STORE_HEADER*)((UINTN)Headers +=0D
+ FirmwareVolumeHeader->HeaderLength);=0D
+ CopyGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGui=
d);=0D
+ VariableStoreHeader->Size =3D PcdGet32(PcdFlashNvStorageVariableSize) -=
=0D
+ FirmwareVolumeHeader->HeaderLength;=0D
+ VariableStoreHeader->Format =3D VARIABLE_STORE_FORMATTED;=0D
+ VariableStoreHeader->State =3D VARIABLE_STORE_HEALTHY;=0D
+=0D
+ Status =3D ReadWriteRpmb (SP_SVC_RPMB_WRITE, (UINTN)Headers, HeadersLeng=
th, 0);=0D
+ if (EFI_ERROR (Status)) {=0D
+ goto Exit;=0D
+ }=0D
+ // Install the combined header in memory=0D
+ CopyMem ((VOID*)Instance->MemBaseAddress, Headers, HeadersLength);=0D
+=0D
+Exit:=0D
+ FreePool (Headers);=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Initialize the firmware block protocol for the specified memory.=0D
+=0D
+ @param Instance MEM_INSTANCE pointer describing the device and the=0D
+ Firmware Block Protocol=0D
+=0D
+ @retval EFI_SUCCESS Initialized successfully or already in=
itialized=0D
+ @retval EFI_UNSUPPORTED SVC to op-tee not supported=0D
+ @retval EFI_INVALID_PARAMETER SVC to op-tee had an invalid param=0D
+ @retval EFI_ACCESS_DENIED SVC to op-tee was denied=0D
+ @retval EFI_OUT_OF_RESOURCES op-tee out of memory=0D
+=0D
+=0D
+=0D
+**/=0D
+STATIC=0D
+EFI_STATUS=0D
+EFIAPI=0D
+FvbInitialize (=0D
+ MEM_INSTANCE *Instance=0D
+ )=0D
+{=0D
+ EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;=0D
+ EFI_STATUS Status;=0D
+=0D
+ if (Instance->Initialized) {=0D
+ return EFI_SUCCESS;=0D
+ }=0D
+=0D
+ // FirmwareVolumeHeader->FvLength is declared to have the Variable area=
=0D
+ // AND the FTW working area AND the FTW Spare contiguous.=0D
+ ASSERT (=0D
+ (PcdGet64 (PcdFlashNvStorageVariableBase64) +=0D
+ PcdGet32 (PcdFlashNvStorageVariableSize)) =3D=3D=0D
+ PcdGet64 (PcdFlashNvStorageFtwWorkingBase64)=0D
+ );=0D
+ ASSERT (=0D
+ (PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) +=0D
+ PcdGet32 (PcdFlashNvStorageFtwWorkingSize)) =3D=3D=0D
+ PcdGet64 (PcdFlashNvStorageFtwSpareBase64));=0D
+=0D
+ // Check if the size of the area is at least one block size=0D
+ ASSERT (=0D
+ (PcdGet32 (PcdFlashNvStorageVariableSize) > 0) &&=0D
+ (PcdGet32 (PcdFlashNvStorageVariableSize) / Instance->BlockSize > 0)=0D
+ );=0D
+ ASSERT (=0D
+ (PcdGet32 (PcdFlashNvStorageFtwWorkingSize) > 0) &&=0D
+ (PcdGet32 (PcdFlashNvStorageFtwWorkingSize) / Instance->BlockSize > 0)=
=0D
+ );=0D
+ ASSERT (=0D
+ (PcdGet32 (PcdFlashNvStorageFtwSpareSize) > 0) &&=0D
+ (PcdGet32 (PcdFlashNvStorageFtwSpareSize) / Instance->BlockSize > 0)=0D
+ );=0D
+=0D
+ // Ensure the Variable areas are aligned on block size boundaries=0D
+ ASSERT ((PcdGet64 (PcdFlashNvStorageVariableBase64) % Instance->BlockSiz=
e) =3D=3D 0);=0D
+ ASSERT ((PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) % Instance->BlockS=
ize) =3D=3D 0);=0D
+ ASSERT ((PcdGet64 (PcdFlashNvStorageFtwSpareBase64) % Instance->BlockSiz=
e) =3D=3D 0);=0D
+=0D
+ // Read the file from disk and copy it to memory=0D
+ ReadEntireFlash (Instance);=0D
+=0D
+ FwVolHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *)Instance->MemBaseAddress;=
=0D
+ Status =3D ValidateFvHeader (FwVolHeader);=0D
+ if (EFI_ERROR (Status)) {=0D
+ // There is no valid header, so time to install one.=0D
+ DEBUG ((DEBUG_INFO, "%a: The FVB Header is not valid.\n", __FUNCTION__=
));=0D
+=0D
+ // Reset memory=0D
+ SetMem64 ((VOID *)Instance->MemBaseAddress, Instance->NBlocks * Instan=
ce->BlockSize, ~0UL);=0D
+ DEBUG ((DEBUG_INFO, "%a: Erasing Flash.\n", __FUNCTION__));=0D
+ Status =3D ReadWriteRpmb (=0D
+ SP_SVC_RPMB_WRITE,=0D
+ Instance->MemBaseAddress,=0D
+ PcdGet32(PcdFlashNvStorageVariableSize) +=0D
+ PcdGet32(PcdFlashNvStorageFtwWorkingSize) +=0D
+ PcdGet32(PcdFlashNvStorageFtwSpareSize),=0D
+ 0=0D
+ );=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+ // Install all appropriate headers=0D
+ DEBUG ((DEBUG_INFO, "%a: Installing a correct one for this volume.\n",=
=0D
+ __FUNCTION__));=0D
+ Status =3D InitializeFvAndVariableStoreHeaders (Instance);=0D
+ if (EFI_ERROR (Status)) {=0D
+ return Status;=0D
+ }=0D
+ } else {=0D
+ DEBUG ((DEBUG_INFO, "%a: Found valid FVB Header.\n", __FUNCTION__));=0D
+ }=0D
+ Instance->Initialized =3D TRUE;=0D
+=0D
+ return Status;=0D
+}=0D
+=0D
+/**=0D
+ Since the RPMB is not byte addressable we need to allocate memory=0D
+ and sync that on reads/writes. Initialize the memory and install the=0D
+ Fvb protocol.=0D
+=0D
+ @param ImageHandle The EFI image handle=0D
+ @param SystemTable MM system table=0D
+=0D
+ @retval EFI_SUCCESS Protocol installed=0D
+=0D
+ @retval EFI_INVALID_PARAMETER Invalid Pcd values specified=0D
+=0D
+ @retval EFI_OUT_OF_RESOURCES Can't allocate necessary memory=0D
+**/=0D
+EFI_STATUS=0D
+EFIAPI=0D
+OpTeeRpmbFvbInit (=0D
+ IN EFI_HANDLE ImageHandle,=0D
+ IN EFI_MM_SYSTEM_TABLE *SystemTable=0D
+ )=0D
+{=0D
+ EFI_STATUS Status;=0D
+ VOID *Addr;=0D
+ UINTN FvLength;=0D
+ UINTN NBlocks;=0D
+=0D
+ FvLength =3D PcdGet32(PcdFlashNvStorageVariableSize) +=0D
+ PcdGet32(PcdFlashNvStorageFtwWorkingSize) +=0D
+ PcdGet32(PcdFlashNvStorageFtwSpareSize);=0D
+=0D
+ NBlocks =3D EFI_SIZE_TO_PAGES (ALIGN_VARIABLE (FvLength));=0D
+ Addr =3D AllocatePages (NBlocks);=0D
+ if (Addr =3D=3D NULL) {=0D
+ ASSERT (0);=0D
+ return EFI_OUT_OF_RESOURCES;=0D
+ }=0D
+=0D
+ SetMem (&mInstance, sizeof (mInstance), 0);=0D
+=0D
+ mInstance.FvbProtocol.GetPhysicalAddress =3D OpTeeRpmbFvbGetPhysicalAddr=
ess;=0D
+ mInstance.FvbProtocol.GetAttributes =3D OpTeeRpmbFvbGetAttributes;=
=0D
+ mInstance.FvbProtocol.SetAttributes =3D OpTeeRpmbFvbSetAttributes;=
=0D
+ mInstance.FvbProtocol.GetBlockSize =3D OpTeeRpmbFvbGetBlockSize;=0D
+ mInstance.FvbProtocol.EraseBlocks =3D OpTeeRpmbFvbErase;=0D
+ mInstance.FvbProtocol.Write =3D OpTeeRpmbFvbWrite;=0D
+ mInstance.FvbProtocol.Read =3D OpTeeRpmbFvbRead;=0D
+=0D
+ mInstance.MemBaseAddress =3D (EFI_PHYSICAL_ADDRESS)Addr;=0D
+ mInstance.Signature =3D FLASH_SIGNATURE;=0D
+ mInstance.Initialize =3D FvbInitialize;=0D
+ mInstance.BlockSize =3D EFI_PAGE_SIZE;=0D
+ mInstance.NBlocks =3D NBlocks;=0D
+=0D
+ // The Pcd is user defined, so make sure we don't overflow=0D
+ if (mInstance.MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageV=
ariableSize)) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ if (mInstance.MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageV=
ariableSize) -=0D
+ PcdGet32 (PcdFlashNvStorageFtwWorkingSize)) {=0D
+ return EFI_INVALID_PARAMETER;=0D
+ }=0D
+=0D
+ // Update the defined PCDs related to Variable Storage=0D
+ PatchPcdSet64 (PcdFlashNvStorageVariableBase64, mInstance.MemBaseAddress=
);=0D
+ PatchPcdSet64 (=0D
+ PcdFlashNvStorageFtwWorkingBase64,=0D
+ mInstance.MemBaseAddress + PcdGet32 (PcdFlashNvStorageVariableSize)=0D
+ );=0D
+ PatchPcdSet64 (=0D
+ PcdFlashNvStorageFtwSpareBase64,=0D
+ mInstance.MemBaseAddress +=0D
+ PcdGet32 (PcdFlashNvStorageVariableSize) +=0D
+ PcdGet32 (PcdFlashNvStorageFtwWorkingSize)=0D
+ );=0D
+=0D
+ Status =3D gMmst->MmInstallProtocolInterface (=0D
+ &mInstance.Handle,=0D
+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,=0D
+ EFI_NATIVE_INTERFACE,=0D
+ &mInstance.FvbProtocol=0D
+ );=0D
+ ASSERT_EFI_ERROR (Status);=0D
+=0D
+ DEBUG ((DEBUG_INFO, "%a: Register OP-TEE RPMB Fvb\n", __FUNCTION__));=0D
+ DEBUG ((DEBUG_INFO, "%a: Using NV store FV in-memory copy at 0x%lx\n",=0D
+ __FUNCTION__, PatchPcdGet64 (PcdFlashNvStorageVariableBase64)));=0D
+=0D
+ return Status;=0D
+}=0D
diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFvb.h b/Drivers/OpTeeRpmb/OpTeeRpmb=
Fvb.h
new file mode 100644
index 000000000000..8305e776dbb6
--- /dev/null
+++ b/Drivers/OpTeeRpmb/OpTeeRpmbFvb.h
@@ -0,0 +1,52 @@
+/** @file=0D
+=0D
+ Copyright (c) 2020, Linaro Ltd. All rights reserved.<BR>=0D
+ SPDX-License-Identifier: BSD-2-Clause-Patent=0D
+=0D
+**/=0D
+=0D
+#ifndef OPTEE_RPMB_FVB_H_=0D
+#define OPTEE_RPMB_FVB_H_=0D
+=0D
+/**=0D
+ Those are not currently defined in any spec, it's an internal=0D
+ contract between OP-TEE and EDK2.=0D
+ For more details check core/arch/arm/include/kernel/stmm_sp.h in OP-TEE=0D
+**/=0D
+#define SP_SVC_RPMB_READ 0xC4000066=0D
+#define SP_SVC_RPMB_WRITE 0xC4000067=0D
+=0D
+#define FLASH_SIGNATURE SIGNATURE_32('r', 'p', 'm', 'b')=0D
+#define INSTANCE_FROM_FVB_THIS(a) CR(a, MEM_INSTANCE, FvbProtocol, \=0D
+ FLASH_SIGNATURE)=0D
+=0D
+typedef struct _MEM_INSTANCE MEM_INSTANCE;=0D
+typedef EFI_STATUS (*MEM_INITIALIZE) (MEM_INSTANCE* Instance);=0D
+=0D
+/**=0D
+ This struct is used by the RPMB driver. Since the upper EDK2 layers=0D
+ expect byte addressable memory, we allocate a memory area of certain=0D
+ size and sync it to the hardware on reads/writes.=0D
+=0D
+ @param[in] Signature Internal signature used to discover the inst=
ance=0D
+ @param[in] Initialize Function used to initialize the instance=0D
+ @param[in] Initialized Set to true if initialized=0D
+ @param[in] FvbProtocol FVB protocol of the instance=0D
+ @param[in] Handle Handle to install=0D
+ @param[in] MemBaseAddress Physical address of the beggining of the all=
ocated memory=0D
+ @param[in] BlockSize Blocksize=0D
+ @param[in] NBlocks Number of allocated blocks=0D
+**/=0D
+struct _MEM_INSTANCE=0D
+{=0D
+ UINT32 Signature;=0D
+ MEM_INITIALIZE Initialize;=0D
+ BOOLEAN Initialized;=0D
+ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL FvbProtocol;=0D
+ EFI_HANDLE Handle;=0D
+ EFI_PHYSICAL_ADDRESS MemBaseAddress;=0D
+ UINT16 BlockSize;=0D
+ UINT16 NBlocks;=0D
+};=0D
+=0D
+#endif=0D
--=20
2.30.0


PierreGondois
 

Hello Ilias,

My review is mostly about coding style, but I would have some (inlined) remarks about your patch,

Regards,

Pierre

On 3/2/21 3:35 PM, Pierre Gondois wrote:


------------------------------------------------------------------------
*From:* devel@edk2.groups.io <devel@edk2.groups.io> on behalf of Ilias Apalodimas via groups.io <ilias.apalodimas=linaro.org@groups.io>
*Sent:* Friday, February 12, 2021 5:34 PM
*To:* devel@edk2.groups.io <devel@edk2.groups.io>; Sami Mujawar <Sami.Mujawar@arm.com>
*Cc:* ardb+tianocore@kernel.org <ardb+tianocore@kernel.org>; sughosh.ganu@linaro.org <sughosh.ganu@linaro.org>; leif@nuviainc.com <leif@nuviainc.com>; Ilias Apalodimas <ilias.apalodimas@linaro.org>
*Subject:* [edk2-devel] [PATCH 1/2 v5] Drivers/OpTeeRpmb: Add an OP-TEE backed RPMB driver
A following patch is adding support for building StMM in order to run it
from OP-TEE.
OP-TEE in combination with a NS-world supplicant can use the RPMB
partition of an eMMC to store EFI variables. The supplicant
functionality is currently available in U-Boot only but can be ported
into EDK2. Assuming similar functionality is added in EDK2, this will
allow any hardware with an RPMB partition to store EFI variables
securely.

So let's add a driver that enables access of the RPMB partition through
OP-TEE. Since the upper layers expect a byte addressable interface,
the driver allocates memory and patches the PCDs, while syncing the
memory/hardware on read/write callbacks.

Signed-off-by: Ilias Apalodimas <ilias.apalodimas@linaro.org>
---
 Drivers/OpTeeRpmb/FixupPcd.c      |  89 +++
 Drivers/OpTeeRpmb/FixupPcd.inf    |  43 ++
 Drivers/OpTeeRpmb/OpTeeRpmbFv.inf |  58 ++
 Drivers/OpTeeRpmb/OpTeeRpmbFvb.c  | 920 ++++++++++++++++++++++++++++++
 Drivers/OpTeeRpmb/OpTeeRpmbFvb.h  |  52 ++
 5 files changed, 1162 insertions(+)
 create mode 100644 Drivers/OpTeeRpmb/FixupPcd.c
 create mode 100644 Drivers/OpTeeRpmb/FixupPcd.inf
 create mode 100644 Drivers/OpTeeRpmb/OpTeeRpmbFv.inf
 create mode 100644 Drivers/OpTeeRpmb/OpTeeRpmbFvb.c
 create mode 100644 Drivers/OpTeeRpmb/OpTeeRpmbFvb.h

diff --git a/Drivers/OpTeeRpmb/FixupPcd.c b/Drivers/OpTeeRpmb/FixupPcd.c
new file mode 100644
index 000000000000..6cd503b71c6d
--- /dev/null
+++ b/Drivers/OpTeeRpmb/FixupPcd.c
@@ -0,0 +1,89 @@
+/** @file

+

+  Update the patched PCDs to their correct value

+

+  Copyright (c) 2020, Linaro Ltd. All rights reserved.<BR>

+

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

+

+**/

+

+/**

+ * Patch the relevant PCDs of the RPMB driver with the correct address of the

+ * allocated memory

+ *

+**/

+#include <Library/BaseLib.h>

+#include <Library/DebugLib.h>

+#include <Library/MmServicesTableLib.h>

+#include <Library/PcdLib.h>

+

+#include <Protocol/FirmwareVolumeBlock.h>

+#include <Protocol/SmmFirmwareVolumeBlock.h>

+

+#include "OpTeeRpmbFvb.h"

+

+/**

+  Fixup the Pcd values for variable storage

+

+  Since the upper layers of EDK2 expect a memory mapped interface and we can't

+  offer that from an RPMB, the driver allocates memory on init and passes that

+  on the upper layers. Since the memory is dynamically allocated and we can't set the

+  PCD is StMM context, we need to patch it correctly on each access
I think: is -> in

+

+  @retval EFI_SUCCESS Protocol was found and PCDs patched up

+

+ **/
I think there should not be a space here.


+EFI_STATUS

+EFIAPI

+FixPcdMemory (

+  VOID

+  )

+{

+  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *FvbProtocol;

+  MEM_INSTANCE                        *Instance;

+  EFI_STATUS                          Status;

+

+  //

+  // Locate SmmFirmwareVolumeBlockProtocol

+  //

+  Status = gMmst->MmLocateProtocol (

+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,

+                    NULL,

+                    (VOID **) &FvbProtocol

+                    );

+  ASSERT_EFI_ERROR (Status);

+

+  Instance = INSTANCE_FROM_FVB_THIS (FvbProtocol);

+  // The Pcd is user defined, so make sure we don't overflow

+  if (Instance->MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageVariableSize)) {

+    return EFI_INVALID_PARAMETER;

+  }

+

+  if (Instance->MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageVariableSize) -

+    PcdGet32 (PcdFlashNvStorageFtwWorkingSize)) {

+    return EFI_INVALID_PARAMETER;

+  }

+

+  // Patch PCDs with the the correct values
I think it s
'the the' -> the

+  PatchPcdSet64 (PcdFlashNvStorageVariableBase64, Instance->MemBaseAddress);

+  PatchPcdSet64 (

+    PcdFlashNvStorageFtwWorkingBase64,

+    Instance->MemBaseAddress + PcdGet32 (PcdFlashNvStorageVariableSize)

+    );

+  PatchPcdSet64 (

+    PcdFlashNvStorageFtwSpareBase64,

+    Instance->MemBaseAddress +

+    PcdGet32 (PcdFlashNvStorageVariableSize) +

+    PcdGet32 (PcdFlashNvStorageFtwWorkingSize)

+    );

+

+  DEBUG ((DEBUG_INFO, "%a: Fixup PcdFlashNvStorageVariableBase64: 0x%lx\n",

+    __FUNCTION__, PcdGet64 (PcdFlashNvStorageVariableBase64)));

+  DEBUG ((DEBUG_INFO, "%a: Fixup PcdFlashNvStorageFtwWorkingBase64: 0x%lx\n",

+    __FUNCTION__, PcdGet64 (PcdFlashNvStorageFtwWorkingBase64)));

+  DEBUG ((DEBUG_INFO, "%a: Fixup PcdFlashNvStorageFtwSpareBase64: 0x%lx\n",

+    __FUNCTION__, PcdGet64 (PcdFlashNvStorageFtwSpareBase64)));

+

+  return Status;

+}

diff --git a/Drivers/OpTeeRpmb/FixupPcd.inf b/Drivers/OpTeeRpmb/FixupPcd.inf
new file mode 100644
index 000000000000..5146257993ef
--- /dev/null
+++ b/Drivers/OpTeeRpmb/FixupPcd.inf
@@ -0,0 +1,43 @@
+## @file

+#  Instance of Base Memory Library without assembly.

+#

+#  Copyright (c) 2020, Linaro Ltd. All rights reserved.<BR>

+#

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

+#

+#

+##

+

+[Defines]

+  INF_VERSION                    = 0x0001001A

+  BASE_NAME                      = FixupPcd

+  FILE_GUID                      = a827c337-a9c6-301b-aeb7-acbc95d8da22

+  MODULE_TYPE                    = BASE

+  VERSION_STRING                 = 0.1

+  LIBRARY_CLASS                  = RpmbPcdFixup|MM_STANDALONE

+  CONSTRUCTOR                    = FixPcdMemory

+

+[Sources]

+  FixupPcd.c

+  OpTeeRpmbFvb.h

+

+[Packages]

+  MdeModulePkg/MdeModulePkg.dec

+  MdePkg/MdePkg.dec

+

+[LibraryClasses]

+  BaseLib

+  DebugLib

+  MmServicesTableLib

+  PcdLib

+

+[Pcd]

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize

+

+[Protocols]

+  gEfiSmmFirmwareVolumeBlockProtocolGuid          ## CONSUMES

diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFv.inf b/Drivers/OpTeeRpmb/OpTeeRpmbFv.inf
new file mode 100644
index 000000000000..c3580859ffde
--- /dev/null
+++ b/Drivers/OpTeeRpmb/OpTeeRpmbFv.inf
@@ -0,0 +1,58 @@
+## @file

+#

+#  Component description file for OpTeeRpmbFv module

+#

+#  Copyright (c) 2020, Linaro Ltd. All rights reserved.<BR>

+#

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

+#

+##

+

+[Defines]

+  INF_VERSION                    = 0x0001001A

+  BASE_NAME                      = OpTeeRpmbFv

+  FILE_GUID                      = 4803FC20-E583-3BCD-8C60-141E85C9A2CF

+  MODULE_TYPE                    = MM_STANDALONE

+  VERSION_STRING                 = 0.1

+  PI_SPECIFICATION_VERSION       = 0x00010032

+  ENTRY_POINT                    = OpTeeRpmbFvbInit

+

+[Sources]

+  OpTeeRpmbFvb.c

+  OpTeeRpmbFvb.h

+

+[Packages]

+  ArmPkg/ArmPkg.dec

+  ArmPlatformPkg/ArmPlatformPkg.dec

+  MdeModulePkg/MdeModulePkg.dec

+  MdePkg/MdePkg.dec

+  StandaloneMmPkg/StandaloneMmPkg.dec

+

+[LibraryClasses]

+  ArmSvcLib

+  BaseLib

+  BaseMemoryLib

+  DebugLib

+  MemoryAllocationLib

+  MmServicesTableLib

+  PcdLib

+  StandaloneMmDriverEntryPoint

+

+[Guids]

+  gEfiAuthenticatedVariableGuid

+  gEfiSystemNvDataFvGuid

+  gEfiVariableGuid

+

+[Pcd]

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize

+

+[Protocols]

+  gEfiSmmFirmwareVolumeBlockProtocolGuid          ## PRODUCES

+

+[Depex]

+  TRUE

diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFvb.c b/Drivers/OpTeeRpmb/OpTeeRpmbFvb.c
new file mode 100644
index 000000000000..950082cf6df4
--- /dev/null
+++ b/Drivers/OpTeeRpmb/OpTeeRpmbFvb.c
@@ -0,0 +1,920 @@
+/** @file

+

+  FV block I/O protocol driver for RPMB eMMC accessed via OP-TEE

+

+  Copyright (c) 2020, Linaro Ltd. All rights reserved.<BR>

+

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

+

+**/

+#include <Library/ArmSvcLib.h>

+#include <Library/BaseLib.h>

+#include <Library/BaseMemoryLib.h>

+#include <Library/DebugLib.h>

+#include <Library/MemoryAllocationLib.h>

+#include <Library/MmServicesTableLib.h>

+#include <Library/PcdLib.h>

+

+#include <IndustryStandard/ArmFfaSvc.h>

+#include <IndustryStandard/ArmMmSvc.h>

+#include <Protocol/FirmwareVolumeBlock.h>

+#include <Protocol/SmmFirmwareVolumeBlock.h>

+#include <Guid/VariableFormat.h>

+

+#include "OpTeeRpmbFvb.h"

+

+// These are what OP-TEE expects in ./core/arch/arm/kernel/stmm_sp.c

+// Since the FFA autodiscovery mechanism is not yet implemented we are

+// hardcoding the ID values for the two operations OP-TEE currently supports

+//

+// mMemMgrId is used to set the page permissions after relocating the executable

+// mStorageId is used to access the RPMB partition via OP-TEE

+// In both cases the return value is located in x3. Once the autodiscovery mechanism

+// is in place, we'll have to account for an error value in x2 as well, handling

+// the autodiscovery failed scenario
+STATIC CONST UINT16 mMemMgrId = 3U;

+STATIC CONST UINT16 mStorageId = 4U;

+

+STATIC MEM_INSTANCE mInstance;

+

+/**

+  Sends an SVC call to OP-TEE for reading/writing an RPMB partition

+

+  @param SvcAct     SVC ID for read/write

+  @param Addr       Base address of the buffer. When reading contents will be

+                    copied to that buffer after reading them from the device.

+                    When writing, the buffer holds the contents we want to

+                    write cwtoin the device

+  @param NumBytes   Number of bytes to read/write

+  @param Offset     Offset into the RPMB file

+

+  @retval           EFI_SUCCESS read/write ok

+

+  @retval           EFI_UNSUPPORTED SVC to op-tee not supported

+

+  @retval           EFI_INVALID_PARAMETER SVC to op-tee had an invalid param

+

+  @retval           EFI_ACCESS_DENIED SVC to op-tee was denied

+

+  @retval           EFI_OUT_OF_RESOURCES op-tee out of memory

+**/

+STATIC

+EFI_STATUS

+ReadWriteRpmb (

+  UINTN  SvcAct,

+  UINTN  Addr,

+  UINTN  NumBytes,

+  UINTN  Offset

+  )
I think the parameters should have IN/OUT indications, and the function header aswell (cf https://edk2-docs.gitbook.io/edk-ii-c-coding-standards-specification/6_documenting_software/62_comments#6-2-1-only-use-c-style-comments-on-the-same-line-as-pre-processor-directives-and-in-doxygen-style-file-and-function-header-comment-blocks).
There are other functions with missing IN/OUT parameters.


+{

+  ARM_SVC_ARGS  SvcArgs;

+  EFI_STATUS    Status;

+

+  ZeroMem (&SvcArgs, sizeof (SvcArgs));

+

+  SvcArgs.Arg0 = ARM_SVC_ID_FFA_MSG_SEND_DIRECT_REQ_AARCH64;

+  SvcArgs.Arg1 = mStorageId;

+  SvcArgs.Arg2 = 0;

+  SvcArgs.Arg3 = SvcAct;

+  SvcArgs.Arg4 = Addr;

+  SvcArgs.Arg5 = NumBytes;

+  SvcArgs.Arg6 = Offset;

+

+  ArmCallSvc (&SvcArgs);

+  if (SvcArgs.Arg3) {

+    DEBUG ((DEBUG_ERROR, "%a: Svc Call 0x%08x Addr: 0x%08x len: 0x%x Offset: 0x%x failed with 0x%x\n",

+      __func__, SvcAct, Addr, NumBytes, Offset, SvcArgs.Arg3));

+  }

+

+  switch (SvcArgs.Arg3) {

+  case ARM_SVC_SPM_RET_SUCCESS:

+    Status = EFI_SUCCESS;

+    break;

+

+  case ARM_SVC_SPM_RET_NOT_SUPPORTED:

+    Status = EFI_UNSUPPORTED;

+    break;

+

+  case ARM_SVC_SPM_RET_INVALID_PARAMS:

+    Status = EFI_INVALID_PARAMETER;

+    break;

+

+  case ARM_SVC_SPM_RET_DENIED:

+    Status = EFI_ACCESS_DENIED;

+    break;

+

+  case ARM_SVC_SPM_RET_NO_MEMORY:

+    Status = EFI_OUT_OF_RESOURCES;

+    break;

+

+  default:

+    Status = EFI_ACCESS_DENIED;

+  }

+

+  return Status;

+}

+

+/**

+  The GetAttributes() function retrieves the attributes and

+  current settings of the block.

+

+  @param This       Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instance.

+

+  @param Attributes Pointer to EFI_FVB_ATTRIBUTES_2 in which the

+                    attributes and current settings are

+                    returned. Type EFI_FVB_ATTRIBUTES_2 is defined

+                    in EFI_FIRMWARE_VOLUME_HEADER.

+

+  @retval EFI_SUCCESS The firmware volume attributes were

+                      returned.

+

+**/

+STATIC

+EFI_STATUS

+OpTeeRpmbFvbGetAttributes (

+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+  OUT       EFI_FVB_ATTRIBUTES_2 *Attributes

+  )

+{

+  *Attributes = EFI_FVB2_READ_ENABLED_CAP   | // Reads may be enabled

+                EFI_FVB2_READ_STATUS        | // Reads are currently enabled

+                EFI_FVB2_WRITE_STATUS       | // Writes are currently enabled

+                EFI_FVB2_WRITE_ENABLED_CAP  | // Writes may be enabled

+                EFI_FVB2_STICKY_WRITE       | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY

+                EFI_FVB2_MEMORY_MAPPED      | // It is memory mapped

+                EFI_FVB2_ERASE_POLARITY;      // After erasure all bits take this value (i.e. '1')

+

+  return EFI_SUCCESS;

+}

+

+/**

+  The SetAttributes() function sets configurable firmware volume

+  attributes and returns the new settings of the firmware volume.

+

+  @param This         Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instance.

+

+  @param Attributes   On input, Attributes is a pointer to

+                      EFI_FVB_ATTRIBUTES_2 that contains the

+                      desired firmware volume settings. On

+                      successful return, it contains the new

+                      settings of the firmware volume. Type

+                      EFI_FVB_ATTRIBUTES_2 is defined in

+                      EFI_FIRMWARE_VOLUME_HEADER.

+

+  @retval EFI_UNSUPPORTED Set attributes not supported

+

+**/

+STATIC

+EFI_STATUS

+OpTeeRpmbFvbSetAttributes (

+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+  IN OUT    EFI_FVB_ATTRIBUTES_2 *Attributes
Parameters should be aligned. (I think this is valid at other places, like for OpTeeRpmbFvbGetPhysicalAddress())

+  )

+{

+  DEBUG ((DEBUG_ERROR, "FvbSetAttributes(0x%X) is not supported\n", *Attributes));

+  return EFI_UNSUPPORTED;

+}

+

+/**

+  The GetPhysicalAddress() function retrieves the base address of

+  a memory-mapped firmware volume. This function should be called

+  only for memory-mapped firmware volumes.

+

+  @param This     Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instance.

+

+  @param Address  Pointer to a caller-allocated

+                  EFI_PHYSICAL_ADDRESS that, on successful

+                  return from GetPhysicalAddress(), contains the

+                  base address of the firmware volume.

+

+  @retval EFI_SUCCESS       The firmware volume base address was returned.

+

+  @retval EFI_UNSUPPORTED   The firmware volume is not memory mapped.

+

+**/

+STATIC

+EFI_STATUS

+OpTeeRpmbFvbGetPhysicalAddress (

+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+  OUT       EFI_PHYSICAL_ADDRESS                *Address

+  )

+{

+  MEM_INSTANCE *Instance;

+

+  Instance = INSTANCE_FROM_FVB_THIS (This);

+  *Address = Instance->MemBaseAddress;

+

+  return EFI_SUCCESS;

+}

+

+/**

+  The GetBlockSize() function retrieves the size of the requested

+  block. It also returns the number of additional blocks with

+  the identical size. The GetBlockSize() function is used to

+  retrieve the block map (see EFI_FIRMWARE_VOLUME_HEADER).

+

+

+  @param This           Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instance.

+

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

+

+  @param BlockSize      Pointer to a caller-allocated UINTN in which

+                        the size of the block is returned.

+

+  @param NumberOfBlocks 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 firmware volume base address was returned.

+

+  @retval EFI_INVALID_PARAMETER   The requested LBA is out of range.

+

+**/

+STATIC

+EFI_STATUS

+OpTeeRpmbFvbGetBlockSize (

+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+  IN        EFI_LBA                            Lba,

+  OUT       UINTN *BlockSize,

+  OUT       UINTN *NumberOfBlocks

+  )

+{

+  MEM_INSTANCE *Instance;

+

+  Instance = INSTANCE_FROM_FVB_THIS (This);

+  if (Lba > Instance->NBlocks) {

+    return EFI_INVALID_PARAMETER;

+  }

+

+  *NumberOfBlocks = Instance->NBlocks - (UINTN)Lba;

+  *BlockSize = Instance->BlockSize;

+

+  return EFI_SUCCESS;

+}

+

+/**

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

+

+  The Read() function reads the requested number of bytes from the

+  requested block and stores them in the provided buffer.

+  Implementations should be mindful that the firmware volume

+  might be in the ReadDisabled state. If it is in this state,

+  the Read() function must return the status code

+  EFI_ACCESS_DENIED without modifying the contents of the

+  buffer. The Read() function must also prevent spanning block

+  boundaries. If a read is requested that would span a block

+  boundary, the read must read up to the boundary but not

+  beyond. The output parameter NumBytes must be set to correctly

+  indicate the number of bytes actually read. The caller must be

+  aware that a read may be partially completed.

+

+  @param This     Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instance.

+

+  @param Lba      The starting logical block index

+                  from which to read.

+

+  @param Offset   Offset into the block at which to begin reading.

+

+  @param NumBytes Pointer to a UINTN. At entry, *NumBytes

+                  contains the total size of the buffer. At

+                  exit, *NumBytes contains the total number of

+                  bytes read.

+

+  @param Buffer   Pointer to a caller-allocated buffer that will

+                  be used to hold the data that is read.

+

+  @retval EFI_SUCCESS         The firmware volume was read successfully,

+                              and contents are in Buffer.

+

+  @retval EFI_BAD_BUFFER_SIZE Read attempted across an 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.
I think one new line should be enough. And would it be possible to align the return codes comments ?
+

+**/

+STATIC

+EFI_STATUS

+OpTeeRpmbFvbRead (

+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+  IN        EFI_LBA                             Lba,

+  IN        UINTN                               Offset,

+  IN OUT    UINTN *NumBytes,

+  IN OUT    UINT8                               *Buffer

+  )

+{

+  EFI_STATUS   Status;

+  MEM_INSTANCE *Instance;

+  VOID         *Base;

+

+  Status = EFI_SUCCESS;

+  Instance = INSTANCE_FROM_FVB_THIS (This);

+  if (!Instance->Initialized) {

+    Status = Instance->Initialize (Instance);

+    if (EFI_ERROR (Status)) {

+      return Status;

+    }

+  }

+

+  Base = (VOID *)Instance->MemBaseAddress + (Lba * Instance->BlockSize) + Offset;

+  // We could read the data from the RPMB instead of memory

+  // The 2 copies should already be identical

+  // Copy from memory image

+  CopyMem (Buffer, Base, *NumBytes);

+

+  return Status;

+}

+

+/**

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

+

+  The Write() function writes the specified number of bytes from

+  the provided buffer to the specified block and offset. If the

+  firmware volume is sticky write, the caller must ensure that

+  all the bits of the specified range to write are in the

+  EFI_FVB_ERASE_POLARITY state before calling the Write()

+  function, or else the result will be unpredictable. This

+  unpredictability arises because, for a sticky-write firmware

+  volume, a write may negate a bit in the EFI_FVB_ERASE_POLARITY

+  state but cannot flip it back again.  Before calling the

+  Write() function,  it is recommended for the caller to first call

+  the EraseBlocks() function to erase the specified block to

+  write. A block erase cycle will transition bits from the

+  (NOT)EFI_FVB_ERASE_POLARITY state back to the

+  EFI_FVB_ERASE_POLARITY state. Implementations should be

+  mindful that the firmware volume might be in the WriteDisabled

+  state. If it is in this state, the Write() function must

+  return the status code EFI_ACCESS_DENIED without modifying the

+  contents of the firmware volume. The Write() function must

+  also prevent spanning block boundaries. If a write is

+  requested that spans a block boundary, the write must store up

+  to the boundary but not beyond. The output parameter NumBytes

+  must be set to correctly indicate the number of bytes actually

+  written. The caller must be aware that a write may be

+  partially completed. All writes, partial or otherwise, must be

+  fully flushed to the hardware before the Write() service

+  returns.

+

+  @param This     Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instance.

+

+  @param Lba      The starting logical block index to write to.

+

+  @param Offset   Offset into the block at which to begin writing.

+

+  @param NumBytes The pointer to a UINTN. At entry, *NumBytes

+                  contains the total size of the buffer. At

+                  exit, *NumBytes contains the total number of

+                  bytes actually written.

+

+  @param Buffer   The 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 The write was attempted across an

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

+                              and could not be written.

+

+

+**/

+STATIC

+EFI_STATUS

+OpTeeRpmbFvbWrite (

+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+  IN        EFI_LBA                             Lba,

+  IN        UINTN                               Offset,

+  IN OUT    UINTN *NumBytes,

+  IN        UINT8                               *Buffer

+  )

+{

+  MEM_INSTANCE *Instance;

+  EFI_STATUS   Status;

+  VOID         *Base;

+

+  Instance = INSTANCE_FROM_FVB_THIS (This);

+  if (!Instance->Initialized) {

+    Status = Instance->Initialize (Instance);

+    if (EFI_ERROR (Status)) {

+      return Status;

+    }

+  }

+  Base = (VOID *)Instance->MemBaseAddress + Lba * Instance->BlockSize + Offset;

+  Status = ReadWriteRpmb (

+             SP_SVC_RPMB_WRITE,

+             (UINTN)Buffer,

+             *NumBytes,

+             (Lba * Instance->BlockSize) + Offset

+             );

+  if (EFI_ERROR (Status)) {

+    return Status;

+  }

+

+  // Update the memory copy

+  CopyMem (Base, Buffer, *NumBytes);

+

+  return Status;

+}

+

+/**

+  Erases and initializes a firmware volume block.

+

+  The EraseBlocks() function erases one or more blocks as denoted

+  by the variable argument list. The entire parameter list of

+  blocks must be verified before 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 EraseBlocks() function must return the

+  status code EFI_INVALID_PARAMETER without modifying the contents

+  of the firmware volume. Implementations should be mindful that

+  the firmware volume might be in the WriteDisabled state. If it

+  is in this state, the EraseBlocks() function must return the

+  status code EFI_ACCESS_DENIED without modifying the contents of

+  the firmware volume. All calls to EraseBlocks() must be fully

+  flushed to the hardware before the EraseBlocks() service

+  returns.

+

+  @param This   Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL

+                instance.

+

+  @param ...    The variable argument list is a list of tuples.

+                Each tuple describes a range of LBAs to erase

+                and consists of the following:

+                - An EFI_LBA that indicates the starting LBA

+                - A UINTN that indicates the number of blocks to

+                  erase.

+

+                The list is terminated with an

+                EFI_LBA_LIST_TERMINATOR. For example, the

+                following indicates that two ranges of blocks

+                (5-7 and 10-11) are to be erased: EraseBlocks

+                (This, 5, 3, 10, 2, EFI_LBA_LIST_TERMINATOR);

+

+  @retval EFI_SUCCESS The erase request 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.

+                            The firmware device may have been

+                            partially erased.

+  @retval EFI_INVALID_PARAMETER One or more of the LBAs listed

+                                in the variable argument list do

+                                not exist in the firmware volume.

+

+**/

+STATIC

+EFI_STATUS

+OpTeeRpmbFvbErase (

+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+  ...

+  )

+{

+  MEM_INSTANCE *Instance;

+  UINTN   NumBytes;

+  UINTN   NumLba;

+  EFI_LBA Start;

+  VOID    *Base;

+  VOID    *Buf;

+  VA_LIST Args;

+  EFI_STATUS Status;

+

+  Instance = INSTANCE_FROM_FVB_THIS (This);

+

+  VA_START (Args, This);

+  for (Start = VA_ARG (Args, EFI_LBA);

+       Start != EFI_LBA_LIST_TERMINATOR;

+       Start = VA_ARG (Args, EFI_LBA)) {

+    NumLba = VA_ARG (Args, UINTN);

+    if (NumLba == 0 || Start + NumLba > Instance->NBlocks) {

+      return EFI_INVALID_PARAMETER;

+    }

+    NumBytes = NumLba * Instance->BlockSize;

+    Base = (VOID *)Instance->MemBaseAddress + Start * Instance->BlockSize;

+    Buf = AllocatePool (NumLba * Instance->BlockSize);

+    if (Buf == NULL) {

+      return EFI_DEVICE_ERROR;

+    }

+    SetMem64 (Buf, NumLba * Instance->BlockSize, ~0UL);

+    // Write the device

+    Status = ReadWriteRpmb (

+               SP_SVC_RPMB_WRITE,

+               (UINTN)Buf,

+               NumBytes,

+               Start * Instance->BlockSize

+               );

+    if (EFI_ERROR (Status)) {

+      return Status;

+    }

+    // Update the in memory copy

+    SetMem64 (Base, NumLba * Instance->BlockSize, ~0UL);

+    FreePool (Buf);

+  }

+

+  VA_END (Args);

+

+  return EFI_SUCCESS;

+}

+

+/**

+  Since we use a memory backed storage we need to restore the RPMB contents

+  into memory before we register the Fvb protocol.

+

+  @param Instance Address to copy flash contents to

+**/

+STATIC

+VOID

+ReadEntireFlash (

+  MEM_INSTANCE *Instance

+ )

+{

+  UINTN ReadAddr;

+  UINTN StorageFtwWorkingSize;

+  UINTN StorageVariableSize;

+  UINTN StorageFtwSpareSize;

+

+  StorageFtwWorkingSize = PcdGet32(PcdFlashNvStorageFtwWorkingSize);

+  StorageVariableSize   = PcdGet32(PcdFlashNvStorageVariableSize);

+  StorageFtwSpareSize   = PcdGet32(PcdFlashNvStorageFtwSpareSize);

+

+  ReadAddr = Instance->MemBaseAddress;

+  // There's no need to check if the read failed here. The upper EDK2 layers

+  // will initialize the flash correctly if the in-memory copy is wrong

+  ReadWriteRpmb (
ReadWriteRpmb() returns an error code, I think we should return it aswell.

+    SP_SVC_RPMB_READ,

+    ReadAddr,

+    StorageVariableSize + StorageFtwWorkingSize + StorageFtwSpareSize,

+    0

+    );

+}

+

+/**

+  Validate the firmware volume header.

+

+  @param FwVolHeader Pointer to the firmware volume header for the RPMB

+

+  @retval EFI_SUCCESS           The firmware volume header is correct

+  @retval EFI_NOT_FOUND         No header present

+  @retval EFI_VOLUME_CORRUPTED  The firmware volume header CRC was invalid

+                                or either one of GUID's, Signature and header

+                                length was invalid

+**/

+STATIC

+EFI_STATUS

+EFIAPI

+ValidateFvHeader (

+  IN EFI_FIRMWARE_VOLUME_HEADER            *FwVolHeader

+  )

+{

+  UINT16                      Checksum;

+  VARIABLE_STORE_HEADER       *VariableStoreHeader;

+  UINTN                       VariableStoreLength;

+  UINTN                       FvLength;

+

+  FvLength = PcdGet32(PcdFlashNvStorageVariableSize) +

+             PcdGet32(PcdFlashNvStorageFtwWorkingSize) +

+             PcdGet32(PcdFlashNvStorageFtwSpareSize);

+

+  // Verify the header revision, header signature, length

+  // Length of FvBlock cannot be 2**64-1

+  // HeaderLength cannot be an odd number

+  //

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

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

+      || (FwVolHeader->FvLength  != FvLength)

+      )

+  {

+    DEBUG ((DEBUG_INFO, "%a: No Firmware Volume header present\n",

+      __FUNCTION__));

+    return EFI_NOT_FOUND;

+  }

+

+  // Check the Firmware Volume Guid

+  if (!CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid)) {

+    DEBUG ((DEBUG_INFO, "%a: Firmware Volume Guid non-compatible\n",

+      __FUNCTION__));

+    return EFI_VOLUME_CORRUPTED;

+  }

+

+  // Verify the header checksum

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

+  if (Checksum != 0) {

+    DEBUG ((DEBUG_INFO, "%a: FV checksum is invalid (Checksum:0x%X)\n",

+      __FUNCTION__, Checksum));

+    return EFI_VOLUME_CORRUPTED;

+  }

+

+  VariableStoreHeader = (VARIABLE_STORE_HEADER*)((UINTN)FwVolHeader +

+                         FwVolHeader->HeaderLength);

+

+  // Check the Variable Store Guid

+  if (!CompareGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid) &&

+      !CompareGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGuid)) {

+    DEBUG ((DEBUG_INFO, "%a: Variable Store Guid non-compatible\n", __FUNCTION__));

+    return EFI_VOLUME_CORRUPTED;

+  }

+

+  VariableStoreLength = PcdGet32 (PcdFlashNvStorageVariableSize) -

+                        FwVolHeader->HeaderLength;

+  if (VariableStoreHeader->Size != VariableStoreLength) {

+    DEBUG ((DEBUG_INFO, "%a: Variable Store Length does not match\n",

+      __FUNCTION__));

+    return EFI_VOLUME_CORRUPTED;

+  }

+

+  return EFI_SUCCESS;

+

+}

+

+/**

+  Initialize Fvb and variable storage headers for the RPMB storage.

+

+  @param Instance   MEM_INSTANCE pointer describing the device and the

+                    Firmware Block Protocol

+

+  @retval           EFI_SUCCESS read/write ok

+

+  @retval           EFI_UNSUPPORTED SVC to op-tee not supported

+

+  @retval           EFI_INVALID_PARAMETER SVC to op-tee had an invalid param

+

+  @retval           EFI_ACCESS_DENIED SVC to op-tee was denied

+

+  @retval           EFI_OUT_OF_RESOURCES op-tee out of memory

+**/

+STATIC

+EFI_STATUS

+InitializeFvAndVariableStoreHeaders (

+  MEM_INSTANCE *Instance

+  )

+{

+  EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader;

+  VARIABLE_STORE_HEADER      *VariableStoreHeader;

+  EFI_STATUS                 Status;

+  UINTN                      HeadersLength;

+  VOID*                      Headers;

+

+  HeadersLength = sizeof (EFI_FIRMWARE_VOLUME_HEADER) +

+                  sizeof (EFI_FV_BLOCK_MAP_ENTRY) +

+                  sizeof (VARIABLE_STORE_HEADER);

+  Headers = AllocateZeroPool (HeadersLength);

+  if (Headers == NULL) {

+    return EFI_OUT_OF_RESOURCES;

+  }

+

+  //

+  // EFI_FIRMWARE_VOLUME_HEADER

+  //

+  FirmwareVolumeHeader = (EFI_FIRMWARE_VOLUME_HEADER*)Headers;

+  CopyGuid (&FirmwareVolumeHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid);

+  FirmwareVolumeHeader->FvLength = PcdGet32(PcdFlashNvStorageVariableSize) +

+ PcdGet32(PcdFlashNvStorageFtwWorkingSize) +

+ PcdGet32(PcdFlashNvStorageFtwSpareSize);

+  FirmwareVolumeHeader->Signature = EFI_FVH_SIGNATURE;

+  FirmwareVolumeHeader->Attributes = EFI_FVB2_READ_ENABLED_CAP |

+                                     EFI_FVB2_READ_STATUS |

+ EFI_FVB2_STICKY_WRITE |

+ EFI_FVB2_MEMORY_MAPPED |

+ EFI_FVB2_ERASE_POLARITY |

+ EFI_FVB2_WRITE_STATUS |

+ EFI_FVB2_WRITE_ENABLED_CAP;

+

+  FirmwareVolumeHeader->HeaderLength = sizeof (EFI_FIRMWARE_VOLUME_HEADER) +

+                                       sizeof (EFI_FV_BLOCK_MAP_ENTRY);

+  FirmwareVolumeHeader->Revision = EFI_FVH_REVISION;

+  FirmwareVolumeHeader->BlockMap[0].NumBlocks = Instance->NBlocks;

+  FirmwareVolumeHeader->BlockMap[0].Length    = Instance->BlockSize;

+  FirmwareVolumeHeader->BlockMap[1].NumBlocks = 0;

+  FirmwareVolumeHeader->BlockMap[1].Length    = 0;

+  FirmwareVolumeHeader->Checksum = CalculateCheckSum16 (

+ (UINT16*)FirmwareVolumeHeader,

+ FirmwareVolumeHeader->HeaderLength

+                                     );

+

+  //

+  // VARIABLE_STORE_HEADER

+  //

+  VariableStoreHeader = (VARIABLE_STORE_HEADER*)((UINTN)Headers +

+ FirmwareVolumeHeader->HeaderLength);

+  CopyGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGuid);

+  VariableStoreHeader->Size = PcdGet32(PcdFlashNvStorageVariableSize) -

+ FirmwareVolumeHeader->HeaderLength;

+  VariableStoreHeader->Format = VARIABLE_STORE_FORMATTED;

+  VariableStoreHeader->State = VARIABLE_STORE_HEALTHY;

+

+  Status = ReadWriteRpmb (SP_SVC_RPMB_WRITE, (UINTN)Headers, HeadersLength, 0);

+  if (EFI_ERROR (Status)) {

+    goto Exit;

+  }

+  // Install the combined header in memory

+  CopyMem ((VOID*)Instance->MemBaseAddress, Headers, HeadersLength);

+

+Exit:

+  FreePool (Headers);

+  return Status;

+}

+

+/**

+  Initialize the firmware block protocol for the specified memory.

+

+  @param Instance   MEM_INSTANCE pointer describing the device and the

+                    Firmware Block Protocol

+

+  @retval EFI_SUCCESS               Initialized successfully or already initialized

+  @retval EFI_UNSUPPORTED           SVC to op-tee not supported

+  @retval EFI_INVALID_PARAMETER     SVC to op-tee had an invalid param

+  @retval EFI_ACCESS_DENIED         SVC to op-tee was denied

+  @retval EFI_OUT_OF_RESOURCES      op-tee out of memory

+

+

+
I think one new line should be enough.

+**/

+STATIC

+EFI_STATUS

+EFIAPI

+FvbInitialize (

+  MEM_INSTANCE *Instance

+  )

+{

+  EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;

+  EFI_STATUS                  Status;

+

+  if (Instance->Initialized) {

+    return EFI_SUCCESS;

+  }

+

+  // FirmwareVolumeHeader->FvLength is declared to have the Variable area

+  // AND the FTW working area AND the FTW Spare contiguous.

+  ASSERT (

+    (PcdGet64 (PcdFlashNvStorageVariableBase64) +

+    PcdGet32 (PcdFlashNvStorageVariableSize)) ==

+    PcdGet64 (PcdFlashNvStorageFtwWorkingBase64)

+    );

+  ASSERT (

+    (PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) +

+    PcdGet32 (PcdFlashNvStorageFtwWorkingSize)) ==

+    PcdGet64 (PcdFlashNvStorageFtwSpareBase64));

+

+  // Check if the size of the area is at least one block size

+  ASSERT (

+    (PcdGet32 (PcdFlashNvStorageVariableSize) > 0) &&

+    (PcdGet32 (PcdFlashNvStorageVariableSize) / Instance->BlockSize > 0)

+    );

+  ASSERT (

+    (PcdGet32 (PcdFlashNvStorageFtwWorkingSize) > 0) &&

+    (PcdGet32 (PcdFlashNvStorageFtwWorkingSize) / Instance->BlockSize
0)
+    );

+  ASSERT (

+    (PcdGet32 (PcdFlashNvStorageFtwSpareSize) > 0) &&

+    (PcdGet32 (PcdFlashNvStorageFtwSpareSize) / Instance->BlockSize > 0)

+    );

+

+  // Ensure the Variable areas are aligned on block size boundaries

+  ASSERT ((PcdGet64 (PcdFlashNvStorageVariableBase64) % Instance->BlockSize) == 0);

+  ASSERT ((PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) % Instance->BlockSize) == 0);

+  ASSERT ((PcdGet64 (PcdFlashNvStorageFtwSpareBase64) % Instance->BlockSize) == 0);

+

+  // Read the file from disk and copy it to memory

+  ReadEntireFlash (Instance);

+

+  FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)Instance->MemBaseAddress;

+  Status = ValidateFvHeader (FwVolHeader);

+  if (EFI_ERROR (Status)) {

+    // There is no valid header, so time to install one.

+    DEBUG ((DEBUG_INFO, "%a: The FVB Header is not valid.\n", __FUNCTION__));

+

+    // Reset memory

+    SetMem64 ((VOID *)Instance->MemBaseAddress, Instance->NBlocks * Instance->BlockSize, ~0UL);

+    DEBUG ((DEBUG_INFO, "%a: Erasing Flash.\n", __FUNCTION__));

+    Status = ReadWriteRpmb (

+               SP_SVC_RPMB_WRITE,

+               Instance->MemBaseAddress,

+               PcdGet32(PcdFlashNvStorageVariableSize) +

+               PcdGet32(PcdFlashNvStorageFtwWorkingSize) +

+               PcdGet32(PcdFlashNvStorageFtwSpareSize),

+               0

+               );

+    if (EFI_ERROR (Status)) {

+      return Status;

+    }

+    // Install all appropriate headers

+    DEBUG ((DEBUG_INFO, "%a: Installing a correct one for this volume.\n",

+      __FUNCTION__));

+    Status = InitializeFvAndVariableStoreHeaders (Instance);

+    if (EFI_ERROR (Status)) {

+      return Status;

+    }

+  } else {

+    DEBUG ((DEBUG_INFO, "%a: Found valid FVB Header.\n", __FUNCTION__));

+  }

+  Instance->Initialized = TRUE;

+

+  return Status;

+}

+

+/**

+  Since the RPMB is not byte addressable we need to allocate memory

+  and sync that on reads/writes. Initialize the memory and install the

+  Fvb protocol.

+

+  @param ImageHandle The EFI image handle

+  @param SystemTable MM system table

+

+  @retval EFI_SUCCESS Protocol installed

+

+  @retval EFI_INVALID_PARAMETER Invalid Pcd values specified

+

+  @retval EFI_OUT_OF_RESOURCES  Can't allocate necessary memory

+**/

+EFI_STATUS

+EFIAPI

+OpTeeRpmbFvbInit (

+  IN EFI_HANDLE           ImageHandle,

+  IN EFI_MM_SYSTEM_TABLE  *SystemTable

+  )

+{

+  EFI_STATUS   Status;

+  VOID         *Addr;

+  UINTN        FvLength;

+  UINTN        NBlocks;

+

+  FvLength = PcdGet32(PcdFlashNvStorageVariableSize) +

+             PcdGet32(PcdFlashNvStorageFtwWorkingSize) +

+             PcdGet32(PcdFlashNvStorageFtwSpareSize);

+

+  NBlocks = EFI_SIZE_TO_PAGES (ALIGN_VARIABLE (FvLength));

+  Addr = AllocatePages (NBlocks);

+  if (Addr == NULL) {

+    ASSERT (0);

+    return EFI_OUT_OF_RESOURCES;

+  }

+

+  SetMem (&mInstance, sizeof (mInstance), 0);

+

+  mInstance.FvbProtocol.GetPhysicalAddress = OpTeeRpmbFvbGetPhysicalAddress;

+  mInstance.FvbProtocol.GetAttributes      = OpTeeRpmbFvbGetAttributes;

+  mInstance.FvbProtocol.SetAttributes      = OpTeeRpmbFvbSetAttributes;

+  mInstance.FvbProtocol.GetBlockSize       = OpTeeRpmbFvbGetBlockSize;

+  mInstance.FvbProtocol.EraseBlocks        = OpTeeRpmbFvbErase;

+  mInstance.FvbProtocol.Write              = OpTeeRpmbFvbWrite;

+  mInstance.FvbProtocol.Read               = OpTeeRpmbFvbRead;

+

+  mInstance.MemBaseAddress = (EFI_PHYSICAL_ADDRESS)Addr;

+  mInstance.Signature      = FLASH_SIGNATURE;

+  mInstance.Initialize     = FvbInitialize;

+  mInstance.BlockSize      = EFI_PAGE_SIZE;

+  mInstance.NBlocks        = NBlocks;

+

+  // The Pcd is user defined, so make sure we don't overflow

+  if (mInstance.MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageVariableSize)) {

+    return EFI_INVALID_PARAMETER;

+  }

+

+  if (mInstance.MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageVariableSize) -

+    PcdGet32 (PcdFlashNvStorageFtwWorkingSize)) {

+    return EFI_INVALID_PARAMETER;

+  }

+

+  // Update the defined PCDs related to Variable Storage

+  PatchPcdSet64 (PcdFlashNvStorageVariableBase64, mInstance.MemBaseAddress);

+  PatchPcdSet64 (

+    PcdFlashNvStorageFtwWorkingBase64,

+    mInstance.MemBaseAddress + PcdGet32 (PcdFlashNvStorageVariableSize)

+    );

+  PatchPcdSet64 (

+    PcdFlashNvStorageFtwSpareBase64,

+    mInstance.MemBaseAddress +

+    PcdGet32 (PcdFlashNvStorageVariableSize) +

+    PcdGet32 (PcdFlashNvStorageFtwWorkingSize)

+    );
It seems this part is really similar to what is FixupPcd.c:FixPcdMemory(), maybe this would be worth re-using it.

+

+  Status = gMmst->MmInstallProtocolInterface (

+                    &mInstance.Handle,

+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,

+                    EFI_NATIVE_INTERFACE,

+                    &mInstance.FvbProtocol

+                    );

+  ASSERT_EFI_ERROR (Status);

+

+  DEBUG ((DEBUG_INFO, "%a: Register OP-TEE RPMB Fvb\n", __FUNCTION__));

+  DEBUG ((DEBUG_INFO, "%a: Using NV store FV in-memory copy at 0x%lx\n",

+    __FUNCTION__, PatchPcdGet64 (PcdFlashNvStorageVariableBase64)));

+

+  return Status;

+}

diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFvb.h b/Drivers/OpTeeRpmb/OpTeeRpmbFvb.h
new file mode 100644
index 000000000000..8305e776dbb6
--- /dev/null
+++ b/Drivers/OpTeeRpmb/OpTeeRpmbFvb.h
@@ -0,0 +1,52 @@
+/** @file

+

+  Copyright (c) 2020, Linaro Ltd. All rights reserved.<BR>

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

+

+**/

+

+#ifndef OPTEE_RPMB_FVB_H_

+#define OPTEE_RPMB_FVB_H_

+

+/**

+ Those are not currently defined in any spec, it's an internal

+ contract between OP-TEE and EDK2.

+ For more details check core/arch/arm/include/kernel/stmm_sp.h in OP-TEE

+**/

+#define SP_SVC_RPMB_READ                0xC4000066

+#define SP_SVC_RPMB_WRITE               0xC4000067

+

+#define FLASH_SIGNATURE            SIGNATURE_32('r', 'p', 'm', 'b')

+#define INSTANCE_FROM_FVB_THIS(a)  CR(a, MEM_INSTANCE, FvbProtocol, \

+                                      FLASH_SIGNATURE)

+

+typedef struct _MEM_INSTANCE         MEM_INSTANCE;

+typedef EFI_STATUS (*MEM_INITIALIZE) (MEM_INSTANCE* Instance);

+

+/**

+  This struct is used by the RPMB driver. Since the upper EDK2 layers

+  expect byte addressable memory, we allocate a memory area of certain

+  size and sync it to the hardware on reads/writes.

+

+  @param[in] Signature        Internal signature used to discover the instance

+  @param[in] Initialize       Function used to initialize the instance

+  @param[in] Initialized      Set to true if initialized

+  @param[in] FvbProtocol      FVB protocol of the instance

+  @param[in] Handle           Handle to install

+  @param[in] MemBaseAddress   Physical address of the beggining of the allocated memory

+  @param[in] BlockSize        Blocksize

+  @param[in] NBlocks          Number of allocated blocks
I think that for doxygen, '@param[in]' is more for functions declarations. For structures, it should be as:

/**
  * This struct is used by the RPMB driver. Since the upper EDK2 layers
  * expect byte addressable memory, we allocate a memory area of certain
  * size and sync it to the hardware on reads/writes.
**/
struct _MEM_INSTANCE {
    ///  Signature        Internal signature used to discover the instance
    UINT32                              Signature;

/// Initialize       Function used to initialize the instance
    MEM_INITIALIZE                      Initialize;

[...]
};

Cf: https://edk2-docs.gitbook.io/edk-ii-c-coding-standards-specification/5_source_files/56_declarations_and_types#5-6-3-2-structure-declaration-with-forward-reference-or-self-reference


+**/

+struct _MEM_INSTANCE

+{

+    UINT32                              Signature;

+    MEM_INITIALIZE                      Initialize;

+    BOOLEAN                             Initialized;

+    EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  FvbProtocol;

+    EFI_HANDLE                          Handle;

+    EFI_PHYSICAL_ADDRESS                MemBaseAddress;

+    UINT16                              BlockSize;

+    UINT16                              NBlocks;

+};

+

+#endif

--
2.30.0



-=-=-=-=-=-=
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#71651): https://edk2.groups.io/g/devel/message/71651 <https://edk2.groups.io/g/devel/message/71651>
Mute This Topic: https://groups.io/mt/80588994/1821310 <https://groups.io/mt/80588994/1821310>
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub <https://edk2.groups.io/g/devel/unsub> [pierre.gondois@arm.com]
-=-=-=-=-=-=


Ilias Apalodimas
 

Hi Pierre,

On Wed, Mar 03, 2021 at 10:20:17AM +0000, Pierre wrote:
Hello Ilias,

My review is mostly about coding style, but I would have some (inlined)
remarks about your patch,

Regards,

Pierre

On 3/2/21 3:35 PM, Pierre Gondois wrote:


[...]

+  offer that from an RPMB, the driver allocates memory on init and
passes that

+  on the upper layers. Since the memory is dynamically allocated and we
can't set the

+  PCD is StMM context, we need to patch it correctly on each access
I think: is -> in
Ok


+

+  @retval EFI_SUCCESS Protocol was found and PCDs patched up

+

+ **/
I think there should not be a space here.
Ok



+EFI_STATUS

+EFIAPI

+FixPcdMemory (
[...]

+

+  // Patch PCDs with the the correct values
I think it s
'the the' -> the
Yea


+  PatchPcdSet64 (PcdFlashNvStorageVariableBase64,
Instance->MemBaseAddress);
[...]

+  @retval           EFI_OUT_OF_RESOURCES op-tee out of memory

+**/

+STATIC

+EFI_STATUS

+ReadWriteRpmb (

+  UINTN  SvcAct,

+  UINTN  Addr,

+  UINTN  NumBytes,

+  UINTN  Offset

+  )
I think the parameters should have IN/OUT indications, and the function
header aswell (cf https://edk2-docs.gitbook.io/edk-ii-c-coding-standards-specification/6_documenting_software/62_comments#6-2-1-only-use-c-style-comments-on-the-same-line-as-pre-processor-directives-and-in-doxygen-style-file-and-function-header-comment-blocks).
There are other functions with missing IN/OUT parameters.
Sure, (did you c/p the wrong link?)



+{
[...]

+OpTeeRpmbFvbSetAttributes (

+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+  IN OUT    EFI_FVB_ATTRIBUTES_2 *Attributes
Parameters should be aligned. (I think this is valid at other places, like
for OpTeeRpmbFvbGetPhysicalAddress())
Ok


+  )
[...]

+  The GetBlockSize() function retrieves the size of the requested

+  block. It also returns the number of additional blocks with

+  the identical size. The GetBlockSize() function is used to

+  retrieve the block map (see EFI_FIRMWARE_VOLUME_HEADER).

+

+

+  @param This           Indicates the
EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instance.

+

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

+

+  @param BlockSize      Pointer to a caller-allocated UINTN in which

+                        the size of the block is returned.

+

+  @param NumberOfBlocks 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 firmware volume base address was
returned.

+

+  @retval EFI_INVALID_PARAMETER   The requested LBA is out of range.

+

+**/

+STATIC

+EFI_STATUS

+OpTeeRpmbFvbGetBlockSize (

+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+  IN        EFI_LBA                            Lba,

+  OUT       UINTN *BlockSize,

+  OUT       UINTN *NumberOfBlocks

+  )

+{

+  MEM_INSTANCE *Instance;

+

+  Instance = INSTANCE_FROM_FVB_THIS (This);

+  if (Lba > Instance->NBlocks) {

+    return EFI_INVALID_PARAMETER;

+  }

+

+  *NumberOfBlocks = Instance->NBlocks - (UINTN)Lba;

+  *BlockSize = Instance->BlockSize;

+

+  return EFI_SUCCESS;

+}

+

+/**

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

+

+  The Read() function reads the requested number of bytes from the

+  requested block and stores them in the provided buffer.

+  Implementations should be mindful that the firmware volume

+  might be in the ReadDisabled state. If it is in this state,

+  the Read() function must return the status code

+  EFI_ACCESS_DENIED without modifying the contents of the

+  buffer. The Read() function must also prevent spanning block

+  boundaries. If a read is requested that would span a block

+  boundary, the read must read up to the boundary but not

+  beyond. The output parameter NumBytes must be set to correctly

+  indicate the number of bytes actually read. The caller must be

+  aware that a read may be partially completed.

+

+  @param This     Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL
instance.

+

+  @param Lba      The starting logical block index

+                  from which to read.

+

+  @param Offset   Offset into the block at which to begin reading.

+

+  @param NumBytes Pointer to a UINTN. At entry, *NumBytes

+                  contains the total size of the buffer. At

+                  exit, *NumBytes contains the total number of

+                  bytes read.

+

+  @param Buffer   Pointer to a caller-allocated buffer that will

+                  be used to hold the data that is read.

+

+  @retval EFI_SUCCESS         The firmware volume was read successfully,

+                              and contents are in Buffer.

+

+  @retval EFI_BAD_BUFFER_SIZE Read attempted across an 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.
I think one new line should be enough. And would it be possible to align the
return codes comments ?
What's misaligned here? the parameters and the retval comments?
This was pretty much copied from a different driver, so I assumed that was the
'right way'. I can of course align them.

+

+**/

+STATIC

+EFI_STATUS


+  ReadAddr = Instance->MemBaseAddress;

+  // There's no need to check if the read failed here. The upper EDK2
layers

+  // will initialize the flash correctly if the in-memory copy is wrong

+  ReadWriteRpmb (
ReadWriteRpmb() returns an error code, I think we should return it aswell.
There's a reason the return code is not checked here. This is only called in
FvbInitialize(). That function will always run, even if the RPMB, the files
and filesystem that OP-TEE creates haven't been created yet. In that case
the OP-TEE API will return an 'error' which is 'file not found' though.
You want to initialize properly with the FVB headers etc and continue with
those contents.

The code that follows does that, so if we checked the return code and exited
early we would never be able to build the flash contents correctly to begin
with.
In any case after the read the headers are checked for validity/correctness
and if an error is found the contents will be rebuilt. So we don't really care
about the return here. Worst case scenario the flash is broken and we need
to rebuild it. That's what the comment is trying to explain.

Is there a better way to initialize the flash and the contents?
Is there a callback in EDK2 to explicitly rebuild the flash if an error is
found during the Fvbinitiaze phase?


+    SP_SVC_RPMB_READ,
+  @retval EFI_OUT_OF_RESOURCES      op-tee out of memory
[...]


+

+

+
I think one new line should be enough.
Ok


[...]

+    mInstance.MemBaseAddress +

+    PcdGet32 (PcdFlashNvStorageVariableSize) +

+    PcdGet32 (PcdFlashNvStorageFtwWorkingSize)

+    );
It seems this part is really similar to what is FixupPcd.c:FixPcdMemory(),
maybe this would be worth re-using it.
This is calculating the offsets of dynamic memory allocation that 'maps' to
our RPMB and it is indeed identical. But since they run into completely
different contexts I tried to avoid introducing dependencies between the 2
files. Is that a big problem?


+
[...]

+/**

+  This struct is used by the RPMB driver. Since the upper EDK2 layers

+  expect byte addressable memory, we allocate a memory area of certain

+  size and sync it to the hardware on reads/writes.

+

+  @param[in] Signature        Internal signature used to discover the
instance

+  @param[in] Initialize       Function used to initialize the instance

+  @param[in] Initialized      Set to true if initialized

+  @param[in] FvbProtocol      FVB protocol of the instance

+  @param[in] Handle           Handle to install

+  @param[in] MemBaseAddress   Physical address of the beggining of the
allocated memory

+  @param[in] BlockSize        Blocksize

+  @param[in] NBlocks          Number of allocated blocks
I think that for doxygen, '@param[in]' is more for functions declarations.
For structures, it should be as:

/**
  * This struct is used by the RPMB driver. Since the upper EDK2 layers
  * expect byte addressable memory, we allocate a memory area of certain
  * size and sync it to the hardware on reads/writes.
**/
struct _MEM_INSTANCE {
    ///  Signature        Internal signature used to discover the instance
    UINT32                              Signature;

/// Initialize       Function used to initialize the instance
    MEM_INITIALIZE                      Initialize;

[...]
};

Cf: https://edk2-docs.gitbook.io/edk-ii-c-coding-standards-specification/5_source_files/56_declarations_and_types#5-6-3-2-structure-declaration-with-forward-reference-or-self-reference
Ok


Thanks
/Ilias


PierreGondois
 

Hi Ilias,

Thanks for the answers, I am re-reviewing the patch because I think I missed some things. I answered to your comments (inlined),

Regards,

Pierre


On 3/3/21 8:02 PM, Ilias Apalodimas wrote:
Hi Pierre,

On Wed, Mar 03, 2021 at 10:20:17AM +0000, Pierre wrote:
Hello Ilias,

My review is mostly about coding style, but I would have some (inlined)
remarks about your patch,

Regards,

Pierre

On 3/2/21 3:35 PM, Pierre Gondois wrote:

[...]

+� offer that from an RPMB, the driver allocates memory on init and
passes that

+� on the upper layers. Since the memory is dynamically allocated and we
can't set the

+� PCD is StMM context, we need to patch it correctly on each access
I think: is -> in
Ok

+

+� @retval EFI_SUCCESS Protocol was found and PCDs patched up

+

+ **/
I think there should not be a space here.
Ok

+EFI_STATUS

+EFIAPI

+FixPcdMemory (
[...]

+

+� // Patch PCDs with the the correct values
I think it s
'the the' -> the
Yea

+� PatchPcdSet64 (PcdFlashNvStorageVariableBase64,
Instance->MemBaseAddress);
[...]

+� @retval���������� EFI_OUT_OF_RESOURCES op-tee out of memory

+**/

+STATIC

+EFI_STATUS

+ReadWriteRpmb (

+� UINTN� SvcAct,

+� UINTN� Addr,

+� UINTN� NumBytes,

+� UINTN� Offset

+� )
I think the parameters should have IN/OUT indications, and the function
header aswell (cf https://edk2-docs.gitbook.io/edk-ii-c-coding-standards-specification/6_documenting_software/62_comments#6-2-1-only-use-c-style-comments-on-the-same-line-as-pre-processor-directives-and-in-doxygen-style-file-and-function-header-comment-blocks).
There are other functions with missing IN/OUT parameters.
Sure, (did you c/p the wrong link?)
Yes it seems so ...

+{
[...]

+OpTeeRpmbFvbSetAttributes (

+� IN CONST� EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+� IN OUT��� EFI_FVB_ATTRIBUTES_2 *Attributes
Parameters should be aligned. (I think this is valid at other places, like
for OpTeeRpmbFvbGetPhysicalAddress())
Ok

+� )
[...]

+� The GetBlockSize() function retrieves the size of the requested

+� block. It also returns the number of additional blocks with

+� the identical size. The GetBlockSize() function is used to

+� retrieve the block map (see EFI_FIRMWARE_VOLUME_HEADER).

+

+

+� @param This���������� Indicates the
EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instance.

+

+� @param Lba����������� Indicates the block for which to return the size.

+

+� @param BlockSize����� Pointer to a caller-allocated UINTN in which

+����������������������� the size of the block is returned.

+

+� @param NumberOfBlocks 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 firmware volume base address was
returned.

+

+� @retval EFI_INVALID_PARAMETER�� The requested LBA is out of range.

+

+**/

+STATIC

+EFI_STATUS

+OpTeeRpmbFvbGetBlockSize (

+� IN CONST� EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,

+� IN������� EFI_LBA��������������������������� Lba,

+� OUT������ UINTN *BlockSize,

+� OUT������ UINTN *NumberOfBlocks

+� )

+{

+� MEM_INSTANCE *Instance;

+

+� Instance = INSTANCE_FROM_FVB_THIS (This);

+� if (Lba > Instance->NBlocks) {

+��� return EFI_INVALID_PARAMETER;

+� }

+

+� *NumberOfBlocks = Instance->NBlocks - (UINTN)Lba;

+� *BlockSize = Instance->BlockSize;

+

+� return EFI_SUCCESS;

+}

+

+/**

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

+

+� The Read() function reads the requested number of bytes from the

+� requested block and stores them in the provided buffer.

+� Implementations should be mindful that the firmware volume

+� might be in the ReadDisabled state. If it is in this state,

+� the Read() function must return the status code

+� EFI_ACCESS_DENIED without modifying the contents of the

+� buffer. The Read() function must also prevent spanning block

+� boundaries. If a read is requested that would span a block

+� boundary, the read must read up to the boundary but not

+� beyond. The output parameter NumBytes must be set to correctly

+� indicate the number of bytes actually read. The caller must be

+� aware that a read may be partially completed.

+

+� @param This���� Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL
instance.

+

+� @param Lba����� The starting logical block index

+����������������� from which to read.

+

+� @param Offset�� Offset into the block at which to begin reading.

+

+� @param NumBytes Pointer to a UINTN. At entry, *NumBytes

+����������������� contains the total size of the buffer. At

+����������������� exit, *NumBytes contains the total number of

+����������������� bytes read.

+

+� @param Buffer�� Pointer to a caller-allocated buffer that will

+����������������� be used to hold the data that is read.

+

+� @retval EFI_SUCCESS�������� The firmware volume was read successfully,

+����������������������������� and contents are in Buffer.

+

+� @retval EFI_BAD_BUFFER_SIZE Read attempted across an 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.
I think one new line should be enough. And would it be possible to align the
return codes comments ?
What's misaligned here? the parameters and the retval comments?
This was pretty much copied from a different driver, so I assumed that was the
'right way'. I can of course align them.
My comment did not belong to the right place I believe, I was referring to the '@retval' of OpTeeRpmbFvbErase(). The parameters of OpTeeRpmbFvbRead() do not appear as aligned though.

+

+**/

+STATIC

+EFI_STATUS


+� ReadAddr = Instance->MemBaseAddress;

+� // There's no need to check if the read failed here. The upper EDK2
layers

+� // will initialize the flash correctly if the in-memory copy is wrong

+� ReadWriteRpmb (
ReadWriteRpmb() returns an error code, I think we should return it aswell.
There's a reason the return code is not checked here. This is only called in
FvbInitialize(). That function will always run, even if the RPMB, the files
and filesystem that OP-TEE creates haven't been created yet. In that case
the OP-TEE API will return an 'error' which is 'file not found' though.
You want to initialize properly with the FVB headers etc and continue with
those contents.

The code that follows does that, so if we checked the return code and exited
early we would never be able to build the flash contents correctly to begin
with.
In any case after the read the headers are checked for validity/correctness
and if an error is found the contents will be rebuilt. So we don't really care
about the return here. Worst case scenario the flash is broken and we need
to rebuild it. That's what the comment is trying to explain.

Is there a better way to initialize the flash and the contents?
Is there a callback in EDK2 to explicitly rebuild the flash if an error is
found during the Fvbinitiaze phase?
Thanks for the explanation. I am not aware of such mechanism.

+��� SP_SVC_RPMB_READ,
+� @retval EFI_OUT_OF_RESOURCES����� op-tee out of memory
[...]

+

+

+
I think one new line should be enough.
Ok

[...]

+��� mInstance.MemBaseAddress +

+��� PcdGet32 (PcdFlashNvStorageVariableSize) +

+��� PcdGet32 (PcdFlashNvStorageFtwWorkingSize)

+��� );
It seems this part is really similar to what is FixupPcd.c:FixPcdMemory(),
maybe this would be worth re-using it.
This is calculating the offsets of dynamic memory allocation that 'maps' to
our RPMB and it is indeed identical. But since they run into completely
different contexts I tried to avoid introducing dependencies between the 2
files. Is that a big problem?
This is not a big problem, but it seems the 'FixupPcd' and 'OpTeeRpmbFvb' modules are currently tied up by the definitions in 'OpTeeRpmbFvb.h'. If there is a chance for them to be separated in the future, dependencies should effectively avoided. Otherwise Iit might be better to factorize the code.

+
[...]

+/**

+� This struct is used by the RPMB driver. Since the upper EDK2 layers

+� expect byte addressable memory, we allocate a memory area of certain

+� size and sync it to the hardware on reads/writes.

+

+� @param[in] Signature������� Internal signature used to discover the
instance

+� @param[in] Initialize������ Function used to initialize the instance

+� @param[in] Initialized����� Set to true if initialized

+� @param[in] FvbProtocol����� FVB protocol of the instance

+� @param[in] Handle���������� Handle to install

+� @param[in] MemBaseAddress�� Physical address of the beggining of the
allocated memory

+� @param[in] BlockSize������� Blocksize

+� @param[in] NBlocks��������� Number of allocated blocks
I think that for doxygen, '@param[in]' is more for functions declarations.
For structures, it should be as:

/**
� * This struct is used by the RPMB driver. Since the upper EDK2 layers
� * expect byte addressable memory, we allocate a memory area of certain
� * size and sync it to the hardware on reads/writes.
**/
struct _MEM_INSTANCE {
��� ///� Signature������� Internal signature used to discover the instance
��� UINT32����������������������������� Signature;

/// Initialize������ Function used to initialize the instance
��� MEM_INITIALIZE��������������������� Initialize;

[...]
};

Cf: https://edk2-docs.gitbook.io/edk-ii-c-coding-standards-specification/5_source_files/56_declarations_and_types#5-6-3-2-structure-declaration-with-forward-reference-or-self-reference
Ok


Thanks
/Ilias


PierreGondois
 

Hi Ilias,
Here is the rest of the review. Sorry to do it in 2 times.

Regards,

Pierre



+/**

+  Fixup the Pcd values for variable storage

+

+  Since the upper layers of EDK2 expect a memory mapped interface and we can't

+  offer that from an RPMB, the driver allocates memory on init and passes that

+  on the upper layers. Since the memory is dynamically allocated and we can't set the

+  PCD is StMM context, we need to patch it correctly on each access

+

+  @retval EFI_SUCCESS Protocol was found and PCDs patched up
The error codes are missing.

+

+ **/

+EFI_STATUS

+EFIAPI

+FixPcdMemory (

+  VOID

+  )

+{

+  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *FvbProtocol;

+  MEM_INSTANCE                        *Instance;

+  EFI_STATUS                          Status;

+

+  //

+  // Locate SmmFirmwareVolumeBlockProtocol

+  //

+  Status = gMmst->MmLocateProtocol (

+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,

+                    NULL,

+                    (VOID **) &FvbProtocol

+                    );

+  ASSERT_EFI_ERROR (Status);

+

+  Instance = INSTANCE_FROM_FVB_THIS (FvbProtocol);

+  // The Pcd is user defined, so make sure we don't overflow

+  if (Instance->MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageVariableSize)) {
I think this can be removed since the next condition is more strict.

+    return EFI_INVALID_PARAMETER;

+  }

+

[...]
+STATIC

+EFI_STATUS

+ReadWriteRpmb (

+  UINTN  SvcAct,

+  UINTN  Addr,

+  UINTN  NumBytes,

+  UINTN  Offset

+  )

+{

+  ARM_SVC_ARGS  SvcArgs;

+  EFI_STATUS    Status;

+

+  ZeroMem (&SvcArgs, sizeof (SvcArgs));

+

+  SvcArgs.Arg0 = ARM_SVC_ID_FFA_MSG_SEND_DIRECT_REQ_AARCH64;
If this is an FFA call, is it possible to:
 - put a reference in the header to the spec (it should be similar to the one at edk2/ArmPkg/Library/StandaloneMmMmuLib/AArch64/ArmMmuStandaloneMmLib.c)
 - check the return status of the SVC call against the ones available at edk2/ArmPkg/Include/IndustryStandard/ArmFfaSvc.h
 - if possible, remove the dependency to <IndustryStandard/ArmMmSvc.h>


+  SvcArgs.Arg1 = mStorageId;

+  SvcArgs.Arg2 = 0;

+  SvcArgs.Arg3 = SvcAct;

+  SvcArgs.Arg4 = Addr;

+  SvcArgs.Arg5 = NumBytes;

+  SvcArgs.Arg6 = Offset;

+

+  ArmCallSvc (&SvcArgs);

+  if (SvcArgs.Arg3) {

+    DEBUG ((DEBUG_ERROR, "%a: Svc Call 0x%08x Addr: 0x%08x len: 0x%x Offset: 0x%x failed with 0x%x\n",

+      __func__, SvcAct, Addr, NumBytes, Offset, SvcArgs.Arg3));

+  }

+

+  switch (SvcArgs.Arg3) {

+  case ARM_SVC_SPM_RET_SUCCESS:

+    Status = EFI_SUCCESS;

+    break;

+

+  case ARM_SVC_SPM_RET_NOT_SUPPORTED:

+    Status = EFI_UNSUPPORTED;

+    break;

+

+  case ARM_SVC_SPM_RET_INVALID_PARAMS:

+    Status = EFI_INVALID_PARAMETER;

+    break;

+

+  case ARM_SVC_SPM_RET_DENIED:

+    Status = EFI_ACCESS_DENIED;

+    break;

+

+  case ARM_SVC_SPM_RET_NO_MEMORY:

+    Status = EFI_OUT_OF_RESOURCES;

+    break;

+

+  default:

+    Status = EFI_ACCESS_DENIED;

+  }

+

+  return Status;

+}
[...]

+STATIC

+EFI_STATUS

+EFIAPI

+ValidateFvHeader (

+  IN EFI_FIRMWARE_VOLUME_HEADER            *FwVolHeader

+  )

+{

+  UINT16                      Checksum;

+  VARIABLE_STORE_HEADER       *VariableStoreHeader;

+  UINTN                       VariableStoreLength;

+  UINTN                       FvLength;

+

+  FvLength = PcdGet32(PcdFlashNvStorageVariableSize) +

+             PcdGet32(PcdFlashNvStorageFtwWorkingSize) +

+             PcdGet32(PcdFlashNvStorageFtwSpareSize);

+

+  // Verify the header revision, header signature, length

+  // Length of FvBlock cannot be 2**64-1

+  // HeaderLength cannot be an odd number

+  //

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

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

+      || (FwVolHeader->FvLength  != FvLength)

+      )
could be on the same line -> ') {'

+  {

+    DEBUG ((DEBUG_INFO, "%a: No Firmware Volume header present\n",

+      __FUNCTION__));

+    return EFI_NOT_FOUND;

+  }

+

+  // Check the Firmware Volume Guid

+  if (!CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid)) {

+    DEBUG ((DEBUG_INFO, "%a: Firmware Volume Guid non-compatible\n",

+      __FUNCTION__));

+    return EFI_VOLUME_CORRUPTED;

+  }

+

+  // Verify the header checksum

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

+  if (Checksum != 0) {

+    DEBUG ((DEBUG_INFO, "%a: FV checksum is invalid (Checksum:0x%X)\n",

+      __FUNCTION__, Checksum));

+    return EFI_VOLUME_CORRUPTED;

+  }

+

+  VariableStoreHeader = (VARIABLE_STORE_HEADER*)((UINTN)FwVolHeader +

+                         FwVolHeader->HeaderLength);

+

+  // Check the Variable Store Guid

+  if (!CompareGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid) &&

+      !CompareGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGuid)) {

+    DEBUG ((DEBUG_INFO, "%a: Variable Store Guid non-compatible\n", __FUNCTION__));

+    return EFI_VOLUME_CORRUPTED;

+  }

+

+  VariableStoreLength = PcdGet32 (PcdFlashNvStorageVariableSize) -

+                        FwVolHeader->HeaderLength;

+  if (VariableStoreHeader->Size != VariableStoreLength) {

+    DEBUG ((DEBUG_INFO, "%a: Variable Store Length does not match\n",

+      __FUNCTION__));

+    return EFI_VOLUME_CORRUPTED;

+  }

+

+  return EFI_SUCCESS;
empty line, could be removed
+

+}

+

[...]

+**/

+STATIC

+EFI_STATUS

+EFIAPI

+FvbInitialize (

+  MEM_INSTANCE *Instance

+  )

+{

+  EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;

+  EFI_STATUS                  Status;

+

+  if (Instance->Initialized) {

+    return EFI_SUCCESS;

+  }

+

+  // FirmwareVolumeHeader->FvLength is declared to have the Variable area

+  // AND the FTW working area AND the FTW Spare contiguous.

+  ASSERT (

+    (PcdGet64 (PcdFlashNvStorageVariableBase64) +

+    PcdGet32 (PcdFlashNvStorageVariableSize)) ==

+    PcdGet64 (PcdFlashNvStorageFtwWorkingBase64)

+    );

+  ASSERT (

+    (PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) +

+    PcdGet32 (PcdFlashNvStorageFtwWorkingSize)) ==

+    PcdGet64 (PcdFlashNvStorageFtwSpareBase64));

+

+  // Check if the size of the area is at least one block size

+  ASSERT (

+    (PcdGet32 (PcdFlashNvStorageVariableSize) > 0) &&
I think the first check (Size > 0) is redundant with the second one (Size > BlockSize).

+    (PcdGet32 (PcdFlashNvStorageVariableSize) / Instance->BlockSize > 0)

+    );

+  ASSERT (

+    (PcdGet32 (PcdFlashNvStorageFtwWorkingSize) > 0) &&

+    (PcdGet32 (PcdFlashNvStorageFtwWorkingSize) / Instance->BlockSize
0)
+    );

+  ASSERT (

+    (PcdGet32 (PcdFlashNvStorageFtwSpareSize) > 0) &&

+    (PcdGet32 (PcdFlashNvStorageFtwSpareSize) / Instance->BlockSize > 0)

+    );

+

+  // Ensure the Variable areas are aligned on block size boundaries

+  ASSERT ((PcdGet64 (PcdFlashNvStorageVariableBase64) % Instance->BlockSize) == 0);

+  ASSERT ((PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) % Instance->BlockSize) == 0);

+  ASSERT ((PcdGet64 (PcdFlashNvStorageFtwSpareBase64) % Instance->BlockSize) == 0);

+

+  // Read the file from disk and copy it to memory

+  ReadEntireFlash (Instance);

+

+  FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)Instance->MemBaseAddress;

+  Status = ValidateFvHeader (FwVolHeader);

+  if (EFI_ERROR (Status)) {

+    // There is no valid header, so time to install one.

+    DEBUG ((DEBUG_INFO, "%a: The FVB Header is not valid.\n", __FUNCTION__));

+

+    // Reset memory

+    SetMem64 ((VOID *)Instance->MemBaseAddress, Instance->NBlocks * Instance->BlockSize, ~0UL);

+    DEBUG ((DEBUG_INFO, "%a: Erasing Flash.\n", __FUNCTION__));

+    Status = ReadWriteRpmb (

+               SP_SVC_RPMB_WRITE,

+               Instance->MemBaseAddress,

+               PcdGet32(PcdFlashNvStorageVariableSize) +

+               PcdGet32(PcdFlashNvStorageFtwWorkingSize) +

+               PcdGet32(PcdFlashNvStorageFtwSpareSize),

+               0

+               );

+    if (EFI_ERROR (Status)) {

+      return Status;

+    }

+    // Install all appropriate headers

+    DEBUG ((DEBUG_INFO, "%a: Installing a correct one for this volume.\n",

+      __FUNCTION__));

+    Status = InitializeFvAndVariableStoreHeaders (Instance);

+    if (EFI_ERROR (Status)) {

+      return Status;

+    }

+  } else {

+    DEBUG ((DEBUG_INFO, "%a: Found valid FVB Header.\n", __FUNCTION__));

+  }

+  Instance->Initialized = TRUE;

+

+  return Status;

+}

+

+/**

+  Since the RPMB is not byte addressable we need to allocate memory

+  and sync that on reads/writes. Initialize the memory and install the

+  Fvb protocol.

+

+  @param ImageHandle The EFI image handle

+  @param SystemTable MM system table

+

+  @retval EFI_SUCCESS Protocol installed

+

+  @retval EFI_INVALID_PARAMETER Invalid Pcd values specified

+

+  @retval EFI_OUT_OF_RESOURCES  Can't allocate necessary memory

+**/

+EFI_STATUS

+EFIAPI

+OpTeeRpmbFvbInit (

+  IN EFI_HANDLE           ImageHandle,

+  IN EFI_MM_SYSTEM_TABLE  *SystemTable

+  )

+{

+  EFI_STATUS   Status;

+  VOID         *Addr;

+  UINTN        FvLength;

+  UINTN        NBlocks;

+

+  FvLength = PcdGet32(PcdFlashNvStorageVariableSize) +

+             PcdGet32(PcdFlashNvStorageFtwWorkingSize) +

+             PcdGet32(PcdFlashNvStorageFtwSpareSize);

+

+  NBlocks = EFI_SIZE_TO_PAGES (ALIGN_VARIABLE (FvLength));

+  Addr = AllocatePages (NBlocks);

+  if (Addr == NULL) {

+    ASSERT (0);

+    return EFI_OUT_OF_RESOURCES;

+  }

+

+  SetMem (&mInstance, sizeof (mInstance), 0);
NIT: you can use ZeroMem()

+

+  mInstance.FvbProtocol.GetPhysicalAddress = OpTeeRpmbFvbGetPhysicalAddress;

+  mInstance.FvbProtocol.GetAttributes      = OpTeeRpmbFvbGetAttributes;

+  mInstance.FvbProtocol.SetAttributes      = OpTeeRpmbFvbSetAttributes;

+  mInstance.FvbProtocol.GetBlockSize       = OpTeeRpmbFvbGetBlockSize;

+  mInstance.FvbProtocol.EraseBlocks        = OpTeeRpmbFvbErase;

+  mInstance.FvbProtocol.Write              = OpTeeRpmbFvbWrite;

+  mInstance.FvbProtocol.Read               = OpTeeRpmbFvbRead;

+

+  mInstance.MemBaseAddress = (EFI_PHYSICAL_ADDRESS)Addr;

+  mInstance.Signature      = FLASH_SIGNATURE;

+  mInstance.Initialize     = FvbInitialize;

+  mInstance.BlockSize      = EFI_PAGE_SIZE;

+  mInstance.NBlocks        = NBlocks;

+

+  // The Pcd is user defined, so make sure we don't overflow

+  if (mInstance.MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageVariableSize)) {
I don't think this is necessary to do any check here since the memory has just been allocated with the right size.
+    return EFI_INVALID_PARAMETER;

+  }

+

+  if (mInstance.MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageVariableSize) -

+    PcdGet32 (PcdFlashNvStorageFtwWorkingSize)) {

+    return EFI_INVALID_PARAMETER;

+  }

+

+  // Update the defined PCDs related to Variable Storage

+  PatchPcdSet64 (PcdFlashNvStorageVariableBase64, mInstance.MemBaseAddress);

+  PatchPcdSet64 (

+    PcdFlashNvStorageFtwWorkingBase64,

+    mInstance.MemBaseAddress + PcdGet32 (PcdFlashNvStorageVariableSize)

+    );

+  PatchPcdSet64 (

+    PcdFlashNvStorageFtwSpareBase64,

+    mInstance.MemBaseAddress +

+    PcdGet32 (PcdFlashNvStorageVariableSize) +

+    PcdGet32 (PcdFlashNvStorageFtwWorkingSize)

+    );
Do we actually need to set these PCDs ? If the PCDs are persistent, we should not need to patch them in FixupPcd.c. FvbInitialize() is using them, but it is not called from OpTeeRpmbFvbInit().

+

+  Status = gMmst->MmInstallProtocolInterface (

+                    &mInstance.Handle,

+ &gEfiSmmFirmwareVolumeBlockProtocolGuid,

+                    EFI_NATIVE_INTERFACE,

+                    &mInstance.FvbProtocol

+                    );

+  ASSERT_EFI_ERROR (Status);

+

+  DEBUG ((DEBUG_INFO, "%a: Register OP-TEE RPMB Fvb\n", __FUNCTION__));

+  DEBUG ((DEBUG_INFO, "%a: Using NV store FV in-memory copy at 0x%lx\n",

+    __FUNCTION__, PatchPcdGet64 (PcdFlashNvStorageVariableBase64)));

+

+  return Status;

+}


Ilias Apalodimas
 

On Fri, Mar 05, 2021 at 05:58:49PM +0000, Pierre wrote:
Hi Ilias,
Here is the rest of the review. Sorry to do it in 2 times.
No worries, I'll try to pick up all the comments.


Regards,

Pierre



+/**

+ Fixup the Pcd values for variable storage

+

+ Since the upper layers of EDK2 expect a memory mapped interface and
we can't

+ offer that from an RPMB, the driver allocates memory on init and
passes that

+ on the upper layers. Since the memory is dynamically allocated and we
can't set the

+ PCD is StMM context, we need to patch it correctly on each access

+

+ @retval EFI_SUCCESS Protocol was found and PCDs patched up
The error codes are missing.
Yea, but I'll remove the overflow check on v6 so that should be fine as-is.


+

+ **/

+EFI_STATUS

+EFIAPI

[...]

+ ASSERT_EFI_ERROR (Status);

+

+ Instance = INSTANCE_FROM_FVB_THIS (FvbProtocol);

+ // The Pcd is user defined, so make sure we don't overflow

+ if (Instance->MemBaseAddress > MAX_UINT64 - PcdGet32
(PcdFlashNvStorageVariableSize)) {
I think this can be removed since the next condition is more strict.
ditto


+ return EFI_INVALID_PARAMETER;

+ }

+

[...]
+STATIC

+EFI_STATUS

+ReadWriteRpmb (

+ UINTN SvcAct,

+ UINTN Addr,

+ UINTN NumBytes,

+ UINTN Offset

+ )

+{

+ ARM_SVC_ARGS SvcArgs;

+ EFI_STATUS Status;

+

+ ZeroMem (&SvcArgs, sizeof (SvcArgs));

+

+ SvcArgs.Arg0 = ARM_SVC_ID_FFA_MSG_SEND_DIRECT_REQ_AARCH64;
If this is an FFA call, is it possible to:
- put a reference in the header to the spec (it should be similar to the
one at
edk2/ArmPkg/Library/StandaloneMmMmuLib/AArch64/ArmMmuStandaloneMmLib.c)
- check the return status of the SVC call against the ones available at
edk2/ArmPkg/Include/IndustryStandard/ArmFfaSvc.h
- if possible, remove the dependency to <IndustryStandard/ArmMmSvc.h>
The call is technically an FFA one but at the moment OP-TEE returns the StMM
return code which is defined in the last header you mention.
The relevant code is in ./core/arch/arm/kernel/stmm_sp.c function
tee2stmm_ret_val().
So unless we redefine that in OP-TEE or (better imho), wait for a full FFA
mechanism to be in place, I'd prefer leaving it as is.
Keep in mind that adding the full FFA will also get rid of the hardcoded IDs
on the beginning of the file.


+ SvcArgs.Arg1 = mStorageId;
+ //
[...]


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

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

+ || (FwVolHeader->FvLength != FvLength)

+ )
could be on the same line -> ') {'
ok


+ {


+ if (VariableStoreHeader->Size != VariableStoreLength) {

+ DEBUG ((DEBUG_INFO, "%a: Variable Store Length does not match\n",

+ __FUNCTION__));

+ return EFI_VOLUME_CORRUPTED;

+ }

+

+ return EFI_SUCCESS;
empty line, could be removed
ok

+

+ (PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) +

+ PcdGet32 (PcdFlashNvStorageFtwWorkingSize)) ==

+ PcdGet64 (PcdFlashNvStorageFtwSpareBase64));

+

+ // Check if the size of the area is at least one block size

+ ASSERT (

+ (PcdGet32 (PcdFlashNvStorageVariableSize) > 0) &&
I think the first check (Size > 0) is redundant with the second one (Size >
BlockSize).
Yea it seems so. This was again a c/p from other drivers handling the
PCD, but we can start
clean here.


+ (PcdGet32 (PcdFlashNvStorageVariableSize) / Instance->BlockSize > 0)

+ );

+ ASSERT (

+ (PcdGet32 (PcdFlashNvStorageFtwWorkingSize) > 0) &&

[...]

+

+ SetMem (&mInstance, sizeof (mInstance), 0);
NIT: you can use ZeroMem()
Sure


+

+ mInstance.FvbProtocol.GetPhysicalAddress =
OpTeeRpmbFvbGetPhysicalAddress;

+ mInstance.FvbProtocol.GetAttributes = OpTeeRpmbFvbGetAttributes;

+ mInstance.FvbProtocol.SetAttributes = OpTeeRpmbFvbSetAttributes;

+ mInstance.FvbProtocol.GetBlockSize = OpTeeRpmbFvbGetBlockSize;

+ mInstance.FvbProtocol.EraseBlocks = OpTeeRpmbFvbErase;

+ mInstance.FvbProtocol.Write = OpTeeRpmbFvbWrite;

+ mInstance.FvbProtocol.Read = OpTeeRpmbFvbRead;

+

+ mInstance.MemBaseAddress = (EFI_PHYSICAL_ADDRESS)Addr;

+ mInstance.Signature = FLASH_SIGNATURE;

+ mInstance.Initialize = FvbInitialize;

+ mInstance.BlockSize = EFI_PAGE_SIZE;

+ mInstance.NBlocks = NBlocks;

+

+ // The Pcd is user defined, so make sure we don't overflow

+ if (mInstance.MemBaseAddress > MAX_UINT64 - PcdGet32
(PcdFlashNvStorageVariableSize)) {
I don't think this is necessary to do any check here since the memory has
just been allocated with the right size.
Yea it's not. I'll probably remove the same piece of code from the
FixupPcd.c as well.


+ );
Do we actually need to set these PCDs ? If the PCDs are persistent, we
should not need to patch them in FixupPcd.c. FvbInitialize() is using them,
but it is not called from OpTeeRpmbFvbInit().
I think it is. There's something 'special' about this driver. The
upper EDK2 lays expect a byte-addressable interface.
So the PCDs are definitely not persistent, they are patchable in module PCDs.
Since RPMB isn't one we are allocating memory and handing that memory
over to EDK2, while syncing the background on the hardware.
Again, it's been a while since I wrote this and memory might be
failing, but I think what's happening here is:

OpTeeRpmbFvbInit is the entry point, which calls in EDK2 code, so you
need to patch them in here, before calling anything. After that the
fixup code runs before calling into the module and fixes up the values
for us.
In any case I'll double check before posting a v6

Thanks
/Ilias

[...]