From nobody Tue May 7 21:50:38 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of groups.io designates 66.175.222.108 as permitted sender) client-ip=66.175.222.108; envelope-from=bounce+27952+66484+1787277+3901457@groups.io; helo=mail02.groups.io; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.108 as permitted sender) smtp.mailfrom=bounce+27952+66484+1787277+3901457@groups.io; dmarc=fail(p=none dis=none) header.from=linaro.org ARC-Seal: i=1; a=rsa-sha256; t=1603282758; cv=none; d=zohomail.com; s=zohoarc; b=P+E5ALy1z4D0Ml4WDDDeX/G9hWUp0b4zanWmo7BjefGkGOBLgx7WgIGhvQcmc1//RbI+DSYLhyCrtrECslrC8p/WGPDTnYJOZxZzW0qFord3J1awnKAmdv+PLtBMOcyZIsijq0+3/BPFHZk7mSD2lIizbZ45elcdedB24xQUXbs= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1603282758; h=Cc:Date:From:In-Reply-To:List-Id:List-Unsubscribe:Message-ID:Reply-To:References:Sender:Subject:To; bh=hNQdAv2oyv4TOJW7J//sdMDFztJ6ubk9gS9abs/Zxe0=; b=HDwgWopL5SYnbh/qIIfNIW4O+segq4omeLWhnxictD8qRnam468zR4IUhWhjeqpEXMAO2IQgkSB5KjYqBU/8ukQUqxyayQ7jqKw+xjlTKJHvaLBe+2E/0IbGt/HTv7rUp8EPhprkVVwQ+GMTKJP4J1XoDFTMN1BWj4A/fEB81gA= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.108 as permitted sender) smtp.mailfrom=bounce+27952+66484+1787277+3901457@groups.io; dmarc=fail header.from= (p=none dis=none) header.from= Received: from mail02.groups.io (mail02.groups.io [66.175.222.108]) by mx.zohomail.com with SMTPS id 1603282758167570.3963215844005; Wed, 21 Oct 2020 05:19:18 -0700 (PDT) Return-Path: X-Received: by 127.0.0.2 with SMTP id xpPCYY1788612xCtauhZ4mwZ; Wed, 21 Oct 2020 05:19:17 -0700 X-Received: from foss.arm.com (foss.arm.com [217.140.110.172]) by mx.groups.io with SMTP id smtpd.web09.10415.1603280147137519834 for ; Wed, 21 Oct 2020 04:35:47 -0700 X-Received: from usa-sjc-imap-foss1.foss.arm.com (unknown [10.121.207.14]) by usa-sjc-mx-foss1.foss.arm.com (Postfix) with ESMTP id D80A21FB; Wed, 21 Oct 2020 04:35:46 -0700 (PDT) X-Received: from a076522.blr.arm.com (a076522.blr.arm.com [10.162.16.44]) by usa-sjc-imap-foss1.foss.arm.com (Postfix) with ESMTPSA id E336A3F66E; Wed, 21 Oct 2020 04:35:44 -0700 (PDT) From: "Sughosh Ganu" To: devel@edk2.groups.io Cc: Ard Biesheuvel , Leif Lindholm , Ilias Apalodimas Subject: [edk2-devel] [PATCH edk2-platforms v1 1/2] Drivers/OpTeeRpmb: Add an OP-TEE backed RPMB driver Date: Wed, 21 Oct 2020 17:05:33 +0530 Message-Id: <20201021113534.25671-2-sughosh.ganu@linaro.org> In-Reply-To: <20201021113534.25671-1-sughosh.ganu@linaro.org> References: <20201021113534.25671-1-sughosh.ganu@linaro.org> Precedence: Bulk List-Unsubscribe: Sender: devel@edk2.groups.io List-Id: Mailing-List: list devel@edk2.groups.io; contact devel+owner@edk2.groups.io Reply-To: devel@edk2.groups.io,sughosh.ganu@linaro.org X-Gm-Message-State: QrcEQtktjFwJzQTJjGnJaUhEx1787277AA= DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=groups.io; q=dns/txt; s=20140610; t=1603282757; bh=1RPI86lniODfng7plc+xP3xx1EWdy9Q/bNv6NYrEIlU=; h=Cc:Date:From:Reply-To:Subject:To; b=B2p69zi/ud91Vwo6vB5UkrI5QSOCd/FvadGq28AzPPnPqv9m9DSf7PdMz9Hc1cegmxA uBbjX1dB1nsobFZ0vUN5haezsAyMsiLG67RzY52S3f7Qf6Ktko+TCd8PB/sYoA9Irmeo0 Ht7h6cOE3tglhiHg8F0Qhl+P0XNK1rBlD9Q= X-ZohoMail-DKIM: pass (identity @groups.io) Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" From: 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 --- Drivers/OpTeeRpmb/FixupPcd.inf | 44 ++ Drivers/OpTeeRpmb/OpTeeRpmbFv.inf | 58 ++ Drivers/OpTeeRpmb/OpTeeRpmbFvb.h | 52 ++ Drivers/OpTeeRpmb/FixupPcd.c | 74 ++ Drivers/OpTeeRpmb/OpTeeRpmbFvb.c | 775 ++++++++++++++++++++ 5 files changed, 1003 insertions(+) diff --git a/Drivers/OpTeeRpmb/FixupPcd.inf b/Drivers/OpTeeRpmb/FixupPcd.inf new file mode 100644 index 0000000000..f0cfdf7a4c --- /dev/null +++ b/Drivers/OpTeeRpmb/FixupPcd.inf @@ -0,0 +1,44 @@ +## @file +# Instance of Base Memory Library without assembly. +# +# Copyright (c) 2020, Linaro Ltd. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# +## + +[Defines] + INF_VERSION =3D 0x0001001A + BASE_NAME =3D FixupPcd + FILE_GUID =3D a827c337-a9c6-301b-aeb7-acbc95d8da22 + MODULE_TYPE =3D BASE + VERSION_STRING =3D 0.1 + LIBRARY_CLASS =3D RpmbPcdFixup|MM_STANDALONE + CONSTRUCTOR =3D FixPcdMemory + +[Sources] + FixupPcd.c + OpTeeRpmbFvb.h + +[Packages] + MdeModulePkg/MdeModulePkg.dec + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + DebugLib + MmServicesTableLib + PcdLib + +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize + + +[Protocols] + gEfiSmmFirmwareVolumeBlockProtocolGuid ## CONSUMES diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFv.inf b/Drivers/OpTeeRpmb/OpTeeRpm= bFv.inf new file mode 100644 index 0000000000..b21f7397e5 --- /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.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION =3D 0x0001001A + BASE_NAME =3D OpTeeRpmbFv + FILE_GUID =3D 4803FC20-E583-3BCD-8C60-141E85C9A2CF + MODULE_TYPE =3D MM_STANDALONE + VERSION_STRING =3D 0.1 + PI_SPECIFICATION_VERSION =3D 0x00010032 + ENTRY_POINT =3D 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.PcdFlashNvStorageVariableBase + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize + +[Protocols] + gEfiSmmFirmwareVolumeBlockProtocolGuid ## PRODUCES + +[Depex] + TRUE diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFvb.h b/Drivers/OpTeeRpmb/OpTeeRpmb= Fvb.h new file mode 100644 index 0000000000..f6c3fe2639 --- /dev/null +++ b/Drivers/OpTeeRpmb/OpTeeRpmbFvb.h @@ -0,0 +1,52 @@ +/** @file + + Copyright (c) 2020, Linaro Ltd. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __OPTEE_RPMB_FV_ +#define __OPTEE_RPMB_FV_ + +/* SVC Args */ +#define SP_SVC_RPMB_READ 0xC4000066 +#define SP_SVC_RPMB_WRITE 0xC4000067 +#define SP_SVC_GET_UART 0xC4000068 + +#define FILENAME "EFI_VARS" + +#define NBLOCKS (3 * 16) // EFI Vars, FTW working, FTW = spare +#define BLOCK_SIZE SIZE_4KB +#define FLASH_SIGNATURE SIGNATURE_32('r', 'p', 'm', 'b') +#define INSTANCE_FROM_FVB_THIS(a) CR(a, MEM_INSTANCE, FvbProtocol, \ + FLASH_SIGNATURE) +enum _RPMB_FILE_MAP { + EFI_VARS, + FTW_WORK, + FTW_SPARE, +}; + +typedef enum _RPMB_FILE_MAP RPMB_FILE_MAP; + +struct _MAP_VAL_TO_FILE { + CHAR8 *Filename; + RPMB_FILE_MAP Map; +}; + +typedef struct _MAP_VAL_TO_FILE MAP_VAL_TO_FILE; + +typedef struct _MEM_INSTANCE MEM_INSTANCE; +typedef EFI_STATUS (*MEM_INITIALIZE) (MEM_INSTANCE* Instance); +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 diff --git a/Drivers/OpTeeRpmb/FixupPcd.c b/Drivers/OpTeeRpmb/FixupPcd.c new file mode 100644 index 0000000000..3cc882fa94 --- /dev/null +++ b/Drivers/OpTeeRpmb/FixupPcd.c @@ -0,0 +1,74 @@ +/** @file + + Update the patched PCDs to their correct value + + Copyright (c) 2020, Linaro Ltd. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +/** + * Patch the relevant PCDs of the RPMB driver with the correct address of = the + * allocated memory + * +**/ +#include +#include +#include +#include + +#include +#include + +#include "OpTeeRpmbFvb.h" + +/** + Fixup the Pcd values for variable storage + + Since the upper layers of EDK2 expect a memory mapped interface and we c= an'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 ca= n'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 + + **/ +EFI_STATUS +EFIAPI +FixPcdMemory ( + VOID + ) +{ + EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol; + MEM_INSTANCE *Instance; + EFI_STATUS Status; + + // + // Locate SmmFirmwareVolumeBlockProtocol + // + Status =3D gMmst->MmLocateProtocol ( + &gEfiSmmFirmwareVolumeBlockProtocolGuid, + NULL, + (VOID **) &FvbProtocol + ); + ASSERT_EFI_ERROR (Status); + + Instance =3D INSTANCE_FROM_FVB_THIS(FvbProtocol); + // Patch PCDs with the the correct values + PatchPcdSet32 (PcdFlashNvStorageVariableBase, Instance->MemBaseAddress); + PatchPcdSet32 (PcdFlashNvStorageFtwWorkingBase, Instance->MemBaseAddress= + + PcdGet32 (PcdFlashNvStorageVariableSize)); + PatchPcdSet32 (PcdFlashNvStorageFtwSpareBase, Instance->MemBaseAddress + + PcdGet32 (PcdFlashNvStorageVariableSize) + + PcdGet32 (PcdFlashNvStorageFtwWorkingSize)); + + DEBUG ((DEBUG_INFO, "%a: Fixup PcdFlashNvStorageVariableBase: 0x%lx\n", + __FUNCTION__, PcdGet32 (PcdFlashNvStorageVariableBase))); + DEBUG ((DEBUG_INFO, "%a: Fixup PcdFlashNvStorageFtwWorkingBase: 0x%lx\n", + __FUNCTION__, PcdGet32 (PcdFlashNvStorageFtwWorkingBase))); + DEBUG ((DEBUG_INFO, "%a: Fixup PcdFlashNvStorageFtwSpareBase: 0x%lx\n", + __FUNCTION__, PcdGet32 (PcdFlashNvStorageFtwSpareBase))); + + return Status; +} diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFvb.c b/Drivers/OpTeeRpmb/OpTeeRpmb= Fvb.c new file mode 100644 index 0000000000..27b857da22 --- /dev/null +++ b/Drivers/OpTeeRpmb/OpTeeRpmbFvb.c @@ -0,0 +1,775 @@ +/** @file + + FV block I/O protocol driver for RPMB eMMC accessed via OP-TEE + + Copyright (c) 2020, Linaro Ltd. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "OpTeeRpmbFvb.h" + +static const UINT16 mem_mgr_id =3D 3U; +static const UINT16 storage_id =3D 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 devi= ce. + 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 OP-TEE return code +**/ + +STATIC +UINTN +ReadWriteRpmb ( + UINTN SvcAct, + UINTN Addr, + UINTN NumBytes, + UINTN Offset + ) +{ + ARM_SVC_ARGS SvcArgs; + + ZeroMem (&SvcArgs, sizeof (SvcArgs)); + + SvcArgs.Arg0 =3D ARM_SVC_ID_FFA_MSG_SEND_DIRECT_REQ_AARCH64; + SvcArgs.Arg1 =3D storage_id; + SvcArgs.Arg2 =3D 0; + SvcArgs.Arg3 =3D SvcAct; + SvcArgs.Arg4 =3D Addr; + SvcArgs.Arg5 =3D NumBytes; + SvcArgs.Arg6 =3D Offset; + + ArmCallSvc (&SvcArgs); + if (SvcArgs.Arg3) { + DEBUG ((DEBUG_ERROR, "%a: Svc Call 0x%08x Addr: 0x%08x len: 0x%x Offse= t: 0x%x failed with 0x%x\n", + __func__, SvcAct, Addr, NumBytes, Offset, SvcArgs.Arg3)); + } + + return SvcArgs.Arg3; +} + +/** + The GetAttributes() function retrieves the attributes and + current settings of the block. + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL insta= nce. + + @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 =3D EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled + EFI_FVB2_READ_STATUS | // Reads are currently enabl= ed + EFI_FVB2_WRITE_STATUS | // Writes are currently enab= led + 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 ta= ke 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 ins= tance. + + @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_SUCCESS The firmware volume attributes were return= ed. + + @retval EFI_INVALID_PARAMETER The attributes requested are in + conflict with the capabilities + as declared in the firmware + volume header. + +**/ +STATIC +EFI_STATUS +OpTeeRpmbFvbSetAttributes ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes + ) +{ + return EFI_SUCCESS; // ignore for now +} + +/** + 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 instanc= e. + + @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 =3D INSTANCE_FROM_FVB_THIS(This); + *Address =3D 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 i= nstance. + + @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 ret= urned. + + @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 =3D INSTANCE_FROM_FVB_THIS(This); + if (Lba >=3D Instance->NBlocks) { + return EFI_INVALID_PARAMETER; + } + + *NumberOfBlocks =3D Instance->NBlocks - (UINTN) Lba; + *BlockSize =3D Instance->BlockSize; + + return EFI_SUCCESS; +} + +/** + Reads the specified number of bytes into a buffer from the specified blo= ck. + + 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 instanc= e. + + @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. + +**/ + +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 =3D EFI_SUCCESS; + MEM_INSTANCE *Instance; + VOID *Base; + + Instance =3D INSTANCE_FROM_FVB_THIS(This); + if (Instance->Initialized =3D=3D FALSE) { + Instance->Initialize (Instance); + } + + Base =3D (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 instanc= e. + + @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 =3D EFI_SUCCESS; + VOID *Base; + UINTN Ret; + + Instance =3D INSTANCE_FROM_FVB_THIS(This); + if (Instance->Initialized =3D=3D FALSE) { + Instance->Initialize (Instance); + } + Base =3D (VOID *)Instance->MemBaseAddress + Lba * Instance->BlockSize + = Offset; + // We can map OP-TEE errors to EFI exitcodes and return a more + // realistic error. Keep it simple for now + Ret =3D ReadWriteRpmb (SP_SVC_RPMB_WRITE, (UINTN) Buffer, *NumBytes, + Lba * Instance->BlockSize + Offset); + if (Ret) { + return EFI_DEVICE_ERROR; + } + + // 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; + UINTN Ret; + + Instance =3D INSTANCE_FROM_FVB_THIS(This); + + VA_START (Args, This); + for (Start =3D VA_ARG (Args, EFI_LBA); + Start !=3D EFI_LBA_LIST_TERMINATOR; + Start =3D VA_ARG (Args, EFI_LBA)) { + NumLba =3D VA_ARG (Args, UINTN); + if (Start + NumLba >=3D Instance->NBlocks) { + return EFI_INVALID_PARAMETER; + } + NumBytes =3D NumLba * Instance->BlockSize; + Base =3D (VOID *)Instance->MemBaseAddress + Start * Instance->BlockSiz= e; + Buf =3D AllocatePool(NumLba * Instance->BlockSize); + SetMem64 (Buf, NumLba * Instance->BlockSize, ~0UL); + if (!Buf) { + return EFI_DEVICE_ERROR; + } + // Write the device + Ret =3D ReadWriteRpmb (SP_SVC_RPMB_WRITE, (UINTN) Buf, NumBytes, + Start * Instance->BlockSize); + if (Ret) { + return EFI_DEVICE_ERROR; + } + // 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 Instace Address to copy flash contents to + + @retval 0 on success, OP-TEE error on failure +**/ +STATIC +VOID +ReadEntireFlash ( + MEM_INSTANCE *Instance + ) +{ + UINTN ReadAddr; + + UINTN StorageFtwWorkingSize =3D PcdGet32(PcdFlashNvStorageFtwWorkingSize= ); + UINTN StorageVariableSize =3D PcdGet32(PcdFlashNvStorageVariableSize); + UINTN StorageFtwSpareSize =3D PcdGet32(PcdFlashNvStorageFtwSpareSize); + + ReadAddr =3D Instance->MemBaseAddress; + // There's no need to check if the read failed here. The upper EDK2 laye= rs + // will initialize the flash correctly if the in-memory copy is wrong + ReadWriteRpmb(SP_SVC_RPMB_READ, ReadAddr, StorageVariableSize + + StorageFtwWorkingSize + StorageFtwSpareSize , 0); +} + + +STATIC +EFI_STATUS +EFIAPI +ValidateFvHeader ( + IN EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader + ) +{ + UINT16 Checksum; + VARIABLE_STORE_HEADER *VariableStoreHeader; + UINTN VariableStoreLength; + UINTN FvLength; + + FvLength =3D 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 !=3D EFI_FVH_REVISION) + || (FwVolHeader->Signature !=3D EFI_FVH_SIGNATURE) + || (FwVolHeader->FvLength !=3D 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_NOT_FOUND; + } + + // Verify the header checksum + Checksum =3D CalculateSum16((UINT16*)FwVolHeader, FwVolHeader->HeaderLen= gth); + if (Checksum !=3D 0) { + DEBUG ((DEBUG_INFO, "%a: FV checksum is invalid (Checksum:0x%X)\n", + __FUNCTION__, Checksum)); + return EFI_NOT_FOUND; + } + + VariableStoreHeader =3D (VOID *)((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_NOT_FOUND; + } + + VariableStoreLength =3D PcdGet32 (PcdFlashNvStorageVariableSize) - + FwVolHeader->HeaderLength; + if (VariableStoreHeader->Size !=3D VariableStoreLength) { + DEBUG ((DEBUG_INFO, "%a: Variable Store Length does not match\n", + __FUNCTION__)); + return EFI_NOT_FOUND; + } + + return EFI_SUCCESS; + +} + +STATIC +EFI_STATUS +InitializeFvAndVariableStoreHeaders ( + MEM_INSTANCE *Instance + ) +{ + EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader; + VARIABLE_STORE_HEADER *VariableStoreHeader; + EFI_STATUS Status =3D EFI_SUCCESS; + UINTN HeadersLength; + VOID* Headers; + UINTN Ret; + + HeadersLength =3D sizeof(EFI_FIRMWARE_VOLUME_HEADER) + + sizeof(EFI_FV_BLOCK_MAP_ENTRY) + + sizeof(VARIABLE_STORE_HEADER); + Headers =3D AllocateZeroPool(HeadersLength); + + // + // EFI_FIRMWARE_VOLUME_HEADER + // + FirmwareVolumeHeader =3D (EFI_FIRMWARE_VOLUME_HEADER*)Headers; + CopyGuid (&FirmwareVolumeHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid= ); + FirmwareVolumeHeader->FvLength =3D + PcdGet32(PcdFlashNvStorageVariableSize) + + PcdGet32(PcdFlashNvStorageFtwWorkingSize) + + PcdGet32(PcdFlashNvStorageFtwSpareSize); + FirmwareVolumeHeader->Signature =3D EFI_FVH_SIGNATURE; + FirmwareVolumeHeader->Attributes =3D 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 =3D sizeof(EFI_FIRMWARE_VOLUME_HEADER= ) + + sizeof(EFI_FV_BLOCK_MAP_ENTRY); + FirmwareVolumeHeader->Revision =3D EFI_FVH_REVISION; + FirmwareVolumeHeader->BlockMap[0].NumBlocks =3D Instance->NBlocks; + FirmwareVolumeHeader->BlockMap[0].Length =3D Instance->BlockSize; + FirmwareVolumeHeader->BlockMap[1].NumBlocks =3D 0; + FirmwareVolumeHeader->BlockMap[1].Length =3D 0; + FirmwareVolumeHeader->Checksum =3D CalculateCheckSum16 ( + (UINT16*)FirmwareVolumeHeader, + FirmwareVolumeHeader->HeaderLength); + + // + // VARIABLE_STORE_HEADER + // + VariableStoreHeader =3D (VOID *)((UINTN)Headers + + FirmwareVolumeHeader->HeaderLength); + CopyGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGui= d); + VariableStoreHeader->Size =3D PcdGet32(PcdFlashNvStorageVariableSize) - + FirmwareVolumeHeader->HeaderLength; + VariableStoreHeader->Format =3D VARIABLE_STORE_FORMATTED; + VariableStoreHeader->State =3D VARIABLE_STORE_HEALTHY; + + Ret =3D ReadWriteRpmb(SP_SVC_RPMB_WRITE, (UINTN) Headers, HeadersLength,= 0); + if (Ret) { + Status =3D EFI_DEVICE_ERROR; + goto Exit; + } + // Install the combined header in memory + CopyMem ((VOID*) Instance->MemBaseAddress, Headers, HeadersLength); + +Exit: + FreePool (Headers); + return Status; +} + +STATIC +EFI_STATUS +EFIAPI +FvbInitialize ( + MEM_INSTANCE *Instance + ) +{ + EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + EFI_STATUS Status; + UINTN Ret; + + if (Instance->Initialized =3D=3D TRUE) { + return EFI_SUCCESS; + } + + // FirmwareVolumeHeader->FvLength is declared to have the Variable area + // AND the FTW working area AND the FTW Spare contiguous. + ASSERT (PcdGet32 (PcdFlashNvStorageVariableBase) + + PcdGet32 (PcdFlashNvStorageVariableSize) =3D=3D + PcdGet32 (PcdFlashNvStorageFtwWorkingBase)); + ASSERT (PcdGet32 (PcdFlashNvStorageFtwWorkingBase) + + PcdGet32 (PcdFlashNvStorageFtwWorkingSize) =3D=3D + PcdGet32 (PcdFlashNvStorageFtwSpareBase)); + + // 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->BlockSiz= e > 0)); + ASSERT ((PcdGet32 (PcdFlashNvStorageFtwSpareSize) > 0) && + (PcdGet32 (PcdFlashNvStorageFtwSpareSize) / Instance->BlockSize = > 0)); + + // Ensure the Variable areas are aligned on block size boundaries + ASSERT ((PcdGet32 (PcdFlashNvStorageVariableBase) % Instance->BlockSize)= =3D=3D 0); + ASSERT ((PcdGet32 (PcdFlashNvStorageFtwWorkingBase) % Instance->BlockSiz= e) =3D=3D 0); + ASSERT ((PcdGet32 (PcdFlashNvStorageFtwSpareBase) % Instance->BlockSize)= =3D=3D 0); + + // Read the file from disk and copy it to memory + ReadEntireFlash (Instance); + + FwVolHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *) Instance->MemBaseAddress; + Status =3D 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 * Instan= ce->BlockSize, ~0UL); + DEBUG ((DEBUG_INFO, "%a: Erasing Flash.\n", __FUNCTION__)); + Ret =3D ReadWriteRpmb(SP_SVC_RPMB_WRITE, Instance->MemBaseAddress, + PcdGet32(PcdFlashNvStorageVariableSize) + + PcdGet32(PcdFlashNvStorageFtwWorkingSize) + + PcdGet32(PcdFlashNvStorageFtwSpareSize), 0); + if (Ret) { + return EFI_DEVICE_ERROR; + } + // Install all appropriate headers + DEBUG ((DEBUG_INFO, "%a: Installing a correct one for this volume.\n", + __FUNCTION__)); + Status =3D InitializeFvAndVariableStoreHeaders (Instance); + if (EFI_ERROR (Status)) { + return Status; + } + } else { + DEBUG ((DEBUG_INFO, "%a: Found valid FVB Header.\n", __FUNCTION__)); + } + Instance->Initialized =3D TRUE; + + return Status; +} + +EFI_STATUS +EFIAPI +OpTeeRpmbFvbInit ( + IN EFI_HANDLE ImageHandle, + IN EFI_MM_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + VOID *Addr; + + Addr =3D AllocatePages(NBLOCKS); + ASSERT (Addr !=3D NULL); + + SetMem (&mInstance, sizeof (mInstance), 0); + + mInstance.FvbProtocol.GetPhysicalAddress =3D OpTeeRpmbFvbGetPhysicalAddr= ess; + mInstance.FvbProtocol.GetAttributes =3D OpTeeRpmbFvbGetAttributes; + mInstance.FvbProtocol.SetAttributes =3D OpTeeRpmbFvbSetAttributes; + mInstance.FvbProtocol.GetBlockSize =3D OpTeeRpmbFvbGetBlockSize; + mInstance.FvbProtocol.EraseBlocks =3D OpTeeRpmbFvbErase; + mInstance.FvbProtocol.Write =3D OpTeeRpmbFvbWrite; + mInstance.FvbProtocol.Read =3D OpTeeRpmbFvbRead; + + mInstance.MemBaseAddress =3D (EFI_PHYSICAL_ADDRESS) Addr; + mInstance.Signature =3D FLASH_SIGNATURE; + mInstance.Initialize =3D FvbInitialize; + mInstance.BlockSize =3D BLOCK_SIZE; + mInstance.NBlocks =3D NBLOCKS; + + // Update the defined PCDs related to Variable Storage + PatchPcdSet32 (PcdFlashNvStorageVariableBase, mInstance.MemBaseAddress); + PatchPcdSet32 (PcdFlashNvStorageFtwWorkingBase, mInstance.MemBaseAddress= + + PcdGet32 (PcdFlashNvStorageVariableSize)); + PatchPcdSet32 (PcdFlashNvStorageFtwSpareBase, mInstance.MemBaseAddress + + PcdGet32 (PcdFlashNvStorageVariableSize) + + PcdGet32 (PcdFlashNvStorageFtwWorkingSize)); + + Status =3D 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__, PatchPcdGet32 (PcdFlashNvStorageVariableBase))); + + return Status; +} --=20 2.17.1 -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- Groups.io Links: You receive all messages sent to this group. View/Reply Online (#66484): https://edk2.groups.io/g/devel/message/66484 Mute This Topic: https://groups.io/mt/77703662/1787277 Group Owner: devel+owner@edk2.groups.io Unsubscribe: https://edk2.groups.io/g/devel/unsub [importer@patchew.org] -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- From nobody Tue May 7 21:50:38 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of groups.io designates 66.175.222.108 as permitted sender) client-ip=66.175.222.108; envelope-from=bounce+27952+66485+1787277+3901457@groups.io; helo=mail02.groups.io; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.108 as permitted sender) smtp.mailfrom=bounce+27952+66485+1787277+3901457@groups.io; dmarc=fail(p=none dis=none) header.from=linaro.org ARC-Seal: i=1; a=rsa-sha256; t=1603282758; cv=none; d=zohomail.com; s=zohoarc; b=kc4+h7ZiKP+b7Of3Equ/rxUhfpcklGS0nngv5xCUBZ3ROYP/DOI81DPAqY/IXwxjP4bgVq7VGCucUiX+Xzp3aG99+vez4aOvrikQXOSBKzN2jDYGoTwyHxPWr4FoCDPufbNMiZmCoJcs1ZBsvqCura8muHEXeLHcNxZGWB+3Vck= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1603282758; h=Cc:Date:From:In-Reply-To:List-Id:List-Unsubscribe:Message-ID:Reply-To:References:Sender:Subject:To; bh=vRpX37khDosU1q/o4AtnOcbQCeUBOekdKHtHYcCnfO0=; b=UvV1dgMLjHQFXP+8VnmT4GtyjFN/cbenXp291iGvMRN0qxMrafDRWqfbpPGtC5KUp8eAd64LlafRKQR9/DkBBxwZOKyAbZvnUMGWFy9g1+Z1tegBHiH0sto1BwAKA9N2R7tw/gciJJIV1OzUf11IHnnFINmB06WtBZYy1LCDoL0= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.108 as permitted sender) smtp.mailfrom=bounce+27952+66485+1787277+3901457@groups.io; dmarc=fail header.from= (p=none dis=none) header.from= Received: from mail02.groups.io (mail02.groups.io [66.175.222.108]) by mx.zohomail.com with SMTPS id 1603282758886977.5650389458872; Wed, 21 Oct 2020 05:19:18 -0700 (PDT) Return-Path: X-Received: by 127.0.0.2 with SMTP id xnWZYY1788612x5sjbcQRtbt; Wed, 21 Oct 2020 05:19:18 -0700 X-Received: from foss.arm.com (foss.arm.com [217.140.110.172]) by mx.groups.io with SMTP id smtpd.web10.10388.1603280149085686551 for ; Wed, 21 Oct 2020 04:35:49 -0700 X-Received: from usa-sjc-imap-foss1.foss.arm.com (unknown [10.121.207.14]) by usa-sjc-mx-foss1.foss.arm.com (Postfix) with ESMTP id CB450D6E; Wed, 21 Oct 2020 04:35:48 -0700 (PDT) X-Received: from a076522.blr.arm.com (a076522.blr.arm.com [10.162.16.44]) by usa-sjc-imap-foss1.foss.arm.com (Postfix) with ESMTPSA id 587123F66E; Wed, 21 Oct 2020 04:35:47 -0700 (PDT) From: "Sughosh Ganu" To: devel@edk2.groups.io Cc: Ard Biesheuvel , Leif Lindholm , Ilias Apalodimas Subject: [edk2-devel] [PATCH edk2-platforms v1 2/2] StMMRpmb: Add support for building StandaloneMm image for OP-TEE Date: Wed, 21 Oct 2020 17:05:34 +0530 Message-Id: <20201021113534.25671-3-sughosh.ganu@linaro.org> In-Reply-To: <20201021113534.25671-1-sughosh.ganu@linaro.org> References: <20201021113534.25671-1-sughosh.ganu@linaro.org> Precedence: Bulk List-Unsubscribe: Sender: devel@edk2.groups.io List-Id: Mailing-List: list devel@edk2.groups.io; contact devel+owner@edk2.groups.io Reply-To: devel@edk2.groups.io,sughosh.ganu@linaro.org X-Gm-Message-State: dT12VaeCsVQ71UZfK3eZCW3dx1787277AA= DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=groups.io; q=dns/txt; s=20140610; t=1603282758; bh=nGyGtgg7qVK8seXzfc092OrMxMMlXUsRH3E4xs/qQwE=; h=Cc:Date:From:Reply-To:Subject:To; b=WR2yQBVdk2uDXis70DphVipWlso60qLozMlhy8Tvh58p3Zpx4rCwzOWAihsVtjM0W+s 4z5JiAMUQR+g1vXpb8o3cnvn6XlW/TbbgboJP6eGHCBNtyQgZXb3kSeP067b8NjxMD1N/ cka6fIzq1J0NW1rZw9PIglEtLPSvyp7XmcA= X-ZohoMail-DKIM: pass (identity @groups.io) Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" From: Ilias Apalodimas With some recent changes in OP-TEE [1] and U-Boot [2] we can compile StMM and launch it from an OP-TEE secure partition which is mimicking SPM. There's a number of advantages in this approach. In Arm world SPM, currently used for dispatching StMM, and SPD used for OP-TEE, are mutually exclusive. Since there's no application in OP-TEE for managing EFI variables, this means that one can have a secure OS or secure variable storage. By re-using StMM we have EDK2s approved application controlling variable storage and the ability to run a secure world OS. This also allows various firmware implementations to adopt EDK2 way of storing variables (including the FTW implementation), as long as OP-TEE is available on that given platform (or any other secure OS that can launch StMM and has a supplicant for handling the RPMB partition). Another advantage is that OP-TEE has the ability to access an eMMC RPMB partition to store those variables. This requires a normal world supplicant, which is implemented in U-Boot currently. The supplicant picks up the encrypted buffer from OP-TEE and wires it to the eMMC driver(s). Similar functionality can be added in EDK2 by porting the supplicant and adapt it to using the native eMMC drivers. There's is one drawback in using OP-TEE. The current SPM calls need to run to completion. This contradicts the current OP-TEE RPC call requirements, used to access the RPMB storage. Thats leads to two different SMC calls for entering secure world to access StMM. So let's add support for a platform that compiles StMM and an RPMB driver that communicates with OP-TEE to read/write the variables. For anyone interested in testing this there's repo that builds all the sources and works on QEMU [3]. [1] https://github.com/OP-TEE/optee_os/pull/3973 [2] http://u-boot.10912.n7.nabble.com/PATCH-0-7-v4-EFI-variable-support-via= -OP-TEE-td412499.html [3] https://git.linaro.org/people/ilias.apalodimas/efi_optee_variables.git/ Signed-off-by: Ilias Apalodimas --- Platform/StMMRpmb/PlatformStandaloneMm.dsc | 182 ++++++++++++++++++++ Platform/StMMRpmb/PlatformStandaloneMm.fdf | 111 ++++++++++++ 2 files changed, 293 insertions(+) diff --git a/Platform/StMMRpmb/PlatformStandaloneMm.dsc b/Platform/StMMRpmb= /PlatformStandaloneMm.dsc new file mode 100644 index 0000000000..e82cd739e1 --- /dev/null +++ b/Platform/StMMRpmb/PlatformStandaloneMm.dsc @@ -0,0 +1,182 @@ +# +# Copyright (c) 2018, ARM Limited. All rights reserved. +# Copyright (c) 2020, Linaro Ltd. All rights reserved. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +##########################################################################= ###### +# +# Defines Section - statements that will be processed to create a Makefile. +# +##########################################################################= ###### +[Defines] + PLATFORM_NAME =3D MmStandaloneRpmb + PLATFORM_GUID =3D A27A486E-D7B9-4D70-9F37-FED9ABE041A2 + PLATFORM_VERSION =3D 1.0 + DSC_SPECIFICATION =3D 0x00010011 + OUTPUT_DIRECTORY =3D Build/$(PLATFORM_NAME) + SUPPORTED_ARCHITECTURES =3D AARCH64 + BUILD_TARGETS =3D DEBUG|RELEASE|NOOPT + SKUID_IDENTIFIER =3D DEFAULT + FLASH_DEFINITION =3D Platform/StMMRpmb/PlatformStandaloneM= m.fdf + DEFINE DEBUG_MESSAGE =3D TRUE + + # LzmaF86 + DEFINE COMPRESSION_TOOL_GUID =3D D42AE6BD-1352-4bfb-909A-CA72A6EAE889 + +##########################################################################= ###### +# +# Library Class section - list of all Library Classes needed by this Platf= orm. +# +##########################################################################= ###### +[LibraryClasses] + ArmSvcLib|ArmPkg/Library/ArmSvcLib/ArmSvcLib.inf + ArmLib|ArmPkg/Library/ArmLib/ArmBaseLib.inf + BaseLib|MdePkg/Library/BaseLib/BaseLib.inf + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf + DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseD= ebugPrintErrorLevelLib.inf + ExtractGuidedSectionLib|EmbeddedPkg/Library/PrePiExtractGuidedSectionLib= /PrePiExtractGuidedSectionLib.inf + FvLib|StandaloneMmPkg/Library/FvLib/FvLib.inf + HobLib|StandaloneMmPkg/Library/StandaloneMmCoreHobLib/StandaloneMmCoreHo= bLib.inf + IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf + MemLib|StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLib.inf + MemoryAllocationLib|StandaloneMmPkg/Library/StandaloneMmCoreMemoryAlloca= tionLib/StandaloneMmCoreMemoryAllocationLib.inf + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseRepor= tStatusCodeLibNull.inf + + # + # Entry point + # + #StandaloneMmCoreEntryPoint|StandaloneMmPkg/Library/StandaloneMmCoreEntr= yPoint/StandaloneMmCoreEntryPoint.inf + StandaloneMmCoreEntryPoint|StandaloneMmPkg/Library/StandaloneMmCoreEntry= Point/StandaloneMmCoreEntryPoint.inf + StandaloneMmDriverEntryPoint|MdePkg/Library/StandaloneMmDriverEntryPoint= /StandaloneMmDriverEntryPoint.inf + + StandaloneMmMmuLib|ArmPkg/Library/StandaloneMmMmuLib/ArmMmuStandaloneMmL= ib.inf + #CacheMaintenanceLib|ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaint= enanceLib.inf + CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLibNull/BaseCache= MaintenanceLibNull.inf + PeCoffExtraActionLib|StandaloneMmPkg/Library/StandaloneMmPeCoffExtraActi= onLib/StandaloneMmPeCoffExtraActionLib.inf + RngLib|MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf + +!if $(UART_ENABLE) + DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf + # ARM PL011 UART Driver + PL011UartClockLib|ArmPlatformPkg/Library/PL011UartClockLib/PL011UartCloc= kLib.inf + PL011UartLib|ArmPlatformPkg/Library/PL011UartLib/PL011UartLib.inf + SerialPortLib|ArmPlatformPkg/Library/PL011SerialPortLib/PL011SerialPortL= ib.inf +!else + SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull= .inf + DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf +!endif + + + # + # It is not possible to prevent the ARM compiler for generic intrinsic f= unctions. + # This library provides the intrinsic functions generate by a given comp= iler. + # NULL means link this library into all ARM images. + # + NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf + +[LibraryClasses.common.MM_STANDALONE] + HobLib|StandaloneMmPkg/Library/StandaloneMmHobLib/StandaloneMmHobLib.inf + MmServicesTableLib|MdePkg/Library/StandaloneMmServicesTableLib/Standalon= eMmServicesTableLib.inf + MemoryAllocationLib|StandaloneMmPkg/Library/StandaloneMmMemoryAllocation= Lib/StandaloneMmMemoryAllocationLib.inf + + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf + PlatformSecureLib|SecurityPkg/Library/PlatformSecureLibNull/PlatformSecu= reLibNull.inf + SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchroniza= tionLib.inf + TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplat= e.inf +##########################################################################= ###### +# +# Pcd Section - list of all EDK II PCD Entries defined by this Platform +# +##########################################################################= ###### + +[PcdsFeatureFlag.common] + gArmTokenSpaceGuid.PcdFfaEnable|TRUE + +[PcdsFixedAtBuild] + gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x800000CF + gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0xff + gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x0f + +!if $(UART_ENABLE) + # PL011 - Serial Terminal + gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterBase|0x40418000 + gEfiMdePkgTokenSpaceGuid.PcdUartDefaultBaudRate|115200 + gArmPlatformTokenSpaceGuid.PL011UartClkInHz|0xA6E49C0 + gEfiMdePkgTokenSpaceGuid.PcdUartDefaultReceiveFifoDepth|0 +!endif + + gEfiMdePkgTokenSpaceGuid.PcdMaximumGuidedExtractHandler|0x2 + # Secure Storage + gEfiSecurityPkgTokenSpaceGuid.PcdUserPhysicalPresence|TRUE + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x2000 + gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x2800 + + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize|0x00004000 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize|0x00004000 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize|0x00004000 + gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize|0x00004000 + +[PcdsPatchableInModule] + # Allocated memory for EDK2 uppers layers + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase|0x0 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0x0 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|0x0 + +##########################################################################= ######################### +# +# Components Section - list of the modules and components that will be pro= cessed by compilation +# tools and the EDK II tools to generate PE32/PE32+/C= off image files. +# +# Note: The EDK II DSC file is not used to specify how compiled binary ima= ges get placed +# into firmware volume images. This section is just a list of module= s to compile from +# source into UEFI-compliant binaries. +# It is the FDF file that contains information on combining binary f= iles into firmware +# volume images, whose concept is beyond UEFI and is described in PI= specification. +# Binary modules do not need to be listed in this section, as they s= hould be +# specified in the FDF file. For example: Shell binary (Shell_Full.e= fi), FAT binary (Fat.efi), +# Logo (Logo.bmp), and etc. +# There may also be modules listed in this section that are not requ= ired in the FDF file, +# When a module listed here is excluded from FDF file, then UEFI-com= pliant binary will be +# generated for it, but the binary will not be put into any firmware= volume. +# +##########################################################################= ######################### +[Components.common] + # + # Standalone MM components + # + Drivers/OpTeeRpmb/OpTeeRpmbFv.inf + StandaloneMmPkg/Core/StandaloneMmCore.inf + StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/StandaloneMmCpu.inf + MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandalon= eMm.inf { + + NULL|Drivers/OpTeeRpmb/FixupPcd.inf + } + MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf { + + AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.= inf + BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf + NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf + NULL|Drivers/OpTeeRpmb/FixupPcd.inf + } + +##########################################################################= ######################### +# +# BuildOptions Section - Define the module specific tool chain flags that = should be used as +# the default flags for a module. These flags are a= ppended to any +# standard flags that are defined by the build proc= ess. They can be +# applied for any modules or only those modules wit= h the specific +# module style (EDK or EDKII) specified in [Compone= nts] section. +# +##########################################################################= ######################### +[BuildOptions.AARCH64] +GCC:*_*_*_DLINK_FLAGS =3D -z common-page-size=3D0x1000 -march=3Darmv8-a+no= fp +GCC:*_*_*_CC_FLAGS =3D -mstrict-align diff --git a/Platform/StMMRpmb/PlatformStandaloneMm.fdf b/Platform/StMMRpmb= /PlatformStandaloneMm.fdf new file mode 100644 index 0000000000..febc6d0d95 --- /dev/null +++ b/Platform/StMMRpmb/PlatformStandaloneMm.fdf @@ -0,0 +1,111 @@ +# +# Copyright (c) 2018, ARM Limited. All rights reserved. +# Copyright (c) 2020, Linaro Ltd. All rights reserved. +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +##########################################################################= ###### +# +# FD Section +# The [FD] Section is made up of the definition statements and a +# description of what goes into the Flash Device Image. Each FD section +# defines one flash "device" image. A flash device image may be one of +# the following: Removable media bootable image (like a boot floppy +# image,) an Option ROM image (that would be "flashed" into an add-in +# card,) a System "Flash" image (that would be burned into a system's +# flash) or an Update ("Capsule") image that will be used to update and +# existing system flash. +# +##########################################################################= ###### + +[FD.BL32_AP_MM] +BaseAddress =3D 0x1000 # any address apart from 0x0 +Size =3D 0x00300000 +ErasePolarity =3D 1 + +BlockSize =3D 0x00001000 +NumBlocks =3D 0x0300 + +##########################################################################= ###### +# +# Following are lists of FD Region layout which correspond to the location= s of different +# images within the flash device. +# +# Regions must be defined in ascending order and may not overlap. +# +# A Layout Region start with a eight digit hex offset (leading "0x" requir= ed) followed by +# the pipe "|" character, followed by the size of the region, also in hex = with the leading +# "0x" characters. Like: +# Offset|Size +# PcdOffsetCName|PcdSizeCName +# RegionType +# +##########################################################################= ###### + +0x00000000|0x00280000 +FV =3D FVMAIN_COMPACT + +[FV.FVMAIN_COMPACT] +FvAlignment =3D 8 +ERASE_POLARITY =3D 1 +MEMORY_MAPPED =3D TRUE +STICKY_WRITE =3D TRUE +LOCK_CAP =3D TRUE +LOCK_STATUS =3D TRUE +WRITE_DISABLED_CAP =3D TRUE +WRITE_ENABLED_CAP =3D TRUE +WRITE_STATUS =3D TRUE +WRITE_LOCK_CAP =3D TRUE +WRITE_LOCK_STATUS =3D TRUE +READ_DISABLED_CAP =3D TRUE +READ_ENABLED_CAP =3D TRUE +READ_STATUS =3D TRUE +READ_LOCK_CAP =3D TRUE +READ_LOCK_STATUS =3D TRUE + + INF StandaloneMmPkg/Core/StandaloneMmCore.inf + INF Drivers/OpTeeRpmb/OpTeeRpmbFv.inf + INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStand= aloneMm.inf + INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf + INF StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/StandaloneMmCpu.inf +##########################################################################= ###### +# +# Rules are use with the [FV] section's module INF type to define +# how an FFS file is created for a given INF file. The following Rule are = the default +# rules for the different module type. User can add the customized rules t= o define the +# content of the FFS file. +# +##########################################################################= ###### + + +##########################################################################= ## +# Example of a DXE_DRIVER FFS file with a Checksum encapsulation section = # +##########################################################################= ## +# +#[Rule.Common.DXE_DRIVER] +# FILE DRIVER =3D $(NAMED_GUID) { +# DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_= NAME).depex +# COMPRESS PI_STD { +# GUIDED { +# PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi +# UI STRING=3D"$(MODULE_NAME)" Optional +# VERSION STRING=3D"$(INF_VERSION)" Optional BUILD_NUM=3D$(BUILD_N= UMBER) +# } +# } +# } +# +##########################################################################= ## + +[Rule.Common.MM_CORE_STANDALONE] + FILE SEC =3D $(NAMED_GUID) FIXED { + PE32 PE32 Align =3D Auto $(INF_OUTPUT)/$(MODULE_NAME).efi + } + +[Rule.Common.MM_STANDALONE] + FILE MM_STANDALONE =3D $(NAMED_GUID) { + SMM_DEPEX SMM_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex + PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi + UI STRING=3D"$(MODULE_NAME)" Optional + VERSION STRING=3D"$(INF_VERSION)" Optional BUILD_NUM=3D$(BUILD_NUMBE= R) + } --=20 2.17.1 -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- Groups.io Links: You receive all messages sent to this group. View/Reply Online (#66485): https://edk2.groups.io/g/devel/message/66485 Mute This Topic: https://groups.io/mt/77703664/1787277 Group Owner: devel+owner@edk2.groups.io Unsubscribe: https://edk2.groups.io/g/devel/unsub [importer@patchew.org] -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-