Date   

Re: [RFC PATCH 02/14] OvmfPkg/PlatformPei: Mark SEC GHCB page in the page encrpytion bitmap.

Tobin Feldman-Fitzthum <tobin@...>
 

Hello Tobin,

Just a high level question, why is this patch included in this
patch series, i don't think you are supporting SEV-ES platform
migration in this patch-set ?
You are correct that we don't support migration for SEV-ES machines, although our approach can potentially be adapted for SEV-ES. I was on the fence about including this patch, because we don't strictly need it for migration. I'm not sure if the SEC GHCB would be significant even if we did support SEV-ES migration. Ultimately it seemed like a good idea because the SEV firmware build does otherwise support SEV-ES. Since I was introducing the hypercall in an environment where SEV-ES can be enabled, it seemed reasonable to include. Syncing page encryption status hypothetically has uses beyond migration.

Note that I am not adding full support for the hypercall in OVMF, which might be a good idea at some point.

-Tobin

Thanks,
Ashish

On Tue, Mar 02, 2021 at 03:48:27PM -0500, Tobin Feldman-Fitzthum wrote:
From: Ashish Kalra <ashish.kalra@...>

Mark the SEC GHCB page that is mapped as unencrypted in
ResetVector code in the hypervisor page encryption bitmap.

Cc: Jordan Justen <jordan.l.justen@...>
Cc: Laszlo Ersek <lersek@...>
Cc: Ard Biesheuvel <ard.biesheuvel@...>

Signed-off-by: Ashish Kalra <ashish.kalra@...>
---
OvmfPkg/PlatformPei/AmdSev.c | 10 ++++++++++
1 file changed, 10 insertions(+)

