Add fwu deployment configuration for SP

Extends fwu deployment with a configuration for running the
update agent within an SP. To support FVP/Qemu based testing,
secure flash is implemented using a file residing on the host
PC, accessed using semihosting.

Signed-off-by: Julian Hall <julian.hall@arm.com>
Change-Id: I216db494129d32822cb8e2011b0924fa1cc4e978
diff --git a/deployments/fwu/config/default-opteesp/CMakeLists.txt b/deployments/fwu/config/default-opteesp/CMakeLists.txt
new file mode 100644
index 0000000..3a00d45
--- /dev/null
+++ b/deployments/fwu/config/default-opteesp/CMakeLists.txt
@@ -0,0 +1,103 @@
+#-------------------------------------------------------------------------------
+# Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+#
+#-------------------------------------------------------------------------------
+cmake_minimum_required(VERSION 3.18 FATAL_ERROR)
+
+# Set default platform.
+set(TS_PLATFORM "arm/fvp/fvp_base_revc-2xaemv8a" CACHE STRING "Target platform location.")
+include(../../../deployment.cmake REQUIRED)
+
+#-------------------------------------------------------------------------------
+#  The CMakeLists.txt for building the default fwu deployment for opteesp
+#
+#  Builds the fwu service provider for running in an SEL0 secure partition
+#  hosted by OPTEE in the role of SPM.
+#-------------------------------------------------------------------------------
+include(${TS_ROOT}/environments/opteesp/env.cmake)
+project(trusted-services LANGUAGES C ASM)
+add_executable(fwu)
+target_include_directories(fwu PRIVATE "${TOP_LEVEL_INCLUDE_DIRS}")
+set(SP_UUID_CANON "6823a838-1b06-470e-9774-0cce8bfb53fd")
+set(SP_HEAP_SIZE "32 * 1024" CACHE STRING "SP heap size in bytes")
+include(${TS_ROOT}/tools/cmake/common/TargetCompileDefinitions.cmake)
+set_target_uuids(
+	SP_UUID ${SP_UUID_CANON}
+	SP_NAME "fwu"
+)
+
+target_include_directories(fwu PRIVATE
+	${CMAKE_CURRENT_LIST_DIR}
+)
+
+#-------------------------------------------------------------------------------
+#  Configure trace output
+#
+#-------------------------------------------------------------------------------
+set(TRACE_PREFIX "FWU" CACHE STRING "Trace prefix")
+set(TRACE_LEVEL "TRACE_LEVEL_DEBUG" CACHE STRING "Trace level")
+
+#-------------------------------------------------------------------------------
+#  Deployment specific components
+#
+#-------------------------------------------------------------------------------
+add_components(TARGET "fwu"
+	BASE_DIR ${TS_ROOT}
+	COMPONENTS
+		"environments/opteesp"
+)
+
+include(../../env/commonsp/fwu_sp.cmake REQUIRED)
+include(../../infra/semihosted-block-store.cmake REQUIRED)
+include(../../fwu.cmake REQUIRED)
+
+#-------------------------------------------------------------------------------
+#  Set target platform to provide drivers needed by the deployment
+#
+#-------------------------------------------------------------------------------
+add_platform(TARGET "fwu")
+
+#-------------------------------------------------------------------------------
+#  Deployment specific build options
+#-------------------------------------------------------------------------------
+target_compile_definitions(fwu PRIVATE
+	ARM64=1
+)
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
+	target_compile_options(fwu PRIVATE
+		-std=c99
+	)
+
+endif()
+
+compiler_generate_stripped_elf(TARGET fwu NAME "${SP_UUID_CANON}.stripped.elf" RES STRIPPED_ELF)
+
+#-------------------------------------------------------------------------------
+#  Deployment specific install options
+#-------------------------------------------------------------------------------
+if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
+	set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/install CACHE PATH "location to install build output to." FORCE)
+endif()
+#TODO: api headers
+
+install(TARGETS fwu
+			PUBLIC_HEADER DESTINATION ${TS_ENV}/include
+			RUNTIME DESTINATION ${TS_ENV}/bin
+		)
+install(FILES ${STRIPPED_ELF} DESTINATION ${TS_ENV}/bin)
+
+get_property(_PROTO_FILES TARGET fwu PROPERTY PROTOBUF_FILES)
+install(FILES ${_PROTO_FILES} DESTINATION ${TS_ENV}/lib/protobuf)
+
+include(${TS_ROOT}/tools/cmake/common/ExportSp.cmake)
+export_sp(
+	SP_UUID_CANON ${SP_UUID_CANON}
+	SP_UUID_LE ${SP_UUID_LE}
+	SP_NAME "fwu"
+	MK_IN ${TS_ROOT}/environments/opteesp/sp.mk.in
+	DTS_IN ${CMAKE_CURRENT_LIST_DIR}/default_fwu.dts.in
+	JSON_IN ${TS_ROOT}/environments/opteesp/sp_pkg.json.in
+)
diff --git a/deployments/fwu/config/default-opteesp/default_fwu.dts.in b/deployments/fwu/config/default-opteesp/default_fwu.dts.in
new file mode 100644
index 0000000..b850174
--- /dev/null
+++ b/deployments/fwu/config/default-opteesp/default_fwu.dts.in
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+@DTS_TAG@
+
+@DTS_NODE@ {
+	compatible = "arm,ffa-manifest-1.0";
+	ffa-version = <0x00010000>; /* 31:16 - Major, 15:0 - Minor */
+	uuid = <@EXPORT_SP_UUID_DT@>;
+	description = "FWU";
+	execution-ctx-count = <1>;
+	exception-level = <1>; /* S-EL0 */
+	execution-state = <0>; /* AArch64 */
+	xlat-granule = <0>; /* 4KiB */
+	messaging-method = <3>; /* Direct messaging only */
+	elf-format = <1>;
+};
diff --git a/deployments/fwu/config/default-opteesp/optee_sp_user_defines.h b/deployments/fwu/config/default-opteesp/optee_sp_user_defines.h
new file mode 100644
index 0000000..66cd9f2
--- /dev/null
+++ b/deployments/fwu/config/default-opteesp/optee_sp_user_defines.h
@@ -0,0 +1,14 @@
+/* SPDX-License-Identifier: BSD-3-Clause */
+/*
+ * Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
+ */
+
+#ifndef OPTEE_SP_USER_DEFINES_H
+#define OPTEE_SP_USER_DEFINES_H
+
+#define OPTEE_SP_FLAGS				0
+
+/* Provisioned stack size */
+#define OPTEE_SP_STACK_SIZE			(64 * 1024)
+
+#endif /* SP_HEADER_DEFINES_H */
diff --git a/deployments/fwu/config/default-sp/CMakeLists.txt b/deployments/fwu/config/default-sp/CMakeLists.txt
new file mode 100644
index 0000000..dcc62da
--- /dev/null
+++ b/deployments/fwu/config/default-sp/CMakeLists.txt
@@ -0,0 +1,97 @@
+#-------------------------------------------------------------------------------
+# Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+#
+#-------------------------------------------------------------------------------
+cmake_minimum_required(VERSION 3.18 FATAL_ERROR)
+
+# Set default platform.
+set(TS_PLATFORM "arm/fvp/fvp_base_revc-2xaemv8a" CACHE STRING "Target platform location.")
+include(../../../deployment.cmake REQUIRED)
+
+#-------------------------------------------------------------------------------
+#  The CMakeLists.txt for building the fwu deployment for generic sp
+#  environment.
+#
+#  Builds the fwu service provider for running in an SEL0 secure
+#  partition hosted by any SPM.
+#-------------------------------------------------------------------------------
+include(${TS_ROOT}/environments/sp/env.cmake)
+set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Build type")
+project(trusted-services LANGUAGES C ASM)
+add_executable(fwu)
+target_include_directories(fwu PRIVATE "${TOP_LEVEL_INCLUDE_DIRS}")
+set(SP_NAME "fwu")
+set(SP_UUID_CANON "6823a838-1b06-470e-9774-0cce8bfb53fd")
+set(SP_UUID_LE "0x38a82368 0x0e47061b 0xce0c7497 0xfd53fb8b")
+set(SP_STACK_SIZE "64 * 1024" CACHE STRING "Stack size")
+set(SP_HEAP_SIZE "32 * 1024" CACHE STRING "Heap size")
+
+#-------------------------------------------------------------------------------
+#  Configure trace output
+#
+#-------------------------------------------------------------------------------
+set(TRACE_PREFIX "FWU" CACHE STRING "Trace prefix")
+set(TRACE_LEVEL "TRACE_LEVEL_DEBUG" CACHE STRING "Trace level")
+
+#-------------------------------------------------------------------------------
+#  Components that are specific to deployment in the sp environment.
+#
+#-------------------------------------------------------------------------------
+add_components(TARGET "fwu"
+	BASE_DIR ${TS_ROOT}
+	COMPONENTS
+		environments/sp
+)
+
+include(../../env/commonsp/fwu_sp.cmake REQUIRED)
+include(../../infra/semihosted-block-store.cmake REQUIRED)
+include(../../fwu.cmake REQUIRED)
+
+#-------------------------------------------------------------------------------
+#  Set target platform to provide drivers needed by the deployment
+#
+#-------------------------------------------------------------------------------
+add_platform(TARGET "fwu")
+
+#-------------------------------------------------------------------------------
+#  Deployment specific build options
+#-------------------------------------------------------------------------------
+target_compile_definitions(fwu PRIVATE
+	ARM64=1
+)
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
+	target_compile_options(fwu PRIVATE
+		-std=c99
+	)
+
+endif()
+
+compiler_generate_binary_output(TARGET fwu NAME "${SP_UUID_CANON}.bin" SP_BINARY)
+install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${SP_UUID_CANON}.bin DESTINATION ${TS_ENV}/bin)
+
+include(${TS_ROOT}/tools/cmake/common/ExportMemoryRegionsToManifest.cmake REQUIRED)
+export_memory_regions_to_manifest(TARGET fwu NAME "${SP_UUID_CANON}_memory_regions.dtsi" RES EXPORT_MEMORY_REGIONS_DTSI)
+
+#-------------------------------------------------------------------------------
+#  Deployment specific install options
+#-------------------------------------------------------------------------------
+if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
+	set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/install CACHE PATH "location to install build output to." FORCE)
+endif()
+install(TARGETS fwu
+			PUBLIC_HEADER DESTINATION ${TS_ENV}/include
+			RUNTIME DESTINATION ${TS_ENV}/bin
+		)
+
+include(${TS_ROOT}/tools/cmake/common/ExportSp.cmake)
+export_sp(
+	SP_UUID_CANON ${SP_UUID_CANON}
+	SP_UUID_LE ${SP_UUID_LE}
+	SP_NAME ${SP_NAME}
+	DTS_IN ${CMAKE_CURRENT_LIST_DIR}/default_${SP_NAME}.dts.in
+	DTS_MEM_REGIONS ${SP_UUID_CANON}_memory_regions.dtsi
+	JSON_IN ${TS_ROOT}/environments/sp/sp_pkg.json.in
+)
diff --git a/deployments/fwu/config/default-sp/default_fwu.dts.in b/deployments/fwu/config/default-sp/default_fwu.dts.in
new file mode 100644
index 0000000..dabba0b
--- /dev/null
+++ b/deployments/fwu/config/default-sp/default_fwu.dts.in
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+@DTS_TAG@
+
+@DTS_NODE@ {
+	compatible = "arm,ffa-manifest-1.0";
+	ffa-version = <0x00010000>; /* 31:16 - Major, 15:0 - Minor */
+	uuid = <@EXPORT_SP_UUID_DT@>;
+	description = "FWU";
+	execution-ctx-count = <1>;
+	exception-level = <1>; /* S-EL0 */
+	execution-state = <0>; /* AArch64 */
+	xlat-granule = <0>; /* 4KiB */
+	messaging-method = <3>; /* Direct messaging only */
+};
diff --git a/deployments/fwu/env/commonsp/fwu_sp.c b/deployments/fwu/env/commonsp/fwu_sp.c
new file mode 100644
index 0000000..016ec50
--- /dev/null
+++ b/deployments/fwu/env/commonsp/fwu_sp.c
@@ -0,0 +1,206 @@
+// SPDX-License-Identifier: BSD-3-Clause
+/*
+ * Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
+ */
+
+#include <stddef.h>
+#include <sp_api.h>
+#include <sp_discovery.h>
+#include <sp_messaging.h>
+#include <sp_rxtx.h>
+#include <trace.h>
+#include <rpc/ffarpc/endpoint/ffarpc_call_ep.h>
+#include <protocols/rpc/common/packed-c/status.h>
+#include <config/ramstore/config_ramstore.h>
+#include <config/loader/sp/sp_config_loader.h>
+#include <media/volume/factory/volume_factory.h>
+#include <service/fwu/config/fwu_configure.h>
+#include <service/discovery/provider/discovery_provider.h>
+#include <service/discovery/provider/serializer/packed-c/packedc_discovery_provider_serializer.h>
+#include <service/fwu/provider/fwu_provider.h>
+#include <service/fwu/provider/serializer/packed-c/packedc_fwu_provider_serializer.h>
+#include <service/fwu/fw_store/banked/bank_scheme.h>
+#include <service/fwu/fw_store/banked/metadata_serializer/v1/metadata_serializer_v1.h>
+#include <service/fwu/fw_store/banked/metadata_serializer/v2/metadata_serializer_v2.h>
+#include <service/fwu/inspector/direct/direct_fw_inspector.h>
+#include <service/fwu/agent/update_agent.h>
+#include <service/fwu/fw_store/banked/banked_fw_store.h>
+
+
+/* Set default limit on the number of storage devices to update */
+#ifndef FWU_SP_MAX_STORAGE_DEVICES
+#define FWU_SP_MAX_STORAGE_DEVICES		(1)
+#endif
+
+/* Parameters that should be passed forward by the bootloader */
+#define HARD_CODED_BOOT_INDEX			(0)
+#define HARD_CODED_METADATA_VER			(2)
+
+
+static bool sp_init(uint16_t *own_sp_id);
+static bool configure_for_platform(void);
+const struct metadata_serializer *select_metadata_serializer(unsigned int version);
+
+void __noreturn sp_main(struct ffa_init_info *init_info)
+{
+	struct ffa_call_ep ffarpc_call_ep = { 0 };
+	struct fwu_provider service_provider = { 0 };
+	struct rpc_interface *service_iface = NULL;
+	struct update_agent update_agent = { 0 };
+	struct fw_store fw_store = { 0 };
+	struct sp_msg req_msg = { 0 };
+	struct sp_msg resp_msg = { 0 };
+	uint16_t own_id = 0;
+	sp_result result = SP_RESULT_INTERNAL_ERROR;
+
+	/* Boot phase */
+	if (!sp_init(&own_id)) {
+		EMSG("Failed to init SP");
+		goto fatal_error;
+	}
+
+	config_ramstore_init();
+
+	if (!sp_config_load(init_info)) {
+		EMSG("Failed to load SP config");
+		goto fatal_error;
+	}
+
+	/* Configuration - discovers required volumes and installers */
+	if (!configure_for_platform()) {
+		EMSG("Failed to configure for platform");
+		goto fatal_error;
+	}
+
+	/* Select FWU metadata serializer for compatibility with bootloader */
+	const struct metadata_serializer *serializer =
+		select_metadata_serializer(HARD_CODED_METADATA_VER);
+
+	if (!serializer) {
+		EMSG("Unsupported FWU metadata version");
+		goto fatal_error;
+	}
+
+	/* Initialise fw store */
+	if (banked_fw_store_init(&fw_store, serializer)) {
+		EMSG("Failed to init fw store");
+		goto fatal_error;
+	}
+
+	if (update_agent_init(&update_agent, HARD_CODED_BOOT_INDEX,
+			direct_fw_inspector_inspect, &fw_store)) {
+		EMSG("Failed to init update agent");
+		goto fatal_error;
+	}
+
+	/* Initialise the FWU service provider */
+	service_iface = fwu_provider_init(
+		&service_provider,
+		&update_agent);
+
+	if (!service_iface) {
+		EMSG("Failed to init service provider");
+		goto fatal_error;
+	}
+
+	fwu_provider_register_serializer(
+		&service_provider,
+		TS_RPC_ENCODING_PACKED_C,
+		packedc_fwu_provider_serializer_instance());
+
+	discovery_provider_register_serializer(
+		&service_provider.discovery_provider,
+		TS_RPC_ENCODING_PACKED_C,
+		packedc_discovery_provider_serializer_instance());
+
+	/* Associate service interface with FFA call endpoint */
+	ffa_call_ep_init(&ffarpc_call_ep, service_iface, own_id);
+
+	/* End of boot phase */
+	result = sp_msg_wait(&req_msg);
+	if (result != SP_RESULT_OK) {
+		EMSG("Failed to send message wait %d", result);
+		goto fatal_error;
+	}
+
+	while (1) {
+		ffa_call_ep_receive(&ffarpc_call_ep, &req_msg, &resp_msg);
+
+		result = sp_msg_send_direct_resp(&resp_msg, &req_msg);
+		if (result != SP_RESULT_OK) {
+			EMSG("Failed to send direct response %d", result);
+			result = sp_msg_wait(&req_msg);
+			if (result != SP_RESULT_OK) {
+				EMSG("Failed to send message wait %d", result);
+				goto fatal_error;
+			}
+		}
+	}
+
+fatal_error:
+	/* SP is not viable */
+	EMSG("FWU SP error");
+	while (1) {}
+}
+
+void sp_interrupt_handler(uint32_t interrupt_id)
+{
+	(void)interrupt_id;
+}
+
+static bool sp_init(uint16_t *own_id)
+{
+	sp_result sp_res = SP_RESULT_INTERNAL_ERROR;
+	static uint8_t tx_buffer[4096] __aligned(4096);
+	static uint8_t rx_buffer[4096] __aligned(4096);
+
+	sp_res = sp_rxtx_buffer_map(tx_buffer, rx_buffer, sizeof(rx_buffer));
+	if (sp_res != SP_RESULT_OK) {
+		EMSG("Failed to map RXTX buffers: %d", sp_res);
+		return false;
+	}
+
+	sp_res = sp_discovery_own_id_get(own_id);
+	if (sp_res != SP_RESULT_OK) {
+		EMSG("Failed to query own ID: %d", sp_res);
+		return false;
+	}
+
+	return true;
+}
+
+static bool configure_for_platform(void)
+{
+	struct uuid_octets device_uuids[FWU_SP_MAX_STORAGE_DEVICES];
+	size_t num_storage_devices = 0;
+
+	int status = volume_factory_init(device_uuids,
+		FWU_SP_MAX_STORAGE_DEVICES, &num_storage_devices);
+
+	if (status) {
+
+		EMSG("Failed to init volume factory: %d", status);
+		return false;
+	}
+
+	status = fwu_configure(device_uuids, num_storage_devices);
+
+	if (status) {
+
+		EMSG("Failed to setup FWU configuration: %d", status);
+		return false;
+	}
+
+	return true;
+}
+
+const struct metadata_serializer *select_metadata_serializer(unsigned int version)
+{
+	if (version == 1)
+		return metadata_serializer_v1();
+
+	if (version == 2)
+		return metadata_serializer_v2();
+
+	return NULL;
+}
\ No newline at end of file
diff --git a/deployments/fwu/env/commonsp/fwu_sp.cmake b/deployments/fwu/env/commonsp/fwu_sp.cmake
new file mode 100644
index 0000000..20d62b8
--- /dev/null
+++ b/deployments/fwu/env/commonsp/fwu_sp.cmake
@@ -0,0 +1,35 @@
+#-------------------------------------------------------------------------------
+# Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+#
+# Includes components needed for deploying the fwu service provider
+# within a secure partition.
+#-------------------------------------------------------------------------------
+
+#-------------------------------------------------------------------------------
+# Common components for fwu sp deployments
+#
+#-------------------------------------------------------------------------------
+add_components(TARGET "fwu"
+	BASE_DIR ${TS_ROOT}
+	COMPONENTS
+		"components/common/fdt"
+		"components/common/trace"
+		"components/common/utils"
+		"components/common/crc32/native"
+		"components/config/ramstore"
+		"components/config/loader/sp"
+		"components/messaging/ffa/libsp"
+		"components/rpc/common/interface"
+		"components/rpc/ffarpc/endpoint"
+		"components/service/common/provider"
+		"components/service/fwu/provider"
+		"components/service/fwu/provider/serializer/packed-c"
+		"components/service/discovery/provider"
+		"components/service/discovery/provider/serializer/packed-c"
+)
+
+target_sources(fwu PRIVATE
+	${CMAKE_CURRENT_LIST_DIR}/fwu_sp.c
+)
diff --git a/deployments/fwu/infra/semihosted-block-store.cmake b/deployments/fwu/infra/semihosted-block-store.cmake
new file mode 100644
index 0000000..5d95077
--- /dev/null
+++ b/deployments/fwu/infra/semihosted-block-store.cmake
@@ -0,0 +1,39 @@
+#-------------------------------------------------------------------------------
+# Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
+#
+# SPDX-License-Identifier: BSD-3-Clause
+#
+# A fwu infrastructure where there is a flash device dedicated to holding
+# device firmware and FWU metadata. Flash is assumed to be UEFI formated
+# (MBR/GPT) with separate partitions for primary/backup metadata and
+# A/B banks for firmware storage. The flash is actually realized by a file
+# residing on the host machine and is accessed using semihosting. This
+# infrastructure is intended for FVP/Qemu based testing.
+#-------------------------------------------------------------------------------
+
+#-------------------------------------------------------------------------------
+#  External project source-level dependencies
+#
+#-------------------------------------------------------------------------------
+include(${TS_ROOT}/external/tf_a/tf-a.cmake)
+add_tfa_dependency(TARGET "fwu")
+
+#-------------------------------------------------------------------------------
+# Infrastructure components
+#
+#-------------------------------------------------------------------------------
+add_components(TARGET "fwu"
+	BASE_DIR ${TS_ROOT}
+	COMPONENTS
+		"components/media/disk"
+		"components/media/volume"
+		"components/media/volume/base_io_dev"
+		"components/media/volume/block_volume"
+		"components/media/volume/factory/single_flash"
+		"components/service/block_storage/block_store"
+		"components/service/block_storage/block_store/device"
+		"components/service/block_storage/block_store/device/semihosting"
+		"components/service/block_storage/block_store/partitioned"
+		"components/service/block_storage/factory/semihosting"
+		"components/service/block_storage/config/gpt"
+)