diff --git a/OvmfPkg/PlatformPei/AmdSev.c b/OvmfPkg/PlatformPei/AmdSev.c
index dddffdebda..c72eeb37c5 100644
--- a/OvmfPkg/PlatformPei/AmdSev.c
+++ b/OvmfPkg/PlatformPei/AmdSev.c
@@ -15,6 +15,7 @@
#include <Library/HobLib.h>
#include <Library/MemEncryptSevLib.h>
#include <Library/MemoryAllocationLib.h>
+#include <Library/MemEncryptHypercallLib.h>
#include <Library/PcdLib.h>
#include <PiPei.h>
#include <Register/Amd/Msr.h>
@@ -52,6 +53,15 @@ AmdSevEsInitialize (
PcdStatus = PcdSetBoolS (PcdSevEsIsEnabled, TRUE);
ASSERT_RETURN_ERROR (PcdStatus);
+ //
+ // GHCB_BASE setup during reset-vector needs to be marked as
+ // decrypted in the hypervisor page encryption bitmap.
+ //
+ SetMemoryEncDecHypercall3 (FixedPcdGet32 (PcdOvmfSecGhcbBase),
+ EFI_SIZE_TO_PAGES(FixedPcdGet32 (PcdOvmfSecGhcbSize)),
+ FALSE
+ );
+
//
// Allocate GHCB and per-CPU variable pages.
// Since the pages must survive across the UEFI to OS transition
--
2.20.1


[PATCH] RedfishPkg/Library: RedfishLib

Abner Chang
 

EDK2 port of DMTF libredfish project. We clone the necessary files from
open source project libredfish (https://github.com/DMTF/libredfish) tag
v1.0.0 and revise it to incorporate with edk2 firmware code base.

The reason of cloning the necessary files instead of using extern
submodule of libredfish project:
libredfish as a C library which is executed under Windows and Linux.
It could be binded with other programming languages such as java and
python. The library uses curl library as the communication service with
Redfish, which is not easy to be abstracted and replaced with EFI specific
protocols (e.g. EFI_REST_EX_PROTOCOL or payload encode/decode library)
and EFI data types. We had the conversation with DMTF community and they
think edk2 is a firmware solution but not the programming language,
therefore they rejected to have edk2 as a binding to libredfish.
According to above, we decide to clone the necessary files from libredfish
modify it to incorporate with edk2.

Signed-off-by: Jiaxin Wu <jiaxin.wu@...>
Signed-off-by: Ting Ye <ting.ye@...>
Signed-off-by: Siyuan Fu <siyuan.fu@...>
Signed-off-by: Fan Wang <fan.wang@...>
Signed-off-by: Abner Chang <abner.chang@...>

Cc: Nickle Wang <nickle.wang@...>
---
RedfishPkg/RedfishPkg.dec | 4 +
RedfishPkg/RedfishLibs.dsc.inc | 3 +-
RedfishPkg/RedfishPkg.dsc | 1 +
.../PrivateLibrary/RedfishLib/RedfishLib.inf | 60 +
.../PrivateInclude/Library/RedfishLib.h | 611 ++++++++
.../PrivateLibrary/RedfishLib/RedfishMisc.h | 82 +
.../edk2libredfish/include/redfish.h | 24 +
.../edk2libredfish/include/redfishPayload.h | 39 +
.../edk2libredfish/include/redfishService.h | 101 ++
.../edk2libredfish/include/redpath.h | 42 +
.../PrivateLibrary/RedfishLib/RedfishLib.c | 993 ++++++++++++
.../PrivateLibrary/RedfishLib/RedfishMisc.c | 201 +++
.../RedfishLib/edk2libredfish/src/payload.c | 732 +++++++++
.../RedfishLib/edk2libredfish/src/redpath.c | 192 +++
.../RedfishLib/edk2libredfish/src/service.c | 1396 +++++++++++++++++
RedfishPkg/RedfishPkg.ci.yaml | 15 +-
16 files changed, 4493 insertions(+), 3 deletions(-)
create mode 100644 RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.inf
create mode 100644 RedfishPkg/PrivateInclude/Library/RedfishLib.h
create mode 100644 RedfishPkg/PrivateLibrary/RedfishLib/RedfishMisc.h
create mode 100644 RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfish.h
create mode 100644 RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfishPayload.h
create mode 100644 RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfishService.h
create mode 100644 RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redpath.h
create mode 100644 RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.c
create mode 100644 RedfishPkg/PrivateLibrary/RedfishLib/RedfishMisc.c
create mode 100644 RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/payload.c
create mode 100644 RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/redpath.c
create mode 100644 RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/service.c

diff --git a/RedfishPkg/RedfishPkg.dec b/RedfishPkg/RedfishPkg.dec
index a6fd81cdae..b3e25268a0 100644
--- a/RedfishPkg/RedfishPkg.dec
+++ b/RedfishPkg/RedfishPkg.dec
@@ -62,6 +62,10 @@
# project).
RedfishCrtLib|PrivateInclude/Library/RedfishCrtLib.h

+ ## @libraryclass Redfish Helper Library
+ # Library provides Redfish helper functions.
+ RedfishLib|PrivateInclude/Library/RedfishLib.h
+
[Protocols]
## Include/Protocol/RedfishDiscover.h
gEfiRedfishDiscoverProtocolGuid = { 0x5db12509, 0x4550, 0x4347, { 0x96, 0xb3, 0x73, 0xc0, 0xff, 0x6e, 0x86, 0x9f }}
diff --git a/RedfishPkg/RedfishLibs.dsc.inc b/RedfishPkg/RedfishLibs.dsc.inc
index 103a596753..50e5dda773 100644
--- a/RedfishPkg/RedfishLibs.dsc.inc
+++ b/RedfishPkg/RedfishLibs.dsc.inc
@@ -5,7 +5,7 @@
# by using "!include RedfishPkg/RedfisLibs.dsc.inc" to specify the library instances
# of EDKII network library classes.
#
-# (C) Copyright 2020 Hewlett Packard Enterprise Development LP<BR>
+# (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
@@ -16,5 +16,6 @@
BaseSortLib|MdeModulePkg/Library/BaseSortLib/BaseSortLib.inf
RedfishCrtLib|RedfishPkg/PrivateLibrary/RedfishCrtLib/RedfishCrtLib.inf
JsonLib|RedfishPkg/Library/JsonLib/JsonLib.inf
+ RedfishLib|RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.inf
!endif

diff --git a/RedfishPkg/RedfishPkg.dsc b/RedfishPkg/RedfishPkg.dsc
index 2cae8a46d8..e0052290b5 100644
--- a/RedfishPkg/RedfishPkg.dsc
+++ b/RedfishPkg/RedfishPkg.dsc
@@ -55,5 +55,6 @@
RedfishPkg/Library/BaseUcs2Utf8Lib/BaseUcs2Utf8Lib.inf
RedfishPkg/PrivateLibrary/RedfishCrtLib/RedfishCrtLib.inf
RedfishPkg/Library/JsonLib/JsonLib.inf
+ RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.inf

!include RedfishPkg/Redfish.dsc.inc
diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.inf b/RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.inf
new file mode 100644
index 0000000000..128d511df7
--- /dev/null
+++ b/RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.inf
@@ -0,0 +1,60 @@
+## @file
+# RedfishLib Library implementation.
+#
+# Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+# (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+ INF_VERSION = 0x0001001b
+ BASE_NAME = DxeRedfishLib
+ FILE_GUID = 9C2CA9CF-4F79-11E8-A7D1-8CDCD426C973
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = RedfishLib| DXE_DRIVER UEFI_APPLICATION UEFI_DRIVER
+
+#
+# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 RISCV64
+#
+
+[Sources]
+ edk2libredfish/src/redpath.c
+ edk2libredfish/src/service.c
+ edk2libredfish/src/payload.c
+ edk2libredfish/include/redfish.h
+ edk2libredfish/include/redfishPayload.h
+ edk2libredfish/include/redfishService.h
+ edk2libredfish/include/redpath.h
+ RedfishLib.c
+ RedfishMisc.h
+ RedfishMisc.c
+
+[Packages]
+ MdePkg/MdePkg.dec
+ MdeModulePkg/MdeModulePkg.dec
+ NetworkPkg/NetworkPkg.dec
+ RedfishPkg/RedfishPkg.dec
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ DebugLib
+ HttpLib
+ MemoryAllocationLib
+ NetLib
+ RedfishContentCodingLib
+ RedfishCrtLib
+ UefiBootServicesTableLib
+ UefiLib
+
+[Protocols]
+ gEfiRestExServiceBindingProtocolGuid ## Consumed
+ gEfiRestExProtocolGuid ## Consumed
+ gEdkIIRedfishCredentialProtocolGuid ## Consumed
+
+[BuildOptions]
+ MSFT:*_*_*_CC_FLAGS = /U_WIN32 /UWIN64 /U_MSC_VER
+ GCC:*_*_*_CC_FLAGS = -Wno-unused-function -Wno-unused-but-set-variable
diff --git a/RedfishPkg/PrivateInclude/Library/RedfishLib.h b/RedfishPkg/PrivateInclude/Library/RedfishLib.h
new file mode 100644
index 0000000000..315b1ec137
--- /dev/null
+++ b/RedfishPkg/PrivateInclude/Library/RedfishLib.h
@@ -0,0 +1,611 @@
+/** @file
+ This library provides a set of utility APIs that allow to create/read/update/delete
+ (CRUD) Redfish resources and provide basic query abilities by using [URI/RedPath]
+ (https://github.com/DMTF/libredfish).
+
+ The query language is based on XPath (https://www.w3.org/TR/1999/REC-xpath-19991116/).
+ This library and query language essentially treat the entire Redfish Service like it
+ was a single JSON document. In other words whenever it encounters an odata.id in JSON
+ document, it will retrieve the new JSON document (if needed). We name the path as
+ RedPath:
+
+ Expression Description
+
+ nodename Selects the JSON entity with the name "nodename".
+ If the value of nodename is an object with "@odata.id",
+ it will continue get the value from "@odata.id".
+
+ / Selects from the root node
+
+ [index] Selects the index number JSON entity from an array or
+ object. If the JSON entity is one collection (has
+ Members & Members@...), means to get the index
+ member in "Members". Index number >=1, 1 means to return
+ the first instance.
+
+ [XXX] Operation on JSON entity.
+ If the JSON entity is one collection (has Members &
+ Members@...), means to get all elements in
+ "Members". If the JSON entity is one array, means to
+ get all elements in array. Others will match the nodename
+ directly (e.g. JSON_OBJECT, JSON_STRING, JSON_TRUE,
+ JSON_FALSE, JSON_INTEGER).
+
+ [nodename] Selects all the elements from an JSON entity that
+ contain a property named "nodename"
+
+ [name=value] Selects all the elements from an JSON entity where
+ the property "name" is equal to "value"
+
+ [name~value] Selects all the elements from an JSON entity where
+ the string property "name" is equal to "value" using
+ case insensitive comparison.
+
+ [name<value] Selects all the elements from an JSON entity where
+ the property "name" is less than "value"
+
+ [name<=value] Selects all the elements from an JSON entity where
+ the property "name" is less than or equal to "value"
+
+ [name>value] Selects all the elements from an JSON entity where
+ the property "name" is greater than "value"
+
+ [name>=value] Selects all the elements from an JSON entity where
+ the property "name" is greater than or equal to "value"
+
+ Some examples:
+
+ /v1/Chassis[1] - Will return the first Chassis instance.
+ /v1/Chassis[SKU=1234] - Will return all Chassis instances with a SKU field equal to 1234.
+ /v1/Systems[Storage] - Will return all the System instances that have Storage field populated.
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef REDFISH_LIB_H_
+#define REDFISH_LIB_H_
+
+#include <Library/JsonLib.h>
+
+#include <Protocol/Http.h>
+#include <Protocol/EdkIIRedfishConfigHandler.h>
+
+#define ODATA_TYPE_NAME_MAX_SIZE 128
+#define ODATA_TYPE_MAX_SIZE 128
+
+///
+/// Library class public defines
+///
+typedef VOID* REDFISH_SERVICE;
+typedef VOID* REDFISH_PAYLOAD;
+
+///
+/// Library class public structures/unions
+///
+typedef struct {
+ EFI_HTTP_STATUS_CODE *StatusCode;
+ UINTN HeaderCount;
+ EFI_HTTP_HEADER *Headers;
+ REDFISH_PAYLOAD Payload;
+} REDFISH_RESPONSE;
+
+///
+/// Odata type-name mapping structure.
+///
+typedef struct {
+ CONST CHAR8 OdataTypeName [ODATA_TYPE_NAME_MAX_SIZE];
+ CONST CHAR8 OdataType [ODATA_TYPE_MAX_SIZE];
+} REDFISH_ODATA_TYPE_MAPPING;
+
+/**
+ This function uses REST EX protocol provided in RedfishConfigServiceInfo.
+ The service enumerator will also handle the authentication flow automatically
+ if HTTP basic auth or Redfish session login is configured to use.
+
+ Callers are responsible for freeing the returned service by RedfishCleanupService().
+
+ @param[in] RedfishConfigServiceInfo Redfish service information the EFI Redfish
+ feature driver communicates with.
+
+ @return New created Redfish Service, or NULL if error happens.
+
+**/
+REDFISH_SERVICE
+EFIAPI
+RedfishCreateService (
+ IN REDFISH_CONFIG_SERVICE_INFORMATION *RedfishConfigServiceInfo
+ );
+
+/**
+ Free the Service and all its related resources.
+
+ @param[in] RedfishService The Service to access the Redfish resources.
+
+**/
+VOID
+EFIAPI
+RedfishCleanupService (
+ IN REDFISH_SERVICE RedfishService
+ );
+
+/**
+ Create REDFISH_PAYLOAD instance in local with JSON represented resource value and
+ the Redfish Service.
+
+ The returned REDFISH_PAYLOAD can be used to create or update Redfish resource in
+ server side.
+
+ Callers are responsible for freeing the returned payload by RedfishCleanupPayload().
+
+ @param[in] Value JSON Value of the redfish resource.
+ @param[in] RedfishService The Service to access the Redfish resources.
+
+ @return REDFISH_PAYLOAD instance of the resource, or NULL if error happens.
+
+**/
+REDFISH_PAYLOAD
+EFIAPI
+RedfishCreatePayload (
+ IN EDKII_JSON_VALUE Value,
+ IN REDFISH_SERVICE RedfishService
+ );
+
+/**
+ Free the RedfishPayload and all its related resources.
+
+ @param[in] Payload Payload to be freed.
+
+**/
+VOID
+EFIAPI
+RedfishCleanupPayload (
+ IN REDFISH_PAYLOAD Payload
+ );
+
+/**
+ This function returns the decoded JSON value of a REDFISH_PAYLOAD.
+
+ Caller doesn't need to free the returned JSON value because it will be released
+ in corresponding RedfishCleanupPayload() function.
+
+ @param[in] Payload A REDFISH_PAYLOAD instance.
+
+ @return Decoded JSON value of the payload.
+
+**/
+EDKII_JSON_VALUE
+EFIAPI
+RedfishJsonInPayload (
+ IN REDFISH_PAYLOAD Payload
+ );
+
+/**
+ Fill the input RedPath string with system UUID from SMBIOS table or use the customized
+ ID if FromSmbios == FALSE.
+
+ This is a helper function to build a RedPath string which can be used to address
+ a Redfish resource for this computer system. The input PathString must have a Systems
+ note in format of "Systems[UUID=%g]" or "Systems[UUID~%g]" to fill the UUID value.
+
+ Example:
+ Use "/v1/Systems[UUID=%g]/Bios" to build a RedPath to address the "Bios" resource
+ for this computer system.
+
+ @param[in] RedPath RedPath format to be build.
+ @param[in] FromSmbios Get system UUID from SMBIOS as computer system instance ID.
+ @param[in] IdString The computer system instance ID.
+
+ @return Full RedPath with system UUID inside, or NULL if error happens.
+
+**/
+CHAR8 *
+EFIAPI
+RedfishBuildPathWithSystemUuid (
+ IN CONST CHAR8 *RedPath,
+ IN BOOLEAN FromSmbios,
+ IN CHAR8 *IdString OPTIONAL
+ );
+
+/**
+ Get a redfish response addressed by a RedPath string, including HTTP StatusCode, Headers
+ and Payload which record any HTTP response messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] RedfishService The Service to access the Redfish resources.
+ @param[in] RedPath RedPath string to address a resource, must start
+ from the root node.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX. The corresponding redfish resource has
+ been returned in Payload within RedResponse.
+ @retval EFI_INVALID_PARAMETER RedfishService, RedPath, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned Payload is NULL, indicates any error happen.
+ 2. If the returned StatusCode is NULL, indicates any error happen.
+ 3. If the returned StatusCode is not 2XX, indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishGetByService (
+ IN REDFISH_SERVICE RedfishService,
+ IN CONST CHAR8 *RedPath,
+ OUT REDFISH_RESPONSE *RedResponse
+ );
+
+/**
+ Get a redfish response addressed by URI, including HTTP StatusCode, Headers
+ and Payload which record any HTTP response messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] RedfishService The Service to access the URI resources.
+ @param[in] URI String to address a resource.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX. The corresponding redfish resource has
+ been returned in Payload within RedResponse.
+ @retval EFI_INVALID_PARAMETER RedfishService, RedPath, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned Payload is NULL, indicates any error happen.
+ 2. If the returned StatusCode is NULL, indicates any error happen.
+ 3. If the returned StatusCode is not 2XX, indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishGetByUri (
+ IN REDFISH_SERVICE RedfishService,
+ IN CONST CHAR8 *Uri,
+ OUT REDFISH_RESPONSE *RedResponse
+ );
+
+/**
+ Get a redfish response addressed by the input Payload and relative RedPath string,
+ including HTTP StatusCode, Headers and Payload which record any HTTP response messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] Payload A existing REDFISH_PAYLOAD instance.
+ @param[in] RedPath Relative RedPath string to address a resource inside Payload.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful:
+ 1. The HTTP StatusCode is NULL and the returned Payload in
+ RedResponse is not NULL, indicates the Redfish resource has
+ been parsed from the input payload directly.
+ 2. The HTTP StatusCode is not NULL and the value is 2XX,
+ indicates the corresponding redfish resource has been returned
+ in Payload within RedResponse.
+ @retval EFI_INVALID_PARAMETER Payload, RedPath, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned Payload is NULL, indicates any error happen.
+ 2. If StatusCode is not NULL and the returned value of StatusCode
+ is not 2XX, indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishGetByPayload (
+ IN REDFISH_PAYLOAD Payload,
+ IN CONST CHAR8 *RedPath,
+ OUT REDFISH_RESPONSE *RedResponse
+ );
+
+/**
+ Use HTTP PATCH to perform updates on pre-existing Redfish resource.
+
+ This function uses the RedfishService to patch a Redfish resource addressed by
+ Uri (only the relative path is required). Changes to one or more properties within
+ the target resource are represented in the input Content, properties not specified
+ in Content won't be changed by this request. The corresponding redfish response will
+ returned, including HTTP StatusCode, Headers and Payload which record any HTTP response
+ messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] RedfishService The Service to access the Redfish resources.
+ @param[in] Uri Relative path to address the resource.
+ @param[in] Content JSON represented properties to be update.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX. The Redfish resource will be returned
+ in Payload within RedResponse if server send it back in the HTTP
+ response message body.
+ @retval EFI_INVALID_PARAMETER RedfishService, Uri, Content, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned StatusCode is NULL, indicates any error happen.
+ 2. If the returned StatusCode is not NULL and the value is not 2XX,
+ indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishPatchToUri (
+ IN REDFISH_SERVICE RedfishService,
+ IN CONST CHAR8 *Uri,
+ IN CONST CHAR8 *Content,
+ OUT REDFISH_RESPONSE *RedResponse
+ );
+
+/**
+ Use HTTP PATCH to perform updates on target payload. Patch to odata.id in Payload directly.
+
+ This function uses the Payload to patch the Target. Changes to one or more properties
+ within the target resource are represented in the input Payload, properties not specified
+ in Payload won't be changed by this request. The corresponding redfish response will
+ returned, including HTTP StatusCode, Headers and Payload which record any HTTP response
+ messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] Target The target payload to be updated.
+ @param[in] Payload Palyoad with properties to be changed.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX. The Redfish resource will be returned
+ in Payload within RedResponse if server send it back in the HTTP
+ response message body.
+ @retval EFI_INVALID_PARAMETER Target, Payload, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned StatusCode is NULL, indicates any error happen.
+ 2. If the returned StatusCode is not NULL and the value is not 2XX,
+ indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishPatchToPayload (
+ IN REDFISH_PAYLOAD Target,
+ IN REDFISH_PAYLOAD Payload,
+ OUT REDFISH_RESPONSE *RedResponse
+ );
+
+/**
+ Use HTTP POST to create a new resource in target payload.
+
+ The POST request should be submitted to the Resource Collection in which the new resource
+ is to belong. The Resource Collection is addressed by Target payload. The Redfish may
+ ignore any service controlled properties. The corresponding redfish response will returned,
+ including HTTP StatusCode, Headers and Payload which record any HTTP response messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] Target Target payload of the Resource Collection.
+ @param[in] Payload The new resource to be created.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX. The Redfish resource will be returned
+ in Payload within RedResponse if server send it back in the HTTP
+ response message body.
+ @retval EFI_INVALID_PARAMETER Target, Payload, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned StatusCode is NULL, indicates any error happen.
+ 2. If the returned StatusCode is not NULL and the value is not 2XX,
+ indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishPostToPayload (
+ IN REDFISH_PAYLOAD Target,
+ IN REDFISH_PAYLOAD Payload,
+ OUT REDFISH_RESPONSE *RedResponse
+ );
+
+/**
+ Use HTTP DELETE to remove a resource.
+
+ This function uses the RedfishService to remove a Redfish resource which is addressed
+ by input Uri (only the relative path is required). The corresponding redfish response will
+ returned, including HTTP StatusCode, Headers and Payload which record any HTTP response
+ messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] RedfishService The Service to access the Redfish resources.
+ @param[in] Uri Relative path to address the resource.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX, the Redfish resource has been removed.
+ If there is any message returned from server, it will be returned
+ in Payload within RedResponse.
+ @retval EFI_INVALID_PARAMETER RedfishService, Uri, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned StatusCode is NULL, indicates any error happen.
+ 2. If the returned StatusCode is not NULL and the value is not 2XX,
+ indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishDeleteByUri (
+ IN REDFISH_SERVICE RedfishService,
+ IN CONST CHAR8 *Uri,
+ OUT REDFISH_RESPONSE *RedResponse
+ );
+
+/**
+ Dump text in fractions.
+
+ @param[in] String ASCII string to dump.
+
+**/
+VOID
+RedfishDumpJsonStringFractions (
+ IN CHAR8 *String
+ );
+
+/**
+ Extract the JSON text content from REDFISH_PAYLOAD and dump to debug console.
+
+ @param[in] Payload The Redfish payload to dump.
+
+**/
+VOID
+RedfishDumpPayload (
+ IN REDFISH_PAYLOAD Payload
+ );
+/**
+ Dump text in JSON value.
+
+ @param[in] JsonValue The Redfish JSON value to dump.
+
+**/
+VOID
+RedfishDumpJson (
+ IN EDKII_JSON_VALUE JsonValue
+ );
+/**
+ This function will cleanup the HTTP header and Redfish payload resources.
+
+ @param[in] StatusCode The status code in HTTP response message.
+ @param[in] HeaderCount Number of HTTP header structures in Headers list.
+ @param[in] Headers Array containing list of HTTP headers.
+ @param[in] Payload The Redfish payload to dump.
+
+**/
+VOID
+RedfishFreeResponse (
+ IN EFI_HTTP_STATUS_CODE *StatusCode,
+ IN UINTN HeaderCount,
+ IN EFI_HTTP_HEADER *Headers,
+ IN REDFISH_PAYLOAD Payload
+ );
+
+/**
+ Check if the "@odata.type" in Payload is valid or not.
+
+ @param[in] Payload The Redfish payload to be checked.
+ @param[in] OdataTypeName OdataType will be retrived from mapping list.
+ @param[in] OdataTypeMappingList The list of OdataType.
+ @param[in] OdataTypeMappingListSize The number of mapping list
+
+ @return TRUE if the "@odata.type" in Payload is valid, otherwise FALSE.
+
+**/
+BOOLEAN
+RedfishIsValidOdataType (
+ IN REDFISH_PAYLOAD Payload,
+ IN CONST CHAR8 *OdataTypeName,
+ IN REDFISH_ODATA_TYPE_MAPPING *OdataTypeMappingList,
+ IN UINTN OdataTypeMappingListSize
+ );
+
+/**
+ Check if the payload is collection
+
+ @param[in] Payload The Redfish payload to be checked.
+
+ @return TRUE if the payload is collection.
+
+**/
+BOOLEAN
+RedfishIsPayloadCollection (
+ IN REDFISH_PAYLOAD Payload
+);
+/**
+ Get collection size.
+
+ @param[in] Payload The Redfish collection payload
+ @param[in] CollectionSize Size of this collection
+
+ @return EFI_SUCCESS Coolection size is returned in CollectionSize
+ @return EFI_INVALID_PARAMETER The payload is not a collection.
+**/
+EFI_STATUS
+RedfishGetCollectionSize(
+ IN REDFISH_PAYLOAD Payload,
+ IN UINTN *CollectionSize
+);
+/**
+ Get Redfish payload of collection member
+
+ @param[in] Payload The Redfish collection payload
+ @param[in] Index Index of collection member
+
+ @return NULL Fail to get collection member.
+ @return Non NULL Payload is returned.
+**/
+REDFISH_PAYLOAD
+RedfishGetPayloadByIndex (
+ IN REDFISH_PAYLOAD Payload,
+ IN UINTN Index
+);
+
+/**
+ Check and return Redfish resource of the given Redpath.
+
+ @param[in] RedfishService Pointer to REDFISH_SERVICE
+ @param[in] Redpath Redpath of the resource.
+ @param[in] Response Optional return the resource.
+
+ @return EFI_STATUS
+**/
+EFI_STATUS
+RedfishCheckIfRedpathExist (
+ IN REDFISH_SERVICE RedfishService,
+ IN CHAR8 *Redpath,
+ IN REDFISH_RESPONSE *Response OPTIONAL
+);
+
+/**
+ This function returns the string of Redfish service version.
+
+ @param[in] RedfishService Redfish service instance.
+ @param[out] ServiceVersionStr Redfish service string.
+
+ @return EFI_STATUS
+
+**/
+EFI_STATUS
+RedfishGetServiceVersion(
+ IN REDFISH_SERVICE RedfishService,
+ OUT CHAR8 **ServiceVersionStr
+ );
+
+/**
+ This function returns the string of Redfish service version.
+
+ @param[in] ServiceVerisonStr The string of Redfish service version.
+ @param[in] Url The URL to build Redpath with ID.
+ Start with "/", for example "/Registries"
+ @param[in] Id ID string
+ @param[out] Redpath Pointer to retrive Redpath, caller has to free
+ the memory allocated for this string.
+ @return EFI_STATUS
+
+**/
+EFI_STATUS
+RedfishBuildRedpathUseId (
+ IN CHAR8 *ServiceVerisonStr,
+ IN CHAR8 *Url,
+ IN CHAR8 *Id,
+ OUT CHAR8 **Redpath
+ );
+#endif
diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/RedfishMisc.h b/RedfishPkg/PrivateLibrary/RedfishLib/RedfishMisc.h
new file mode 100644
index 0000000000..d01a433d1a
--- /dev/null
+++ b/RedfishPkg/PrivateLibrary/RedfishLib/RedfishMisc.h
@@ -0,0 +1,82 @@
+/** @file
+ Internal Functions for RedfishLib.
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef DXE_REDFISH_MISC_LIB_H_
+#define DXE_REDFISH_MISC_LIB_H_
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/JsonLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/PrintLib.h>
+#include <Library/RedfishLib.h>
+#include <Library/UefiLib.h>
+#include <Protocol/EdkIIRedfishCredential.h>
+#include <redfish.h>
+
+#define ARRAY_SIZE(Array) (sizeof (Array) / sizeof ((Array)[0]))
+
+/**
+ Creates a REDFISH_SERVICE which can be later used to access the Redfish resources.
+
+ This function will configure REST EX child according to parameters described in
+ Redfish network host interface in SMBIOS type 42 record. The service enumerator will also
+ handle the authentication flow automatically if HTTP basic auth or Redfish session
+ login is configured to use.
+
+ @param[in] RedfishConfigServiceInfo Redfish service information the EFI Redfish
+ feature driver communicates with.
+ @param[in] AuthMethod None, HTTP basic auth, or Redfish session login.
+ @param[in] UserId User Name used for authentication.
+ @param[in] Password Password used for authentication.
+
+ @return New created Redfish service, or NULL if error happens.
+
+**/
+REDFISH_SERVICE
+RedfishCreateLibredfishService (
+ IN REDFISH_CONFIG_SERVICE_INFORMATION *RedfishConfigServiceInfo,
+ IN EDKII_REDFISH_AUTH_METHOD AuthMethod,
+ IN CHAR8 *UserId,
+ IN CHAR8 *Password
+ );
+
+/**
+ Retrieve platform's Redfish authentication information.
+
+ This functions returns the Redfish authentication method together with the user
+ Id and password.
+ For AuthMethodNone, UserId and Password will point to NULL which means authentication
+ is not required to access the Redfish service.
+ For AuthMethodHttpBasic, the UserId and Password could be used for
+ HTTP header authentication as defined by RFC7235. For AuthMethodRedfishSession,
+ the UserId and Password could be used for Redfish session login as defined by
+ Redfish API specification (DSP0266).
+
+ Callers are responsible for freeing the returned string storage pointed by UserId
+ and Password.
+
+ @param[out] AuthMethod Type of Redfish authentication method.
+ @param[out] UserId The pointer to store the returned UserId string.
+ @param[out] Password The pointer to store the returned Password string.
+
+ @retval EFI_SUCCESS Get the authentication information successfully.
+ @retval EFI_INVALID_PARAMETER AuthMethod or UserId or Password is NULL.
+ @retval EFI_UNSUPPORTED Unsupported authentication method is found.
+**/
+EFI_STATUS
+RedfishGetAuthInfo (
+ OUT EDKII_REDFISH_AUTH_METHOD *AuthMethod,
+ OUT CHAR8 **UserId,
+ OUT CHAR8 **Password
+ );
+
+#endif
diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfish.h b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfish.h
new file mode 100644
index 0000000000..de1feb22fb
--- /dev/null
+++ b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfish.h
@@ -0,0 +1,24 @@
+/** @file
+ This file is cloned from DMTF libredfish library tag v1.0.0 and maintained
+ by EDKII.
+
+//----------------------------------------------------------------------------
+// Copyright Notice:
+// Copyright 2017 Distributed Management Task Force, Inc. All rights reserved.
+// License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/libredfish/LICENSE.md
+//----------------------------------------------------------------------------
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#ifndef LIBREDFISH_REDFISH_H_
+#define LIBREDFISH_REDFISH_H_
+
+#include <redfishService.h>
+#include <redfishPayload.h>
+#include <redpath.h>
+
+#endif
diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfishPayload.h b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfishPayload.h
new file mode 100644
index 0000000000..03380d9394
--- /dev/null
+++ b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfishPayload.h
@@ -0,0 +1,39 @@
+/** @file
+ This file is cloned from DMTF libredfish library tag v1.0.0 and maintained
+ by EDKII.
+
+//----------------------------------------------------------------------------
+// Copyright Notice:
+// Copyright 2017 Distributed Management Task Force, Inc. All rights reserved.
+// License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/libredfish/LICENSE.md
+//----------------------------------------------------------------------------
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#ifndef LIBREDFISH_REDFISH_PAYLOAD_H_
+#define LIBREDFISH_REDFISH_PAYLOAD_H_
+
+#include <PrivateInclude/Library/RedfishCrtLib.h>
+
+#include <jansson.h>
+#include <redfishService.h>
+#include <redpath.h>
+
+redfishPayload* createRedfishPayload(json_t* value, redfishService* service);
+redfishPayload* getPayloadByNodeName(redfishPayload* payload, const char* nodeName, EFI_HTTP_STATUS_CODE** StatusCode);
+redfishPayload* getPayloadByIndex(redfishPayload* payload, size_t index, EFI_HTTP_STATUS_CODE** StatusCode);
+redfishPayload* getPayloadForPath(redfishPayload* payload, redPathNode* redpath, EFI_HTTP_STATUS_CODE** StatusCode);
+redfishPayload* getPayloadForPathString(redfishPayload* payload, const char* string, EFI_HTTP_STATUS_CODE** StatusCode);
+redfishPayload* patchPayload(redfishPayload* target, redfishPayload* payload, EFI_HTTP_STATUS_CODE** StatusCode);
+redfishPayload* postContentToPayload(redfishPayload* target, const char* data, size_t dataSize, const char* contentType, EFI_HTTP_STATUS_CODE** StatusCode);
+redfishPayload* postPayload(redfishPayload* target, redfishPayload* payload, EFI_HTTP_STATUS_CODE** StatusCode);
+void cleanupPayload(redfishPayload* payload);
+bool isPayloadCollection (redfishPayload *Payload);
+size_t getCollectionSize(redfishPayload* payload);
+redfishPayload* getPayloadByIndex (redfishPayload* payload, size_t index, EFI_HTTP_STATUS_CODE** StatusCode);
+
+#endif
diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfishService.h b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfishService.h
new file mode 100644
index 0000000000..5bcb381c05
--- /dev/null
+++ b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redfishService.h
@@ -0,0 +1,101 @@
+/** @file
+ This file is cloned from DMTF libredfish library tag v1.0.0 and maintained
+ by EDKII.
+
+//----------------------------------------------------------------------------
+// Copyright Notice:
+// Copyright 2017 Distributed Management Task Force, Inc. All rights reserved.
+// License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/libredfish/LICENSE.md
+//----------------------------------------------------------------------------
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef LIBREDFISH_REDFISH_SERVICE_H_
+#define LIBREDFISH_REDFISH_SERVICE_H_
+
+#include <IndustryStandard/Http11.h>
+
+#include <Library/BaseLib.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/HttpLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/NetLib.h>
+#include <Library/RedfishContentCodingLib.h>
+#include <Library/UefiRuntimeServicesTableLib.h>
+#include <Library/UefiBootServicesTableLib.h>
+
+#include <PrivateInclude/Library/RedfishCrtLib.h>
+
+#include <Protocol/EdkIIRedfishConfigHandler.h>
+#include <Protocol/RestEx.h>
+
+#include <jansson.h>
+
+typedef struct {
+ char* host;
+ json_t* versions;
+ unsigned int flags;
+ char* sessionToken;
+ char* basicAuthStr;
+ //
+ // point to the <HOST> part in above "host" field, which will be put into
+ // the "Host" header of HTTP request message.
+ //
+ char* HostHeaderValue;
+ EFI_REST_EX_PROTOCOL *RestEx;
+} redfishService;
+
+typedef struct {
+ json_t* json;
+ redfishService* service;
+} redfishPayload;
+
+#define REDFISH_AUTH_BASIC 0
+#define REDFISH_AUTH_BEARER_TOKEN 1
+#define REDFISH_AUTH_SESSION 2
+
+#define REDFISH_HTTP_RESPONSE_TIMEOUT 5000 /// 5 seconds in uints of millisecond.
+
+///
+/// Library class public defines
+///
+#define HTTP_FLAG L"http://"
+#define HTTPS_FLAG L"https://"
+
+///
+/// The redfish first URL should be "/redfish/v1/", while we use "/redfish/v1" here without "/"
+/// in the end is to avoid the 301 Perment redirect response from Redfish profile simulator.
+///
+#define REDFISH_FIRST_URL L"/redfish/v1"
+
+typedef struct {
+ unsigned int authType;
+ union {
+ struct {
+ char* username;
+ char* password;
+ } userPass;
+ struct {
+ char* token;
+ } authToken;
+ } authCodes;
+} enumeratorAuthentication;
+
+//Values for flags
+#define REDFISH_FLAG_SERVICE_NO_VERSION_DOC 0x00000001 //The Redfish Service lacks the version document (in violation of the Redfish spec)
+redfishService* createServiceEnumerator(REDFISH_CONFIG_SERVICE_INFORMATION *RedfishConfigServiceInfo, const char* rootUri, enumeratorAuthentication* auth, unsigned int flags);
+json_t* getUriFromService(redfishService* service, const char* uri, EFI_HTTP_STATUS_CODE** StatusCode);
+json_t* patchUriFromService(redfishService* service, const char* uri, const char* content, EFI_HTTP_STATUS_CODE** StatusCode);
+json_t* postUriFromService(redfishService* service, const char* uri, const char* content, size_t contentLength, const char* contentType, EFI_HTTP_STATUS_CODE** StatusCode);
+json_t* deleteUriFromService(redfishService* service, const char* uri, EFI_HTTP_STATUS_CODE** StatusCode);
+redfishPayload* getRedfishServiceRoot(redfishService* service, const char* version, EFI_HTTP_STATUS_CODE** StatusCode);
+redfishPayload* getPayloadByPath(redfishService* service, const char* path, EFI_HTTP_STATUS_CODE** StatusCode);
+void cleanupServiceEnumerator(redfishService* service);
+
+#endif
diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redpath.h b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redpath.h
new file mode 100644
index 0000000000..bdec6098e5
--- /dev/null
+++ b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/include/redpath.h
@@ -0,0 +1,42 @@
+/** @file
+ This file is cloned from DMTF libredfish library tag v1.0.0 and maintained
+ by EDKII.
+
+//----------------------------------------------------------------------------
+// Copyright Notice:
+// Copyright 2017 Distributed Management Task Force, Inc. All rights reserved.
+// License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/libredfish/LICENSE.md
+//----------------------------------------------------------------------------
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#ifndef LIBREDFISH_REDPATH_H_
+#define LIBREDFISH_REDPATH_H_
+
+#include <PrivateInclude/Library/RedfishCrtLib.h>
+
+#include <jansson.h>
+
+typedef struct _redPathNode
+{
+ bool isRoot;
+ bool isIndex;
+
+ char* version;
+ char* nodeName;
+ size_t index;
+ char* op;
+ char* propName;
+ char* value;
+
+ struct _redPathNode* next;
+} redPathNode;
+
+redPathNode* parseRedPath(const char* path);
+void cleanupRedPath(redPathNode* node);
+
+#endif
diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.c b/RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.c
new file mode 100644
index 0000000000..7a61dbf9be
--- /dev/null
+++ b/RedfishPkg/PrivateLibrary/RedfishLib/RedfishLib.c
@@ -0,0 +1,993 @@
+/** @file
+ Provides a set of utility APIs that allow to create/read/update/delete
+ (CRUD) Redfish resources and provide basic query.
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "RedfishMisc.h"
+
+/**
+ This function uses REST EX protocol provided in RedfishConfigServiceInfo.
+ The service enumerator will also handle the authentication flow automatically
+ if HTTP basic auth or Redfish session login is configured to use.
+
+ Callers are responsible for freeing the returned service by RedfishCleanupService().
+
+ @param[in] RedfishConfigServiceInfo Redfish service information the EFI Redfish
+ feature driver communicates with.
+
+ @return New created Redfish Service, or NULL if error happens.
+
+**/
+REDFISH_SERVICE
+EFIAPI
+RedfishCreateService (
+ IN REDFISH_CONFIG_SERVICE_INFORMATION *RedfishConfigServiceInfo
+ )
+{
+ REDFISH_SERVICE RedfishService;
+ EDKII_REDFISH_AUTH_METHOD AuthMethod;
+ CHAR8 *UserId;
+ CHAR8 *Password;
+ EFI_STATUS Status;
+
+ RedfishService = NULL;
+ UserId = NULL;
+ Password = NULL;
+
+ //
+ // Check Input Parameters.
+ //
+ if (RedfishConfigServiceInfo == NULL) {
+ return NULL;
+ }
+
+ //
+ // Get Authentication Configuration.
+ //
+ Status = RedfishGetAuthInfo (&AuthMethod, &UserId, &Password);
+ if (EFI_ERROR (Status)) {
+ goto ON_EXIT;
+ }
+
+ //
+ // Create a redfish service node based on Redfish network host interface.
+ //
+ RedfishService = RedfishCreateLibredfishService (
+ RedfishConfigServiceInfo,
+ AuthMethod,
+ UserId,
+ Password
+ );
+
+ON_EXIT:
+ if (UserId != NULL) {
+ FreePool (UserId);
+ }
+ if (Password!= NULL) {
+ FreePool (Password);
+ }
+
+ return RedfishService;
+}
+
+/**
+ Free the Service and all its related resources.
+
+ @param[in] RedfishService The Service to access the Redfish resources.
+
+**/
+VOID
+EFIAPI
+RedfishCleanupService (
+ IN REDFISH_SERVICE RedfishService
+ )
+{
+ if (RedfishService == NULL) {
+ return;
+ }
+
+ cleanupServiceEnumerator (RedfishService);
+}
+/**
+ Create REDFISH_PAYLOAD instance in local with JSON represented resource value and
+ the Redfish Service.
+
+ The returned REDFISH_PAYLOAD can be used to create or update Redfish resource in
+ server side.
+
+ Callers are responsible for freeing the returned payload by RedfishCleanupPayload().
+
+ @param[in] Value JSON Value of the redfish resource.
+ @param[in] RedfishService The Service to access the Redfish resources.
+
+ @return REDFISH_PAYLOAD instance of the resource, or NULL if error happens.
+
+**/
+REDFISH_PAYLOAD
+EFIAPI
+RedfishCreatePayload (
+ IN EDKII_JSON_VALUE Value,
+ IN REDFISH_SERVICE RedfishService
+ )
+{
+ EDKII_JSON_VALUE CopyValue;
+
+ CopyValue = JsonValueClone (Value);
+ return createRedfishPayload (CopyValue, RedfishService);
+}
+
+/**
+ Free the RedfishPayload and all its related resources.
+
+ @param[in] Payload Payload to be freed.
+
+**/
+VOID
+EFIAPI
+RedfishCleanupPayload (
+ IN REDFISH_PAYLOAD Payload
+ )
+{
+ if (Payload == NULL) {
+ return;
+ }
+
+ cleanupPayload ((redfishPayload *) Payload);
+}
+
+/**
+ This function returns the decoded JSON value of a REDFISH_PAYLOAD.
+
+ Caller doesn't need to free the returned JSON value because it will be released
+ in corresponding RedfishCleanupPayload() function.
+
+ @param[in] Payload A REDFISH_PAYLOAD instance.
+
+ @return Decoded JSON value of the payload.
+
+**/
+
+EDKII_JSON_VALUE
+EFIAPI
+RedfishJsonInPayload (
+ IN REDFISH_PAYLOAD Payload
+ )
+{
+ if (Payload == NULL) {
+ return NULL;
+ }
+
+ return ((redfishPayload*)Payload)->json;
+}
+
+/**
+ Fill the input RedPath string with system UUID from SMBIOS table or use the customized
+ ID if FromSmbios == FALSE.
+
+ This is a helper function to build a RedPath string which can be used to address
+ a Redfish resource for this computer system. The input PathString must have a Systems
+ note in format of "Systems[UUID=%g]" or "Systems[UUID~%g]" to fill the UUID value.
+
+ Example:
+ Use "/v1/Systems[UUID=%g]/Bios" to build a RedPath to address the "Bios" resource
+ for this computer system.
+
+ @param[in] RedPath RedPath format to be build.
+ @param[in] FromSmbios Get system UUID from SMBIOS as computer system instance ID.
+ @param[in] IdString The computer system instance ID.
+
+ @return Full RedPath with system UUID inside, or NULL if error happens.
+
+**/
+CHAR8 *
+EFIAPI
+RedfishBuildPathWithSystemUuid (
+ IN CONST CHAR8 *RedPath,
+ IN BOOLEAN FromSmbios,
+ IN CHAR8 *IdString OPTIONAL
+ )
+{
+ UINTN BufSize;
+ CHAR8* RetRedPath;
+ EFI_GUID SystemUuid;
+ EFI_STATUS Status;
+
+ if (RedPath == NULL) {
+ return NULL;
+ }
+
+ //
+ // Find system UUID from SMBIOS table.
+ //
+ if (FromSmbios == TRUE) {
+ Status = NetLibGetSystemGuid(&SystemUuid);
+ if (EFI_ERROR (Status)) {
+ return NULL;
+ }
+ // AsciiStrLen ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") = 36
+ BufSize = AsciiStrSize (RedPath) + AsciiStrLen ("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX");
+ } else {
+ BufSize = AsciiStrSize (RedPath) + AsciiStrLen (IdString);
+ }
+
+ RetRedPath = AllocateZeroPool (BufSize);
+ if (RetRedPath == NULL) {
+ return NULL;
+ }
+ if (FromSmbios == TRUE) {
+ AsciiSPrint (RetRedPath, BufSize, RedPath, &SystemUuid);
+ } else {
+ AsciiSPrint (RetRedPath, BufSize, RedPath, IdString);
+ }
+ return RetRedPath;
+}
+/**
+ Get a redfish response addressed by a RedPath string, including HTTP StatusCode, Headers
+ and Payload which record any HTTP response messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] RedfishService The Service to access the Redfish resources.
+ @param[in] RedPath RedPath string to address a resource, must start
+ from the root node.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX. The corresponding redfish resource has
+ been returned in Payload within RedResponse.
+ @retval EFI_INVALID_PARAMETER RedfishService, RedPath, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned Payload is NULL, indicates any error happen.
+ 2. If the returned StatusCode is NULL, indicates any error happen.
+ 3. If the returned StatusCode is not 2XX, indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishGetByService (
+ IN REDFISH_SERVICE RedfishService,
+ IN CONST CHAR8 *RedPath,
+ OUT REDFISH_RESPONSE *RedResponse
+ )
+{
+ if (RedfishService == NULL || RedPath == NULL || RedResponse == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ ZeroMem (RedResponse, sizeof (REDFISH_RESPONSE));
+
+ RedResponse->Payload = (REDFISH_PAYLOAD) getPayloadByPath (RedfishService, RedPath, &(RedResponse->StatusCode));
+
+ //
+ // 1. If the returned Payload is NULL, indicates any error happen.
+ // 2. If the returned StatusCode is NULL, indicates any error happen.
+ //
+ if (RedResponse->Payload == NULL || RedResponse->StatusCode == NULL) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ //
+ // 3. If the returned StatusCode is not 2XX, indicates any error happen.
+ // NOTE: If there is any error message returned from server, it will be returned in
+ // Payload within RedResponse.
+ //
+ if (*(RedResponse->StatusCode) < HTTP_STATUS_200_OK || \
+ *(RedResponse->StatusCode) > HTTP_STATUS_206_PARTIAL_CONTENT) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+/**
+ Get a redfish response addressed by URI, including HTTP StatusCode, Headers
+ and Payload which record any HTTP response messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] RedfishService The Service to access the URI resources.
+ @param[in] URI String to address a resource.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX. The corresponding redfish resource has
+ been returned in Payload within RedResponse.
+ @retval EFI_INVALID_PARAMETER RedfishService, RedPath, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned Payload is NULL, indicates any error happen.
+ 2. If the returned StatusCode is NULL, indicates any error happen.
+ 3. If the returned StatusCode is not 2XX, indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishGetByUri (
+ IN REDFISH_SERVICE RedfishService,
+ IN CONST CHAR8 *Uri,
+ OUT REDFISH_RESPONSE *RedResponse
+ )
+{
+ EDKII_JSON_VALUE JsonValue;
+
+ if (RedfishService == NULL || Uri == NULL || RedResponse == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ ZeroMem (RedResponse, sizeof (REDFISH_RESPONSE));
+
+ JsonValue = getUriFromService (RedfishService, Uri, &RedResponse->StatusCode);
+ RedResponse->Payload = createRedfishPayload(JsonValue, RedfishService);
+
+ //
+ // 1. If the returned Payload is NULL, indicates any error happen.
+ // 2. If the returned StatusCode is NULL, indicates any error happen.
+ //
+ if (RedResponse->Payload == NULL || RedResponse->StatusCode == NULL) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ //
+ // 3. If the returned StatusCode is not 2XX, indicates any error happen.
+ // NOTE: If there is any error message returned from server, it will be returned in
+ // Payload within RedResponse.
+ //
+ if (*(RedResponse->StatusCode) < HTTP_STATUS_200_OK || \
+ *(RedResponse->StatusCode) > HTTP_STATUS_206_PARTIAL_CONTENT) {
+ return EFI_DEVICE_ERROR;
+ }
+ return EFI_SUCCESS;
+}
+/**
+ Get a redfish response addressed by the input Payload and relative RedPath string,
+ including HTTP StatusCode, Headers and Payload which record any HTTP response messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] Payload A existing REDFISH_PAYLOAD instance.
+ @param[in] RedPath Relative RedPath string to address a resource inside Payload.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful:
+ 1. The HTTP StatusCode is NULL and the returned Payload in
+ RedResponse is not NULL, indicates the Redfish resource has
+ been parsed from the input payload directly.
+ 2. The HTTP StatusCode is not NULL and the value is 2XX,
+ indicates the corresponding redfish resource has been returned
+ in Payload within RedResponse.
+ @retval EFI_INVALID_PARAMETER Payload, RedPath, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned Payload is NULL, indicates any error happen.
+ 2. If StatusCode is not NULL and the returned value of StatusCode
+ is not 2XX, indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishGetByPayload (
+ IN REDFISH_PAYLOAD Payload,
+ IN CONST CHAR8 *RedPath,
+ OUT REDFISH_RESPONSE *RedResponse
+ )
+{
+ if (Payload == NULL || RedPath == NULL || RedResponse == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ ZeroMem (RedResponse, sizeof (REDFISH_RESPONSE));
+
+ RedResponse->Payload = (REDFISH_PAYLOAD) getPayloadForPathString (Payload, RedPath, &(RedResponse->StatusCode));
+
+ //
+ // 1. If the returned Payload is NULL, indicates any error happen.
+ //
+ if (RedResponse->Payload == NULL) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ //
+ // 2. If StatusCode is not NULL and the returned value of StatusCode is not 2XX, indicates any
+ // error happen.
+ // NOTE: If there is any error message returned from server, it will be returned in
+ // Payload within RedResponse.
+ //
+ if (RedResponse->StatusCode != NULL && \
+ (*(RedResponse->StatusCode) < HTTP_STATUS_200_OK || \
+ *(RedResponse->StatusCode) > HTTP_STATUS_206_PARTIAL_CONTENT
+ )) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+/**
+ Use HTTP PATCH to perform updates on pre-existing Redfish resource.
+
+ This function uses the RedfishService to patch a Redfish resource addressed by
+ Uri (only the relative path is required). Changes to one or more properties within
+ the target resource are represented in the input Content, properties not specified
+ in Content won't be changed by this request. The corresponding redfish response will
+ returned, including HTTP StatusCode, Headers and Payload which record any HTTP response
+ messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] RedfishService The Service to access the Redfish resources.
+ @param[in] Uri Relative path to address the resource.
+ @param[in] Content JSON represented properties to be update.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX. The Redfish resource will be returned
+ in Payload within RedResponse if server send it back in the HTTP
+ response message body.
+ @retval EFI_INVALID_PARAMETER RedfishService, Uri, Content, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned StatusCode is NULL, indicates any error happen.
+ 2. If the returned StatusCode is not NULL and the value is not 2XX,
+ indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishPatchToUri (
+ IN REDFISH_SERVICE RedfishService,
+ IN CONST CHAR8 *Uri,
+ IN CONST CHAR8 *Content,
+ OUT REDFISH_RESPONSE *RedResponse
+ )
+{
+ EFI_STATUS Status;
+ EDKII_JSON_VALUE JsonValue;
+
+ Status = EFI_SUCCESS;
+ JsonValue = NULL;
+
+ if (RedfishService == NULL || Uri == NULL || Content == NULL || RedResponse == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ ZeroMem (RedResponse, sizeof (REDFISH_RESPONSE));
+
+ JsonValue = (EDKII_JSON_VALUE) patchUriFromService (
+ RedfishService,
+ Uri,
+ Content,
+ &(RedResponse->StatusCode)
+ );
+
+ //
+ // 1. If the returned StatusCode is NULL, indicates any error happen.
+ //
+ if (RedResponse->StatusCode == NULL) {
+ Status = EFI_DEVICE_ERROR;
+ goto ON_EXIT;
+ }
+
+ //
+ // 2. If the returned StatusCode is not NULL and the value is not 2XX, indicates any error happen.
+ // NOTE: If there is any error message returned from server, it will be returned in
+ // Payload within RedResponse.
+ //
+ if (*(RedResponse->StatusCode) < HTTP_STATUS_200_OK || \
+ *(RedResponse->StatusCode) > HTTP_STATUS_206_PARTIAL_CONTENT) {
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ON_EXIT:
+ if (JsonValue != NULL) {
+ RedResponse->Payload = createRedfishPayload (JsonValue, RedfishService);
+ if (RedResponse->Payload == NULL) {
+ //
+ // Ignore the error when create RedfishPayload, just free the JsonValue since it's not what
+ // we care about if the returned StatusCode is 2XX.
+ //
+ JsonValueFree (JsonValue);
+ }
+ }
+
+ return Status;
+}
+/**
+ Use HTTP PATCH to perform updates on target payload. Patch to odata.id in Payload directly.
+
+ This function uses the Payload to patch the Target. Changes to one or more properties
+ within the target resource are represented in the input Payload, properties not specified
+ in Payload won't be changed by this request. The corresponding redfish response will
+ returned, including HTTP StatusCode, Headers and Payload which record any HTTP response
+ messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] Target The target payload to be updated.
+ @param[in] Payload Palyoad with properties to be changed.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX. The Redfish resource will be returned
+ in Payload within RedResponse if server send it back in the HTTP
+ response message body.
+ @retval EFI_INVALID_PARAMETER Target, Payload, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned StatusCode is NULL, indicates any error happen.
+ 2. If the returned StatusCode is not NULL and the value is not 2XX,
+ indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishPatchToPayload (
+ IN REDFISH_PAYLOAD Target,
+ IN REDFISH_PAYLOAD Payload,
+ OUT REDFISH_RESPONSE *RedResponse
+ )
+{
+ if (Target == NULL || Payload == NULL || RedResponse == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ ZeroMem (RedResponse, sizeof (REDFISH_RESPONSE));
+
+ RedResponse->Payload = (REDFISH_PAYLOAD) patchPayload (
+ Target,
+ Payload,
+ &(RedResponse->StatusCode)
+ );
+
+ //
+ // 1. If the returned StatusCode is NULL, indicates any error happen.
+ //
+ if (RedResponse->StatusCode == NULL) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ //
+ // 2. If the returned StatusCode is not NULL and the value is not 2XX, indicates any error happen.
+ // NOTE: If there is any error message returned from server, it will be returned in
+ // Payload within RedResponse.
+ //
+ if (*(RedResponse->StatusCode) < HTTP_STATUS_200_OK || \
+ *(RedResponse->StatusCode) > HTTP_STATUS_206_PARTIAL_CONTENT) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+/**
+ Use HTTP POST to create a new resource in target payload.
+
+ The POST request should be submitted to the Resource Collection in which the new resource
+ is to belong. The Resource Collection is addressed by Target payload. The Redfish may
+ ignore any service controlled properties. The corresponding redfish response will returned,
+ including HTTP StatusCode, Headers and Payload which record any HTTP response messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] Target Target payload of the Resource Collection.
+ @param[in] Payload The new resource to be created.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX. The Redfish resource will be returned
+ in Payload within RedResponse if server send it back in the HTTP
+ response message body.
+ @retval EFI_INVALID_PARAMETER Target, Payload, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned StatusCode is NULL, indicates any error happen.
+ 2. If the returned StatusCode is not NULL and the value is not 2XX,
+ indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishPostToPayload (
+ IN REDFISH_PAYLOAD Target,
+ IN REDFISH_PAYLOAD Payload,
+ OUT REDFISH_RESPONSE *RedResponse
+ )
+{
+ if (Target == NULL || Payload == NULL || RedResponse == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ ZeroMem (RedResponse, sizeof (REDFISH_RESPONSE));
+
+ RedResponse->Payload = (REDFISH_PAYLOAD) postPayload (
+ Target,
+ Payload,
+ &(RedResponse->StatusCode)
+ );
+
+ //
+ // 1. If the returned StatusCode is NULL, indicates any error happen.
+ //
+ if (RedResponse->StatusCode == NULL) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ //
+ // 2. If the returned StatusCode is not NULL and the value is not 2XX, indicates any error happen.
+ // NOTE: If there is any error message returned from server, it will be returned in
+ // Payload within RedResponse.
+ //
+ if (*(RedResponse->StatusCode) < HTTP_STATUS_200_OK || \
+ *(RedResponse->StatusCode) > HTTP_STATUS_206_PARTIAL_CONTENT) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+/**
+ Use HTTP DELETE to remove a resource.
+
+ This function uses the RedfishService to remove a Redfish resource which is addressed
+ by input Uri (only the relative path is required). The corresponding redfish response will
+ returned, including HTTP StatusCode, Headers and Payload which record any HTTP response
+ messages.
+
+ Callers are responsible for freeing the HTTP StatusCode, Headers and Payload returned in
+ redfish response data.
+
+ @param[in] RedfishService The Service to access the Redfish resources.
+ @param[in] Uri Relative path to address the resource.
+ @param[out] RedResponse Pointer to the Redfish response data.
+
+ @retval EFI_SUCCESS The opeartion is successful, indicates the HTTP StatusCode is not
+ NULL and the value is 2XX, the Redfish resource has been removed.
+ If there is any message returned from server, it will be returned
+ in Payload within RedResponse.
+ @retval EFI_INVALID_PARAMETER RedfishService, Uri, or RedResponse is NULL.
+ @retval EFI_DEVICE_ERROR An unexpected system or network error occurred. Callers can get
+ more error info from returned HTTP StatusCode, Headers and Payload
+ within RedResponse:
+ 1. If the returned StatusCode is NULL, indicates any error happen.
+ 2. If the returned StatusCode is not NULL and the value is not 2XX,
+ indicates any error happen.
+**/
+EFI_STATUS
+EFIAPI
+RedfishDeleteByUri (
+ IN REDFISH_SERVICE RedfishService,
+ IN CONST CHAR8 *Uri,
+ OUT REDFISH_RESPONSE *RedResponse
+ )
+{
+ EFI_STATUS Status;
+ EDKII_JSON_VALUE JsonValue;
+
+ Status = EFI_SUCCESS;
+ JsonValue = NULL;
+
+ if (RedfishService == NULL || Uri == NULL || RedResponse == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ ZeroMem (RedResponse, sizeof (REDFISH_RESPONSE));
+
+ JsonValue = (EDKII_JSON_VALUE) deleteUriFromService (
+ RedfishService,
+ Uri,
+ &(RedResponse->StatusCode)
+ );
+
+ //
+ // 1. If the returned StatusCode is NULL, indicates any error happen.
+ //
+ if (RedResponse->StatusCode == NULL) {
+ Status = EFI_DEVICE_ERROR;
+ goto ON_EXIT;
+ }
+
+ //
+ // 2. If the returned StatusCode is not NULL and the value is not 2XX, indicates any error happen.
+ // NOTE: If there is any error message returned from server, it will be returned in
+ // Payload within RedResponse.
+ //
+ if (*(RedResponse->StatusCode) < HTTP_STATUS_200_OK || \
+ *(RedResponse->StatusCode) > HTTP_STATUS_206_PARTIAL_CONTENT) {
+ Status = EFI_DEVICE_ERROR;
+ }
+
+ON_EXIT:
+ if (JsonValue != NULL) {
+ RedResponse->Payload = createRedfishPayload (JsonValue, RedfishService);
+ if (RedResponse->Payload == NULL) {
+ //
+ // Ignore the error when create RedfishPayload, just free the JsonValue since it's not what
+ // we care about if the returned StatusCode is 2XX.
+ //
+ JsonValueFree (JsonValue);
+ }
+ }
+
+ return Status;
+}
+/**
+ Dump text in fractions.
+
+ @param[in] String ASCII string to dump.
+
+**/
+VOID
+RedfishDumpJsonStringFractions (
+ IN CHAR8 *String
+ )
+{
+ CHAR8 *NextFraction;
+ UINTN StringFractionSize = 200;
+ UINTN StrLen;
+ UINTN Count;
+ CHAR8 BackupChar;
+
+ if (String == NULL) {
+ return ;
+ }
+
+ DEBUG((DEBUG_INFO, "JSON text:\n"));
+ NextFraction = String;
+ StrLen = AsciiStrLen (String);
+ if (StrLen == 0) {
+ return;
+ }
+ for (Count = 0; Count < (StrLen / StringFractionSize); Count++) {
+ BackupChar = *(NextFraction + StringFractionSize);
+ *(NextFraction + StringFractionSize) = 0;
+ DEBUG((DEBUG_INFO, "%a", NextFraction));
+ *(NextFraction + StringFractionSize) = BackupChar;
+ NextFraction += StringFractionSize;
+ }
+ if ((StrLen % StringFractionSize) != 0) {
+ DEBUG((DEBUG_INFO, "%a\n\n", NextFraction));
+ }
+}
+/**
+ Dump text in JSON value.
+
+ @param[in] JsonValue The Redfish JSON value to dump.
+
+**/
+VOID
+RedfishDumpJson (
+ IN EDKII_JSON_VALUE JsonValue
+ )
+{
+ CHAR8 *String;
+
+ String = JsonDumpString (JsonValue, 0);
+ if (String == NULL) {
+ return;
+ }
+ RedfishDumpJsonStringFractions (String);
+ FreePool(String);
+}
+/**
+ Extract the JSON text content from REDFISH_PAYLOAD and dump to debug console.
+
+ @param[in] Payload The Redfish payload to dump.
+
+**/
+VOID
+RedfishDumpPayload (
+ IN REDFISH_PAYLOAD Payload
+ )
+{
+ EDKII_JSON_VALUE JsonValue;
+ CHAR8 *String;
+
+ JsonValue = NULL;
+ String = NULL;
+
+ if (Payload == NULL) {
+ return;
+ }
+
+ JsonValue = RedfishJsonInPayload (Payload);
+ if (JsonValue == NULL) {
+ return;
+ }
+
+ String = JsonDumpString (JsonValue, 0);
+ if (String == NULL) {
+ return;
+ }
+
+ RedfishDumpJsonStringFractions (String);
+ FreePool(String);
+}
+/**
+ This function will cleanup the HTTP header and Redfish payload resources.
+
+ @param[in] StatusCode The status code in HTTP response message.
+ @param[in] HeaderCount Number of HTTP header structures in Headers list.
+ @param[in] Headers Array containing list of HTTP headers.
+ @param[in] Payload The Redfish payload to dump.
+
+**/
+VOID
+RedfishFreeResponse (
+ IN EFI_HTTP_STATUS_CODE *StatusCode,
+ IN UINTN HeaderCount,
+ IN EFI_HTTP_HEADER *Headers,
+ IN REDFISH_PAYLOAD Payload
+ )
+{
+ if (StatusCode != NULL) {
+ FreePool (StatusCode);
+ StatusCode = NULL;
+ }
+
+ if (HeaderCount != 0 && Headers != NULL) {
+ HttpFreeHeaderFields(Headers, HeaderCount);
+ Headers = NULL;
+ }
+
+ if (Payload != NULL) {
+ RedfishCleanupPayload (Payload);
+ Payload = NULL;
+ }
+}
+/**
+ Check if the "@odata.type" in Payload is valid or not.
+
+ @param[in] Payload The Redfish payload to be checked.
+ @param[in] OdataTypeName OdataType will be retrived from mapping list.
+ @param[in] OdataTypeMappingList The list of OdataType.
+ @param[in] OdataTypeMappingListSize The number of mapping list
+
+ @return TRUE if the "@odata.type" in Payload is valid, otherwise FALSE.
+
+**/
+BOOLEAN
+RedfishIsValidOdataType (
+ IN REDFISH_PAYLOAD Payload,
+ IN CONST CHAR8 *OdataTypeName,
+ IN REDFISH_ODATA_TYPE_MAPPING *OdataTypeMappingList,
+ IN UINTN OdataTypeMappingListSize
+ )
+{
+ UINTN Index;
+ EDKII_JSON_VALUE OdataType;
+ EDKII_JSON_VALUE JsonValue;
+
+ if (Payload == NULL || OdataTypeName == NULL) {
+ return FALSE;
+ }
+
+ JsonValue = RedfishJsonInPayload (Payload);
+ if (!JsonValueIsObject (JsonValue)) {
+ return FALSE;
+ }
+
+ OdataType = JsonObjectGetValue (JsonValueGetObject (JsonValue), "@odata.type");
+ if (!JsonValueIsString (OdataType) || JsonValueGetAsciiString (OdataType) == NULL) {
+ return FALSE;
+ }
+
+ for (Index = 0; Index < OdataTypeMappingListSize; Index ++) {
+ if (AsciiStrCmp (OdataTypeMappingList[Index].OdataTypeName, OdataTypeName) == 0 &&
+ AsciiStrCmp (OdataTypeMappingList[Index].OdataType, JsonValueGetAsciiString (OdataType)) == 0) {
+ return TRUE;
+ }
+ }
+ DEBUG ((DEBUG_INFO, "%a: This Odata type is not in the list.\n", __FUNCTION__));
+ return FALSE;
+}
+/**
+ Check if the payload is collection
+
+ @param[in] Payload The Redfish payload to be checked.
+
+ @return TRUE if the payload is collection.
+
+**/
+BOOLEAN
+RedfishIsPayloadCollection (
+ IN REDFISH_PAYLOAD Payload
+)
+{
+ return isPayloadCollection (Payload);
+}
+/**
+ Get collection size.
+
+ @param[in] Payload The Redfish collection payload
+ @param[in] CollectionSize Size of this collection
+
+ @return EFI_SUCCESS Coolection size is returned in CollectionSize
+ @return EFI_INVALID_PARAMETER The payload is not a collection.
+**/
+EFI_STATUS
+RedfishGetCollectionSize(
+ IN REDFISH_PAYLOAD Payload,
+ IN UINTN *CollectionSize
+ )
+{
+ if (Payload == NULL || CollectionSize == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+ if (RedfishIsPayloadCollection(Payload) != TRUE) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ *CollectionSize = (UINTN)getCollectionSize(Payload);
+ return EFI_SUCCESS;
+}
+/**
+ Get Redfish payload of collection member
+
+ @param[in] Payload The Redfish collection payload
+ @param[in] Index Index of collection member
+
+ @return NULL Fail to get collection member.
+ @return Non NULL Payload is returned.
+**/
+REDFISH_PAYLOAD
+RedfishGetPayloadByIndex (
+ IN REDFISH_PAYLOAD Payload,
+ IN UINTN Index
+)
+{
+ REDFISH_RESPONSE RedfishResponse;
+ REDFISH_PAYLOAD PayloadReturn;
+
+ PayloadReturn = (VOID *)getPayloadByIndex (Payload, Index, &RedfishResponse.StatusCode);
+ if(PayloadReturn == NULL ||
+ (*(RedfishResponse.StatusCode) < HTTP_STATUS_200_OK && *(RedfishResponse.StatusCode) > HTTP_STATUS_206_PARTIAL_CONTENT)){
+ return NULL;
+ }
+ return PayloadReturn;
+}
+/**
+ Check and return Redfish resource of the given Redpath.
+
+ @param[in] RedfishService Pointer to REDFISH_SERVICE
+ @param[in] Redpath Redpath of the resource.
+ @param[in] Response Optional return the resource.
+
+ @return EFI_STATUS
+**/
+EFI_STATUS
+RedfishCheckIfRedpathExist (
+ IN REDFISH_SERVICE RedfishService,
+ IN CHAR8 *Redpath,
+ IN REDFISH_RESPONSE *Response OPTIONAL
+ )
+{
+ EFI_STATUS Status;
+ REDFISH_RESPONSE TempResponse;
+
+ if (Redpath == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+ Status = RedfishGetByService (RedfishService, Redpath, &TempResponse);
+ if (EFI_ERROR (Status)) {
+ return Status;
+ }
+ if (Response == NULL) {
+ RedfishFreeResponse(
+ TempResponse.StatusCode,
+ TempResponse.HeaderCount,
+ TempResponse.Headers,
+ TempResponse.Payload
+ );
+ } else {
+ CopyMem ((VOID *)Response, (VOID *)&TempResponse, sizeof (REDFISH_RESPONSE));
+ }
+ return EFI_SUCCESS;
+}
diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/RedfishMisc.c b/RedfishPkg/PrivateLibrary/RedfishLib/RedfishMisc.c
new file mode 100644
index 0000000000..7077c37154
--- /dev/null
+++ b/RedfishPkg/PrivateLibrary/RedfishLib/RedfishMisc.c
@@ -0,0 +1,201 @@
+/** @file
+ Internal Functions for RedfishLib.
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "RedfishMisc.h"
+
+EDKII_REDFISH_CREDENTIAL_PROTOCOL *mCredentialProtocol = NULL;
+
+/**
+ This function returns the string of Redfish service version.
+
+ @param[in] RedfishService Redfish service instance.
+ @param[out] ServiceVersionStr Redfish service string.
+
+ @return EFI_STATUS
+
+**/
+EFI_STATUS
+RedfishGetServiceVersion (
+ IN REDFISH_SERVICE RedfishService,
+ OUT CHAR8 **ServiceVersionStr
+ )
+{
+ redfishService *Redfish;
+ CHAR8 **KeysArray;
+ UINTN KeysNum;
+
+ if (RedfishService == NULL || ServiceVersionStr == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+ Redfish = (redfishService *)RedfishService;
+ if (Redfish->versions == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+ KeysArray = JsonObjectGetKeys (Redfish->versions, &KeysNum);
+ if (KeysNum == 0 || KeysArray == NULL) {
+ return EFI_NOT_FOUND;
+ }
+ *ServiceVersionStr = *KeysArray;
+ return EFI_SUCCESS;
+}
+
+/**
+ Creates a REDFISH_SERVICE which can be later used to access the Redfish resources.
+
+ This function will configure REST EX child according to parameters described in
+ Redfish network host interface in SMBIOS type 42 record. The service enumerator will also
+ handle the authentication flow automatically if HTTP basic auth or Redfish session
+ login is configured to use.
+
+ @param[in] RedfishConfigServiceInfo Redfish service information the EFI Redfish
+ feature driver communicates with.
+ @param[in] AuthMethod None, HTTP basic auth, or Redfish session login.
+ @param[in] UserId User Name used for authentication.
+ @param[in] Password Password used for authentication.
+
+ @return New created Redfish service, or NULL if error happens.
+
+**/
+REDFISH_SERVICE
+RedfishCreateLibredfishService (
+ IN REDFISH_CONFIG_SERVICE_INFORMATION *RedfishConfigServiceInfo,
+ IN EDKII_REDFISH_AUTH_METHOD AuthMethod,
+ IN CHAR8 *UserId,
+ IN CHAR8 *Password
+ )
+{
+
+ UINTN Flags;
+ enumeratorAuthentication Auth;
+ redfishService* Redfish;
+
+ Redfish = NULL;
+
+ ZeroMem (&Auth, sizeof (Auth));
+ if (AuthMethod == AuthMethodHttpBasic) {
+ Auth.authType = REDFISH_AUTH_BASIC;
+ } else if (AuthMethod == AuthMethodRedfishSession) {
+ Auth.authType = REDFISH_AUTH_SESSION;
+ }
+ Auth.authCodes.userPass.username = UserId;
+ Auth.authCodes.userPass.password = Password;
+
+ Flags = REDFISH_FLAG_SERVICE_NO_VERSION_DOC;
+
+ if (AuthMethod != AuthMethodNone) {
+ Redfish = createServiceEnumerator(RedfishConfigServiceInfo, NULL, &Auth, (unsigned int ) Flags);
+ } else {
+ Redfish = createServiceEnumerator(RedfishConfigServiceInfo, NULL, NULL, (unsigned int) Flags);
+ }
+
+ //
+ // Zero the Password after use.
+ //
+ if (Password != NULL) {
+ ZeroMem (Password, AsciiStrLen(Password));
+ }
+
+ return (REDFISH_SERVICE) Redfish;
+}
+
+/**
+ Retrieve platform's Redfish authentication information.
+
+ This functions returns the Redfish authentication method together with the user
+ Id and password.
+ For AuthMethodNone, UserId and Password will point to NULL which means authentication
+ is not required to access the Redfish service.
+ For AuthMethodHttpBasic, the UserId and Password could be used for
+ HTTP header authentication as defined by RFC7235. For AuthMethodRedfishSession,
+ the UserId and Password could be used for Redfish session login as defined by
+ Redfish API specification (DSP0266).
+
+ Callers are responsible for freeing the returned string storage pointed by UserId
+ and Password.
+
+ @param[out] AuthMethod Type of Redfish authentication method.
+ @param[out] UserId The pointer to store the returned UserId string.
+ @param[out] Password The pointer to store the returned Password string.
+
+ @retval EFI_SUCCESS Get the authentication information successfully.
+ @retval EFI_INVALID_PARAMETER AuthMethod or UserId or Password is NULL.
+ @retval EFI_UNSUPPORTED Unsupported authentication method is found.
+**/
+EFI_STATUS
+RedfishGetAuthInfo (
+ OUT EDKII_REDFISH_AUTH_METHOD *AuthMethod,
+ OUT CHAR8 **UserId,
+ OUT CHAR8 **Password
+ )
+{
+ EFI_STATUS Status;
+
+ if (AuthMethod == NULL || UserId == NULL || Password == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // Locate Redfish Credential Protocol.
+ //
+ if (mCredentialProtocol == NULL) {
+ Status = gBS->LocateProtocol (&gEdkIIRedfishCredentialProtocolGuid, NULL, (VOID **)&mCredentialProtocol);
+ if (EFI_ERROR (Status)) {
+ return EFI_UNSUPPORTED;
+ }
+ }
+
+ ASSERT (mCredentialProtocol != NULL);
+
+ Status = mCredentialProtocol->GetAuthInfo (mCredentialProtocol, AuthMethod, UserId, Password);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "RedfishGetAuthInfo: failed to retrieve Redfish credential - %r\n", Status));
+ return Status;
+ }
+
+ return Status;
+}
+/**
+ This function returns the string of Redfish service version.
+
+ @param[in] ServiceVerisonStr The string of Redfish service version.
+ @param[in] Url The URL to build Redpath with ID.
+ Start with "/", for example "/Registries"
+ @param[in] Id ID string
+ @param[out] Redpath Pointer to retrive Redpath, caller has to free
+ the memory allocated for this string.
+ @return EFI_STATUS
+
+**/
+EFI_STATUS
+RedfishBuildRedpathUseId (
+ IN CHAR8 *ServiceVerisonStr,
+ IN CHAR8 *Url,
+ IN CHAR8 *Id,
+ OUT CHAR8 **Redpath
+ )
+{
+ UINTN RedpathSize;
+
+ if (Redpath == NULL || ServiceVerisonStr == NULL || Url == NULL || Id == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ RedpathSize = AsciiStrLen ("/") +
+ AsciiStrLen (ServiceVerisonStr) +
+ AsciiStrLen (Url) +
+ AsciiStrLen ("[Id=]") +
+ AsciiStrLen (Id) + 1;
+ *Redpath = AllocatePool(RedpathSize);
+ if (*Redpath == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+ AsciiSPrint (*Redpath, RedpathSize, "/%a%a[Id=%a]", ServiceVerisonStr, Url, Id);
+ return EFI_SUCCESS;
+}
diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/payload.c b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/payload.c
new file mode 100644
index 0000000000..3d60acd926
--- /dev/null
+++ b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/payload.c
@@ -0,0 +1,732 @@
+/** @file
+ This file is cloned from DMTF libredfish library tag v1.0.0 and maintained
+ by EDKII.
+
+//----------------------------------------------------------------------------
+// Copyright Notice:
+// Copyright 2017 Distributed Management Task Force, Inc. All rights reserved.
+// License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/libredfish/LICENSE.md
+//----------------------------------------------------------------------------
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#include <redfishPayload.h>
+
+static redfishPayload* getOpResult(redfishPayload* payload, const char* propName, const char* op, const char* value, EFI_HTTP_STATUS_CODE** StatusCode);
+static redfishPayload* collectionEvalOp(redfishPayload* payload, const char* propName, const char* op, const char* value, EFI_HTTP_STATUS_CODE** StatusCode);
+static redfishPayload* arrayEvalOp(redfishPayload* payload, const char* propName, const char* op, const char* value, EFI_HTTP_STATUS_CODE** StatusCode);
+static redfishPayload* createCollection(redfishService* service, size_t count, redfishPayload** payloads);
+static json_t* json_object_get_by_index(json_t* json, size_t index);
+
+bool isPayloadCollection(redfishPayload* payload)
+{
+ json_t* members;
+ json_t* count;
+
+ if(!payload || !json_is_object(payload->json))
+ {
+ return false;
+ }
+ members = json_object_get(payload->json, "Members");
+ count = json_object_get(payload->json, "Members@...");
+ return ((members != NULL) && (count != NULL));
+}
+
+size_t getCollectionSize(redfishPayload* payload)
+{
+ json_t* members;
+ json_t* count;
+
+ if(!payload || !json_is_object(payload->json))
+ {
+ return 0;
+ }
+ members = json_object_get(payload->json, "Members");
+ count = json_object_get(payload->json, "Members@...");
+ if(!members || !count)
+ {
+ return 0;
+ }
+ return (size_t)json_integer_value(count);
+}
+
+bool isPayloadArray(redfishPayload* payload)
+{
+ if(!payload || !json_is_array(payload->json))
+ {
+ return false;
+ }
+ return true;
+}
+
+char* payloadToString(redfishPayload* payload, bool prettyPrint)
+{
+ size_t flags = 0;
+ if(!payload)
+ {
+ return NULL;
+ }
+ if(prettyPrint)
+ {
+ flags = JSON_INDENT(2);
+ }
+ return json_dumps(payload->json, flags);
+}
+
+redfishPayload* createRedfishPayload(json_t* value, redfishService* service)
+{
+ redfishPayload* payload;
+ payload = (redfishPayload*)malloc(sizeof(redfishPayload));
+ if(payload != NULL)
+ {
+ payload->json = value;
+ payload->service = service;
+ }
+ return payload;
+}
+
+redfishPayload* getPayloadByNodeName(redfishPayload* payload, const char* nodeName, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ json_t* value;
+ json_t* odataId;
+ const char* uri;
+
+ if(!payload || !nodeName || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+
+ value = json_object_get(payload->json, nodeName);
+ if(value == NULL)
+ {
+ return NULL;
+ }
+ json_incref(value);
+ if(json_object_size(value) == 1)
+ {
+ odataId = json_object_get(value, "@odata.id");
+ if(odataId != NULL)
+ {
+ json_incref(odataId);
+ uri = json_string_value(odataId);
+ json_decref(value);
+ value = getUriFromService(payload->service, uri, StatusCode);
+ json_decref(odataId);
+ if(value == NULL || *StatusCode == NULL)
+ {
+ return NULL;
+ }
+ }
+ }
+ if (*StatusCode == NULL || (**StatusCode >= HTTP_STATUS_200_OK && **StatusCode <= HTTP_STATUS_206_PARTIAL_CONTENT)) {
+ if(json_is_string(value))
+ {
+ odataId = json_object();
+ json_object_set(odataId, nodeName, value);
+ json_decref(value);
+ value = odataId;
+ }
+ }
+
+ return createRedfishPayload(value, payload->service);
+}
+
+redfishPayload* getPayloadByIndex(redfishPayload* payload, size_t index, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ json_t* value = NULL;
+ json_t* odataId;
+ const char* uri;
+ BOOLEAN FromServerFlag = FALSE;
+
+ if(!payload || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+
+ if(isPayloadCollection(payload))
+ {
+ redfishPayload* members = getPayloadByNodeName(payload, "Members", StatusCode);
+ if ((*StatusCode == NULL && members == NULL) ||
+ (*StatusCode != NULL && (**StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT))) {
+ return members;
+ }
+
+ if (*StatusCode != NULL) {
+ //
+ // The Payload (members) are retrived from server.
+ //
+ FreePool (*StatusCode);
+ *StatusCode = NULL;
+ FromServerFlag = TRUE;
+ }
+
+ redfishPayload* ret = getPayloadByIndex(members, index, StatusCode);
+ if (*StatusCode == NULL && ret != NULL && FromServerFlag) {
+ //
+ // In such a case, the Redfish resource is parsed from the input payload (members) directly.
+ // Since the members are retrived from server, we still return HTTP_STATUS_200_OK.
+ //
+ *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE));
+ if (*StatusCode == NULL) {
+ ret = NULL;
+ } else {
+ **StatusCode = HTTP_STATUS_200_OK;
+ }
+ }
+
+ cleanupPayload(members);
+ return ret;
+ }
+
+ if(json_is_array(payload->json))
+ {
+ //
+ // The valid range for index is from 0 to the return value of json_array_size() minus 1
+ //
+ value = json_array_get(payload->json, index);
+ }
+ else if(json_is_object(payload->json))
+ {
+ value = json_object_get_by_index(payload->json, index);
+ }
+
+ if(value == NULL)
+ {
+ return NULL;
+ }
+
+ json_incref(value);
+ if(json_object_size(value) == 1)
+ {
+ odataId = json_object_get(value, "@odata.id");
+ if(odataId != NULL)
+ {
+ uri = json_string_value(odataId);
+ json_decref(value);
+ value = getUriFromService(payload->service, uri, StatusCode);
+ if(value == NULL)
+ {
+ return NULL;
+ }
+ }
+ }
+ return createRedfishPayload(value, payload->service);
+}
+
+redfishPayload* getPayloadForPath(redfishPayload* payload, redPathNode* redpath, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ redfishPayload* ret = NULL;
+ redfishPayload* tmp;
+
+ if(!payload || !redpath || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+ BOOLEAN FromServerFlag = FALSE;
+
+ if(redpath->nodeName)
+ {
+ ret = getPayloadByNodeName(payload, redpath->nodeName, StatusCode);
+ if ((*StatusCode == NULL && ret == NULL) ||
+ (*StatusCode != NULL && (**StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT))) {
+ //
+ // Any error happen, return directly.
+ //
+ return ret;
+ }
+ }
+ else if(redpath->isIndex)
+ {
+ ASSERT (redpath->index >= 1);
+ ret = getPayloadByIndex(payload, redpath->index - 1, StatusCode);
+ if ((*StatusCode == NULL && ret == NULL) ||
+ (*StatusCode != NULL && (**StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT))) {
+ //
+ // Any error happen, return directly.
+ //
+ return ret;
+ }
+ }
+ else if(redpath->op)
+ {
+ ret = getOpResult(payload, redpath->propName, redpath->op, redpath->value, StatusCode);
+ if ((*StatusCode == NULL && ret == NULL) ||
+ (*StatusCode != NULL && (**StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT))) {
+ //
+ // Any error happen, return directly.
+ //
+ return ret;
+ }
+ }
+ else
+ {
+ return NULL;
+ }
+
+ if(redpath->next == NULL || ret == NULL)
+ {
+ return ret;
+ }
+ else
+ {
+ if (*StatusCode != NULL) {
+ FreePool (*StatusCode);
+ *StatusCode = NULL;
+ FromServerFlag = TRUE;
+ }
+
+ tmp = getPayloadForPath(ret, redpath->next, StatusCode);
+ if (*StatusCode == NULL && tmp != NULL && FromServerFlag) {
+ //
+ // In such a case, the Redfish resource is parsed from the input payload (ret) directly.
+ // Since the ret are retrived from server, we still return HTTP_STATUS_200_OK.
+ //
+ *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE));
+ if (*StatusCode == NULL) {
+ tmp = NULL;
+ } else {
+ **StatusCode = HTTP_STATUS_200_OK;
+ }
+ }
+
+ cleanupPayload(ret);
+ return tmp;
+ }
+}
+
+redfishPayload* getPayloadForPathString(redfishPayload* payload, const char* string, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ redPathNode* redpath;
+ redfishPayload* ret;
+
+ if(!string || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+
+ redpath = parseRedPath(string);
+ if(redpath == NULL)
+ {
+ return NULL;
+ }
+ ret = getPayloadForPath(payload, redpath, StatusCode);
+ cleanupRedPath(redpath);
+ return ret;
+}
+
+redfishPayload* patchPayload(redfishPayload* target, redfishPayload* payload, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ json_t* json;
+ char* content;
+ char* uri;
+
+ if(!target || !payload || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+
+ json = json_object_get(target->json, "@odata.id");
+ if(json == NULL)
+ {
+ return NULL;
+ }
+ uri = strdup(json_string_value(json));
+
+ content = json_dumps(payload->json, 0);
+ json_decref(json);
+
+ json = patchUriFromService(target->service, uri, content, StatusCode);
+ free(uri);
+ free(content);
+ if(json == NULL)
+ {
+ return NULL;
+ }
+
+ return createRedfishPayload(json, target->service);
+}
+
+redfishPayload* postContentToPayload(redfishPayload* target, const char* data, size_t dataSize, const char* contentType, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ json_t* json;
+ char* uri;
+
+ if(!target || !data || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+
+ json = json_object_get(target->json, "@odata.id");
+ if(json == NULL)
+ {
+ json = json_object_get(target->json, "target");
+ if(json == NULL)
+ {
+ return NULL;
+ }
+ }
+ uri = strdup(json_string_value(json));
+ json = postUriFromService(target->service, uri, data, dataSize, contentType, StatusCode);
+ free(uri);
+ if(json == NULL)
+ {
+ return NULL;
+ }
+
+ return createRedfishPayload(json, target->service);
+}
+
+redfishPayload* postPayload(redfishPayload* target, redfishPayload* payload, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ char* content;
+ redfishPayload* ret;
+
+ if(!target || !payload || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+
+ if(!json_is_object(payload->json))
+ {
+ return NULL;
+ }
+ content = payloadToString(payload, false);
+ ret = postContentToPayload(target, content, strlen(content), NULL, StatusCode);
+ free(content);
+ return ret;
+}
+
+void cleanupPayload(redfishPayload* payload)
+{
+ if(!payload)
+ {
+ return;
+ }
+ json_decref(payload->json);
+ //Don't free payload->service, let the caller handle cleaning up the service
+ free(payload);
+}
+
+static redfishPayload* getOpResult(redfishPayload* payload, const char* propName, const char* op, const char* value, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ const char* propStr;
+ json_t* stringProp;
+ bool ret = false;
+ redfishPayload* prop;
+ long long intVal, intPropVal;
+ json_type jsonType;
+
+ if(isPayloadCollection(payload))
+ {
+ return collectionEvalOp(payload, propName, op, value, StatusCode);
+ }
+ if(isPayloadArray(payload))
+ {
+ return arrayEvalOp(payload, propName, op, value, StatusCode);
+ }
+
+ prop = getPayloadByNodeName(payload, propName, StatusCode);
+ if ((*StatusCode == NULL && prop == NULL) ||
+ (*StatusCode != NULL && (**StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT))) {
+ return prop;
+ }
+ stringProp = prop->json;
+ jsonType = prop->json->type;
+ switch(jsonType)
+ {
+ case JSON_OBJECT:
+ stringProp = json_object_get(prop->json, propName);
+ case JSON_STRING:
+ if(strcmp(op, "=") == 0)
+ {
+ propStr = json_string_value(stringProp);
+ if(propStr == NULL)
+ {
+ cleanupPayload(prop);
+ return NULL;
+ }
+ ret = (strcmp(propStr, value) == 0);
+ } else if(strcmp(op, "~") == 0)
+ {
+ propStr = json_string_value(stringProp);
+ if(propStr == NULL)
+ {
+ cleanupPayload(prop);
+ return NULL;
+ }
+ ret = (strcasecmp(propStr, value) == 0);
+ }
+ break;
+ case JSON_TRUE:
+ if(strcmp(op, "=") == 0)
+ {
+ ret = (strcmp(value, "true") == 0);
+ }
+ break;
+ case JSON_FALSE:
+ if(strcmp(op, "=") == 0)
+ {
+ ret = (strcmp(value, "false") == 0);
+ }
+ break;
+ case JSON_INTEGER:
+ intPropVal = json_integer_value(prop->json);
+ intVal = strtoll(value, NULL, 0);
+ if(strcmp(op, "=") == 0)
+ {
+ ret = (intPropVal == intVal);
+ }
+ else if(strcmp(op, "<") == 0)
+ {
+ ret = (intPropVal < intVal);
+ }
+ else if(strcmp(op, ">") == 0)
+ {
+ ret = (intPropVal > intVal);
+ }
+ else if(strcmp(op, "<=") == 0)
+ {
+ ret = (intPropVal <= intVal);
+ }
+ else if(strcmp(op, ">=") == 0)
+ {
+ ret = (intPropVal >= intVal);
+ }
+ break;
+ default:
+ break;
+ }
+ cleanupPayload(prop);
+ if(ret)
+ {
+ return payload;
+ }
+ else
+ {
+ return NULL;
+ }
+}
+
+static redfishPayload* collectionEvalOp(redfishPayload* payload, const char* propName, const char* op, const char* value, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ redfishPayload* ret;
+ redfishPayload* tmp;
+ redfishPayload* members;
+ redfishPayload** valid;
+ size_t validMax;
+ size_t validCount = 0;
+ size_t i;
+
+ validMax = getCollectionSize(payload);
+ if(validMax == 0)
+ {
+ return NULL;
+ }
+
+ valid = (redfishPayload**)calloc(validMax, sizeof(redfishPayload*));
+ if(valid == NULL)
+ {
+ return NULL;
+ }
+ /*Technically getPayloadByIndex would do this, but this optimizes things*/
+ members = getPayloadByNodeName(payload, "Members", StatusCode);
+ if ((*StatusCode == NULL && members == NULL) ||
+ (*StatusCode != NULL && (**StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT))) {
+ return members;
+ }
+
+ for(i = 0; i < validMax; i++)
+ {
+ if (*StatusCode != NULL) {
+ FreePool (*StatusCode);
+ *StatusCode = NULL;
+ }
+
+ tmp = getPayloadByIndex(members, i, StatusCode);
+ if ((*StatusCode == NULL && tmp == NULL) ||
+ (*StatusCode != NULL && (**StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT))) {
+ return tmp;
+ }
+
+ if (*StatusCode != NULL) {
+ FreePool (*StatusCode);
+ *StatusCode = NULL;
+ }
+
+ valid[validCount] = getOpResult(tmp, propName, op, value, StatusCode);
+ /*
+ if ((*StatusCode == NULL && valid[validCount] == NULL) ||
+ (*StatusCode != NULL && (**StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT))) {
+ return valid[validCount];
+ }
+ */
+ if(valid[validCount] != NULL)
+ {
+ validCount++;
+ }
+ else
+ {
+ cleanupPayload(tmp);
+ }
+ }
+ cleanupPayload(members);
+ if(validCount == 0)
+ {
+ free(valid);
+ return NULL;
+ }
+ if(validCount == 1)
+ {
+ ret = valid[0];
+ free(valid);
+ return ret;
+ }
+ else
+ {
+ ret = createCollection(payload->service, validCount, valid);
+ free(valid);
+ return ret;
+ }
+}
+
+static redfishPayload* arrayEvalOp(redfishPayload* payload, const char* propName, const char* op, const char* value, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ redfishPayload* ret;
+ redfishPayload* tmp;
+ redfishPayload** valid;
+ size_t validMax;
+ size_t validCount = 0;
+ size_t i;
+
+ validMax = json_array_size(payload->json);
+ if(validMax == 0)
+ {
+ return NULL;
+ }
+
+ valid = (redfishPayload**)calloc(validMax, sizeof(redfishPayload*));
+ if(valid == NULL)
+ {
+ return NULL;
+ }
+ for(i = 0; i < validMax; i++)
+ {
+ if (*StatusCode != NULL) {
+ FreePool (*StatusCode);
+ *StatusCode = NULL;
+ }
+
+ tmp = getPayloadByIndex(payload, i, StatusCode);
+ if ((*StatusCode == NULL && tmp == NULL) ||
+ (*StatusCode != NULL && (**StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT))) {
+ return tmp;
+ }
+
+ if (*StatusCode != NULL) {
+ FreePool (*StatusCode);
+ *StatusCode = NULL;
+ }
+
+ valid[validCount] = getOpResult(tmp, propName, op, value, StatusCode);
+ /*
+ if ((*StatusCode == NULL && valid[validCount] == NULL) ||
+ (*StatusCode != NULL && (**StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT))) {
+ return valid[validCount];
+ }
+ */
+
+ if(valid[validCount] != NULL)
+ {
+ validCount++;
+ }
+ else
+ {
+ cleanupPayload(tmp);
+ }
+ }
+ if(validCount == 0)
+ {
+ free(valid);
+ return NULL;
+ }
+ if(validCount == 1)
+ {
+ ret = valid[0];
+ free(valid);
+ return ret;
+ }
+ else
+ {
+ ret = createCollection(payload->service, validCount, valid);
+ free(valid);
+ return ret;
+ }
+}
+
+static redfishPayload* createCollection(redfishService* service, size_t count, redfishPayload** payloads)
+{
+ redfishPayload* ret;
+ json_t* collectionJson = json_object();
+ json_t* jcount = json_integer((json_int_t)count);
+ json_t* members = json_array();
+ size_t i;
+
+ if(!collectionJson)
+ {
+ return NULL;
+ }
+ if(!members)
+ {
+ json_decref(collectionJson);
+ return NULL;
+ }
+ json_object_set(collectionJson, "Members@...", jcount);
+ json_decref(jcount);
+ for(i = 0; i < count; i++)
+ {
+ json_array_append(members, payloads[i]->json);
+ cleanupPayload(payloads[i]);
+ }
+ json_object_set(collectionJson, "Members", members);
+ json_decref(members);
+
+ ret = createRedfishPayload(collectionJson, service);
+ return ret;
+}
+
+static json_t* json_object_get_by_index(json_t* json, size_t index)
+{
+ void* iter;
+ size_t i;
+
+ iter = json_object_iter(json);
+ for(i = 0; i < index; i++)
+ {
+ iter = json_object_iter_next(json, iter);
+ if(iter == NULL) break;
+ }
+ if(iter == NULL)
+ {
+ return NULL;
+ }
+ return json_object_iter_value(iter);
+}
+/* vim: set tabstop=4 shiftwidth=4 expandtab: */
diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/redpath.c b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/redpath.c
new file mode 100644
index 0000000000..1fb4346c2b
--- /dev/null
+++ b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/redpath.c
@@ -0,0 +1,192 @@
+/** @file
+ This file is cloned from DMTF libredfish library tag v1.0.0 and maintained
+ by EDKII.
+
+//----------------------------------------------------------------------------
+// Copyright Notice:
+// Copyright 2017 Distributed Management Task Force, Inc. All rights reserved.
+// License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/libredfish/LICENSE.md
+//----------------------------------------------------------------------------
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+#include <redpath.h>
+
+static char* getVersion(const char* path, char** end);
+static void parseNode(const char* path, redPathNode* node, redPathNode** end);
+
+static char* getStringTill(const char* string, const char* terminator, char** retEnd);
+
+redPathNode* parseRedPath(const char* path)
+{
+ redPathNode* node;
+ redPathNode* endNode;
+ char* curPath;
+ char* end;
+
+ if(!path || strlen(path) == 0)
+ {
+ return NULL;
+ }
+
+ node = (redPathNode*)calloc(1, sizeof(redPathNode));
+ if(!node)
+ {
+ return NULL;
+ }
+ if(path[0] == '/')
+ {
+ node->isRoot = true;
+ if(path[1] == 'v')
+ {
+ node->version = getVersion(path+1, &curPath);
+ if(curPath == NULL)
+ {
+ return node;
+ }
+ if(curPath[0] == '/')
+ {
+ curPath++;
+ }
+ node->next = parseRedPath(curPath);
+ }
+ else
+ {
+ node->next = parseRedPath(path+1);
+ }
+ return node;
+ }
+ node->isRoot = false;
+ curPath = getStringTill(path, "/", &end);
+ endNode = node;
+ parseNode(curPath, node, &endNode);
+ free(curPath);
+ if(end != NULL)
+ {
+ endNode->next = parseRedPath(end+1);
+ }
+ return node;
+}
+
+void cleanupRedPath(redPathNode* node)
+{
+ if(!node)
+ {
+ return;
+ }
+ cleanupRedPath(node->next);
+ node->next = NULL;
+ if(node->version)
+ {
+ free(node->version);
+ }
+ if(node->nodeName)
+ {
+ free(node->nodeName);
+ }
+ if(node->op)
+ {
+ free(node->op);
+ }
+ if(node->propName)
+ {
+ free(node->propName);
+ }
+ if(node->value)
+ {
+ free(node->value);
+ }
+ free(node);
+}
+
+static char* getVersion(const char* path, char** end)
+{
+ return getStringTill(path, "/", end);
+}
+
+static void parseNode(const char* path, redPathNode* node, redPathNode** end)
+{
+ char* indexStart;
+ char* index;
+ char* indexEnd;
+ char* nodeName = getStringTill(path, "[", &indexStart);
+ size_t tmpIndex;
+ char* opChars;
+
+ node->nodeName = nodeName;
+ if(indexStart == NULL)
+ {
+ *end = node;
+ return;
+ }
+ node->next = (redPathNode*)calloc(1, sizeof(redPathNode));
+ if(!node->next)
+ {
+ return;
+ }
+ //Skip past [
+ indexStart++;
+ *end = node->next;
+ index = getStringTill(indexStart, "]", NULL);
+ tmpIndex = (size_t)strtoull(index, &indexEnd, 0);
+ if(indexEnd != index)
+ {
+ free(index);
+ node->next->index = tmpIndex;
+ node->next->isIndex = true;
+ return;
+ }
+ opChars = strpbrk(index, "<>=~");
+ if(opChars == NULL)
+ {
+ //TODO handle last() and position()
+ node->next->op = strdup("exists");
+ node->next->propName = index;
+ return;
+ }
+ node->next->propName = (char*)malloc((opChars - index)+1);
+ memcpy(node->next->propName, index, (opChars - index));
+ node->next->propName[(opChars - index)] = 0;
+
+ tmpIndex = 1;
+ while(1)
+ {
+ if(opChars[tmpIndex] == '=' || opChars[tmpIndex] == '<' || opChars[tmpIndex] == '>' || opChars[tmpIndex] == '~')
+ {
+ tmpIndex++;
+ continue;
+ }
+ break;
+ }
+
+ node->next->op = (char*)malloc(tmpIndex+1);
+ memcpy(node->next->op, opChars, tmpIndex);
+ node->next->op[tmpIndex] = 0;
+
+ node->next->value = strdup(opChars+tmpIndex);
+ free(index);
+}
+
+static char* getStringTill(const char* string, const char* terminator, char** retEnd)
+{
+ char* ret;
+ char* end;
+ end = strstr((char*)string, terminator);
+ if(retEnd)
+ {
+ *retEnd = end;
+ }
+ if(end == NULL)
+ {
+ //No terminator
+ return strdup(string);
+ }
+ ret = (char*)malloc((end-string)+1);
+ memcpy(ret, string, (end-string));
+ ret[(end-string)] = 0;
+ return ret;
+}
diff --git a/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/service.c b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/service.c
new file mode 100644
index 0000000000..7713f89e6d
--- /dev/null
+++ b/RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/service.c
@@ -0,0 +1,1396 @@
+/** @file
+ This file is cloned from DMTF libredfish library tag v1.0.0 and maintained
+ by EDKII.
+
+//----------------------------------------------------------------------------
+// Copyright Notice:
+// Copyright 2017 Distributed Management Task Force, Inc. All rights reserved.
+// License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/libredfish/LICENSE.md
+//----------------------------------------------------------------------------
+
+ Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
+ (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <redfishService.h>
+#include <redfishPayload.h>
+#include <redpath.h>
+
+static int initRest(redfishService* service, void * restProtocol);
+static redfishService* createServiceEnumeratorNoAuth(const char* host, const char* rootUri, bool enumerate, unsigned int flags, void * restProtocol);
+static redfishService* createServiceEnumeratorBasicAuth(const char* host, const char* rootUri, const char* username, const char* password, unsigned int flags, void * restProtocol);
+static redfishService* createServiceEnumeratorSessionAuth(const char* host, const char* rootUri, const char* username, const char* password, unsigned int flags, void * restProtocol);
+static char* makeUrlForService(redfishService* service, const char* uri);
+static json_t* getVersions(redfishService* service, const char* rootUri);
+static void addStringToJsonObject(json_t* object, const char* key, const char* value);
+
+CHAR16*
+C8ToC16 (CHAR8 *AsciiStr)
+{
+ CHAR16 *Str;
+ UINTN BufLen;
+
+ BufLen = (AsciiStrLen (AsciiStr) + 1) * 2;
+ Str = AllocatePool (BufLen);
+ ASSERT (Str != NULL);
+
+ AsciiStrToUnicodeStrS (AsciiStr, Str, AsciiStrLen (AsciiStr) + 1);
+
+ return Str;
+}
+
+VOID
+RestConfigFreeHttpRequestData (
+ IN EFI_HTTP_REQUEST_DATA *RequestData
+ )
+{
+ if (RequestData == NULL) {
+ return ;
+ }
+
+ if (RequestData->Url != NULL) {
+ FreePool (RequestData->Url);
+ }
+
+ FreePool (RequestData);
+}
+
+VOID
+RestConfigFreeHttpMessage (
+ IN EFI_HTTP_MESSAGE *Message,
+ IN BOOLEAN IsRequest
+ )
+{
+ if (Message == NULL) {
+ return ;
+ }
+
+ if (IsRequest) {
+ RestConfigFreeHttpRequestData (Message->Data.Request);
+ Message->Data.Request = NULL;
+ } else {
+ if (Message->Data.Response != NULL) {
+ FreePool (Message->Data.Response);
+ Message->Data.Response = NULL;
+ }
+ }
+
+ if (Message->Headers != NULL) {
+ FreePool (Message->Headers);
+ Message->Headers = NULL;
+ }
+ if (Message->Body != NULL) {
+ FreePool (Message->Body);
+ Message->Body = NULL;
+ }
+}
+
+/**
+ Converts the Unicode string to ASCII string to a new allocated buffer.
+
+ @param[in] String Unicode string to be converted.
+
+ @return Buffer points to ASCII string, or NULL if error happens.
+
+**/
+
+CHAR8 *
+UnicodeStrDupToAsciiStr (
+ CONST CHAR16 *String
+ )
+{
+ CHAR8 *AsciiStr;
+ UINTN BufLen;
+ EFI_STATUS Status;
+
+ BufLen = StrLen (String) + 1;
+ AsciiStr = AllocatePool (BufLen);
+ if (AsciiStr == NULL) {
+ return NULL;
+ }
+
+ Status = UnicodeStrToAsciiStrS (String, AsciiStr, BufLen);
+ if (EFI_ERROR (Status)) {
+ return NULL;
+ }
+
+ return AsciiStr;
+}
+/**
+ This function encodes the content.
+
+ @param[in] ContentEncodedValue HTTP conent encoded value.
+ @param[in] OriginalContent Original content.
+ @param[out] EncodedContent Pointer to receive encoded content.
+ @param[out] EncodedContentLength Length of encoded content.
+
+ @retval EFI_SUCCESS Content encoded successfully.
+ @retval EFI_UNSUPPORTED No source encoding funciton,
+ @retval EFI_INVALID_PARAMETER One of the given parameter is invalid.
+
+**/
+EFI_STATUS
+EncodeRequestContent (
+ IN CHAR8 *ContentEncodedValue,
+ IN CHAR8 *OriginalContent,
+ OUT VOID **EncodedContent,
+ OUT UINTN *EncodedContentLength
+)
+{
+ EFI_STATUS Status;
+ VOID *EncodedPointer;
+ UINTN EncodedLength;
+
+ if (OriginalContent == NULL || EncodedContent == NULL || EncodedContentLength == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+ Status = RedfishContentEncode (
+ ContentEncodedValue,
+ OriginalContent,
+ AsciiStrLen (OriginalContent),
+ &EncodedPointer,
+ &EncodedLength
+ );
+ if (Status == EFI_SUCCESS) {
+ *EncodedContent = EncodedPointer;
+ *EncodedContentLength = EncodedLength;
+ return EFI_SUCCESS;
+ }
+ return Status;
+}
+
+/**
+ This function decodes the content. The Memory block pointed by
+ ContentPointer would be freed and replaced with the cooked Redfish
+ payload.
+
+ @param[in] ContentEncodedValue HTTP conent encoded value.
+ @param[in, out] ContentPointer Pointer to encoded content.
+ Pointer of decoded content when out.
+ @param[in, out] ContentLength Pointer to the length of encoded content.
+ Length of decoded content when out.
+
+ @retval EFI_SUCCESS Functinos found.
+ @retval EFI_UNSUPPORTED No functions found.
+ @retval EFI_INVALID_PARAMETER One of the given parameter is invalid.
+
+**/
+EFI_STATUS
+DecodeResponseContent (
+ IN CHAR8 *ContentEncodedValue,
+ IN OUT VOID **ContentPointer,
+ IN OUT UINTN *ContentLength
+)
+{
+ EFI_STATUS Status;
+ VOID *DecodedPointer;
+ UINTN DecodedLength;
+
+ if (ContentEncodedValue == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+ Status = RedfishContentDecode (
+ ContentEncodedValue,
+ *ContentPointer,
+ *ContentLength,
+ &DecodedPointer,
+ &DecodedLength
+ );
+ if (Status == EFI_SUCCESS) {
+ FreePool (*ContentPointer);
+ *ContentPointer = DecodedPointer;
+ *ContentLength = DecodedLength;
+ }
+ return Status;
+}
+
+/**
+ Create a HTTP URL string for specific Redfish resource.
+
+ This function build a URL string from the Redfish Host interface record and caller specified
+ relative path of the resource.
+
+ Callers are responsible for freeing the returned string storage pointed by HttpUrl.
+
+ @param[in] RedfishData Redfish network host interface record.
+ @param[in] RelativePath Relative path of a resource.
+ @param[out] HttpUrl The pointer to store the returned URL string.
+
+ @retval EFI_SUCCESS Build the URL string successfully.
+ @retval EFI_INVALID_PARAMETER RedfishData or HttpUrl is NULL.
+ @retval EFI_OUT_OF_RESOURCES There are not enough memory resources.
+
+**/
+EFI_STATUS
+RedfishBuildUrl (
+ IN REDFISH_CONFIG_SERVICE_INFORMATION *RedfishConfigServiceInfo,
+ IN CHAR16 *RelativePath, OPTIONAL
+ OUT CHAR16 **HttpUrl
+ )
+{
+ CHAR16 *Url;
+ CHAR16 *UrlHead;
+ UINTN UrlLength;
+ UINTN PathLen;
+
+ if ((RedfishConfigServiceInfo == NULL) || (HttpUrl == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ //
+ // RFC2616: http_URL = "http(s):" "//" host [ ":" port ] [ abs_path [ "?" query ]]
+ //
+ if (RelativePath == NULL) {
+ PathLen = 0;
+ } else {
+ PathLen = StrLen (RelativePath);
+ }
+ UrlLength = StrLen (HTTPS_FLAG) + StrLen (REDFISH_FIRST_URL) + 1 + StrLen(RedfishConfigServiceInfo->RedfishServiceLocation) + PathLen;
+ Url = AllocateZeroPool (UrlLength * sizeof (CHAR16));
+ if (Url == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ UrlHead = Url;
+ //
+ // Copy "http://" or "https://" according RedfishServiceIpPort.
+ //
+ if (!RedfishConfigServiceInfo->RedfishServiceUseHttps) {
+ StrCpyS (Url, StrLen (HTTPS_FLAG) + 1, HTTP_FLAG);
+ Url = Url + StrLen (HTTP_FLAG);
+ } else {
+ StrCpyS (Url, StrLen (HTTPS_FLAG) + 1, HTTPS_FLAG);
+ Url = Url + StrLen (HTTPS_FLAG);
+ }
+
+ StrCpyS (Url, StrLen (RedfishConfigServiceInfo->RedfishServiceLocation) + 1, RedfishConfigServiceInfo->RedfishServiceLocation);
+ Url = Url + StrLen (RedfishConfigServiceInfo->RedfishServiceLocation);
+
+ //
+ // Copy abs_path
+ //
+ if (RelativePath != NULL && PathLen != 0 ) {
+ StrnCpyS (Url, UrlLength, RelativePath, PathLen);
+ }
+ *HttpUrl = UrlHead;
+ return EFI_SUCCESS;
+}
+
+redfishService* createServiceEnumerator(REDFISH_CONFIG_SERVICE_INFORMATION *RedfishConfigServiceInfo, const char* rootUri, enumeratorAuthentication* auth, unsigned int flags)
+{
+ EFI_STATUS Status;
+ CHAR16 *HttpUrl;
+ CHAR8 *AsciiHost;
+ EFI_REST_EX_PROTOCOL *RestEx;
+ redfishService *ret;
+
+ HttpUrl = NULL;
+ AsciiHost = NULL;
+ RestEx = NULL;
+ ret = NULL;
+
+ if (RedfishConfigServiceInfo->RedfishServiceRestExHandle == NULL) {
+ goto ON_EXIT;
+ }
+ Status = RedfishBuildUrl(RedfishConfigServiceInfo, NULL, &HttpUrl);
+ if (EFI_ERROR (Status)) {
+ goto ON_EXIT;
+ }
+
+ ASSERT (HttpUrl != NULL);
+
+ AsciiHost = UnicodeStrDupToAsciiStr (HttpUrl);
+ if (AsciiHost == NULL) {
+ goto ON_EXIT;
+ }
+
+ Status = gBS->HandleProtocol (
+ RedfishConfigServiceInfo->RedfishServiceRestExHandle,
+ &gEfiRestExProtocolGuid,
+ (VOID **)&RestEx
+ );
+ if (EFI_ERROR (Status)) {
+ goto ON_EXIT;
+ }
+ if(auth == NULL) {
+ ret = createServiceEnumeratorNoAuth(AsciiHost, rootUri, true, flags, RestEx);
+ } else if(auth->authType == REDFISH_AUTH_BASIC) {
+ ret = createServiceEnumeratorBasicAuth(AsciiHost, rootUri, auth->authCodes.userPass.username, auth->authCodes.userPass.password, flags, RestEx);
+ } else if(auth->authType == REDFISH_AUTH_SESSION) {
+ ret = createServiceEnumeratorSessionAuth(AsciiHost, rootUri, auth->authCodes.userPass.username, auth->authCodes.userPass.password, flags, RestEx);
+ } else {
+ goto ON_EXIT;
+ }
+
+ ret->RestEx = RestEx;
+ON_EXIT:
+ if (HttpUrl != NULL) {
+ FreePool (HttpUrl);
+ }
+
+ if (AsciiHost != NULL) {
+ FreePool (AsciiHost);
+ }
+
+ return ret;
+}
+
+json_t* getUriFromService(redfishService* service, const char* uri, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ char* url;
+ json_t* ret;
+ HTTP_IO_HEADER *HttpIoHeader = NULL;
+ EFI_STATUS Status;
+ EFI_HTTP_REQUEST_DATA *RequestData = NULL;
+ EFI_HTTP_MESSAGE *RequestMsg = NULL;
+ EFI_HTTP_MESSAGE ResponseMsg;
+ EFI_HTTP_HEADER *ContentEncodedHeader;
+
+ if(service == NULL || uri == NULL || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+
+ url = makeUrlForService(service, uri);
+ if(!url)
+ {
+ return NULL;
+ }
+
+ DEBUG((DEBUG_INFO, "libredfish: getUriFromService(): %a\n", url));
+
+ //
+ // Step 1: Create HTTP request message with 4 headers:
+ //
+ HttpIoHeader = HttpIoCreateHeader ((service->sessionToken || service->basicAuthStr) ? 6 : 5);
+ if (HttpIoHeader == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ if(service->sessionToken)
+ {
+ Status = HttpIoSetHeader (HttpIoHeader, "X-Auth-Token", service->sessionToken);
+ ASSERT_EFI_ERROR (Status);
+ } else if (service->basicAuthStr) {
+ Status = HttpIoSetHeader (HttpIoHeader, "Authorization", service->basicAuthStr);
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ Status = HttpIoSetHeader (HttpIoHeader, "Host", service->HostHeaderValue);
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "OData-Version", "4.0");
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "Accept", "application/json");
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "User-Agent", "libredfish");
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "Connection", "Keep-Alive");
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Step 2: build the rest of HTTP request info.
+ //
+ RequestData = AllocateZeroPool (sizeof (EFI_HTTP_REQUEST_DATA));
+ if (RequestData == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ RequestData->Method = HttpMethodGet;
+ RequestData->Url = C8ToC16 (url);
+
+ //
+ // Step 3: fill in EFI_HTTP_MESSAGE
+ //
+ RequestMsg = AllocateZeroPool (sizeof (EFI_HTTP_MESSAGE));
+ if (RequestMsg == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ RequestMsg->Data.Request = RequestData;
+ RequestMsg->HeaderCount = HttpIoHeader->HeaderCount;
+ RequestMsg->Headers = HttpIoHeader->Headers;
+
+ ZeroMem (&ResponseMsg, sizeof (ResponseMsg));
+
+ //
+ // Step 4: call RESTEx to get response from REST service.
+ //
+ Status = service->RestEx->SendReceive (service->RestEx, RequestMsg, &ResponseMsg);
+ if (EFI_ERROR (Status)) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ //
+ // Step 5: Return the HTTP StatusCode and Body message.
+ //
+ if (ResponseMsg.Data.Response != NULL) {
+ *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE));
+ if (*StatusCode == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ //
+ // The caller shall take the responsibility to free the buffer.
+ //
+ **StatusCode = ResponseMsg.Data.Response->StatusCode;
+ }
+
+ if (ResponseMsg.BodyLength != 0 && ResponseMsg.Body != NULL) {
+ //
+ // Check if data is encoded.
+ //
+ ContentEncodedHeader = HttpFindHeader (ResponseMsg.HeaderCount, ResponseMsg.Headers, HTTP_HEADER_CONTENT_ENCODING);
+ if (ContentEncodedHeader != NULL) {
+ //
+ // The content is encoded.
+ //
+ Status = DecodeResponseContent (ContentEncodedHeader->FieldValue, &ResponseMsg.Body, &ResponseMsg.BodyLength);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((DEBUG_ERROR, "%a: Failed to decompress the response content %r\n.", __FUNCTION__, Status));
+ ret = NULL;
+ goto ON_EXIT;
+ }
+ }
+ ret = json_loadb (ResponseMsg.Body, ResponseMsg.BodyLength, 0, NULL);
+ } else {
+ //
+ // There is no message body returned from server.
+ //
+ ret = NULL;
+ }
+
+ON_EXIT:
+ if (url != NULL) {
+ free (url);
+ }
+
+ if (HttpIoHeader != NULL) {
+ HttpIoFreeHeader (HttpIoHeader);
+ }
+
+ if (RequestData != NULL) {
+ RestConfigFreeHttpRequestData (RequestData);
+ }
+
+ if (RequestMsg != NULL) {
+ FreePool (RequestMsg);
+ }
+
+ RestConfigFreeHttpMessage (&ResponseMsg, FALSE);
+
+ return ret;
+}
+
+json_t* patchUriFromService(redfishService* service, const char* uri, const char* content, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ char* url;
+ json_t* ret;
+ HTTP_IO_HEADER *HttpIoHeader = NULL;
+ EFI_STATUS Status;
+ EFI_HTTP_REQUEST_DATA *RequestData = NULL;
+ EFI_HTTP_MESSAGE *RequestMsg = NULL;
+ EFI_HTTP_MESSAGE ResponseMsg;
+ CHAR8 ContentLengthStr[80];
+ CHAR8 *EncodedContent;
+ UINTN EncodedContentLen;
+
+ if(service == NULL || uri == NULL || content == NULL || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+
+ url = makeUrlForService(service, uri);
+ if(!url)
+ {
+ return NULL;
+ }
+
+ DEBUG((DEBUG_INFO, "libredfish: patchUriFromService(): %a\n", url));
+
+ //
+ // Step 1: Create HTTP request message with 4 headers:
+ //
+ HttpIoHeader = HttpIoCreateHeader ((service->sessionToken || service->basicAuthStr) ? 9 : 8);
+ if (HttpIoHeader == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ if(service->sessionToken)
+ {
+ Status = HttpIoSetHeader (HttpIoHeader, "X-Auth-Token", service->sessionToken);
+ ASSERT_EFI_ERROR (Status);
+ } else if (service->basicAuthStr) {
+ Status = HttpIoSetHeader (HttpIoHeader, "Authorization", service->basicAuthStr);
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ Status = HttpIoSetHeader (HttpIoHeader, "Host", service->HostHeaderValue);
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "Content-Type", "application/json");
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "Accept", "application/json");
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "User-Agent", "libredfish");
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "Connection", "Keep-Alive");
+ ASSERT_EFI_ERROR (Status);
+
+ AsciiSPrint(
+ ContentLengthStr,
+ sizeof (ContentLengthStr),
+ "%lu",
+ (UINT64) strlen(content)
+ );
+ Status = HttpIoSetHeader (HttpIoHeader, "Content-Length", ContentLengthStr);
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "OData-Version", "4.0");
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Step 2: build the rest of HTTP request info.
+ //
+ RequestData = AllocateZeroPool (sizeof (EFI_HTTP_REQUEST_DATA));
+ if (RequestData == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ RequestData->Method = HttpMethodPatch;
+ RequestData->Url = C8ToC16 (url);
+
+ //
+ // Step 3: fill in EFI_HTTP_MESSAGE
+ //
+ RequestMsg = AllocateZeroPool (sizeof (EFI_HTTP_MESSAGE));
+ if (RequestMsg == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ EncodedContent = (CHAR8 *)content;
+ EncodedContentLen = strlen(content);
+ //
+ // We currently only support gzip Content-Encoding.
+ //
+ Status = EncodeRequestContent ((CHAR8 *)HTTP_CONTENT_ENCODING_GZIP, (CHAR8 *)content, (VOID **)&EncodedContent, &EncodedContentLen);
+ if (Status == EFI_INVALID_PARAMETER) {
+ DEBUG((DEBUG_ERROR, "%a: Error to encode content.\n", __FUNCTION__));
+ ret = NULL;
+ goto ON_EXIT;
+ } else if (Status == EFI_UNSUPPORTED) {
+ DEBUG((DEBUG_INFO, "No content coding for %a! Use raw data instead.\n", HTTP_CONTENT_ENCODING_GZIP));
+ Status = HttpIoSetHeader (HttpIoHeader, "Content-Encoding", HTTP_CONTENT_ENCODING_IDENTITY);
+ ASSERT_EFI_ERROR (Status);
+ } else {
+ Status = HttpIoSetHeader (HttpIoHeader, "Content-Encoding", HTTP_CONTENT_ENCODING_GZIP);
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ RequestMsg->Data.Request = RequestData;
+ RequestMsg->HeaderCount = HttpIoHeader->HeaderCount;
+ RequestMsg->Headers = HttpIoHeader->Headers;
+ RequestMsg->BodyLength = EncodedContentLen;
+ RequestMsg->Body = (VOID*) EncodedContent;
+
+ ZeroMem (&ResponseMsg, sizeof (ResponseMsg));
+
+ //
+ // Step 4: call RESTEx to get response from REST service.
+ //
+ Status = service->RestEx->SendReceive (service->RestEx, RequestMsg, &ResponseMsg);
+ if (EFI_ERROR (Status)) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ //
+ // Step 5: Return the HTTP StatusCode and Body message.
+ //
+ if (ResponseMsg.Data.Response != NULL) {
+ *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE));
+ if (*StatusCode == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ //
+ // The caller shall take the responsibility to free the buffer.
+ //
+ **StatusCode = ResponseMsg.Data.Response->StatusCode;
+ }
+
+ if (EncodedContent != content) {
+ FreePool (EncodedContent);
+ }
+
+
+ if (ResponseMsg.BodyLength != 0 && ResponseMsg.Body != NULL) {
+ ret = json_loadb (ResponseMsg.Body, ResponseMsg.BodyLength, 0, NULL);
+ } else {
+ //
+ // There is no message body returned from server.
+ //
+ ret = NULL;
+ }
+
+ON_EXIT:
+ if (url != NULL) {
+ free (url);
+ }
+
+ if (HttpIoHeader != NULL) {
+ HttpIoFreeHeader (HttpIoHeader);
+ }
+
+ if (RequestData != NULL) {
+ RestConfigFreeHttpRequestData (RequestData);
+ }
+
+ if (RequestMsg != NULL) {
+ FreePool (RequestMsg);
+ }
+
+ RestConfigFreeHttpMessage (&ResponseMsg, FALSE);
+
+ return ret;
+}
+
+json_t* postUriFromService(redfishService* service, const char* uri, const char* content, size_t contentLength, const char* contentType, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ char* url = NULL;
+ json_t* ret;
+ HTTP_IO_HEADER *HttpIoHeader = NULL;
+ EFI_STATUS Status;
+ EFI_HTTP_REQUEST_DATA *RequestData = NULL;
+ EFI_HTTP_MESSAGE *RequestMsg = NULL;
+ EFI_HTTP_MESSAGE ResponseMsg;
+ CHAR8 ContentLengthStr[80];
+ EFI_HTTP_HEADER *HttpHeader = NULL;
+
+ ret = NULL;
+
+ if(service == NULL || uri == NULL || content == NULL || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+
+ url = makeUrlForService(service, uri);
+ if(!url)
+ {
+ return NULL;
+ }
+
+ DEBUG((DEBUG_INFO, "libredfish: postUriFromService(): %a\n", url));
+
+ if(contentLength == 0)
+ {
+ contentLength = strlen(content);
+ }
+
+ //
+ // Step 1: Create HTTP request message with 4 headers:
+ //
+ HttpIoHeader = HttpIoCreateHeader ((service->sessionToken || service->basicAuthStr) ? 8 : 7);
+ if (HttpIoHeader == NULL) {
+ goto ON_EXIT;
+ }
+
+ if(service->sessionToken)
+ {
+ Status = HttpIoSetHeader (HttpIoHeader, "X-Auth-Token", service->sessionToken);
+ ASSERT_EFI_ERROR (Status);
+ } else if (service->basicAuthStr) {
+ Status = HttpIoSetHeader (HttpIoHeader, "Authorization", service->basicAuthStr);
+ ASSERT_EFI_ERROR (Status);
+ }
+
+ if(contentType == NULL) {
+ Status = HttpIoSetHeader (HttpIoHeader, "Content-Type", "application/json");
+ ASSERT_EFI_ERROR (Status);
+ } else {
+ Status = HttpIoSetHeader (HttpIoHeader, "Content-Type", (CHAR8 *) contentType);
+ ASSERT_EFI_ERROR (Status);
+ }
+ Status = HttpIoSetHeader (HttpIoHeader, "Host", service->HostHeaderValue);
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "Accept", "application/json");
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "User-Agent", "libredfish");
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "Connection", "Keep-Alive");
+ ASSERT_EFI_ERROR (Status);
+ AsciiSPrint(
+ ContentLengthStr,
+ sizeof (ContentLengthStr),
+ "%lu",
+ (UINT64) contentLength
+ );
+ Status = HttpIoSetHeader (HttpIoHeader, "Content-Length", ContentLengthStr);
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "OData-Version", "4.0");
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Step 2: build the rest of HTTP request info.
+ //
+ RequestData = AllocateZeroPool (sizeof (EFI_HTTP_REQUEST_DATA));
+ if (RequestData == NULL) {
+ goto ON_EXIT;
+ }
+
+ RequestData->Method = HttpMethodPost;
+ RequestData->Url = C8ToC16 (url);
+
+ //
+ // Step 3: fill in EFI_HTTP_MESSAGE
+ //
+ RequestMsg = AllocateZeroPool (sizeof (EFI_HTTP_MESSAGE));
+ if (RequestMsg == NULL) {
+ goto ON_EXIT;
+ }
+
+ RequestMsg->Data.Request = RequestData;
+ RequestMsg->HeaderCount = HttpIoHeader->HeaderCount;
+ RequestMsg->Headers = HttpIoHeader->Headers;
+ RequestMsg->BodyLength = contentLength;
+ RequestMsg->Body = (VOID*) content;
+
+ ZeroMem (&ResponseMsg, sizeof (ResponseMsg));
+
+ //
+ // Step 4: call RESTEx to get response from REST service.
+ //
+ Status = service->RestEx->SendReceive (service->RestEx, RequestMsg, &ResponseMsg);
+ if (EFI_ERROR (Status)) {
+ goto ON_EXIT;
+ }
+
+ //
+ // Step 5: Return the HTTP StatusCode and Body message.
+ //
+ if (ResponseMsg.Data.Response != NULL) {
+ *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE));
+ if (*StatusCode == NULL) {
+ goto ON_EXIT;
+ }
+
+ //
+ // The caller shall take the responsibility to free the buffer.
+ //
+ **StatusCode = ResponseMsg.Data.Response->StatusCode;
+ }
+
+ if (ResponseMsg.BodyLength != 0 && ResponseMsg.Body != NULL) {
+ ret = json_loadb (ResponseMsg.Body, ResponseMsg.BodyLength, 0, NULL);
+ }
+
+ //
+ // Step 6: Parsing the HttpHeader to retrive the X-Auth-Token if the HTTP StatusCode is correct.
+ //
+ if (ResponseMsg.Data.Response->StatusCode == HTTP_STATUS_200_OK ||
+ ResponseMsg.Data.Response->StatusCode == HTTP_STATUS_204_NO_CONTENT) {
+ HttpHeader = HttpFindHeader (ResponseMsg.HeaderCount, ResponseMsg.Headers, "X-Auth-Token");
+ if (HttpHeader != NULL) {
+ if(service->sessionToken)
+ {
+ free(service->sessionToken);
+ }
+ service->sessionToken = AllocateCopyPool (AsciiStrSize (HttpHeader->FieldValue), HttpHeader->FieldValue);
+ }
+
+ /*
+ //
+ // Below opeation seems to be unnecessary.
+ // Besides, the FieldValue for the Location is the full HTTP URI (Http://0.0.0.0:5000/XXX), so we can't use it as the
+ // parameter of getUriFromService () directly.
+ //
+ HttpHeader = HttpFindHeader (ResponseMsg.HeaderCount, ResponseMsg.Headers, "Location");
+ if (HttpHeader != NULL) {
+ ret = getUriFromService(service, HttpHeader->FieldValue);
+ goto ON_EXIT;
+ }
+ */
+ }
+
+ON_EXIT:
+ if (url != NULL) {
+ free (url);
+ }
+
+ if (HttpIoHeader != NULL) {
+ HttpIoFreeHeader (HttpIoHeader);
+ }
+
+ if (RequestData != NULL) {
+ RestConfigFreeHttpRequestData (RequestData);
+ }
+
+ if (RequestMsg != NULL) {
+ FreePool (RequestMsg);
+ }
+
+ RestConfigFreeHttpMessage (&ResponseMsg, FALSE);
+
+ return ret;
+}
+
+json_t* deleteUriFromService(redfishService* service, const char* uri, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ char* url;
+ json_t* ret;
+ HTTP_IO_HEADER *HttpIoHeader = NULL;
+ EFI_STATUS Status;
+ EFI_HTTP_REQUEST_DATA *RequestData = NULL;
+ EFI_HTTP_MESSAGE *RequestMsg = NULL;
+ EFI_HTTP_MESSAGE ResponseMsg;
+
+ ret = NULL;
+
+ if(service == NULL || uri == NULL || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+
+ url = makeUrlForService(service, uri);
+ if(!url)
+ {
+ return NULL;
+ }
+
+ DEBUG((DEBUG_INFO, "libredfish: deleteUriFromService(): %a\n", url));
+
+ //
+ // Step 1: Create HTTP request message with 4 headers:
+ //
+ HttpIoHeader = HttpIoCreateHeader ((service->sessionToken || service->basicAuthStr) ? 5 : 4);
+ if (HttpIoHeader == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ if(service->sessionToken)
+ {
+ Status = HttpIoSetHeader (HttpIoHeader, "X-Auth-Token", service->sessionToken);
+ ASSERT_EFI_ERROR (Status);
+ } else if (service->basicAuthStr) {
+ Status = HttpIoSetHeader (HttpIoHeader, "Authorization", service->basicAuthStr);
+ ASSERT_EFI_ERROR (Status);
+ }
+ Status = HttpIoSetHeader (HttpIoHeader, "Host", service->HostHeaderValue);
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "User-Agent", "libredfish");
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "OData-Version", "4.0");
+ ASSERT_EFI_ERROR (Status);
+ Status = HttpIoSetHeader (HttpIoHeader, "Connection", "Keep-Alive");
+ ASSERT_EFI_ERROR (Status);
+
+ //
+ // Step 2: build the rest of HTTP request info.
+ //
+ RequestData = AllocateZeroPool (sizeof (EFI_HTTP_REQUEST_DATA));
+ if (RequestData == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ RequestData->Method = HttpMethodDelete;
+ RequestData->Url = C8ToC16 (url);
+
+ //
+ // Step 3: fill in EFI_HTTP_MESSAGE
+ //
+ RequestMsg = AllocateZeroPool (sizeof (EFI_HTTP_MESSAGE));
+ if (RequestMsg == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ RequestMsg->Data.Request = RequestData;
+ RequestMsg->HeaderCount = HttpIoHeader->HeaderCount;
+ RequestMsg->Headers = HttpIoHeader->Headers;
+
+ ZeroMem (&ResponseMsg, sizeof (ResponseMsg));
+
+ //
+ // Step 4: call RESTEx to get response from REST service.
+ //
+ Status = service->RestEx->SendReceive (service->RestEx, RequestMsg, &ResponseMsg);
+ if (EFI_ERROR (Status)) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ //
+ // Step 5: Return the HTTP StatusCode and Body message.
+ //
+ if (ResponseMsg.Data.Response != NULL) {
+ *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE));
+ if (*StatusCode == NULL) {
+ ret = NULL;
+ goto ON_EXIT;
+ }
+
+ //
+ // The caller shall take the responsibility to free the buffer.
+ //
+ **StatusCode = ResponseMsg.Data.Response->StatusCode;
+ }
+
+ if (ResponseMsg.BodyLength != 0 && ResponseMsg.Body != NULL) {
+ ret = json_loadb (ResponseMsg.Body, ResponseMsg.BodyLength, 0, NULL);
+ }
+
+ON_EXIT:
+ if (url != NULL) {
+ free (url);
+ }
+
+ if (HttpIoHeader != NULL) {
+ HttpIoFreeHeader (HttpIoHeader);
+ }
+
+ if (RequestData != NULL) {
+ RestConfigFreeHttpRequestData (RequestData);
+ }
+
+ if (RequestMsg != NULL) {
+ FreePool (RequestMsg);
+ }
+
+ RestConfigFreeHttpMessage (&ResponseMsg, FALSE);
+
+ return ret;
+}
+
+redfishPayload* getRedfishServiceRoot(redfishService* service, const char* version, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ json_t* value;
+ json_t* versionNode;
+ const char* verUrl;
+
+ if(version == NULL)
+ {
+ versionNode = json_object_get(service->versions, "v1");
+ }
+ else
+ {
+ versionNode = json_object_get(service->versions, version);
+ }
+ if(versionNode == NULL)
+ {
+ return NULL;
+ }
+ verUrl = json_string_value(versionNode);
+ if(verUrl == NULL)
+ {
+ return NULL;
+ }
+ value = getUriFromService(service, verUrl, StatusCode);
+ if(value == NULL)
+ {
+ if((service->flags & REDFISH_FLAG_SERVICE_NO_VERSION_DOC) == 0)
+ {
+ json_decref(versionNode);
+ }
+ return NULL;
+ }
+ return createRedfishPayload(value, service);
+}
+
+redfishPayload* getPayloadByPath(redfishService* service, const char* path, EFI_HTTP_STATUS_CODE** StatusCode)
+{
+ redPathNode* redpath;
+ redfishPayload* root;
+ redfishPayload* ret;
+
+ if(!service || !path || StatusCode == NULL)
+ {
+ return NULL;
+ }
+
+ *StatusCode = NULL;
+
+ redpath = parseRedPath(path);
+ if(!redpath)
+ {
+ return NULL;
+ }
+ if(!redpath->isRoot)
+ {
+ cleanupRedPath(redpath);
+ return NULL;
+ }
+ root = getRedfishServiceRoot(service, redpath->version, StatusCode);
+ if (*StatusCode == NULL || **StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT) {
+ cleanupRedPath(redpath);
+ return root;
+ }
+
+ if(redpath->next == NULL)
+ {
+ cleanupRedPath(redpath);
+ return root;
+ }
+
+ FreePool (*StatusCode);
+ *StatusCode = NULL;
+
+ ret = getPayloadForPath(root, redpath->next, StatusCode);
+ if (*StatusCode == NULL && ret != NULL) {
+ //
+ // In such a case, the Redfish resource is parsed from the input payload (root) directly.
+ // So, we still return HTTP_STATUS_200_OK.
+ //
+ *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE));
+ if (*StatusCode == NULL) {
+ ret = NULL;
+ } else {
+ **StatusCode = HTTP_STATUS_200_OK;
+ }
+ }
+ cleanupPayload(root);
+ cleanupRedPath(redpath);
+ return ret;
+}
+
+void cleanupServiceEnumerator(redfishService* service)
+{
+ if(!service)
+ {
+ return;
+ }
+ free(service->host);
+ json_decref(service->versions);
+ if(service->sessionToken != NULL)
+ {
+ ZeroMem (service->sessionToken, (UINTN)strlen(service->sessionToken));
+ FreePool(service->sessionToken);
+ }
+ if (service->basicAuthStr != NULL) {
+ ZeroMem (service->basicAuthStr, (UINTN)strlen(service->basicAuthStr));
+ FreePool (service->basicAuthStr);
+ }
+ free(service);
+}
+
+static int initRest(redfishService* service, void * restProtocol)
+{
+ service->RestEx = restProtocol;
+ return 0;
+}
+
+static redfishService* createServiceEnumeratorNoAuth(const char* host, const char* rootUri, bool enumerate, unsigned int flags, void * restProtocol)
+{
+ redfishService* ret;
+ char *HostStart;
+
+ ret = (redfishService*)calloc(1, sizeof(redfishService));
+ ZeroMem (ret, sizeof(redfishService));
+ if(initRest(ret, restProtocol) != 0)
+ {
+ free(ret);
+ return NULL;
+ }
+ ret->host = AllocateCopyPool(AsciiStrSize(host), host);
+ ret->flags = flags;
+ if(enumerate)
+ {
+ ret->versions = getVersions(ret, rootUri);
+ }
+ HostStart = strstr (ret->host, "//");
+ if (HostStart != NULL && (*(HostStart + 2) != '\0')) {
+ ret->HostHeaderValue = HostStart + 2;
+ }
+
+ return ret;
+}
+
+EFI_STATUS
+createBasicAuthStr (
+ IN redfishService* service,
+ IN CONST CHAR8 *UserId,
+ IN CONST CHAR8 *Password
+ )
+{
+ EFI_STATUS Status;
+ CHAR8 *RawAuthValue;
+ UINTN RawAuthBufSize;
+ CHAR8 *EnAuthValue;
+ UINTN EnAuthValueSize;
+ CHAR8 *BasicWithEnAuthValue;
+ UINTN BasicBufSize;
+
+ EnAuthValue = NULL;
+ EnAuthValueSize = 0;
+
+ RawAuthBufSize = AsciiStrLen (UserId) + AsciiStrLen (Password) + 2;
+ RawAuthValue = AllocatePool (RawAuthBufSize);
+ if (RawAuthValue == NULL) {
+ return EFI_OUT_OF_RESOURCES;
+ }
+
+ //
+ // Build raw AuthValue (UserId:Password).
+ //
+ AsciiSPrint (
+ RawAuthValue,
+ RawAuthBufSize,
+ "%a:%a",
+ UserId,
+ Password
+ );
+
+ //
+ // Encoding RawAuthValue into Base64 format.
+ //
+ Status = Base64Encode (
+ (CONST UINT8 *) RawAuthValue,
+ AsciiStrLen (RawAuthValue),
+ EnAuthValue,
+ &EnAuthValueSize
+ );
+ if (Status == EFI_BUFFER_TOO_SMALL) {
+ EnAuthValue = (CHAR8 *) AllocateZeroPool (EnAuthValueSize);
+ if (EnAuthValue == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ return Status;
+ }
+
+ Status = Base64Encode (
+ (CONST UINT8 *) RawAuthValue,
+ AsciiStrLen (RawAuthValue),
+ EnAuthValue,
+ &EnAuthValueSize
+ );
+ }
+
+ if (EFI_ERROR (Status)) {
+ goto Exit;
+ }
+
+ BasicBufSize = AsciiStrLen ("Basic ") + AsciiStrLen(EnAuthValue) + 2;
+ BasicWithEnAuthValue = AllocatePool (BasicBufSize);
+ if (BasicWithEnAuthValue == NULL) {
+ Status = EFI_OUT_OF_RESOURCES;
+ goto Exit;
+ }
+
+ //
+ // Build encoded EnAuthValue with Basic (Basic EnAuthValue).
+ //
+ AsciiSPrint (
+ BasicWithEnAuthValue,
+ BasicBufSize,
+ "%a %a",
+ "Basic",
+ EnAuthValue
+ );
+
+ service->basicAuthStr = BasicWithEnAuthValue;
+
+Exit:
+ if (RawAuthValue != NULL) {
+ ZeroMem (RawAuthValue, RawAuthBufSize);
+ FreePool (RawAuthValue);
+ }
+
+ if (EnAuthValue != NULL) {
+ ZeroMem (EnAuthValue, EnAuthValueSize);
+ FreePool (EnAuthValue);
+ }
+
+ return Status;
+}
+
+static redfishService* createServiceEnumeratorBasicAuth(const char* host, const char* rootUri, const char* username, const char* password, unsigned int flags, void * restProtocol)
+{
+ redfishService* ret;
+ EFI_STATUS Status;
+
+ ret = createServiceEnumeratorNoAuth(host, rootUri, false, flags, restProtocol);
+
+ // add basic auth str
+ Status = createBasicAuthStr (ret, username, password);
+ if (EFI_ERROR(Status)) {
+ cleanupServiceEnumerator (ret);
+ return NULL;
+ }
+
+ ret->versions = getVersions(ret, rootUri);
+ return ret;
+}
+
+static redfishService* createServiceEnumeratorSessionAuth(const char* host, const char* rootUri, const char* username, const char* password, unsigned int flags, void * restProtocol)
+{
+ redfishService* ret;
+ redfishPayload* payload;
+ redfishPayload* links;
+ json_t* sessionPayload;
+ json_t* session;
+ json_t* odataId;
+ const char* uri;
+ json_t* post;
+ char* content;
+ EFI_HTTP_STATUS_CODE *StatusCode;
+
+ content = NULL;
+ StatusCode = NULL;
+
+ ret = createServiceEnumeratorNoAuth(host, rootUri, true, flags, restProtocol);
+ if(ret == NULL)
+ {
+ return NULL;
+ }
+ payload = getRedfishServiceRoot(ret, NULL, &StatusCode);
+ if(StatusCode == NULL || *StatusCode < HTTP_STATUS_200_OK || *StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT)
+ {
+ if (StatusCode != NULL) {
+ FreePool (StatusCode);
+ }
+
+ if (payload != NULL) {
+ cleanupPayload(payload);
+ }
+ cleanupServiceEnumerator(ret);
+ return NULL;
+ }
+
+ if (StatusCode != NULL) {
+ FreePool (StatusCode);
+ StatusCode = NULL;
+ }
+
+ links = getPayloadByNodeName(payload, "Links", &StatusCode);
+ cleanupPayload(payload);
+ if(links == NULL)
+ {
+ cleanupServiceEnumerator(ret);
+ return NULL;
+ }
+ session = json_object_get(links->json, "Sessions");
+ if(session == NULL)
+ {
+ cleanupPayload(links);
+ cleanupServiceEnumerator(ret);
+ return NULL;
+ }
+ odataId = json_object_get(session, "@odata.id");
+ if(odataId == NULL)
+ {
+ cleanupPayload(links);
+ cleanupServiceEnumerator(ret);
+ return NULL;
+ }
+ uri = json_string_value(odataId);
+ post = json_object();
+ addStringToJsonObject(post, "UserName", username);
+ addStringToJsonObject(post, "Password", password);
+ content = json_dumps(post, 0);
+ json_decref(post);
+ sessionPayload = postUriFromService(ret, uri, content, 0, NULL, &StatusCode);
+
+ if (content != NULL) {
+ ZeroMem (content, (UINTN)strlen(content));
+ free(content);
+ }
+
+ if(sessionPayload == NULL || StatusCode == NULL || *StatusCode < HTTP_STATUS_200_OK || *StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT)
+ {
+ //Failed to create session!
+
+ cleanupPayload(links);
+ cleanupServiceEnumerator(ret);
+
+ if (StatusCode != NULL) {
+ FreePool (StatusCode);
+ }
+
+ if (sessionPayload != NULL) {
+ json_decref(sessionPayload);
+ }
+
+ return NULL;
+ }
+ json_decref(sessionPayload);
+ cleanupPayload(links);
+ FreePool (StatusCode);
+ return ret;
+}
+
+static char* makeUrlForService(redfishService* service, const char* uri)
+{
+ char* url;
+ if(service->host == NULL)
+ {
+ return NULL;
+ }
+ url = (char*)malloc(strlen(service->host)+strlen(uri)+1);
+ strcpy(url, service->host);
+ strcat(url, uri);
+ return url;
+}
+
+static json_t* getVersions(redfishService* service, const char* rootUri)
+{
+ json_t* ret = NULL;
+ EFI_HTTP_STATUS_CODE* StatusCode = NULL;
+
+ if(service->flags & REDFISH_FLAG_SERVICE_NO_VERSION_DOC)
+ {
+ service->versions = json_object();
+ if(service->versions == NULL)
+ {
+ return NULL;
+ }
+ addStringToJsonObject(service->versions, "v1", "/redfish/v1");
+ return service->versions;
+ }
+ if(rootUri != NULL)
+ {
+ ret = getUriFromService(service, rootUri, &StatusCode);
+ }
+ else
+ {
+ ret = getUriFromService(service, "/redfish", &StatusCode);
+ }
+
+ if (ret == NULL || StatusCode == NULL || *StatusCode < HTTP_STATUS_200_OK || *StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT) {
+ if (ret != NULL) {
+ json_decref(ret);
+ }
+ ret = NULL;
+ }
+
+ if (StatusCode != NULL) {
+ FreePool (StatusCode);
+ }
+
+ return ret;
+}
+
+static void addStringToJsonObject(json_t* object, const char* key, const char* value)
+{
+ json_t* jValue = json_string(value);
+
+ json_object_set(object, key, jValue);
+
+ json_decref(jValue);
+}
diff --git a/RedfishPkg/RedfishPkg.ci.yaml b/RedfishPkg/RedfishPkg.ci.yaml
index fde6fa89bc..1fe9bdb8d1 100644
--- a/RedfishPkg/RedfishPkg.ci.yaml
+++ b/RedfishPkg/RedfishPkg.ci.yaml
@@ -1,7 +1,7 @@
## @file
# CI configuration for NetworkPkg
#
-# (C) Copyright 2020 Hewlett Packard Enterprise Development LP<BR>
+# (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
{
@@ -41,7 +41,18 @@
## load.c is overrided from open source.
"Library/JsonLib/load.c",
"Library/JsonLib/jansson_config.h",
- "Library/JsonLib/jansson_private_config.h"
+ "Library/JsonLib/jansson_private_config.h",
+ ##
+ ## For libredfish open source
+ ## The files under edk2libredfish are cloned
+ ## from DMTF open source
+ "PrivateLibrary/RedfishLib/edk2libredfish/include/redfish.h",
+ "PrivateLibrary/RedfishLib/edk2libredfish/include/redfishPayload.h",
+ "PrivateLibrary/RedfishLib/edk2libredfish/include/redfishService.h",
+ "PrivateLibrary/RedfishLib/edk2libredfish/include/redpath.h",
+ "PrivateLibrary/RedfishLib/edk2libredfish/src/payload.c",
+ "PrivateLibrary/RedfishLib/edk2libredfish/src/redpath.c",
+ "PrivateLibrary/RedfishLib/edk2libredfish/src/service.c"
]
},
"CompilerPlugin": {
--
2.17.1


Re: [PATCH 0/2 v5] Add support for running StandaloneMm as OP-TEE TA

Sami Mujawar
 

Hi Ard, Leif,

This patch series is creating 2 new folders Platform/StMMRpmb & Drivers/OpTeeRpmb.
- Should these be in Drivers\StandaloneMmRpmbPkg similar to Drivers\OptionRomPkg ?
- Also, the maintainer.txt file would need updating accordingly.

Any advice/suggestions about this, please.

Regards,

Sami Mujawar

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Ilias Apalodimas via groups.io
Sent: 12 February 2021 05:35 PM
To: devel@edk2.groups.io; Sami Mujawar <Sami.Mujawar@...>
Cc: ardb+tianocore@...; sughosh.ganu@...; leif@...; Ilias Apalodimas <ilias.apalodimas@...>
Subject: [edk2-devel] [PATCH 0/2 v5] Add support for running StandaloneMm as OP-TEE TA

Hi,

This is v5 of [1]

Changes since V4:
- More coding stule fixes proposed by Sami, which Ecc or Patchcheck didn't
report.
- Adding missing error handling in InitializeFvAndVariableStoreHeaders().
An allocation wasn't properly checked for success

Changes since V3:
- Coding style fixes proposed by Sami
- Fixed all reported PatchCheck errors
- Added overflow checks on the base aaddress allocated for EFI variables.
The size of the partition is user defined (via Pcd's) and the memory layout
and allocation address depends on OP-TEE. So let's make sure we won't overflow
when calculating the 3 partitions needed for FTW
- Switched some PcdGet/Set32 to 64 to accomodate 64-bit addressing
- Removed some duplicate entries in Platform/StMMRpmb/PlatformStandaloneMm.dsc
- Added reviewed-by tags on patch 2/2

Changes since V2:
- Allocate a dynamic number of pages based on the Pcd values instead
of a static number
- Clean up unused structs in header file
- Added checks in OpTeeRpmbFvbGetBlockSize and handle NumLba=0

Changes since V1:
Some enhancements made by Ilias to the Optee Rpmb driver

[1] https://edk2.groups.io/g/devel/message/66483?p=,,,20,0,0,0::Created,,ilias+apalodimas,20,2,0,77703661

Ilias Apalodimas (2):
Drivers/OpTeeRpmb: Add an OP-TEE backed RPMB driver
StMMRpmb: Add support for building StandaloneMm image for OP-TEE

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 ++
Platform/StMMRpmb/PlatformStandaloneMm.dsc | 165 ++++
Platform/StMMRpmb/PlatformStandaloneMm.fdf | 111 +++
7 files changed, 1438 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
create mode 100644 Platform/StMMRpmb/PlatformStandaloneMm.dsc
create mode 100644 Platform/StMMRpmb/PlatformStandaloneMm.fdf

--
2.30.0


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

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@...>
*Sent:* Friday, February 12, 2021 5:34 PM
*To:* devel@edk2.groups.io <devel@edk2.groups.io>; Sami Mujawar <Sami.Mujawar@...>
*Cc:* ardb+tianocore@... <ardb+tianocore@...>; sughosh.ganu@... <sughosh.ganu@...>; leif@... <leif@...>; Ilias Apalodimas <ilias.apalodimas@...>
*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@...>
---
 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@...]
-=-=-=-=-=-=


Re: [PATCH 2/2 v5] StMMRpmb: Add support for building StandaloneMm image for OP-TEE

PierreGondois
 

Hello Ilias,

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@...>
*Sent:* Friday, February 12, 2021 5:34 PM
*To:* devel@edk2.groups.io <devel@edk2.groups.io>; Sami Mujawar <Sami.Mujawar@...>
*Cc:* ardb+tianocore@... <ardb+tianocore@...>; sughosh.ganu@... <sughosh.ganu@...>; leif@... <leif@...>; Ilias Apalodimas <ilias.apalodimas@...>
*Subject:* [edk2-devel] [PATCH 2/2 v5] StMMRpmb: Add support for building StandaloneMm image for OP-TEE
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 <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 <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/ <https://git.linaro.org/people/ilias.apalodimas/efi_optee_variables.git/>

Reviewed-by: Sami Mujawar <sami.mujawar@...>
Signed-off-by: Ilias Apalodimas <ilias.apalodimas@...>
---
 Platform/StMMRpmb/PlatformStandaloneMm.dsc | 165 +++++++++++++++++++++
 Platform/StMMRpmb/PlatformStandaloneMm.fdf | 111 ++++++++++++++
 2 files changed, 276 insertions(+)
 create mode 100644 Platform/StMMRpmb/PlatformStandaloneMm.dsc
 create mode 100644 Platform/StMMRpmb/PlatformStandaloneMm.fdf

diff --git a/Platform/StMMRpmb/PlatformStandaloneMm.dsc b/Platform/StMMRpmb/PlatformStandaloneMm.dsc
new file mode 100644
index 000000000000..1f1ddf968c1f
--- /dev/null
+++ b/Platform/StMMRpmb/PlatformStandaloneMm.dsc
@@ -0,0 +1,165 @@
+#

+#  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                  = MmStandaloneRpmb

+  PLATFORM_GUID                  = A27A486E-D7B9-4D70-9F37-FED9ABE041A2

+  PLATFORM_VERSION               = 1.0

+  DSC_SPECIFICATION              = 0x00010011
I think we are at the revision 0x0001001C, cf https://edk2-docs.gitbook.io/edk-ii-dsc-specification/3_edk_ii_dsc_file_format/35_-defines-_section


+  OUTPUT_DIRECTORY               = Build/$(PLATFORM_NAME)

+  SUPPORTED_ARCHITECTURES        = AARCH64

+  BUILD_TARGETS                  = DEBUG|RELEASE|NOOPT

+  SKUID_IDENTIFIER               = DEFAULT

+  FLASH_DEFINITION               = Platform/StMMRpmb/PlatformStandaloneMm.fdf

+  DEFINE DEBUG_MESSAGE           = TRUE

+

+  # LzmaF86

+  DEFINE COMPRESSION_TOOL_GUID   = D42AE6BD-1352-4bfb-909A-CA72A6EAE889

+

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

+#

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

+#

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

+[LibraryClasses]

+  ArmSvcLib|ArmPkg/Library/ArmSvcLib/ArmSvcLib.inf

+  ArmLib|ArmPkg/Library/ArmLib/ArmBaseLib.inf

+  BaseLib|MdePkg/Library/BaseLib/BaseLib.inf

+ SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf

+ VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf

+ BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf

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

+ ExtractGuidedSectionLib|EmbeddedPkg/Library/PrePiExtractGuidedSectionLib/PrePiExtractGuidedSectionLib.inf

+  FvLib|StandaloneMmPkg/Library/FvLib/FvLib.inf

+ HobLib|StandaloneMmPkg/Library/StandaloneMmCoreHobLib/StandaloneMmCoreHobLib.inf

+ IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf

+ MemLib|StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLib.inf

+ MemoryAllocationLib|StandaloneMmPkg/Library/StandaloneMmCoreMemoryAllocationLib/StandaloneMmCoreMemoryAllocationLib.inf

+  PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf

+ PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf

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

+ VariablePolicyLib|MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.inf

+ ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf

+

+  #

+  # Entry point

+  #

+ StandaloneMmCoreEntryPoint|StandaloneMmPkg/Library/StandaloneMmCoreEntryPoint/StandaloneMmCoreEntryPoint.inf

+ StandaloneMmDriverEntryPoint|MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEntryPoint.inf

+

+ StandaloneMmMmuLib|ArmPkg/Library/StandaloneMmMmuLib/ArmMmuStandaloneMmLib.inf

+ CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLibNull/BaseCacheMaintenanceLibNull.inf

+ PeCoffExtraActionLib|StandaloneMmPkg/Library/StandaloneMmPeCoffExtraActionLib/StandaloneMmPeCoffExtraActionLib.inf

+  RngLib|MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf

+

+ SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf

+ DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf
It seems in the previous patch you are using some 'DEBUG ()' and 'ASSERT () statements. Wouldn't using BaseDebugLibNull and BaseSerialPortLibNull make them useless for DEBUG and RELEASE build ?

+

+  #

+  # It is not possible to prevent the ARM compiler for generic intrinsic functions.

+  # This library provides the intrinsic functions generate by a given compiler.

+  # 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/StandaloneMmServicesTableLib.inf

+ MemoryAllocationLib|StandaloneMmPkg/Library/StandaloneMmMemoryAllocationLib/StandaloneMmMemoryAllocationLib.inf

+

+ IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf

+  OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf

+ PlatformSecureLib|SecurityPkg/Library/PlatformSecureLibNull/PlatformSecureLibNull.inf

+ SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf

+ TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf

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

+#

+# Pcd Section - list of all EDK II PCD Entries defined by this Platform

+#

+################################################################################
Since this comment is for the PCD section, I think it would be better to remove the empty line after the comment and add one at the top of this comment.
+

+[PcdsFeatureFlag.common]

+  gArmTokenSpaceGuid.PcdFfaEnable|TRUE

+

+[PcdsFixedAtBuild]

+ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x800000CF

+  gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0xff

+ gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x0f

+

+ 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.PcdFlashNvStorageVariableBase64|0x0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64|0x0

+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64|0x0

+

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

+#

+# Components Section - list of the modules and components that will be processed by compilation

+#                      tools and the EDK II tools to generate PE32/PE32+/Coff image files.

+#

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

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

+#       source into UEFI-compliant binaries.

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

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

+#       Binary modules do not need to be listed in this section, as they should be

+#       specified in the FDF file. For example: Shell binary (Shell_Full.efi), FAT binary (Fat.efi),

+#       Logo (Logo.bmp), and etc.

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

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

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

+#

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

+[Components.common]

+  #

+  # Standalone MM components

+  #

+  Drivers/OpTeeRpmb/OpTeeRpmbFv.inf

+  StandaloneMmPkg/Core/StandaloneMmCore.inf

+ StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/StandaloneMmCpu.inf

+ MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandaloneMm.inf {

+    <LibraryClasses>

+      NULL|Drivers/OpTeeRpmb/FixupPcd.inf

+  }

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

+    <LibraryClasses>

+ 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 asOn 3/2/21 4:43 PM, Pierre wrote:

+#                        the default flags for a module. These flags are appended to any

+#                        standard flags that are defined by the build process. They can be

+#                        applied for any modules or only those modules with the specific

+#                        module style (EDK or EDKII) specified in [Components] section.

+#

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

+[BuildOptions.AARCH64]

+GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000 -march=armv8-a+nofp

+GCC:*_*_*_CC_FLAGS = -mstrict-align

diff --git a/Platform/StMMRpmb/PlatformStandaloneMm.fdf b/Platform/StMMRpmb/PlatformStandaloneMm.fdf
new file mode 100644
index 000000000000..febc6d0d959b
--- /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   = 0x1000 # any address apart from 0x0

+Size          = 0x00300000

+ErasePolarity = 1

+

+BlockSize     = 0x00001000

+NumBlocks     = 0x0300

+

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

+#

+# Following are lists of FD Region layout which correspond to the locations 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" required) 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 <FV, DATA, or FILE>

+#

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

+

+0x00000000|0x00280000

+FV = FVMAIN_COMPACT

+

+[FV.FVMAIN_COMPACT]

+FvAlignment        = 8

+ERASE_POLARITY     = 1

+MEMORY_MAPPED      = TRUE

+STICKY_WRITE       = TRUE

+LOCK_CAP           = TRUE

+LOCK_STATUS        = TRUE

+WRITE_DISABLED_CAP = TRUE

+WRITE_ENABLED_CAP  = TRUE

+WRITE_STATUS       = TRUE

+WRITE_LOCK_CAP     = TRUE

+WRITE_LOCK_STATUS  = TRUE

+READ_DISABLED_CAP  = TRUE

+READ_ENABLED_CAP   = TRUE

+READ_STATUS        = TRUE

+READ_LOCK_CAP      = TRUE

+READ_LOCK_STATUS   = TRUE

+

+  INF StandaloneMmPkg/Core/StandaloneMmCore.inf

+  INF Drivers/OpTeeRpmb/OpTeeRpmbFv.inf

+  INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandaloneMm.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 to 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 = $(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="$(MODULE_NAME)" Optional

+#        VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)

+#      }

+#    }

+#  }

+#

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

+

+[Rule.Common.MM_CORE_STANDALONE]

+  FILE SEC = $(NAMED_GUID) FIXED {

+    PE32  PE32 Align = Auto $(INF_OUTPUT)/$(MODULE_NAME).efi

+  }

+

+[Rule.Common.MM_STANDALONE]

+  FILE MM_STANDALONE = $(NAMED_GUID) {

+    SMM_DEPEX SMM_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex

+    PE32      PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi

+    UI        STRING="$(MODULE_NAME)" Optional

+    VERSION   STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)

+  }

--
2.30.0



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


Re: [PATCH - resend] MdeModulePkg/Universal/SmbiosDxe: Scan for existing tables

Ni, Ray
 


Hi Ray,
thanks for your feedback.

Currently a single HOB containing all the SMBIOS table is exported by
coreboot.
As coreboot doesn't support multiple HOBs with the same ID, #2 isn't a
solution.
Hi Patrick,
I checked the code in deep.
The HOB is not created by coreboot. It's the PayloadEntry that creates the HOB.
Can we update PayloadEntry to create multiple HOBs?

Guo,
Any comments?

The reason I like this approach is it doesn't require the other bootloaders to write
a SMBIOS driver that merges all SMBIOS structures together into one table.

Thanks,
Ray


Re: [PATCH - resend] MdeModulePkg/Universal/SmbiosDxe: Scan for existing tables

Ni, Ray
 

I have 5 more comments embedded, can you read and reply?

-----Original Message-----
From: Patrick Rudolph <patrick.rudolph@...>
Sent: Wednesday, March 3, 2021 4:38 PM
To: Ni, Ray <ray.ni@...>
Cc: devel@edk2.groups.io; Chaganty, Rangasai V
<rangasai.v.chaganty@...>; Bi, Dandan <dandan.bi@...>; Zeng,
Star <star.zeng@...>; Gao, Zhichao <zhichao.gao@...>; You,
Benjamin <benjamin.you@...>;
philipp.deppenwiese@...; Ma, Maurice
<maurice.ma@...>; Dong, Guo <guo.dong@...>
Subject: Re: [edk2-devel] [PATCH - resend]
MdeModulePkg/Universal/SmbiosDxe: Scan for existing tables

Hi Ray,
thanks for your feedback.

Currently a single HOB containing all the SMBIOS table is exported by
coreboot.
As coreboot doesn't support multiple HOBs with the same ID, #2 isn't a
solution.

I'll look into passing a HOB instead of using
EfiGetSystemConfigurationTable and see if I can get rid of the table
shadow copy.

Regards,
Patrick Rudolph

On Wed, Mar 3, 2021 at 9:13 AM Ni, Ray <ray.ni@...> wrote:

In general, I agree this solution that lets SMBIOS driver directly absorbs the
SMBIOS table from PEI.
This can eliminate the needs of a separate driver that consumes the HOB
and calls SMBIOS protocol to add the SMBIOS structures.

There are two options for the HOB design:
1. A single HOB that points to the SMBIOS table.
2. Multiple HOBs that each points to a SMBIOS structure.

In my opinion, option #2 is more flexible because it doesn't require the
bootloader to consolidate all the SMBIOS structures together.
The CPU module in the bootloader can produce the type 4 and 7 structures.
The PCI module in the bootloader can produce the type 9 structures.

But, I am not sure if option #2 is conflict with what coreboot does. Does
coreboot produce the whole SMBIOS table in a single buffer?
Option #2 also doesn't care whether it's a SMBIOS 3.0 table or 2.x table.

+ Status = EfiGetSystemConfigurationTable (
1. Why don't you directly get the data from HOB list? This can eliminate the
code in BlSupportDxe that gets data in HOB and publishes to
configuration table.

+ValidateSmbios20Table(
+ValidateSmbios30Table(
2. I will defer to experts (Dandan, Star and Zhichao) to review whether the
above two functions are implemented properly.


+ParseAndAddExistingSmbiosTable(
+ IN EFI_HANDLE ImageHandle,
+ IN SMBIOS_STRUCTURE_POINTER Smbios,
+ IN UINTN Length
+) {
+ EFI_STATUS Status;
+ CHAR8 *String;
+ EFI_SMBIOS_HANDLE SmbiosHandle;
+ SMBIOS_STRUCTURE_POINTER SmbiosEnd;
+
+ SmbiosEnd.Raw = Smbios.Raw + Length;
+
+ do {
+ // Check for end marker
+ if (Smbios.Hdr->Type == 127) {
3. Please use SMBIOS_TYPE_END_OF_TABLE instead of hardcode 127.


+ CopyMem (Smbios.Raw, (VOID *)Smbios30Table, Smbios30Table-
TableMaximumSize);
4. Should we copy from Smbios30Table->TableAddress instead of
Smbios30Table?


+ Status = ParseAndAddExistingSmbiosTable(ImageHandle, Smbios,
Smbios30Table->TableMaximumSize);
5. Can you explain in specific why SMBIOS table should be duplicated
before parsing?


Re: [PATCH v1] MdePkg: Support standalone MM Driver Unload capability

Wu, Jiaxin
 

Hi Mike & Zhiguang & Liming,

Could you help review this patch?

Thanks,
Jiaxin

-----Original Message-----
From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Wu,
Jiaxin
Sent: Monday, March 1, 2021 3:44 PM
To: devel@edk2.groups.io
Cc: Kinney, Michael D <michael.d.kinney@...>; Liming Gao
<gaoliming@...>; Liu, Zhiguang <zhiguang.liu@...>; Fu,
Siyuan <siyuan.fu@...>
Subject: [edk2-devel] [PATCH v1] MdePkg: Support standalone MM Driver
Unload capability

https://bugzilla.tianocore.org/show_bug.cgi?id=3240

This patch is to support standalone MM Driver Unload capability
by providing _DriverUnloadHandler() function.

Change-Id: I26cdbfccb7052685c464d6394e472c7579b7b67e
Cc: Michael D Kinney <michael.d.kinney@...>
Cc: Liming Gao <gaoliming@...>
Cc: Zhiguang Liu <zhiguang.liu@...>
Cc: Siyuan Fu <siyuan.fu@...>
Signed-off-by: Jiaxin Wu <Jiaxin.wu@...>
---
.../Include/Library/StandaloneMmDriverEntryPoint.h | 25 ++++++++++
.../StandaloneMmDriverEntryPoint.c | 56
+++++++++++++++++++++-
.../StandaloneMmDriverEntryPoint.inf | 5 +-
3 files changed, 84 insertions(+), 2 deletions(-)

diff --git a/MdePkg/Include/Library/StandaloneMmDriverEntryPoint.h
b/MdePkg/Include/Library/StandaloneMmDriverEntryPoint.h
index 25b2d8d68d..12f7886640 100644
--- a/MdePkg/Include/Library/StandaloneMmDriverEntryPoint.h
+++ b/MdePkg/Include/Library/StandaloneMmDriverEntryPoint.h
@@ -16,10 +16,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent
/// Declare the PI Specification Revision that this driver requires to execute
/// correctly.
///
extern CONST UINT32 _gMmRevision;

+///
+/// Declare the number of unload handler in the image.
+///
+extern CONST UINT8 _gDriverUnloadImageCount;
+
/**
The entry point of PE/COFF Image for a Standalone MM Driver.

This function is the entry point for a Standalone MM Driver.
This function must call ProcessLibraryConstructorList() and
@@ -120,6 +125,26 @@ EFIAPI
ProcessModuleEntryPointList (
IN EFI_HANDLE ImageHandle,
IN EFI_MM_SYSTEM_TABLE *MmSystemTable
);

+/**
+ Autogenerated function that calls a set of module unload handlers.
+
+ This function must be called from the unload handler registered by
_ModuleEntryPoint().
+ This function calls the set of module unload handlers.
+ This function is autogenerated by build tools and those build tools are
responsible
+ for collecting the module unload handlers and calling them in a specified
order.
+
+ @param ImageHandle The image handle of the DXE Driver, DXE Runtime
Driver, DXE SMM Driver, or UEFI Driver.
+
+ @retval EFI_SUCCESS The unload handlers executed normally.
+ @retval !EFI_SUCCESS The unload handlers failed to execute normally.
+
+**/
+EFI_STATUS
+EFIAPI
+ProcessModuleUnloadList (
+ IN EFI_HANDLE ImageHandle
+ );
+
#endif
diff --git
a/MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEnt
ryPoint.c
b/MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEnt
ryPoint.c
index 2c41e23a03..d74c9bdfed 100644
---
a/MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEnt
ryPoint.c
+++
b/MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEnt
ryPoint.c
@@ -1,23 +1,63 @@
/** @file
Entry point to a Standalone MM driver.

-Copyright (c) 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2015 - 2021, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2016 - 2018, ARM Ltd. All rights reserved.<BR>
Copyright (c) 2018, Linaro, Limited. All rights reserved.<BR>

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

**/

#include <PiMm.h>

+#include <Protocol/LoadedImage.h>
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/MmServicesTableLib.h>
#include <Library/StandaloneMmDriverEntryPoint.h>

+/**
+ Unloads an image from memory.
+
+ This function is a callback that a driver registers to do cleanup
+ when the UnloadImage boot service function is called.
+
+ @param ImageHandle The handle to the image to unload.
+
+ @return Status returned by all unload().
+
+**/
+EFI_STATUS
+EFIAPI
+_DriverUnloadHandler (
+ EFI_HANDLE ImageHandle
+ )
+{
+ EFI_STATUS Status;
+
+ //
+ // If an UnloadImage() handler is specified, then call it
+ //
+ Status = ProcessModuleUnloadList (ImageHandle);
+
+ //
+ // If the driver specific unload handler does not return an error, then call all
of the
+ // library destructors. If the unload handler returned an error, then the
driver can not be
+ // unloaded, and the library destructors should not be called
+ //
+ if (!EFI_ERROR (Status)) {
+ ProcessLibraryDestructorList (ImageHandle, gMmst);
+ }
+
+ //
+ // Return the status from the driver specific unload handler
+ //
+ return Status;
+}
+
/**
The entry point of PE/COFF Image for a Standalone MM Driver.

This function is the entry point for a Standalone MM Driver.
This function must call ProcessLibraryConstructorList() and
@@ -44,10 +84,11 @@ _ModuleEntryPoint (
IN EFI_HANDLE ImageHandle,
IN IN EFI_MM_SYSTEM_TABLE *MmSystemTable
)
{
EFI_STATUS Status;
+ EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;

if (_gMmRevision != 0) {
//
// Make sure that the MM spec revision of the platform
// is >= MM spec revision of the driver
@@ -60,10 +101,23 @@ _ModuleEntryPoint (
//
// Call constructor for all libraries
//
ProcessLibraryConstructorList (ImageHandle, MmSystemTable);

+ //
+ // Install unload handler...
+ //
+ if (_gDriverUnloadImageCount != 0) {
+ Status = gMmst->MmHandleProtocol (
+ ImageHandle,
+ &gEfiLoadedImageProtocolGuid,
+ (VOID **)&LoadedImage
+ );
+ ASSERT_EFI_ERROR (Status);
+ LoadedImage->Unload = _DriverUnloadHandler;
+ }
+
//
// Call the driver entry point
//
Status = ProcessModuleEntryPointList (ImageHandle, MmSystemTable);

diff --git
a/MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEnt
ryPoint.inf
b/MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEnt
ryPoint.inf
index 2f33a6d4ad..9303566309 100644
---
a/MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEnt
ryPoint.inf
+++
b/MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEnt
ryPoint.inf
@@ -1,9 +1,9 @@
## @file
# Module entry point library for Standalone MM driver.
#
-# Copyright (c) 2015, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2015 - 2021, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2016-2018, ARM Ltd. All rights reserved.<BR>
# Copyright (c) 2018, Linaro, Limited. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
@@ -34,5 +34,8 @@

[LibraryClasses]
BaseLib
DebugLib
MmServicesTableLib
+
+[Protocols]
+ gEfiLoadedImageProtocolGuid ## SOMETIMES_CONSUMES
--
2.16.2.windows.1





Re: [PATCH - resend] MdeModulePkg/Universal/SmbiosDxe: Scan for existing tables

Patrick Rudolph
 

Hi Ray,
thanks for your feedback.

Currently a single HOB containing all the SMBIOS table is exported by coreboot.
As coreboot doesn't support multiple HOBs with the same ID, #2 isn't a solution.

I'll look into passing a HOB instead of using
EfiGetSystemConfigurationTable and see if I can get rid of the table
shadow copy.

Regards,
Patrick Rudolph

On Wed, Mar 3, 2021 at 9:13 AM Ni, Ray <ray.ni@...> wrote:

In general, I agree this solution that lets SMBIOS driver directly absorbs the SMBIOS table from PEI.
This can eliminate the needs of a separate driver that consumes the HOB and calls SMBIOS protocol to add the SMBIOS structures.

There are two options for the HOB design:
1. A single HOB that points to the SMBIOS table.
2. Multiple HOBs that each points to a SMBIOS structure.

In my opinion, option #2 is more flexible because it doesn't require the bootloader to consolidate all the SMBIOS structures together.
The CPU module in the bootloader can produce the type 4 and 7 structures.
The PCI module in the bootloader can produce the type 9 structures.

But, I am not sure if option #2 is conflict with what coreboot does. Does coreboot produce the whole SMBIOS table in a single buffer?
Option #2 also doesn't care whether it's a SMBIOS 3.0 table or 2.x table.

+ Status = EfiGetSystemConfigurationTable (
1. Why don't you directly get the data from HOB list? This can eliminate the code in BlSupportDxe that gets data in HOB and publishes to
configuration table.

+ValidateSmbios20Table(
+ValidateSmbios30Table(
2. I will defer to experts (Dandan, Star and Zhichao) to review whether the above two functions are implemented properly.


+ParseAndAddExistingSmbiosTable(
+ IN EFI_HANDLE ImageHandle,
+ IN SMBIOS_STRUCTURE_POINTER Smbios,
+ IN UINTN Length
+) {
+ EFI_STATUS Status;
+ CHAR8 *String;
+ EFI_SMBIOS_HANDLE SmbiosHandle;
+ SMBIOS_STRUCTURE_POINTER SmbiosEnd;
+
+ SmbiosEnd.Raw = Smbios.Raw + Length;
+
+ do {
+ // Check for end marker
+ if (Smbios.Hdr->Type == 127) {
3. Please use SMBIOS_TYPE_END_OF_TABLE instead of hardcode 127.


+ CopyMem (Smbios.Raw, (VOID *)Smbios30Table, Smbios30Table-
TableMaximumSize);
4. Should we copy from Smbios30Table->TableAddress instead of Smbios30Table?


+ Status = ParseAndAddExistingSmbiosTable(ImageHandle, Smbios,
Smbios30Table->TableMaximumSize);
5. Can you explain in specific why SMBIOS table should be duplicated before parsing?


Re: [PATCH - resend] MdeModulePkg/Universal/SmbiosDxe: Scan for existing tables

Ni, Ray
 

In general, I agree this solution that lets SMBIOS driver directly absorbs the SMBIOS table from PEI.
This can eliminate the needs of a separate driver that consumes the HOB and calls SMBIOS protocol to add the SMBIOS structures.

There are two options for the HOB design:
1. A single HOB that points to the SMBIOS table.
2. Multiple HOBs that each points to a SMBIOS structure.

In my opinion, option #2 is more flexible because it doesn't require the bootloader to consolidate all the SMBIOS structures together.
The CPU module in the bootloader can produce the type 4 and 7 structures.
The PCI module in the bootloader can produce the type 9 structures.

But, I am not sure if option #2 is conflict with what coreboot does. Does coreboot produce the whole SMBIOS table in a single buffer?
Option #2 also doesn't care whether it's a SMBIOS 3.0 table or 2.x table.

+ Status = EfiGetSystemConfigurationTable (
1. Why don't you directly get the data from HOB list? This can eliminate the code in BlSupportDxe that gets data in HOB and publishes to
configuration table.

+ValidateSmbios20Table(
+ValidateSmbios30Table(
2. I will defer to experts (Dandan, Star and Zhichao) to review whether the above two functions are implemented properly.


+ParseAndAddExistingSmbiosTable(
+ IN EFI_HANDLE ImageHandle,
+ IN SMBIOS_STRUCTURE_POINTER Smbios,
+ IN UINTN Length
+) {
+ EFI_STATUS Status;
+ CHAR8 *String;
+ EFI_SMBIOS_HANDLE SmbiosHandle;
+ SMBIOS_STRUCTURE_POINTER SmbiosEnd;
+
+ SmbiosEnd.Raw = Smbios.Raw + Length;
+
+ do {
+ // Check for end marker
+ if (Smbios.Hdr->Type == 127) {
3. Please use SMBIOS_TYPE_END_OF_TABLE instead of hardcode 127.


+ CopyMem (Smbios.Raw, (VOID *)Smbios30Table, Smbios30Table-
TableMaximumSize);
4. Should we copy from Smbios30Table->TableAddress instead of Smbios30Table?


+ Status = ParseAndAddExistingSmbiosTable(ImageHandle, Smbios,
Smbios30Table->TableMaximumSize);
5. Can you explain in specific why SMBIOS table should be duplicated before parsing?


Re: [PATCH V5] ShellPkg: add more items for smbiosview -t 3 .

Gao, Zhichao
 

I am OK with the patch. But the patch is using incorrect “Line ending”:

python ./BaseTools/Scripts/PatchCheck.py -1

Checking git commit: HEAD

ShellPkg: add more items for smbiosview -t 3 .

The commit message format passed all checks.

Code format is not valid:

* Line ending ('\n') is not CRLF

   File: ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c

   Line:       if (Struct->Hdr->Length > 0x13) {

* Line ending ('\n') is not CRLF

   File: ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c

   Line:         PRINT_STRUCT_VALUE (Struct, Type3, ContainedElementCount);

* Line ending ('\n') is not CRLF

 

It is a good habit to use above check before send the patch. You should change your edit setting when you’re working on edk2. Others are OK to me,

Reviewed-by: Zhichao Gao <zhichao.gao@...>

Do not send the patch again. I would make the change. Because of it is hard freeze now, the patch would be merged after the 202102 stable create.

 

By the way, are you follow the development process https://github.com/tianocore/tianocore.github.io/wiki/EDK-II-Development-Process to send the patch? I am confused why I cannot extract your patch thru extractor tool.

 

Thanks,

Zhichao

 

From: Mars CC Lin <mars_cc_lin@...>
Sent: Wednesday, March 3, 2021 3:28 PM
To: devel@edk2.groups.io
Cc: Gao, Zhichao <zhichao.gao@...>; Philippe Mathieu-Daude <philmd@...>; Liming Gao <gaoliming@...>
Subject: [PATCH V5] ShellPkg: add more items for smbiosview -t 3 .

 

https://bugzilla.tianocore.org/show_bug.cgi?id=3177
Add ContainedElementCount, ContainedElementRecordLength and
ContainedElements for smbiosview type 3.

Signed-off-by: Mars CC Lin <mars_cc_lin@...>
Cc: Zhichao Gao <zhichao.gao@...>
Cc: Philippe Mathieu-Daude <philmd@...>
Cc: Liming Gao <gaoliming@...>
---
.../SmbiosView/PrintInfo.c | 15 +++++++++++++++
.../SmbiosView/SmbiosViewStrings.uni | 1 +
2 files changed, 16 insertions(+)

diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
index 478f63078a..04e4882272 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
@@ -404,6 +404,21 @@ SmbiosPrintStructure (
if (Struct->Hdr->Length > 0x12) {
PRINT_STRUCT_VALUE (Struct, Type3, NumberofPowerCords);
}
+ if (Struct->Hdr->Length > 0x13) {
+ PRINT_STRUCT_VALUE (Struct, Type3, ContainedElementCount);
+ }
+ if (Struct->Hdr->Length > 0x14) {
+ PRINT_STRUCT_VALUE (Struct, Type3, ContainedElementRecordLength);
+ }
+ if (Struct->Hdr->Length > 0x15) {
+ for (Index = 0; Index < Struct->Type3->ContainedElementCount; Index++) {
+ ShellPrintHiiEx(-1,-1,NULL,STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_CONTAINED_ELEMENT), gShellDebug1HiiHandle, Index+1);
+ for (Index2 = 0; Index2< Struct->Type3->ContainedElementRecordLength; Index2++) {
+ Print (L"%02X ", Buffer[0x15 + (Index * Struct->Type3->ContainedElementRecordLength) + Index2]);
+ }
+ Print (L"\n");
+ }
+ }
}
if (AE_SMBIOS_VERSION (0x2, 0x7) && (Struct->Hdr->Length > 0x13)) {
if (Struct->Hdr->Length > (0x15 + (Struct->Type3->ContainedElementCount * Struct->Type3->ContainedElementRecordLength))) {
diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
index 97e1d54fcf..20a556a175 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
@@ -93,6 +93,7 @@
#string STR_SMBIOSVIEW_PRINTINFO_POWER_SUPPLY_STATE #language en-US "Power Supply State "
#string STR_SMBIOSVIEW_PRINTINFO_THERMAL_STATE #language en-US "Thermal state "
#string STR_SMBIOSVIEW_PRINTINFO_SECURITY_STATUS #language en-US "Security Status "
+#string STR_SMBIOSVIEW_PRINTINFO_CONTAINED_ELEMENT #language en-US "Contained Element %d: "
#string STR_SMBIOSVIEW_PRINTINFO_SUPOPRT #language en-US "Support "
#string STR_SMBIOSVIEW_PRINTINFO_CURRENT #language en-US "Current "
#string STR_SMBIOSVIEW_PRINTINFO_INSTALLED #language en-US "Installed "
--
2.29.1.windows.1


[PATCH V5] ShellPkg: add more items for smbiosview -t 3 .

Mars CC Lin
 

https://bugzilla.tianocore.org/show_bug.cgi?id=3177
Add ContainedElementCount, ContainedElementRecordLength and
ContainedElements for smbiosview type 3.

Signed-off-by: Mars CC Lin <mars_cc_lin@...>
Cc: Zhichao Gao <zhichao.gao@...>
Cc: Philippe Mathieu-Daude <philmd@...>
Cc: Liming Gao <gaoliming@...>
---
.../SmbiosView/PrintInfo.c | 15 +++++++++++++++
.../SmbiosView/SmbiosViewStrings.uni | 1 +
2 files changed, 16 insertions(+)

diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
index 478f63078a..04e4882272 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
@@ -404,6 +404,21 @@ SmbiosPrintStructure (
if (Struct->Hdr->Length > 0x12) {
PRINT_STRUCT_VALUE (Struct, Type3, NumberofPowerCords);
}
+ if (Struct->Hdr->Length > 0x13) {
+ PRINT_STRUCT_VALUE (Struct, Type3, ContainedElementCount);
+ }
+ if (Struct->Hdr->Length > 0x14) {
+ PRINT_STRUCT_VALUE (Struct, Type3, ContainedElementRecordLength);
+ }
+ if (Struct->Hdr->Length > 0x15) {
+ for (Index = 0; Index < Struct->Type3->ContainedElementCount; Index++) {
+ ShellPrintHiiEx(-1,-1,NULL,STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_CONTAINED_ELEMENT), gShellDebug1HiiHandle, Index+1);
+ for (Index2 = 0; Index2< Struct->Type3->ContainedElementRecordLength; Index2++) {
+ Print (L"%02X ", Buffer[0x15 + (Index * Struct->Type3->ContainedElementRecordLength) + Index2]);
+ }
+ Print (L"\n");
+ }
+ }
}
if (AE_SMBIOS_VERSION (0x2, 0x7) && (Struct->Hdr->Length > 0x13)) {
if (Struct->Hdr->Length > (0x15 + (Struct->Type3->ContainedElementCount * Struct->Type3->ContainedElementRecordLength))) {
diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
index 97e1d54fcf..20a556a175 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
@@ -93,6 +93,7 @@
#string STR_SMBIOSVIEW_PRINTINFO_POWER_SUPPLY_STATE #language en-US "Power Supply State "
#string STR_SMBIOSVIEW_PRINTINFO_THERMAL_STATE #language en-US "Thermal state "
#string STR_SMBIOSVIEW_PRINTINFO_SECURITY_STATUS #language en-US "Security Status "
+#string STR_SMBIOSVIEW_PRINTINFO_CONTAINED_ELEMENT #language en-US "Contained Element %d: "
#string STR_SMBIOSVIEW_PRINTINFO_SUPOPRT #language en-US "Support "
#string STR_SMBIOSVIEW_PRINTINFO_CURRENT #language en-US "Current "
#string STR_SMBIOSVIEW_PRINTINFO_INSTALLED #language en-US "Installed "
--
2.29.1.windows.1


[PATCH edk2-platforms v3 4/4] SbsaQemu: fix typo

Masahisa Kojima
 

Fix typo in Readme.md

Signed-off-by: Masahisa Kojima <masahisa.kojima@...>
Reviewed-by: Leif Lindholm <leif@...>
---
Platform/Qemu/SbsaQemu/Readme.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Platform/Qemu/SbsaQemu/Readme.md b/Platform/Qemu/SbsaQemu/Readme.md
index 50f61b6e3bf4..cef98383884a 100644
--- a/Platform/Qemu/SbsaQemu/Readme.md
+++ b/Platform/Qemu/SbsaQemu/Readme.md
@@ -97,7 +97,7 @@ Create a directory $WORKSPACE that would hold source code of the components.
cd $WORKSPACE
build -b RELEASE -a AARCH64 -t GCC5 -p edk2-platforms/Platform/Qemu/SbsaQemu/SbsaQemu.dsc
```
- Copy SBSA_FLASH0.fd and SBSA_FLASH0.fd to top $WORKSPACE directory.
+ Copy SBSA_FLASH0.fd and SBSA_FLASH1.fd to top $WORKSPACE directory.
Then extend the file size to match the machine flash size.
```
cp Build/SbsaQemu/RELEASE_GCC5/FV/SBSA_FLASH[01].fd .
--
2.17.1


[PATCH edk2-platforms v3 3/4] SbsaQemu: add standalone MM build instruction

Masahisa Kojima
 

This commit adds the standalone MM build instruction
to enable UEFI secure boot.

Signed-off-by: Masahisa Kojima <masahisa.kojima@...>
---
Platform/Qemu/SbsaQemu/Readme.md | 35 ++++++++++++++++++++
1 file changed, 35 insertions(+)

diff --git a/Platform/Qemu/SbsaQemu/Readme.md b/Platform/Qemu/SbsaQemu/Readme.md
index 63786d9d0fd3..50f61b6e3bf4 100644
--- a/Platform/Qemu/SbsaQemu/Readme.md
+++ b/Platform/Qemu/SbsaQemu/Readme.md
@@ -104,6 +104,41 @@ Create a directory $WORKSPACE that would hold source code of the components.
truncate -s 256M SBSA_FLASH[01].fd
```

+## Build UEFI with standalone MM based UEFI secure boot
+
+1. Compile standalone MM image
+
+ ```
+ cd $WORKSPACE
+ build -b RELEASE -a AARCH64 -t GCC5 -p edk2-platforms/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMM.dsc
+ ```
+
+2. Compile TF-A with BL32(Secure Payload)
+
+ Detailed build instructions can be found on the following link:
+ https://git.trustedfirmware.org/TF-A/trusted-firmware-a.git/tree/docs/plat/qemu-sbsa.rst
+
+ Then copy `bl1.bin` and `fip.bin` to the the edk2-non-osi directory:
+
+3. Compile EDK2 with UEFI secure boot enabled
+
+ ```
+ cd $WORKSPACE
+ build -b RELEASE -a AARCH64 -t GCC5 -p edk2-platforms/Platform/Qemu/SbsaQemu/SbsaQemu.dsc -DSECURE_BOOT_ENABLE=TRUE
+ ```
+
+ Copy SBSA_FLASH0.fd and SBSA_FLASH1.fd to top $WORKSPACE directory.
+ Then extend the file size to match the machine flash size.
+ ```
+ cp Build/SbsaQemu/RELEASE_GCC5/FV/SBSA_FLASH[01].fd .
+ truncate -s 256M SBSA_FLASH[01].fd
+ ```
+
+ To keep the UEFI variable storage after the succeeding build, use `dd` instead of `cp`.
+ ```
+ dd if=./Build/SbsaQemu/RELEASE_GCC5/FV/SBSA_FLASH0.fd of=./SBSA_FLASH0.fd conv=notrunc bs=2M count=8
+ ```
+
# Running

The resulting SBSA_FLASH0.fd file will contain Secure flash0 image (TF-A code).
--
2.17.1


[PATCH edk2-platforms v3 2/4] SbsaQemu: add MM based UEFI secure boot support

Masahisa Kojima
 

This implements support for UEFI secure boot on SbsaQemu using
the standalone MM framework. This moves all of the software handling
of the UEFI authenticated variable store into the standalone MM
context residing in a secure partition.

Secure variable storage is located at 0x01000000 in secure NOR Flash.

Non-secure shared memory between UEFI and standalone MM
is allocated at the top of DRAM.
DRAM size of SbsaQemu varies depends on the QEMU parameter,
the non-secure shared memory base address is passed from
trusted-firmware through the device tree "/reserved-memory" node.

Together with "/reserved-memory" parsing implementation newly added
in this commit, pre-existing "/memory" node parsing is moved to
a helper function in FdtHelperLib.

Signed-off-by: Masahisa Kojima <masahisa.kojima@...>
---
Platform/Qemu/SbsaQemu/SbsaQemu.dsc | 25 ++++-
Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc | 39 +++++++
Platform/Qemu/SbsaQemu/SbsaQemu.fdf | 81 ++++++++++++--
Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf | 7 +-
Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuLib.inf | 3 +
Silicon/Qemu/SbsaQemu/Include/Library/FdtHelperLib.h | 27 +++++
Silicon/Qemu/SbsaQemu/Library/FdtHelperLib/FdtHelperLib.c | 111 ++++++++++++++++++++
Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuMem.c | 55 +++-------
8 files changed, 294 insertions(+), 54 deletions(-)

diff --git a/Platform/Qemu/SbsaQemu/SbsaQemu.dsc b/Platform/Qemu/SbsaQemu/SbsaQemu.dsc
index c1f8a4696560..8a239bd17138 100644
--- a/Platform/Qemu/SbsaQemu/SbsaQemu.dsc
+++ b/Platform/Qemu/SbsaQemu/SbsaQemu.dsc
@@ -28,6 +28,8 @@ [Defines]

DEFINE DEBUG_PRINT_ERROR_LEVEL = 0x8000004F

+ DEFINE SECURE_BOOT_ENABLE = FALSE
+
#
# Network definition
#
@@ -152,12 +154,10 @@ [LibraryClasses.common]
# Secure Boot dependencies
#
TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf
- AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf

# re-use the UserPhysicalPresent() dummy implementation from the ovmf tree
PlatformSecureLib|OvmfPkg/Library/PlatformSecureLib/PlatformSecureLib.inf

- VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf
VariablePolicyLib|MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.inf
VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf

@@ -300,6 +300,8 @@ [PcdsFeatureFlag.common]
gEfiMdeModulePkgTokenSpaceGuid.PcdConOutGopSupport|TRUE
gEfiMdeModulePkgTokenSpaceGuid.PcdConOutUgaSupport|FALSE

+ gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE
+
[PcdsFixedAtBuild.common]
gEfiMdePkgTokenSpaceGuid.PcdMaximumUnicodeStringLength|1000000
gEfiMdePkgTokenSpaceGuid.PcdMaximumAsciiStringLength|1000000
@@ -551,6 +553,9 @@ [PcdsDynamicDefault.common]
gArmVirtSbsaQemuPlatformTokenSpaceGuid.PcdChassisAssetTag|L"AT0000"
gArmVirtSbsaQemuPlatformTokenSpaceGuid.PcdChassisSKU|L"SK0000"

+ gArmTokenSpaceGuid.PcdMmBufferBase|0x10000000000
+ gArmTokenSpaceGuid.PcdMmBufferSize|0x00200000
+
################################################################################
#
# Components Section - list of all EDK II Modules needed by this Platform
@@ -628,19 +633,31 @@ [Components.common]
#
ArmPkg/Drivers/CpuDxe/CpuDxe.inf
MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
+!if $(SECURE_BOOT_ENABLE) == FALSE
+ MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf {
<LibraryClasses>
NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf
+ AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf
+ VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf
# don't use unaligned CopyMem () on the UEFI varstore NOR flash region
BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
}
+!else
+ ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf {
+ <LibraryClasses>
+ NULL|StandaloneMmPkg/Library/VariableMmDependency/VariableMmDependency.inf
+ }
+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
+ SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
+!endif
MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf {
<LibraryClasses>
+!if $(SECURE_BOOT_ENABLE) == TRUE
NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf
+!endif
}
- SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
- MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
diff --git a/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc
index 87f5ee351eaa..b80379acd1ad 100644
--- a/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc
+++ b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc
@@ -77,6 +77,18 @@ [LibraryClasses.common.MM_STANDALONE]
HobLib|StandaloneMmPkg/Library/StandaloneMmHobLib/StandaloneMmHobLib.inf
MmServicesTableLib|MdePkg/Library/StandaloneMmServicesTableLib/StandaloneMmServicesTableLib.inf
MemoryAllocationLib|StandaloneMmPkg/Library/StandaloneMmMemoryAllocationLib/StandaloneMmMemoryAllocationLib.inf
+ AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf
+ BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf
+ IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf
+ NorFlashPlatformLib|Silicon/Qemu/SbsaQemu/Library/SbsaQemuNorFlashLib/SbsaQemuNorFlashLib.inf
+ OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf
+ RngLib|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf
+ PlatformSecureLib|SecurityPkg/Library/PlatformSecureLibNull/PlatformSecureLibNull.inf
+ SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf
+ TimerLib|ArmPkg/Library/ArmArchTimerLib/ArmArchTimerLib.inf
+ VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf
+ SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf
+ ArmGenericTimerCounterLib|ArmPkg/Library/ArmGenericTimerPhyCounterLib/ArmGenericTimerPhyCounterLib.inf

################################################################################
#
@@ -94,6 +106,20 @@ [PcdsFixedAtBuild]

gEfiMdePkgTokenSpaceGuid.PcdMaximumGuidedExtractHandler|0x2

+ gArmTokenSpaceGuid.PcdFdBaseAddress|0x01000000
+ gArmTokenSpaceGuid.PcdFdSize|0x000C0000
+
+ gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x2000
+ gEfiSecurityPkgTokenSpaceGuid.PcdUserPhysicalPresence|TRUE
+ gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x2800
+
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase|0x01000000
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize|0x00040000
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0x01040000
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize|0x00040000
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|0x01080000
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize|0x00040000
+
###################################################################################################
#
# Components Section - list of the modules and components that will be processed by compilation
@@ -118,6 +144,19 @@ [Components.common]
#
StandaloneMmPkg/Core/StandaloneMmCore.inf
StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/StandaloneMmCpu.inf
+ ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
+ MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandaloneMm.inf
+
+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf {
+ <LibraryClasses>
+ DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
+ NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf
+ NULL|MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.inf
+ # don't use unaligned CopyMem () on the UEFI varstore NOR flash region
+ BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
+ VariablePolicyLib|MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.inf
+ VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf
+ }

###################################################################################################
#
diff --git a/Platform/Qemu/SbsaQemu/SbsaQemu.fdf b/Platform/Qemu/SbsaQemu/SbsaQemu.fdf
index b61ae1891233..36d09d34a374 100644
--- a/Platform/Qemu/SbsaQemu/SbsaQemu.fdf
+++ b/Platform/Qemu/SbsaQemu/SbsaQemu.fdf
@@ -21,10 +21,10 @@

[FD.SBSA_FLASH0]
BaseAddress = 0x00000000
-Size = 0x00400000
+Size = 0x01100000
ErasePolarity = 1
BlockSize = 0x00001000
-NumBlocks = 0x400
+NumBlocks = 0x1100

################################################################################
#
@@ -50,6 +50,66 @@ [FD.SBSA_FLASH0]
0x00008000|0x00300000
FILE = Platform/Qemu/Sbsa/fip.bin

+!if $(SECURE_BOOT_ENABLE)
+## Place for Secure Variables.
+# Must be aligned to Flash Block size 0x40000
+0x01000000|0x00040000
+gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize
+#NV_VARIABLE_STORE
+DATA = {
+ ## This is the EFI_FIRMWARE_VOLUME_HEADER
+ # ZeroVector []
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ # FileSystemGuid: gEfiSystemNvDataFvGuid =
+ # { 0xFFF12B8D, 0x7696, 0x4C8B,
+ # { 0xA9, 0x85, 0x27, 0x47, 0x07, 0x5B, 0x4F, 0x50 }}
+ 0x8D, 0x2B, 0xF1, 0xFF, 0x96, 0x76, 0x8B, 0x4C,
+ 0xA9, 0x85, 0x27, 0x47, 0x07, 0x5B, 0x4F, 0x50,
+ # FvLength: 0xC0000
+ 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00,
+ # Signature "_FVH" # Attributes
+ 0x5f, 0x46, 0x56, 0x48, 0xff, 0xfe, 0x04, 0x00,
+ # HeaderLength # CheckSum # ExtHeaderOffset #Reserved #Revision
+ 0x48, 0x00, 0x28, 0x09, 0x00, 0x00, 0x00, 0x02,
+ # Blockmap[0]: 0x3 Blocks * 0x40000 Bytes / Block
+ 0x3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
+ # Blockmap[1]: End
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ ## This is the VARIABLE_STORE_HEADER
+ # It is compatible with SECURE_BOOT_ENABLE == FALSE as well.
+ # Signature: gEfiAuthenticatedVariableGuid =
+ # { 0xaaf32c78, 0x947b, 0x439a,
+ # { 0xa1, 0x80, 0x2e, 0x14, 0x4e, 0xc3, 0x77, 0x92 }}
+ 0x78, 0x2c, 0xf3, 0xaa, 0x7b, 0x94, 0x9a, 0x43,
+ 0xa1, 0x80, 0x2e, 0x14, 0x4e, 0xc3, 0x77, 0x92,
+ # Size: 0x40000 (gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize) -
+ # 0x48 (size of EFI_FIRMWARE_VOLUME_HEADER) = 0x3ffb8
+ # This can speed up the Variable Dispatch a bit.
+ 0xB8, 0xFF, 0x03, 0x00,
+ # FORMATTED: 0x5A #HEALTHY: 0xFE #Reserved: UINT16 #Reserved1: UINT32
+ 0x5A, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+}
+
+0x01040000|0x00040000
+gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize
+#NV_FTW_WORKING
+DATA = {
+ # EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER->Signature = gEdkiiWorkingBlockSignatureGuid =
+ # { 0x9e58292b, 0x7c68, 0x497d, { 0xa0, 0xce, 0x65, 0x0, 0xfd, 0x9f, 0x1b, 0x95 }}
+ 0x2b, 0x29, 0x58, 0x9e, 0x68, 0x7c, 0x7d, 0x49,
+ 0xa0, 0xce, 0x65, 0x0, 0xfd, 0x9f, 0x1b, 0x95,
+ # Crc:UINT32 #WorkingBlockValid:1, WorkingBlockInvalid:1, Reserved
+ 0x5b, 0xe7, 0xc6, 0x86, 0xFE, 0xFF, 0xFF, 0xFF,
+ # WriteQueueSize: UINT64
+ 0xE0, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00
+}
+
+0x01080000|0x00040000
+gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
+#NV_FTW_SPARE
+!endif
+
################################################################################
#
# FD Section for FLASH1
@@ -169,15 +229,25 @@ [FV.FvMain]
INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
- INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
- INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
- INF SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
INF MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
INF MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf

+ #
+ # Variable services
+ #
+!if $(SECURE_BOOT_ENABLE) == FALSE
+ INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
+ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
+!else
+ INF ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
+ INF SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
+!endif
+
#
# Multiple Console IO support
#
@@ -189,7 +259,6 @@ [FV.FvMain]

INF ArmPkg/Drivers/ArmGic/ArmGicDxe.inf
INF ArmPkg/Drivers/TimerDxe/TimerDxe.inf
- INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf

#
diff --git a/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf
index a1acefcfb0a7..dbe1555c68f2 100644
--- a/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf
+++ b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf
@@ -19,8 +19,8 @@
################################################################################

[FD.STANDALONE_MM]
-BaseAddress = 0x20001000|gArmTokenSpaceGuid.PcdFdBaseAddress
-Size = 0x00e00000|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the device (14MiB).
+BaseAddress = 0x20002000
+Size = 0x00e00000
ErasePolarity = 1

BlockSize = 0x00001000
@@ -49,6 +49,9 @@ [FV.FVMAIN_COMPACT]
READ_LOCK_STATUS = TRUE

INF StandaloneMmPkg/Core/StandaloneMmCore.inf
+ INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
+ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandaloneMm.inf
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
INF StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/StandaloneMmCpu.inf

################################################################################
diff --git a/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuLib.inf b/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuLib.inf
index c067a80cc715..3cd398bcb7e7 100644
--- a/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuLib.inf
+++ b/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuLib.inf
@@ -35,11 +35,14 @@ [LibraryClasses]
FdtLib
MemoryAllocationLib
PcdLib
+ FdtHelperLib

[Pcd]
gArmTokenSpaceGuid.PcdSystemMemoryBase
gArmTokenSpaceGuid.PcdSystemMemorySize
gArmVirtSbsaQemuPlatformTokenSpaceGuid.PcdDeviceTreeBaseAddress
+ gArmTokenSpaceGuid.PcdMmBufferBase
+ gArmTokenSpaceGuid.PcdMmBufferSize

[FixedPcd]
gArmTokenSpaceGuid.PcdFdBaseAddress
diff --git a/Silicon/Qemu/SbsaQemu/Include/Library/FdtHelperLib.h b/Silicon/Qemu/SbsaQemu/Include/Library/FdtHelperLib.h
index ea9159857215..6b618847a0a6 100644
--- a/Silicon/Qemu/SbsaQemu/Include/Library/FdtHelperLib.h
+++ b/Silicon/Qemu/SbsaQemu/Include/Library/FdtHelperLib.h
@@ -33,4 +33,31 @@ FdtHelperCountCpus (
VOID
);

+/**
+ Get memory information from device tree passed by Qemu.
+
+ @param [out] NewBase A pointer to store the memory phisical address.
+ @param [out] NewSize A pointer to store the memory size.
+
+**/
+VOID
+FdtHelperGetMemInfo (
+ OUT UINT64 *NewBase,
+ OUT UINT64 *NewSize
+ );
+
+/**
+ Get reserved memory information from device tree passed by Qemu.
+
+ @param [out] NsBufBase A pointer to store the reserved memory
+ phisical address.
+ @param [out] NsBufSize A pointer to store the reserved memory size.
+
+**/
+VOID
+FdtHelperGetReservedMemInfo (
+ OUT UINT64 *NsBufBase,
+ OUT UINT32 *NsBufSize
+ );
+
#endif /* FDT_HELPER_LIB_ */
diff --git a/Silicon/Qemu/SbsaQemu/Library/FdtHelperLib/FdtHelperLib.c b/Silicon/Qemu/SbsaQemu/Library/FdtHelperLib/FdtHelperLib.c
index 7fdfb055db76..8308f71bdd34 100644
--- a/Silicon/Qemu/SbsaQemu/Library/FdtHelperLib/FdtHelperLib.c
+++ b/Silicon/Qemu/SbsaQemu/Library/FdtHelperLib/FdtHelperLib.c
@@ -96,3 +96,114 @@ FdtHelperCountCpus (

return CpuCount;
}
+
+/**
+ Get memory information from device tree passed by Qemu.
+
+ @param [out] NewBase A pointer to store the memory phisical address.
+ @param [out] NewSize A pointer to store the memory size.
+
+**/
+VOID
+FdtHelperGetMemInfo (
+ OUT UINT64 *NewBase,
+ OUT UINT64 *NewSize
+ )
+{
+ VOID *DeviceTreeBase;
+ INT32 Node, Prev;
+ CONST CHAR8 *Type;
+ CONST UINT64 *RegProp;
+ INT32 Len;
+ UINT64 CurBase;
+ UINT64 CurSize;
+
+ DeviceTreeBase = (VOID *)(UINTN)PcdGet64 (PcdDeviceTreeBaseAddress);
+ ASSERT (DeviceTreeBase != NULL);
+
+ // Make sure we have a valid device tree blob
+ ASSERT (fdt_check_header (DeviceTreeBase) == 0);
+
+ // Look for the lowest memory node
+ for (Prev = 0;; Prev = Node) {
+ Node = fdt_next_node (DeviceTreeBase, Prev, NULL);
+ if (Node < 0) {
+ break;
+ }
+
+ // Check for memory node
+ Type = fdt_getprop (DeviceTreeBase, Node, "device_type", &Len);
+ if (Type && AsciiStrnCmp (Type, "memory", Len) == 0) {
+ // Get the 'reg' property of this node. For now, we will assume
+ // two 8 byte quantities for base and size, respectively.
+ RegProp = fdt_getprop (DeviceTreeBase, Node, "reg", &Len);
+ if (RegProp != 0 && Len == (2 * sizeof (UINT64))) {
+
+ CurBase = fdt64_to_cpu (ReadUnaligned64 (RegProp));
+ CurSize = fdt64_to_cpu (ReadUnaligned64 (RegProp + 1));
+
+ DEBUG ((DEBUG_INFO, "%a: System RAM @ 0x%lx - 0x%lx\n",
+ __FUNCTION__, CurBase, CurBase + CurSize - 1));
+
+ if (*NewBase > CurBase || *NewBase == 0) {
+ *NewBase = CurBase;
+ *NewSize = CurSize;
+ }
+ } else {
+ DEBUG ((DEBUG_ERROR, "%a: Failed to parse FDT memory node\n",
+ __FUNCTION__));
+ }
+ }
+ }
+}
+
+/**
+ Get reserved memory information from device tree passed by Qemu.
+
+ @param [out] NsBufBase A pointer to store the reserved memory
+ phisical address.
+ @param [out] NsBufSize A pointer to store the reserved memory size.
+
+**/
+VOID
+FdtHelperGetReservedMemInfo (
+ OUT UINT64 *NsBufBase,
+ OUT UINT32 *NsBufSize
+ )
+{
+ VOID *DeviceTreeBase;
+ CONST UINT64 *RegProp;
+ INT32 ParentOffset;
+ INT32 Offset;
+ INT32 Len;
+
+ DeviceTreeBase = (VOID *)(UINTN)PcdGet64 (PcdDeviceTreeBaseAddress);
+ ASSERT (DeviceTreeBase != NULL);
+
+ // Make sure we have a valid device tree blob
+ ASSERT (fdt_check_header (DeviceTreeBase) == 0);
+
+ ParentOffset = fdt_path_offset(DeviceTreeBase, "/reserved-memory");
+ if (ParentOffset < 0) {
+ DEBUG ((DEBUG_ERROR, "%a: reserved-memory node not found\n",
+ __FUNCTION__));
+ }
+ Offset = fdt_subnode_offset(DeviceTreeBase, ParentOffset, "ns-buf-spm-mm");
+ if (Offset < 0) {
+ DEBUG ((DEBUG_ERROR, "%a: ns-buf-spm-mm node not found\n",
+ __FUNCTION__));
+ }
+ // Get the 'reg' property of this node. 8 byte quantities for base address
+ // and 4 byte quantities for size.
+ RegProp = fdt_getprop (DeviceTreeBase, Offset, "reg", &Len);
+ if (RegProp != 0 && Len == (sizeof (UINT64) + sizeof(UINT32))) {
+ *NsBufBase = fdt64_to_cpu (ReadUnaligned64 (RegProp));
+ *NsBufSize = fdt32_to_cpu (ReadUnaligned32 ((UINT32 *)(RegProp + 1)));
+
+ DEBUG ((DEBUG_INFO, "%a: ns buf @ 0x%lx - 0x%lx\n",
+ __FUNCTION__, *NsBufBase, *NsBufBase + *NsBufSize - 1));
+ } else {
+ DEBUG ((DEBUG_ERROR, "%a: Failed to parse FDT reserved-memory node Len %d\n",
+ __FUNCTION__, Len));
+ }
+}
diff --git a/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuMem.c b/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuMem.c
index 8c2eb0b6a028..d4c47c7fd4d6 100644
--- a/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuMem.c
+++ b/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuMem.c
@@ -13,6 +13,7 @@
#include <Library/MemoryAllocationLib.h>
#include <Library/PcdLib.h>
#include <libfdt.h>
+#include <Library/FdtHelperLib.h>

// Number of Virtual Memory Map Descriptors
#define MAX_VIRTUAL_MEMORY_MAP_DESCRIPTORS 4
@@ -23,59 +24,29 @@ SbsaQemuLibConstructor (
VOID
)
{
- VOID *DeviceTreeBase;
- INT32 Node, Prev;
- UINT64 NewBase, CurBase;
- UINT64 NewSize, CurSize;
- CONST CHAR8 *Type;
- INT32 Len;
- CONST UINT64 *RegProp;
+ UINT64 NewBase, NsBufBase;
+ UINT64 NewSize;
+ UINT32 NsBufSize;
RETURN_STATUS PcdStatus;

NewBase = 0;
NewSize = 0;
+ NsBufBase = 0;
+ NsBufSize = 0;

- DeviceTreeBase = (VOID *)(UINTN)PcdGet64 (PcdDeviceTreeBaseAddress);
- ASSERT (DeviceTreeBase != NULL);
+ FdtHelperGetMemInfo (&NewBase, &NewSize);

- // Make sure we have a valid device tree blob
- ASSERT (fdt_check_header (DeviceTreeBase) == 0);
+ // StandaloneMM non-secure shared buffer is allocated at the top of
+ // the system memory by trusted-firmware using "/reserved-memory" node.
+ FdtHelperGetReservedMemInfo(&NsBufBase, &NsBufSize);

- // Look for the lowest memory node
- for (Prev = 0;; Prev = Node) {
- Node = fdt_next_node (DeviceTreeBase, Prev, NULL);
- if (Node < 0) {
- break;
- }
-
- // Check for memory node
- Type = fdt_getprop (DeviceTreeBase, Node, "device_type", &Len);
- if (Type && AsciiStrnCmp (Type, "memory", Len) == 0) {
- // Get the 'reg' property of this node. For now, we will assume
- // two 8 byte quantities for base and size, respectively.
- RegProp = fdt_getprop (DeviceTreeBase, Node, "reg", &Len);
- if (RegProp != 0 && Len == (2 * sizeof (UINT64))) {
-
- CurBase = fdt64_to_cpu (ReadUnaligned64 (RegProp));
- CurSize = fdt64_to_cpu (ReadUnaligned64 (RegProp + 1));
-
- DEBUG ((DEBUG_INFO, "%a: System RAM @ 0x%lx - 0x%lx\n",
- __FUNCTION__, CurBase, CurBase + CurSize - 1));
-
- if (NewBase > CurBase || NewBase == 0) {
- NewBase = CurBase;
- NewSize = CurSize;
- }
- } else {
- DEBUG ((DEBUG_ERROR, "%a: Failed to parse FDT memory node\n",
- __FUNCTION__));
- }
- }
- }
+ NewSize -= NsBufSize;

// Make sure the start of DRAM matches our expectation
ASSERT (FixedPcdGet64 (PcdSystemMemoryBase) == NewBase);
PcdStatus = PcdSet64S (PcdSystemMemorySize, NewSize);
+ PcdStatus = PcdSet64S (PcdMmBufferBase, NsBufBase);
+ PcdStatus = PcdSet64S (PcdMmBufferSize, (UINT64)NsBufSize);
ASSERT_RETURN_ERROR (PcdStatus);

return RETURN_SUCCESS;
--
2.17.1


[PATCH edk2-platforms v3 1/4] SbsaQemu: Build infrastructure for StandaloneMm image

Masahisa Kojima
 

Add the build infrastructure for compilation of StandaloneMm image.
SbsaQemu.fdf is modified to extend the FLASH0 region enough big to
contain StandaloneMM image(BL32).

Signed-off-by: Masahisa Kojima <masahisa.kojima@...>
---
Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc | 132 ++++++++++++++++++++
Platform/Qemu/SbsaQemu/SbsaQemu.fdf | 6 +-
Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf | 93 ++++++++++++++
3 files changed, 228 insertions(+), 3 deletions(-)

diff --git a/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc
new file mode 100644
index 000000000000..87f5ee351eaa
--- /dev/null
+++ b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc
@@ -0,0 +1,132 @@
+#
+# Copyright (c) 2020, Linaro Limited. All rights reserved.
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+
+################################################################################
+#
+# Defines Section - statements that will be processed to create a Makefile.
+#
+################################################################################
+[Defines]
+ PLATFORM_NAME = SbsaQemuStandaloneMm
+ PLATFORM_GUID = A64CC0F5-7ACD-4975-BBE7-7EF6739C8668
+ PLATFORM_VERSION = 1.0
+ DSC_SPECIFICATION = 0x00010011
+ OUTPUT_DIRECTORY = Build/$(PLATFORM_NAME)
+ SUPPORTED_ARCHITECTURES = AARCH64
+ BUILD_TARGETS = DEBUG|RELEASE|NOOPT
+ SKUID_IDENTIFIER = DEFAULT
+ FLASH_DEFINITION = Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf
+ DEFINE DEBUG_MESSAGE = TRUE
+
+ # LzmaF86
+ DEFINE COMPRESSION_TOOL_GUID = D42AE6BD-1352-4bfb-909A-CA72A6EAE889
+
+################################################################################
+#
+# Library Class section - list of all Library Classes needed by this Platform.
+#
+################################################################################
+[LibraryClasses]
+ #
+ # Basic
+ #
+ BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
+ BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
+ DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
+ DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf
+ ExtractGuidedSectionLib|EmbeddedPkg/Library/PrePiExtractGuidedSectionLib/PrePiExtractGuidedSectionLib.inf
+ FvLib|StandaloneMmPkg/Library/FvLib/FvLib.inf
+ HobLib|StandaloneMmPkg/Library/StandaloneMmCoreHobLib/StandaloneMmCoreHobLib.inf
+ IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf
+ MemLib|StandaloneMmPkg/Library/StandaloneMmMemLib/StandaloneMmMemLib.inf
+ MemoryAllocationLib|StandaloneMmPkg/Library/StandaloneMmCoreMemoryAllocationLib/StandaloneMmCoreMemoryAllocationLib.inf
+ PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
+ PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf
+ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
+ ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf
+
+ #
+ # Entry point
+ #
+ StandaloneMmDriverEntryPoint|MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEntryPoint.inf
+
+ ArmLib|ArmPkg/Library/ArmLib/ArmBaseLib.inf
+ StandaloneMmMmuLib|ArmPkg/Library/StandaloneMmMmuLib/ArmMmuStandaloneMmLib.inf
+ ArmSvcLib|ArmPkg/Library/ArmSvcLib/ArmSvcLib.inf
+ CacheMaintenanceLib|ArmPkg/Library/ArmCacheMaintenanceLib/ArmCacheMaintenanceLib.inf
+ PeCoffExtraActionLib|StandaloneMmPkg/Library/StandaloneMmPeCoffExtraActionLib/StandaloneMmPeCoffExtraActionLib.inf
+
+ # ARM PL011 UART Driver
+ PL011UartClockLib|ArmPlatformPkg/Library/PL011UartClockLib/PL011UartClockLib.inf
+ PL011UartLib|ArmPlatformPkg/Library/PL011UartLib/PL011UartLib.inf
+ SerialPortLib|ArmPlatformPkg/Library/PL011SerialPortLib/PL011SerialPortLib.inf
+
+ StandaloneMmCoreEntryPoint|StandaloneMmPkg/Library/StandaloneMmCoreEntryPoint/StandaloneMmCoreEntryPoint.inf
+
+ #
+ # It is not possible to prevent the ARM compiler for generic intrinsic functions.
+ # This library provides the instrinsic functions generate by a given compiler.
+ # And NULL mean 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/StandaloneMmServicesTableLib.inf
+ MemoryAllocationLib|StandaloneMmPkg/Library/StandaloneMmMemoryAllocationLib/StandaloneMmMemoryAllocationLib.inf
+
+################################################################################
+#
+# Pcd Section - list of all EDK II PCD Entries defined by this Platform
+#
+################################################################################
+[PcdsFixedAtBuild]
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x800000CF
+ gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0xff
+ gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x0f
+
+ ## PL011 - Serial Terminal
+ gEfiMdeModulePkgTokenSpaceGuid.PcdSerialRegisterBase|0x60040000
+ gEfiMdePkgTokenSpaceGuid.PcdUartDefaultBaudRate|115200
+
+ gEfiMdePkgTokenSpaceGuid.PcdMaximumGuidedExtractHandler|0x2
+
+###################################################################################################
+#
+# Components Section - list of the modules and components that will be processed by compilation
+# tools and the EDK II tools to generate PE32/PE32+/Coff image files.
+#
+# Note: The EDK II DSC file is not used to specify how compiled binary images get placed
+# into firmware volume images. This section is just a list of modules to compile from
+# source into UEFI-compliant binaries.
+# It is the FDF file that contains information on combining binary files into firmware
+# volume images, whose concept is beyond UEFI and is described in PI specification.
+# Binary modules do not need to be listed in this section, as they should be
+# specified in the FDF file. For example: Shell binary (Shell_Full.efi), FAT binary (Fat.efi),
+# Logo (Logo.bmp), and etc.
+# There may also be modules listed in this section that are not required in the FDF file,
+# When a module listed here is excluded from FDF file, then UEFI-compliant binary will be
+# generated for it, but the binary will not be put into any firmware volume.
+#
+###################################################################################################
+[Components.common]
+ #
+ # MM Core
+ #
+ StandaloneMmPkg/Core/StandaloneMmCore.inf
+ StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/StandaloneMmCpu.inf
+
+###################################################################################################
+#
+# BuildOptions Section - Define the module specific tool chain flags that should be used as
+# the default flags for a module. These flags are appended to any
+# standard flags that are defined by the build process. They can be
+# applied for any modules or only those modules with the specific
+# module style (EDK or EDKII) specified in [Components] section.
+#
+###################################################################################################
+[BuildOptions.AARCH64]
+ GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000 -march=armv8-a+nofp
diff --git a/Platform/Qemu/SbsaQemu/SbsaQemu.fdf b/Platform/Qemu/SbsaQemu/SbsaQemu.fdf
index c35e3ed44054..b61ae1891233 100644
--- a/Platform/Qemu/SbsaQemu/SbsaQemu.fdf
+++ b/Platform/Qemu/SbsaQemu/SbsaQemu.fdf
@@ -21,10 +21,10 @@

[FD.SBSA_FLASH0]
BaseAddress = 0x00000000
-Size = 0x00200000
+Size = 0x00400000
ErasePolarity = 1
BlockSize = 0x00001000
-NumBlocks = 0x200
+NumBlocks = 0x400

################################################################################
#
@@ -47,7 +47,7 @@ [FD.SBSA_FLASH0]
FILE = Platform/Qemu/Sbsa/bl1.bin

# and FIP (BL2 + BL31)
-0x00008000|0x00020000
+0x00008000|0x00300000
FILE = Platform/Qemu/Sbsa/fip.bin

################################################################################
diff --git a/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf
new file mode 100644
index 000000000000..a1acefcfb0a7
--- /dev/null
+++ b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf
@@ -0,0 +1,93 @@
+#
+# Copyright (c) 2020, Linaro Limited. 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.STANDALONE_MM]
+BaseAddress = 0x20001000|gArmTokenSpaceGuid.PcdFdBaseAddress
+Size = 0x00e00000|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the device (14MiB).
+ErasePolarity = 1
+
+BlockSize = 0x00001000
+NumBlocks = 0x0e00
+
+0x00000000|0x00280000
+gArmTokenSpaceGuid.PcdFvBaseAddress|gArmTokenSpaceGuid.PcdFvSize
+FV = FVMAIN_COMPACT
+
+[FV.FVMAIN_COMPACT]
+FvAlignment = 16
+ERASE_POLARITY = 1
+MEMORY_MAPPED = TRUE
+STICKY_WRITE = TRUE
+LOCK_CAP = TRUE
+LOCK_STATUS = TRUE
+WRITE_DISABLED_CAP = TRUE
+WRITE_ENABLED_CAP = TRUE
+WRITE_STATUS = TRUE
+WRITE_LOCK_CAP = TRUE
+WRITE_LOCK_STATUS = TRUE
+READ_DISABLED_CAP = TRUE
+READ_ENABLED_CAP = TRUE
+READ_STATUS = TRUE
+READ_LOCK_CAP = TRUE
+READ_LOCK_STATUS = TRUE
+
+ INF StandaloneMmPkg/Core/StandaloneMmCore.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 to 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 = $(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="$(MODULE_NAME)" Optional
+# VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+# }
+# }
+# }
+#
+############################################################################
+
+[Rule.Common.MM_CORE_STANDALONE]
+ FILE SEC = $(NAMED_GUID) RELOCS_STRIPPED FIXED {
+ PE32 PE32 Align = Auto $(INF_OUTPUT)/$(MODULE_NAME).efi
+ }
+
+[Rule.Common.MM_STANDALONE]
+ FILE MM_STANDALONE = $(NAMED_GUID) {
+ SMM_DEPEX SMM_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex
+ PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi
+ UI STRING="$(MODULE_NAME)" Optional
+ VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
+ }
--
2.17.1


[PATCH edk2-platforms v3 0/4] add MM based UEFI secure boot on SbsaQemu

Masahisa Kojima
 

This patch series implment the UEFI secure boot on SbsaQemu.

Cc: Ard Biesheuvel <ardb+tianocore@...>
Cc: Leif Lindholm <leif@...>
Cc: Graeme Gregory <graeme@...>
Cc: Radoslaw Biernacki <rad@...>
Cc: Shashi Mallela <shashi.mallela@...>

v3:
- create device-tree parsing helper functions
- update the .dsc file layout to minimize the modification
- remove unnesessary blank line updates

v2:
- get aligned to the tf-a update, it supports 512 cores
and memory map is updated.

Masahisa Kojima (4):
SbsaQemu: Build infrastructure for StandaloneMm image
SbsaQemu: add MM based UEFI secure boot support
SbsaQemu: add standalone MM build instruction
SbsaQemu: fix typo

Platform/Qemu/SbsaQemu/SbsaQemu.dsc | 25 ++-
.../Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc | 171 ++++++++++++++++++
Platform/Qemu/SbsaQemu/SbsaQemu.fdf | 83 ++++++++-
.../Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf | 96 ++++++++++
.../Library/SbsaQemuLib/SbsaQemuLib.inf | 3 +
.../SbsaQemu/Include/Library/FdtHelperLib.h | 27 +++
.../Library/FdtHelperLib/FdtHelperLib.c | 111 ++++++++++++
.../Library/SbsaQemuLib/SbsaQemuMem.c | 55 ++----
Platform/Qemu/SbsaQemu/Readme.md | 37 +++-
9 files changed, 554 insertions(+), 54 deletions(-)
create mode 100644 Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc
create mode 100644 Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf

--
2.17.1


Re: [PATCH edk2-platforms v2 2/4] SbsaQemu: add MM based UEFI secure boot support

Masahisa Kojima
 

On Tue, 2 Mar 2021 at 02:22, Leif Lindholm <leif@...> wrote:

On Mon, Mar 01, 2021 at 14:19:50 +0900, Masahisa Kojima wrote:
This implements support for UEFI secure boot on SbsaQemu using
the standalone MM framework. This moves all of the software handling
of the UEFI authenticated variable store into the standalone MM
context residing in a secure partition.

Secure variable storage is located at 0x01000000 in secure NOR Flash.

Non-secure shared memory between UEFI and standalone MM
is allocated at the top of DRAM.
DRAM size of SbsaQemu varies depends on the QEMU parameter,
the non-secure shared memory base address is passed from
trusted-firmware through the device tree "/reserved-memory" node.

Signed-off-by: Masahisa Kojima <masahisa.kojima@...>
---
Platform/Qemu/SbsaQemu/SbsaQemu.dsc | 43 +++++++---
.../Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc | 39 +++++++++
Platform/Qemu/SbsaQemu/SbsaQemu.fdf | 82 +++++++++++++++++--
.../Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf | 7 +-
.../Library/SbsaQemuLib/SbsaQemuLib.inf | 2 +
.../Library/SbsaQemuLib/SbsaQemuMem.c | 37 ++++++++-
6 files changed, 190 insertions(+), 20 deletions(-)

diff --git a/Platform/Qemu/SbsaQemu/SbsaQemu.dsc b/Platform/Qemu/SbsaQemu/SbsaQemu.dsc
index c1f8a4696560..a75116ee70fc 100644
--- a/Platform/Qemu/SbsaQemu/SbsaQemu.dsc
+++ b/Platform/Qemu/SbsaQemu/SbsaQemu.dsc
@@ -28,6 +28,8 @@ [Defines]

DEFINE DEBUG_PRINT_ERROR_LEVEL = 0x8000004F

+ DEFINE SECURE_BOOT_ENABLE = FALSE
+
#
# Network definition
#
@@ -152,12 +154,10 @@ [LibraryClasses.common]
# Secure Boot dependencies
#
TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf
- AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf

# re-use the UserPhysicalPresent() dummy implementation from the ovmf tree
PlatformSecureLib|OvmfPkg/Library/PlatformSecureLib/PlatformSecureLib.inf

- VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf
VariablePolicyLib|MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.inf
VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf

@@ -171,6 +171,7 @@ [LibraryClasses.common]
ArmPlatformLib|ArmPlatformPkg/Library/ArmPlatformLibNull/ArmPlatformLibNull.inf

TimerLib|ArmPkg/Library/ArmArchTimerLib/ArmArchTimerLib.inf
+
This blank line is added for no apparent reason.

NorFlashPlatformLib|Silicon/Qemu/SbsaQemu/Library/SbsaQemuNorFlashLib/SbsaQemuNorFlashLib.inf

CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf
@@ -300,6 +301,8 @@ [PcdsFeatureFlag.common]
gEfiMdeModulePkgTokenSpaceGuid.PcdConOutGopSupport|TRUE
gEfiMdeModulePkgTokenSpaceGuid.PcdConOutUgaSupport|FALSE

+ gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE
+
[PcdsFixedAtBuild.common]
gEfiMdePkgTokenSpaceGuid.PcdMaximumUnicodeStringLength|1000000
gEfiMdePkgTokenSpaceGuid.PcdMaximumAsciiStringLength|1000000
@@ -551,6 +554,9 @@ [PcdsDynamicDefault.common]
gArmVirtSbsaQemuPlatformTokenSpaceGuid.PcdChassisAssetTag|L"AT0000"
gArmVirtSbsaQemuPlatformTokenSpaceGuid.PcdChassisSKU|L"SK0000"

+ gArmTokenSpaceGuid.PcdMmBufferBase|0x10000000000
+ gArmTokenSpaceGuid.PcdMmBufferSize|0x00200000
+
################################################################################
#
# Components Section - list of all EDK II Modules needed by this Platform
@@ -604,7 +610,6 @@ [Components.common]
ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf
ArmPkg/Drivers/CpuPei/CpuPei.inf

-
MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf {
<LibraryClasses>
NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf
@@ -628,24 +633,40 @@ [Components.common]
#
ArmPkg/Drivers/CpuDxe/CpuDxe.inf
MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
- MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf {
- <LibraryClasses>
- NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf
- # don't use unaligned CopyMem () on the UEFI varstore NOR flash region
- BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
- }
MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf {
<LibraryClasses>
+!if $(SECURE_BOOT_ENABLE) == TRUE
NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf
+!endif
}
- SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
- MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf

+ #
+ # Variable services
+ #
+!if $(SECURE_BOOT_ENABLE) == FALSE
+ MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf {
+ <LibraryClasses>
+ NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf
+ AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf
+ VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf
+ # don't use unaligned CopyMem () on the UEFI varstore NOR flash region
+ BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
Would this diff be neater if this if statement moved up to the
original location of the
MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf {
stanza?

+ }
+!else
+ ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf {
+ <LibraryClasses>
+ NULL|StandaloneMmPkg/Library/VariableMmDependency/VariableMmDependency.inf
+ }
+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
+ SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
+!endif
+
MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
diff --git a/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc
index 87f5ee351eaa..b80379acd1ad 100644
--- a/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc
+++ b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.dsc
@@ -77,6 +77,18 @@ [LibraryClasses.common.MM_STANDALONE]
HobLib|StandaloneMmPkg/Library/StandaloneMmHobLib/StandaloneMmHobLib.inf
MmServicesTableLib|MdePkg/Library/StandaloneMmServicesTableLib/StandaloneMmServicesTableLib.inf
MemoryAllocationLib|StandaloneMmPkg/Library/StandaloneMmMemoryAllocationLib/StandaloneMmMemoryAllocationLib.inf
+ AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf
+ BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf
+ IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf
+ NorFlashPlatformLib|Silicon/Qemu/SbsaQemu/Library/SbsaQemuNorFlashLib/SbsaQemuNorFlashLib.inf
+ OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf
+ RngLib|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf
+ PlatformSecureLib|SecurityPkg/Library/PlatformSecureLibNull/PlatformSecureLibNull.inf
+ SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf
+ TimerLib|ArmPkg/Library/ArmArchTimerLib/ArmArchTimerLib.inf
+ VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf
+ SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf
+ ArmGenericTimerCounterLib|ArmPkg/Library/ArmGenericTimerPhyCounterLib/ArmGenericTimerPhyCounterLib.inf

################################################################################
#
@@ -94,6 +106,20 @@ [PcdsFixedAtBuild]

gEfiMdePkgTokenSpaceGuid.PcdMaximumGuidedExtractHandler|0x2

+ gArmTokenSpaceGuid.PcdFdBaseAddress|0x01000000
+ gArmTokenSpaceGuid.PcdFdSize|0x000C0000
+
+ gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x2000
+ gEfiSecurityPkgTokenSpaceGuid.PcdUserPhysicalPresence|TRUE
+ gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x2800
+
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase|0x01000000
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize|0x00040000
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0x01040000
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize|0x00040000
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|0x01080000
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize|0x00040000
+
###################################################################################################
#
# Components Section - list of the modules and components that will be processed by compilation
@@ -118,6 +144,19 @@ [Components.common]
#
StandaloneMmPkg/Core/StandaloneMmCore.inf
StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/StandaloneMmCpu.inf
+ ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
+ MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandaloneMm.inf
+
+ MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf {
+ <LibraryClasses>
+ DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
+ NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf
+ NULL|MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLibStandaloneMm.inf
+ # don't use unaligned CopyMem () on the UEFI varstore NOR flash region
+ BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
+ VariablePolicyLib|MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.inf
+ VariablePolicyHelperLib|MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf
+ }

###################################################################################################
#
diff --git a/Platform/Qemu/SbsaQemu/SbsaQemu.fdf b/Platform/Qemu/SbsaQemu/SbsaQemu.fdf
index b61ae1891233..a46a47063ccc 100644
--- a/Platform/Qemu/SbsaQemu/SbsaQemu.fdf
+++ b/Platform/Qemu/SbsaQemu/SbsaQemu.fdf
@@ -21,10 +21,10 @@

[FD.SBSA_FLASH0]
BaseAddress = 0x00000000
-Size = 0x00400000
+Size = 0x01100000
ErasePolarity = 1
BlockSize = 0x00001000
-NumBlocks = 0x400
+NumBlocks = 0x1100

################################################################################
#
@@ -50,6 +50,66 @@ [FD.SBSA_FLASH0]
0x00008000|0x00300000
FILE = Platform/Qemu/Sbsa/fip.bin

+!if $(SECURE_BOOT_ENABLE)
+## Place for Secure Variables.
+# Must be aligned to Flash Block size 0x40000
+0x01000000|0x00040000
+gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize
+#NV_VARIABLE_STORE
+DATA = {
+ ## This is the EFI_FIRMWARE_VOLUME_HEADER
+ # ZeroVector []
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ # FileSystemGuid: gEfiSystemNvDataFvGuid =
+ # { 0xFFF12B8D, 0x7696, 0x4C8B,
+ # { 0xA9, 0x85, 0x27, 0x47, 0x07, 0x5B, 0x4F, 0x50 }}
+ 0x8D, 0x2B, 0xF1, 0xFF, 0x96, 0x76, 0x8B, 0x4C,
+ 0xA9, 0x85, 0x27, 0x47, 0x07, 0x5B, 0x4F, 0x50,
+ # FvLength: 0xC0000
+ 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00,
+ # Signature "_FVH" # Attributes
+ 0x5f, 0x46, 0x56, 0x48, 0xff, 0xfe, 0x04, 0x00,
+ # HeaderLength # CheckSum # ExtHeaderOffset #Reserved #Revision
+ 0x48, 0x00, 0x28, 0x09, 0x00, 0x00, 0x00, 0x02,
+ # Blockmap[0]: 0x3 Blocks * 0x40000 Bytes / Block
+ 0x3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
+ # Blockmap[1]: End
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ ## This is the VARIABLE_STORE_HEADER
+ # It is compatible with SECURE_BOOT_ENABLE == FALSE as well.
+ # Signature: gEfiAuthenticatedVariableGuid =
+ # { 0xaaf32c78, 0x947b, 0x439a,
+ # { 0xa1, 0x80, 0x2e, 0x14, 0x4e, 0xc3, 0x77, 0x92 }}
+ 0x78, 0x2c, 0xf3, 0xaa, 0x7b, 0x94, 0x9a, 0x43,
+ 0xa1, 0x80, 0x2e, 0x14, 0x4e, 0xc3, 0x77, 0x92,
+ # Size: 0x40000 (gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize) -
+ # 0x48 (size of EFI_FIRMWARE_VOLUME_HEADER) = 0x3ffb8
+ # This can speed up the Variable Dispatch a bit.
+ 0xB8, 0xFF, 0x03, 0x00,
+ # FORMATTED: 0x5A #HEALTHY: 0xFE #Reserved: UINT16 #Reserved1: UINT32
+ 0x5A, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+}
+
+0x01040000|0x00040000
+gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize
+#NV_FTW_WORKING
+DATA = {
+ # EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER->Signature = gEdkiiWorkingBlockSignatureGuid =
+ # { 0x9e58292b, 0x7c68, 0x497d, { 0xa0, 0xce, 0x65, 0x0, 0xfd, 0x9f, 0x1b, 0x95 }}
+ 0x2b, 0x29, 0x58, 0x9e, 0x68, 0x7c, 0x7d, 0x49,
+ 0xa0, 0xce, 0x65, 0x0, 0xfd, 0x9f, 0x1b, 0x95,
+ # Crc:UINT32 #WorkingBlockValid:1, WorkingBlockInvalid:1, Reserved
+ 0x5b, 0xe7, 0xc6, 0x86, 0xFE, 0xFF, 0xFF, 0xFF,
+ # WriteQueueSize: UINT64
+ 0xE0, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00
+}
+
+0x01080000|0x00040000
+gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
+#NV_FTW_SPARE
+!endif
+
################################################################################
#
# FD Section for FLASH1
@@ -169,15 +229,25 @@ [FV.FvMain]
INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
- INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
- INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
- INF SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
INF MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
INF MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
INF EmbeddedPkg/RealTimeClockRuntimeDxe/RealTimeClockRuntimeDxe.inf
INF EmbeddedPkg/MetronomeDxe/MetronomeDxe.inf
INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf

+ #
+ # Variable services
+ #
+!if $(SECURE_BOOT_ENABLE) == FALSE
+ INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
+ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
+!else
+ INF ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
+ INF SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
+!endif
+
#
# Multiple Console IO support
#
@@ -189,7 +259,6 @@ [FV.FvMain]

INF ArmPkg/Drivers/ArmGic/ArmGicDxe.inf
INF ArmPkg/Drivers/TimerDxe/TimerDxe.inf
- INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashDxe.inf
INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf

#
@@ -294,6 +363,7 @@ [FV.FVMAIN_COMPACT]
INF ArmPlatformPkg/MemoryInitPei/MemoryInitPeim.inf
INF ArmPkg/Drivers/CpuPei/CpuPei.inf
INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf
+
Another spuriously added blank line.

INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf

# IDE/AHCI Support
diff --git a/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf
index a1acefcfb0a7..dbe1555c68f2 100644
--- a/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf
+++ b/Platform/Qemu/SbsaQemu/SbsaQemuStandaloneMm.fdf
@@ -19,8 +19,8 @@
################################################################################

[FD.STANDALONE_MM]
-BaseAddress = 0x20001000|gArmTokenSpaceGuid.PcdFdBaseAddress
-Size = 0x00e00000|gArmTokenSpaceGuid.PcdFdSize # The size in bytes of the device (14MiB).
+BaseAddress = 0x20002000
+Size = 0x00e00000
ErasePolarity = 1

BlockSize = 0x00001000
@@ -49,6 +49,9 @@ [FV.FVMAIN_COMPACT]
READ_LOCK_STATUS = TRUE

INF StandaloneMmPkg/Core/StandaloneMmCore.inf
+ INF ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
+ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteStandaloneMm.inf
+ INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf
INF StandaloneMmPkg/Drivers/StandaloneMmCpu/AArch64/StandaloneMmCpu.inf

################################################################################
diff --git a/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuLib.inf b/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuLib.inf
index c067a80cc715..1d7f12202ecc 100644
--- a/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuLib.inf
+++ b/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuLib.inf
@@ -40,6 +40,8 @@ [Pcd]
gArmTokenSpaceGuid.PcdSystemMemoryBase
gArmTokenSpaceGuid.PcdSystemMemorySize
gArmVirtSbsaQemuPlatformTokenSpaceGuid.PcdDeviceTreeBaseAddress
+ gArmTokenSpaceGuid.PcdMmBufferBase
+ gArmTokenSpaceGuid.PcdMmBufferSize

[FixedPcd]
gArmTokenSpaceGuid.PcdFdBaseAddress
diff --git a/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuMem.c b/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuMem.c
index 8c2eb0b6a028..fa164ff455f5 100644
--- a/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuMem.c
+++ b/Silicon/Qemu/SbsaQemu/Library/SbsaQemuLib/SbsaQemuMem.c
@@ -25,15 +25,20 @@ SbsaQemuLibConstructor (
{
VOID *DeviceTreeBase;
INT32 Node, Prev;
- UINT64 NewBase, CurBase;
+ UINT64 NewBase, CurBase, NsBufBase;
UINT64 NewSize, CurSize;
+ UINT32 NsBufSize;
CONST CHAR8 *Type;
INT32 Len;
CONST UINT64 *RegProp;
RETURN_STATUS PcdStatus;
+ INT32 ParentOffset;
+ INT32 Offset;

NewBase = 0;
NewSize = 0;
+ NsBufBase = 0;
+ NsBufSize = 0;

DeviceTreeBase = (VOID *)(UINTN)PcdGet64 (PcdDeviceTreeBaseAddress);
ASSERT (DeviceTreeBase != NULL);
@@ -73,9 +78,39 @@ SbsaQemuLibConstructor (
}
}

+ // StandaloneMM non-secure shared buffer is allocated at the top of
+ // the system memory by trusted-firmware using "/reserved-memory" node.
+ ParentOffset = fdt_path_offset(DeviceTreeBase, "/reserved-memory");
+ if (ParentOffset < 0) {
+ DEBUG ((DEBUG_ERROR, "%a: reserved-memory node not found\n",
+ __FUNCTION__));
+ }
+ Offset = fdt_subnode_offset(DeviceTreeBase, ParentOffset, "ns-buf-spm-mm");
+ if (Offset < 0) {
+ DEBUG ((DEBUG_ERROR, "%a: ns-buf-spm-mm node not found\n",
+ __FUNCTION__));
+ }
+ // Get the 'reg' property of this node. 8 byte quantities for base address
+ // and 4 byte quantities for size.
+ RegProp = fdt_getprop (DeviceTreeBase, Offset, "reg", &Len);
+ if (RegProp != 0 && Len == (sizeof (UINT64) + sizeof(UINT32))) {
+ NsBufBase = fdt64_to_cpu (ReadUnaligned64 (RegProp));
+ NsBufSize = fdt32_to_cpu (ReadUnaligned32 ((UINT32 *)(RegProp + 1)));
+
+ DEBUG ((DEBUG_INFO, "%a: ns buf @ 0x%lx - 0x%lx\n",
+ __FUNCTION__, NsBufBase, NsBufBase + NsBufSize - 1));
+ } else {
+ DEBUG ((DEBUG_ERROR, "%a: Failed to parse FDT reserved-memory node Len %d\n",
+ __FUNCTION__, Len));
+ }
Could the above device-tree parsing be moved to a helper function in
Silicon/Qemu/SbsaQemu/Library/FdtHelperLib/ ?

(Yes, I should also move the memory node parsing there, but it wasn't
quite worth creating the library just for that before.)
I created both "memory" and "/reserved-memory" parsing helper function.
Could you check the next version of patch?

Thanks,
Masahisa


Best Regards,

Leif

+
+ NewSize -= NsBufSize;
+
// Make sure the start of DRAM matches our expectation
ASSERT (FixedPcdGet64 (PcdSystemMemoryBase) == NewBase);
PcdStatus = PcdSet64S (PcdSystemMemorySize, NewSize);
+ PcdStatus = PcdSet64S (PcdMmBufferBase, NsBufBase);
+ PcdStatus = PcdSet64S (PcdMmBufferSize, (UINT64)NsBufSize);
ASSERT_RETURN_ERROR (PcdStatus);

return RETURN_SUCCESS;
--
2.17.1


Re: [PATCH v3] ShellPkg: add more items for smbiosview -t 3 .

Gao, Zhichao
 

Hi Mars,

 

I still cannot extract your patch thru this email. But I got it from the BZ link. There still some problems I missed last time.

You should add a length check before showing the contained elements.

 

Thanks,

Zhichao

 

From: Mars CC Lin <mars_cc_lin@...>
Sent: Tuesday, March 2, 2021 11:14 AM
To: devel@edk2.groups.io
Cc: mars_cc_lin@...; Gao, Zhichao <zhichao.gao@...>; Philippe Mathieu-Daude <philmd@...>; Liming Gao <gaoliming@...>
Subject: [PATCH v3] ShellPkg: add more items for smbiosview -t 3 .

 

https://bugzilla.tianocore.org/show_bug.cgi?id=3177
Add ContainedElementCount, ContainedElementRecordLength and
ContainedElements for smbiosview type 3.

Signed-off-by: Mars CC Lin <mars_cc_lin@...>
Cc: Zhichao Gao <zhichao.gao@...>
Cc: Philippe Mathieu-Daude <philmd@...>
Cc: Liming Gao <gaoliming@...>
---
.../SmbiosView/PrintInfo.c | 14 ++++++++++++++
.../SmbiosView/SmbiosViewStrings.uni | 1 +
2 files changed, 15 insertions(+)

diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
index a3dc7b68c4..4be6cf2df4 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/PrintInfo.c
@@ -280,6 +280,7 @@ SmbiosPrintStructure (
)
{
UINT8 Index;
+ UINT8 Index2 = 0;
UINT8 *Buffer;

if (Struct == NULL) {
@@ -404,6 +405,19 @@ SmbiosPrintStructure (
if (Struct->Hdr->Length > 0x12) {
PRINT_STRUCT_VALUE (Struct, Type3, NumberofPowerCords);
}
+ if (Struct->Hdr->Length > 0x13) {
+ PRINT_STRUCT_VALUE (Struct, Type3, ContainedElementCount);
+ }
+ if (Struct->Hdr->Length > 0x14) {
+ PRINT_STRUCT_VALUE (Struct, Type3, ContainedElementRecordLength);
+ }
+ for (Index = 0; Index < Struct->Type3->ContainedElementCount; Index++) {
+ ShellPrintHiiEx(-1,-1,NULL,STRING_TOKEN (STR_SMBIOSVIEW_PRINTINFO_CONTAINED_ELEMENT), gShellDebug1HiiHandle, Index+1);
+ for (Index2 = 0; Index2< Struct->Type3->ContainedElementRecordLength; Index2++) {
+ Print (L"%02X ", Buffer[0x15 + (Index * Struct->Type3->ContainedElementRecordLength) + Index2]);
+ }
+ Print (L"\n");
+ }
}
if (AE_SMBIOS_VERSION (0x2, 0x7) && (Struct->Hdr->Length > 0x13)) {
if (Struct->Hdr->Length > (0x15 + (Struct->Type3->ContainedElementCount * Struct->Type3->ContainedElementRecordLength))) {
diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
index 8bcba7ccf7..9433e8a25f 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosViewStrings.uni
@@ -93,6 +93,7 @@
#string STR_SMBIOSVIEW_PRINTINFO_POWER_SUPPLY_STATE #language en-US "Power Supply State "
#string STR_SMBIOSVIEW_PRINTINFO_THERMAL_STATE #language en-US "Thermal state "
#string STR_SMBIOSVIEW_PRINTINFO_SECURITY_STATUS #language en-US "Security Status "
+#string STR_SMBIOSVIEW_PRINTINFO_CONTAINED_ELEMENT #language en-US "Contained Element %d: "
#string STR_SMBIOSVIEW_PRINTINFO_SUPOPRT #language en-US "Support "
#string STR_SMBIOSVIEW_PRINTINFO_CURRENT #language en-US "Current "
#string STR_SMBIOSVIEW_PRINTINFO_INSTALLED #language en-US "Installed "
--
2.29.1.windows.1


[PATCH 1/1] BaseTools: Modify struct parser for StructPcd

Yuwei Chen
 

Currently the struct parser for StructPcd Generation does not
fliter the types such as UINT8 which should be ignored successfully.
This patch modifies this issue.

Cc: Bob Feng <bob.c.feng@...>
Cc: Liming Gao <gaoliming@...>
Signed-off-by: Yuwei Chen <yuwei.chen@...>
---
BaseTools/Scripts/ConvertFceToStructurePcd.py | 2 ++
1 file changed, 2 insertions(+)

diff --git a/BaseTools/Scripts/ConvertFceToStructurePcd.py b/BaseTools/Scripts/ConvertFceToStructurePcd.py
index 867660fba9cf..d72a20d62a5d 100644
--- a/BaseTools/Scripts/ConvertFceToStructurePcd.py
+++ b/BaseTools/Scripts/ConvertFceToStructurePcd.py
@@ -197,6 +197,8 @@ class parser_lst(object):
efitxt = efivarstore_format.findall(self.text)
for i in efitxt:
struct = struct_re.findall(i.replace(' ',''))
+ if struct[0] in self._ignore:
+ continue
name = name_re.findall(i.replace(' ',''))
if struct and name:
efivarstore_dict[name[0]]=struct[0]
--
2.27.0.windows.1

19901 - 19920 of 92217