From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from EUR02-HE1-obe.outbound.protection.outlook.com (EUR02-HE1-obe.outbound.protection.outlook.com [40.107.1.78]) by mx.groups.io with SMTP id smtpd.web09.3390.1613135482973691523 for ; Fri, 12 Feb 2021 05:11:24 -0800 Authentication-Results: mx.groups.io; dkim=pass header.i=@armh.onmicrosoft.com header.s=selector2-armh-onmicrosoft-com header.b=epC2GuaW; spf=pass (domain: arm.com, ip: 40.107.1.78, mailfrom: sami.mujawar@arm.com) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=armh.onmicrosoft.com; s=selector2-armh-onmicrosoft-com; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=WY4oXApWI8Ya57bKyqzxPw25V9ZGNZWf/8YFdv7kWLg=; b=epC2GuaWh9DLAoo+VSjtbsqr7cMMb7ZXc0whFXbCGSIhkpaYuybCuUOqRdcILPpAojMAqYRjfROzLc+hAvl0UrSdloOs+Z5jxIRmKbsJ3riixP0bi30E/IaM+KaUPCjyoQ2WVCXj1SuXIT7HfBGtL4W0LWSlRIV1ar8cuRE+s8Q= Received: from AM0PR02CA0133.eurprd02.prod.outlook.com (2603:10a6:20b:28c::30) by AM8PR08MB5666.eurprd08.prod.outlook.com (2603:10a6:20b:1de::21) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.3846.34; Fri, 12 Feb 2021 13:11:19 +0000 Received: from VE1EUR03FT012.eop-EUR03.prod.protection.outlook.com (2603:10a6:20b:28c:cafe::56) by AM0PR02CA0133.outlook.office365.com (2603:10a6:20b:28c::30) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.3846.26 via Frontend Transport; Fri, 12 Feb 2021 13:11:19 +0000 X-MS-Exchange-Authentication-Results: spf=pass (sender IP is 63.35.35.123) smtp.mailfrom=arm.com; edk2.groups.io; dkim=pass (signature was verified) header.d=armh.onmicrosoft.com;edk2.groups.io; dmarc=pass action=none header.from=arm.com; Received-SPF: Pass (protection.outlook.com: domain of arm.com designates 63.35.35.123 as permitted sender) receiver=protection.outlook.com; client-ip=63.35.35.123; helo=64aa7808-outbound-1.mta.getcheckrecipient.com; Received: from 64aa7808-outbound-1.mta.getcheckrecipient.com (63.35.35.123) by VE1EUR03FT012.mail.protection.outlook.com (10.152.18.211) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.3846.25 via Frontend Transport; Fri, 12 Feb 2021 13:11:18 +0000 Received: ("Tessian outbound af289585f0f4:v71"); Fri, 12 Feb 2021 13:11:18 +0000 X-CR-MTA-TID: 64aa7808 Received: from 1b275d39d5e4.1 by 64aa7808-outbound-1.mta.getcheckrecipient.com id D163A348-09FD-4C6F-BE79-EB6EF5C711D8.1; Fri, 12 Feb 2021 13:11:13 +0000 Received: from EUR05-AM6-obe.outbound.protection.outlook.com by 64aa7808-outbound-1.mta.getcheckrecipient.com with ESMTPS id 1b275d39d5e4.1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384); Fri, 12 Feb 2021 13:11:13 +0000 ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none; b=lK42+api8cmsusvR0qFFZUI/Ri6X6hVWhYxXojIW+XqqlhtxTdIHzv1yrPAvuGz1Gw49x+suonLzUzDoDy9CgxJDmWwVgHt+rnTYf/rEp8ZAMye7uSeIJig19M2GGaxuFcwu+Iux/C5TdHjC1bq003rbhl/XW2m4sKEIr3QEudZhkOd8F/fJFdCWzQL57WQllnAlonf7BrxDeM1EnwE6D5pM0a2MxpNBGZFLP6IZr3jW/0ZkyBQ6PjcU9rQ3WMjzwd7N1Hp0AIhJOHilVjv7tW73tHnkMqBEuD9vxJT3chqFTLJClAhaWSlp2wfcL6egK6SrEaOXRWTKbzVJ+jeHUA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector9901; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=WY4oXApWI8Ya57bKyqzxPw25V9ZGNZWf/8YFdv7kWLg=; b=VaY575+Zam1g2z/pNhrlAnlkPesnSKSDJE6V017e7mtQZsYISnocIyXXPjZ9P+23zyDsxc15+EuLE0/OkaP5m/EtLhJ7ecnxolWhcJLxW33jsmJcSzXYbJi3cmc2VvTAHCF1izrj4o2kUr+Jq/2niP3EIwxUyFtAA5H/JpGNRYv93DU6mpi5VNPegUj/l3nvZFfV7F5dcZYsRFFZK2sbSboN2ZSr7fSHQMv7C9pfhK5N13U5x2CB9vWK0aDeF7HFeOAYPvLjgx2tojivMGRaG5+O4/u70Js2+fHW/11KLzNKnU+F3RhaV18HSwcrudhp8ldvaOQQ1qXzznIOuqPHfQ== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=arm.com; dmarc=pass action=none header.from=arm.com; dkim=pass header.d=arm.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=armh.onmicrosoft.com; s=selector2-armh-onmicrosoft-com; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=WY4oXApWI8Ya57bKyqzxPw25V9ZGNZWf/8YFdv7kWLg=; b=epC2GuaWh9DLAoo+VSjtbsqr7cMMb7ZXc0whFXbCGSIhkpaYuybCuUOqRdcILPpAojMAqYRjfROzLc+hAvl0UrSdloOs+Z5jxIRmKbsJ3riixP0bi30E/IaM+KaUPCjyoQ2WVCXj1SuXIT7HfBGtL4W0LWSlRIV1ar8cuRE+s8Q= Received: from DB7PR08MB3097.eurprd08.prod.outlook.com (2603:10a6:5:1d::27) by DB8PR08MB3977.eurprd08.prod.outlook.com (2603:10a6:10:ad::31) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.3846.29; Fri, 12 Feb 2021 13:11:11 +0000 Received: from DB7PR08MB3097.eurprd08.prod.outlook.com ([fe80::8c43:eec3:76be:9001]) by DB7PR08MB3097.eurprd08.prod.outlook.com ([fe80::8c43:eec3:76be:9001%4]) with mapi id 15.20.3846.035; Fri, 12 Feb 2021 13:11:11 +0000 From: "Sami Mujawar" To: Ilias Apalodimas , "devel@edk2.groups.io" CC: "ard+tianocore@kernel.org" , "sughosh.ganu@linaro.org" , "leif@nuviainc.com" , nd Subject: Re: [PATCH 1/2 v4] Drivers/OpTeeRpmb: Add an OP-TEE backed RPMB driver Thread-Topic: [PATCH 1/2 v4] Drivers/OpTeeRpmb: Add an OP-TEE backed RPMB driver Thread-Index: AQHW+hWt2Qkm2OVERUurwurCWlV8tapUcbbQ Date: Fri, 12 Feb 2021 13:11:10 +0000 Message-ID: References: <20210203101626.1200943-1-ilias.apalodimas@linaro.org> <20210203101626.1200943-2-ilias.apalodimas@linaro.org> In-Reply-To: <20210203101626.1200943-2-ilias.apalodimas@linaro.org> Accept-Language: en-GB, en-US X-MS-Has-Attach: X-MS-TNEF-Correlator: x-ts-tracking-id: 0F5A68EE39F1B64791F9B443B46C83D4.1 x-checkrecipientchecked: true Authentication-Results-Original: linaro.org; dkim=none (message not signed) header.d=none;linaro.org; dmarc=none action=none header.from=arm.com; x-originating-ip: [86.156.70.33] x-ms-publictraffictype: Email X-MS-Office365-Filtering-HT: Tenant X-MS-Office365-Filtering-Correlation-Id: 1e238066-7e6d-496d-e422-08d8cf57af96 x-ms-traffictypediagnostic: DB8PR08MB3977:|AM8PR08MB5666: X-Microsoft-Antispam-PRVS: x-checkrecipientrouted: true nodisclaimer: true x-ms-oob-tlc-oobclassifiers: OLM:10000;OLM:10000; X-MS-Exchange-SenderADCheck: 1 X-Microsoft-Antispam-Untrusted: BCL:0; X-Microsoft-Antispam-Message-Info-Original: 6tAdqrxL99fQVA/CDCXzM6RkFKckGW554KtIxfaKaM0macsklq4+J7lDSZ/8JyQsIWK/YhXBIvmFRqmIr6qfL5d3ayTESzRYlpfZIN5NTQ0s9Wjm+FJ7dQIyn9kgCfeDpLi3kZGIE4SCt90U35QyUv62h1IKbLkfjvF2HLMBtcthSvye6I3dLbNEXQdzcfBjTXXvoTWxWZIm4gKBNMPjX9lFqj5d7KvotX8As1GuCUu+GGRv08xyLk4Vb8o4Hq5tXdBNB6rXR9BV+iZr5bTGhB3pjUj9A4w4T2ie99lPJCeNqQhWqaGHoLr1qUsLrAkeDc/hACrskbBupjeuFQ+Oi99xE6yT7k0N6GDjehYoOfBqBubiZJa/Y5+1i/PCpwzaDykyyPeuvdccWmqyr8T/ipNqNsvS20e4ve4ZRAJkH4UH1ilX3Y1D02QET/XVs9Q5tSZ7zYhLs7Z+B5X8SwpYbNNqACa1EenNwiAzYOWDTgAjjBkUCl9qz2qBan33LcBI9+tzg4sWVU++YcJ2yoIy0DU7zlDqJrQhJnBRjebcBfHNSoSTJP+wwhg3tUi1G5R1jZCqGwRs94HtCp6PomRY5o1QZD7xIsyhfI8Eg7Rk9XY= X-Forefront-Antispam-Report-Untrusted: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:DB7PR08MB3097.eurprd08.prod.outlook.com;PTR:;CAT:NONE;SFS:(6029001)(4636009)(39850400004)(136003)(366004)(396003)(346002)(376002)(966005)(5660300002)(30864003)(86362001)(7696005)(76116006)(66946007)(52536014)(478600001)(6506007)(66476007)(64756008)(66446008)(66556008)(83380400001)(19627235002)(26005)(71200400001)(55016002)(33656002)(8676002)(4326008)(9686003)(186003)(316002)(2906002)(8936002)(53546011)(54906003)(110136005)(579004)(559001);DIR:OUT;SFP:1101; x-ms-exchange-antispam-messagedata: =?us-ascii?Q?+3gWkEyE00ATKlvpvPZRI2JiWvuS2KnPYz4bv2bxmJmD9bOkenomURpaI0Zl?= =?us-ascii?Q?1YUbG+1bntOlPqUBndQStOj8qREzBNJBAEBmxjfGeNkvM5DoSbSZzrfhxbLT?= =?us-ascii?Q?txaXZRm+mZWSnf6a4ISvuPXlzn/qincAUS7gk41P2cS3fyyW3vUP4kwWoZZI?= =?us-ascii?Q?cEBEtW6F1/HBCWGF14zKnYmNerS2NSFpBWUl6rUvlu6henT1mZtaHz82jYvn?= =?us-ascii?Q?oLPPUpp1QxTuQdzOBvxGMQPg7rvu5mVf0b6QJcilSZaVq7mZcqlltAZC37OE?= =?us-ascii?Q?7WBKN4yqVby/19N/TSN/sLG6YMx/dDZ2yg8Qe/WAy92MED8qvHFiVyVPNwpZ?= =?us-ascii?Q?j41rMjiBXn+1XOQ42xQrY4+zdjXU76LlPjiekuy7Px8lhhwL9FxueGXYjKr2?= =?us-ascii?Q?sqLcakxCCNKXX09cD/Scktt1SNDYkgoTcZuvqY9Ab5B+LHx2SbWu2bQbvbA6?= =?us-ascii?Q?CHVWmZMSd2JNriLhTsSFSJfTdmAYrTk9LCjMnMo0av8pdwrbsGOReQQN1qbx?= =?us-ascii?Q?lixareMrmcjCfTEqxA1ovM5mGjKpkbeeukP45E6n5+7YBEyt+801ZMe5Fnze?= =?us-ascii?Q?grjdAp+It6ha+HRtborIux5QNF3QD/PVkPwJtTEvlsaODKKkXlpiFAwRYkAU?= =?us-ascii?Q?g81AfVx/QxE052RZvonpY+l73fLqTifAv9HSK357O1RY4We0oyea7gQIzG7T?= =?us-ascii?Q?Z1uEtyFypIJZCwDBkWFqQuCadnMOMo3Z9R5jMCpinWBbmWBL4U7aA9J/RB6d?= =?us-ascii?Q?kKd/2QokijxwZ3+Qr+LC5X4xEqbxTESalLgycni3kR27mLB1leOo2PjllRP+?= =?us-ascii?Q?ua0KhpSBSpH8C9CqqU5iX7yGstb/pby4LJsozwvRfIe2ky8FuPtJCFR5p2m2?= =?us-ascii?Q?06R0Dmjavpt/qBOl9jcg7p0S4UHdAZVRqDDeUIuH8gcuY97kYL8/k8RT6QBy?= =?us-ascii?Q?HKLILS2EsowtqibraFp8OO+krg6BIvZqsymP3OzUVHLNN7lWhPp9dA2sd4ih?= =?us-ascii?Q?JyKEs6lWCFEuRVwK7MbYPBI0yGGfFEajTIGKThNSyJ3UUl1nvDsmOMPt4DmS?= =?us-ascii?Q?qB9Nw1HvnPH4zTS3uU1Yj+iG55P0eHa4ylutaSowkfn5eE0Iyf3CKo8gAfpT?= =?us-ascii?Q?APCX0zkwCP5YYFXE+oNUTBUwQtiLcR8Hr658Q9f5o4No6usV/UbXvlY/bE3f?= =?us-ascii?Q?zNiF+iRXSU2CzD5a2PrgVWtcY2iWhB0G3yr2k7moDHfTxg+kIAq6gd5facLk?= =?us-ascii?Q?Hl2OKun/WItw2CJuXpjOuZ3ykG4DQn8J30KqbITW4hHclZAi9RTSLx1lN77J?= =?us-ascii?Q?7uc=3D?= x-ms-exchange-transport-forked: True MIME-Version: 1.0 X-MS-Exchange-Transport-CrossTenantHeadersStamped: DB8PR08MB3977 Original-Authentication-Results: linaro.org; dkim=none (message not signed) header.d=none;linaro.org; dmarc=none action=none header.from=arm.com; Return-Path: Sami.Mujawar@arm.com X-EOPAttributedMessage: 0 X-MS-Exchange-Transport-CrossTenantHeadersStripped: VE1EUR03FT012.eop-EUR03.prod.protection.outlook.com X-MS-Office365-Filtering-Correlation-Id-Prvs: 76e162de-0edd-4d6f-8223-08d8cf57aaf5 X-Microsoft-Antispam: BCL:0; X-Microsoft-Antispam-Message-Info: E4DkOiruWmVgGdTuyGlnwJNmXHlyNJNMeUTKvOJGjZrPpFY3G/427vjymi7jb+I+FJGLmQ84zIQq4svOpRdVlFvesIcdo9skQ2zncDUe5CyaqkAlEmh/7yw4bf0nPddh2uPBB0pwrRJeW0Ca6FrGLO4TlLe4MDp4pqDmZ4gev03vpD3KAS+IaEj4BgiIVsirLDNR4DYkp5RXtUzRBvIzWxRiohtmMazbVyP1lvqe+m8w2qZk82KhWMl5nRCf3aVx8jwGbc3HVWnzAsXUC0ZXSzj/hmB6fjt8gY9tyjcWbEW9NXZocRIx4kf7tBki64H1FlO+oBePIdL1dM2ZUELqHLTqrKwjvjFTqfyuTeb+p1JKe5Cf9S6Hx+RwnoKbfF2Kly2/YFJ4dVMwQpgKVRR0jgJJ+WqeLPqnRv/Wz4aUoZVUWqacIYgqBCUyQoV61REzS9XKO604Kqi+N0uZvgPSA96/WQ1gETGYNhgbHLjZ+Z1TjCT8HWYVTEAokXeBTsHgVwKFK6aSIIgNs2CdTfOOo4yyahobS7/v58jKo/g4I2XL4l39KRWc7si4rDx6+4RXaz3wTxU+CkZ5W1ENeMVCZoBZVDn+DQwpM8GcghqBcVtRn9Jm8D9MxwCRMr6/ezP6lUUwKUpc0n3LAXMcvIaqZHVcEg5LcVMpNbAeQUQicbCZQ1m0MXpjvSRIoYPEfVFNVJLhoqwbch+Hk2c/4ewyEey/tmgB8j5fAHfGpOdHnDQ= X-Forefront-Antispam-Report: CIP:63.35.35.123;CTRY:IE;LANG:en;SCL:1;SRV:;IPV:CAL;SFV:NSPM;H:64aa7808-outbound-1.mta.getcheckrecipient.com;PTR:ec2-63-35-35-123.eu-west-1.compute.amazonaws.com;CAT:NONE;SFS:(6029001)(4636009)(346002)(376002)(136003)(396003)(39840400004)(46966006)(36840700001)(7696005)(53546011)(478600001)(4326008)(81166007)(70586007)(6506007)(316002)(966005)(2906002)(55016002)(5660300002)(70206006)(30864003)(47076005)(336012)(26005)(82310400003)(19627235002)(33656002)(186003)(83380400001)(36860700001)(8676002)(52536014)(9686003)(8936002)(86362001)(54906003)(110136005)(356005)(579004);DIR:OUT;SFP:1101; X-OriginatorOrg: arm.com X-MS-Exchange-CrossTenant-OriginalArrivalTime: 12 Feb 2021 13:11:18.6171 (UTC) X-MS-Exchange-CrossTenant-Network-Message-Id: 1e238066-7e6d-496d-e422-08d8cf57af96 X-MS-Exchange-CrossTenant-Id: f34e5979-57d9-4aaa-ad4d-b122a662184d X-MS-Exchange-CrossTenant-OriginalAttributedTenantConnectingIp: TenantId=f34e5979-57d9-4aaa-ad4d-b122a662184d;Ip=[63.35.35.123];Helo=[64aa7808-outbound-1.mta.getcheckrecipient.com] X-MS-Exchange-CrossTenant-AuthSource: VE1EUR03FT012.eop-EUR03.prod.protection.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Anonymous X-MS-Exchange-CrossTenant-FromEntityHeader: HybridOnPrem X-MS-Exchange-Transport-CrossTenantHeadersStamped: AM8PR08MB5666 Content-Language: en-US Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Hi Ilias, Apologies for the delay in reviewing this patch. Please find my response inline marked [SAMI]. There are some coding standard issues remaining. I believe these are not re= ported by Ecc.=20 Also, InitializeFvAndVariableStoreHeaders() would need error handling for a= memory allocation failure. Regards, Sami Mujawar -----Original Message----- From: Ilias Apalodimas =20 Sent: 03 February 2021 10:16 AM To: devel@edk2.groups.io; Sami Mujawar Cc: ard+tianocore@kernel.org; sughosh.ganu@linaro.org; leif@nuviainc.com; I= lias Apalodimas Subject: [PATCH 1/2 v4] 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 --- Drivers/OpTeeRpmb/FixupPcd.c | 84 +++ Drivers/OpTeeRpmb/FixupPcd.inf | 44 ++ Drivers/OpTeeRpmb/OpTeeRpmbFv.inf | 58 +++ Drivers/OpTeeRpmb/OpTeeRpmbFvb.c | 822 ++++++++++++++++++++++++++++++ Drivers/OpTeeRpmb/OpTeeRpmbFvb.h | 52 ++ 5 files changed, 1060 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..177f9b9e1556 --- /dev/null +++ b/Drivers/OpTeeRpmb/FixupPcd.c @@ -0,0 +1,84 @@ +/** @file + + Update the patched PCDs to their correct value + + Copyright (c) 2020, Linaro Ltd. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +/** + * Patch the relevant PCDs of the RPMB driver with the correct address of = the + * allocated memory + * +**/ +#include +#include +#include +#include + +#include +#include + +#include "OpTeeRpmbFvb.h" + +/** + Fixup the Pcd values for variable storage + + Since the upper layers of EDK2 expect a memory mapped interface and we c= an't + offer that from an RPMB, the driver allocates memory on init and passes = that + on the upper layers. Since the memory is dynamically allocated and we ca= n't set the + PCD is StMM context, we need to patch it correctly on each access + + @retval EFI_SUCCESS Protocol was found and PCDs patched up + + **/ +EFI_STATUS +EFIAPI +FixPcdMemory ( + VOID + ) +{ + EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol; + MEM_INSTANCE *Instance; + EFI_STATUS Status; + + // + // Locate SmmFirmwareVolumeBlockProtocol + // + Status =3D gMmst->MmLocateProtocol ( + &gEfiSmmFirmwareVolumeBlockProtocolGuid, + NULL, + (VOID **) &FvbProtocol + ); + ASSERT_EFI_ERROR (Status); + + Instance =3D INSTANCE_FROM_FVB_THIS(FvbProtocol); [SAMI] Space needed before opening parenthesis. See https://edk2-docs.gitbook.io/edk-ii-c-coding-standards-specification/5= _source_files/52_spacing#5-2-2-6-always-put-space-before-an-open-parenthesi= s Please also check other places in this patch. [/SAMI] + // The Pcd is user defined, so make sure we don't overflow + if (Instance->MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageV= ariableSize)) { + return EFI_INVALID_PARAMETER; + } + + if (Instance->MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageV= ariableSize) - + PcdGet32 (PcdFlashNvStorageFtwWorkingSize)) { + return EFI_INVALID_PARAMETER; + } + + // Patch PCDs with the the correct values + PatchPcdSet64 (PcdFlashNvStorageVariableBase64, Instance->MemBaseAddress= ); + PatchPcdSet64 (PcdFlashNvStorageFtwWorkingBase64, Instance->MemBaseAddre= ss + + PcdGet32 (PcdFlashNvStorageVariableSize)); [SAMI] Please see alignment guidelines described in EDKII coding standard a= t: https://edk2-docs.gitbook.io/edk-ii-c-coding-standards-specification/5_sou= rce_files/52_spacing#5-2-2-4-subsequent-lines-of-multi-line-function-calls-= should-line-up-two-spaces-from-the-beginning-of-the-function-name Please also fix this at other places in this patch. [/SAMI] + 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.in= f new file mode 100644 index 000000000000..f58ad6f682b5 --- /dev/null +++ b/Drivers/OpTeeRpmb/FixupPcd.inf @@ -0,0 +1,44 @@ +## @file +# Instance of Base Memory Library without assembly. +# +# Copyright (c) 2020, Linaro Ltd. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# +## + +[Defines] + INF_VERSION =3D 0x0001001A + BASE_NAME =3D FixupPcd + FILE_GUID =3D a827c337-a9c6-301b-aeb7-acbc95d8da22 + MODULE_TYPE =3D BASE + VERSION_STRING =3D 0.1 + LIBRARY_CLASS =3D RpmbPcdFixup|MM_STANDALONE + CONSTRUCTOR =3D FixPcdMemory + +[Sources] + FixupPcd.c + OpTeeRpmbFvb.h + +[Packages] + MdeModulePkg/MdeModulePkg.dec + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + DebugLib + MmServicesTableLib + PcdLib + +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize [SAMI] Please sort in alphabetical order. [/SAMI] + + +[Protocols] + gEfiSmmFirmwareVolumeBlockProtocolGuid ## CONSUMES diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFv.inf b/Drivers/OpTeeRpmb/OpTeeRpm= bFv.inf new file mode 100644 index 000000000000..90ad6dfea65e --- /dev/null +++ b/Drivers/OpTeeRpmb/OpTeeRpmbFv.inf @@ -0,0 +1,58 @@ +## @file +# +# Component description file for OpTeeRpmbFv module +# +# Copyright (c) 2020, Linaro Ltd. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION =3D 0x0001001A + BASE_NAME =3D OpTeeRpmbFv + FILE_GUID =3D 4803FC20-E583-3BCD-8C60-141E85C9A2CF + MODULE_TYPE =3D MM_STANDALONE + VERSION_STRING =3D 0.1 + PI_SPECIFICATION_VERSION =3D 0x00010032 + ENTRY_POINT =3D OpTeeRpmbFvbInit + +[Sources] + OpTeeRpmbFvb.c + OpTeeRpmbFvb.h + +[Packages] + ArmPkg/ArmPkg.dec + ArmPlatformPkg/ArmPlatformPkg.dec + MdeModulePkg/MdeModulePkg.dec + MdePkg/MdePkg.dec + StandaloneMmPkg/StandaloneMmPkg.dec + +[LibraryClasses] + ArmSvcLib + BaseLib + BaseMemoryLib + DebugLib + MemoryAllocationLib + MmServicesTableLib + PcdLib + StandaloneMmDriverEntryPoint + +[Guids] + gEfiAuthenticatedVariableGuid + gEfiSystemNvDataFvGuid + gEfiVariableGuid + +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase64 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase64 + gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize [SAMI] Please sort in alphabetical order. [/SAMI] + +[Protocols] + gEfiSmmFirmwareVolumeBlockProtocolGuid ## PRODUCES + +[Depex] + TRUE diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFvb.c b/Drivers/OpTeeRpmb/OpTeeRpmb= Fvb.c new file mode 100644 index 000000000000..bfd61bae330a --- /dev/null +++ b/Drivers/OpTeeRpmb/OpTeeRpmbFvb.c @@ -0,0 +1,822 @@ +/** @file + + FV block I/O protocol driver for RPMB eMMC accessed via OP-TEE + + Copyright (c) 2020, Linaro Ltd. All rights reserved.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#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 suppor= ts +// +// mMemMgrId is used to set the page permissions after relocating the exec= utable +// 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, ha= ndling +// the autodiscovery failed scenario +STATIC CONST UINT16 mMemMgrId =3D 3U; +STATIC CONST UINT16 mStorageId =3D 4U; + +STATIC MEM_INSTANCE mInstance; + +/** + Sends an SVC call to OP-TEE for reading/writing an RPMB partition + + @param SvcAct SVC ID for read/write + @param Addr Base address of the buffer. When reading contents will= be + copied to that buffer after reading them from the devi= ce. + When writing, the buffer holds the contents we want to + write cwtoin the device + @param NumBytes Number of bytes to read/write + @param Offset Offset into the RPMB file + + @retval OP-TEE return code +**/ +STATIC +EFI_STATUS +ReadWriteRpmb ( + UINTN SvcAct, + UINTN Addr, + UINTN NumBytes, + UINTN Offset + ) +{ + ARM_SVC_ARGS SvcArgs; + EFI_STATUS Status; + + ZeroMem (&SvcArgs, sizeof (SvcArgs)); + + SvcArgs.Arg0 =3D ARM_SVC_ID_FFA_MSG_SEND_DIRECT_REQ_AARCH64; + SvcArgs.Arg1 =3D mStorageId; + SvcArgs.Arg2 =3D 0; + SvcArgs.Arg3 =3D SvcAct; + SvcArgs.Arg4 =3D Addr; + SvcArgs.Arg5 =3D NumBytes; + SvcArgs.Arg6 =3D Offset; + + ArmCallSvc (&SvcArgs); + if (SvcArgs.Arg3) { + DEBUG ((DEBUG_ERROR, "%a: Svc Call 0x%08x Addr: 0x%08x len: 0x%x Offse= t: 0x%x failed with 0x%x\n", + __func__, SvcAct, Addr, NumBytes, Offset, SvcArgs.Arg3)); + } + + switch (SvcArgs.Arg3) { + case ARM_SVC_SPM_RET_SUCCESS: + Status =3D EFI_SUCCESS; + break; + + case ARM_SVC_SPM_RET_NOT_SUPPORTED: + Status =3D EFI_UNSUPPORTED; + break; + + case ARM_SVC_SPM_RET_INVALID_PARAMS: + Status =3D EFI_INVALID_PARAMETER; + break; + + case ARM_SVC_SPM_RET_DENIED: + Status =3D EFI_ACCESS_DENIED; + break; + + case ARM_SVC_SPM_RET_NO_MEMORY: + Status =3D EFI_OUT_OF_RESOURCES; + break; + + default: + Status =3D 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 insta= nce. + + @param Attributes Pointer to EFI_FVB_ATTRIBUTES_2 in which the + attributes and current settings are + returned. Type EFI_FVB_ATTRIBUTES_2 is defined + in EFI_FIRMWARE_VOLUME_HEADER. + + @retval EFI_SUCCESS The firmware volume attributes were + returned. + +**/ +STATIC +EFI_STATUS +OpTeeRpmbFvbGetAttributes ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + OUT EFI_FVB_ATTRIBUTES_2 *Attributes + ) +{ + *Attributes =3D EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled + EFI_FVB2_READ_STATUS | // Reads are currently enabl= ed + EFI_FVB2_WRITE_STATUS | // Writes are currently enab= led + EFI_FVB2_WRITE_ENABLED_CAP | // Writes may be enabled + EFI_FVB2_STICKY_WRITE | // A block erase is required= to flip bits into EFI_FVB2_ERASE_POLARITY + EFI_FVB2_MEMORY_MAPPED | // It is memory mapped + EFI_FVB2_ERASE_POLARITY; // After erasure all bits ta= ke this value (i.e. '1') + + return EFI_SUCCESS; +} + +/** + The SetAttributes() function sets configurable firmware volume + attributes and returns the new settings of the firmware volume. + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL ins= tance. + + @param Attributes On input, Attributes is a pointer to + EFI_FVB_ATTRIBUTES_2 that contains the + desired firmware volume settings. On + successful return, it contains the new + settings of the firmware volume. Type + EFI_FVB_ATTRIBUTES_2 is defined in + EFI_FIRMWARE_VOLUME_HEADER. + + @retval EFI_SUCCESS The firmware volume attributes were return= ed. + + @retval EFI_INVALID_PARAMETER The attributes requested are in + conflict with the capabilities + as declared in the firmware + volume header. + +**/ +STATIC +EFI_STATUS +OpTeeRpmbFvbSetAttributes ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes + ) +{ + return EFI_SUCCESS; // ignore for now [SAMI] Should this be EFI_UNSUPPORTED? If not, a comment may be helpful. [/SAMI] +} + +/** + The GetPhysicalAddress() function retrieves the base address of + a memory-mapped firmware volume. This function should be called + only for memory-mapped firmware volumes. + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instanc= e. + + @param Address Pointer to a caller-allocated + EFI_PHYSICAL_ADDRESS that, on successful + return from GetPhysicalAddress(), contains the + base address of the firmware volume. + + @retval EFI_SUCCESS The firmware volume base address was returned. + + @retval EFI_UNSUPPORTED The firmware volume is not memory mapped. + +**/ +STATIC +EFI_STATUS +OpTeeRpmbFvbGetPhysicalAddress ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + OUT EFI_PHYSICAL_ADDRESS *Address + ) +{ + MEM_INSTANCE *Instance; + + Instance =3D INSTANCE_FROM_FVB_THIS(This); + *Address =3D Instance->MemBaseAddress; + + return EFI_SUCCESS; +} + +/** + The GetBlockSize() function retrieves the size of the requested + block. It also returns the number of additional blocks with + the identical size. The GetBlockSize() function is used to + retrieve the block map (see EFI_FIRMWARE_VOLUME_HEADER). + + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL i= nstance. + + @param Lba Indicates the block for which to return the size. + + @param BlockSize Pointer to a caller-allocated UINTN in which + the size of the block is returned. + + @param NumberOfBlocks Pointer to a caller-allocated UINTN in + which the number of consecutive blocks, + starting with Lba, is returned. All + blocks in this range have a size of + BlockSize. + + + @retval EFI_SUCCESS The firmware volume base address was ret= urned. + + @retval EFI_INVALID_PARAMETER The requested LBA is out of range. + +**/ +STATIC +EFI_STATUS +OpTeeRpmbFvbGetBlockSize ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + IN EFI_LBA Lba, + OUT UINTN *BlockSize, + OUT UINTN *NumberOfBlocks + ) +{ + MEM_INSTANCE *Instance; + + Instance =3D INSTANCE_FROM_FVB_THIS(This); + if (Lba > Instance->NBlocks) { + return EFI_INVALID_PARAMETER; + } + + *NumberOfBlocks =3D Instance->NBlocks - (UINTN) Lba; [SAMI] There should be no space between (UINTN) and Lba. Please see point 2 at https://edk2-docs.gitbook.io/edk-ii-c-coding-standard= s-specification/v/release%2F2.20/3_quick_reference#3-2-3-formatting-horizon= tal-spacing [/SAMI] + *BlockSize =3D Instance->BlockSize; + + return EFI_SUCCESS; +} + +/** + Reads the specified number of bytes into a buffer from the specified blo= ck. + + The Read() function reads the requested number of bytes from the + requested block and stores them in the provided buffer. + Implementations should be mindful that the firmware volume + might be in the ReadDisabled state. If it is in this state, + the Read() function must return the status code + EFI_ACCESS_DENIED without modifying the contents of the + buffer. The Read() function must also prevent spanning block + boundaries. If a read is requested that would span a block + boundary, the read must read up to the boundary but not + beyond. The output parameter NumBytes must be set to correctly + indicate the number of bytes actually read. The caller must be + aware that a read may be partially completed. + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instanc= e. + + @param Lba The starting logical block index + from which to read. + + @param Offset Offset into the block at which to begin reading. + + @param NumBytes Pointer to a UINTN. At entry, *NumBytes + contains the total size of the buffer. At + exit, *NumBytes contains the total number of + bytes read. + + @param Buffer Pointer to a caller-allocated buffer that will + be used to hold the data that is read. + + @retval EFI_SUCCESS The firmware volume was read successfully, + and contents are in Buffer. + + @retval EFI_BAD_BUFFER_SIZE Read attempted across an LBA + boundary. On output, NumBytes + contains the total number of bytes + returned in Buffer. + + @retval EFI_ACCESS_DENIED The firmware volume is in the + ReadDisabled state. + + @retval EFI_DEVICE_ERROR The block device is not + functioning correctly and could + not be read. + +**/ +STATIC +EFI_STATUS +OpTeeRpmbFvbRead ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + IN EFI_LBA Lba, + IN UINTN Offset, + IN OUT UINTN *NumBytes, + IN OUT UINT8 *Buffer + ) +{ + EFI_STATUS Status =3D EFI_SUCCESS; + MEM_INSTANCE *Instance; + VOID *Base; + + Instance =3D INSTANCE_FROM_FVB_THIS(This); + if (!Instance->Initialized) { + Instance->Initialize (Instance); [SAMI] Should the status be checked here and returned?=20 Or is the assumption that Initialize will always succeed. If so,=20 - a comment would be helpful. - the Status variable here is redundant.=20 Same comment for OpTeeRpmbFvbWrite(). [/SAMI] + } + + Base =3D (VOID *)Instance->MemBaseAddress + Lba * Instance->BlockSize + = Offset; [SAMI] Use of parentheses is encouraged. See https://edk2-docs.gitbook.io/e= dk-ii-c-coding-standards-specification/5_source_files/52_spacing#5-2-2-10-u= se-extra-parentheses-rather-than-depending-on-in-depth-knowledge-of-the-ord= er-of-precedence-of-c [/SAMI] + // We could read the data from the RPMB instead of memory + // The 2 copies should already be identical + // Copy from memory image + CopyMem (Buffer, Base, *NumBytes); + + return Status; +} + +/** + Writes the specified number of bytes from the input buffer to the block. + + The Write() function writes the specified number of bytes from + the provided buffer to the specified block and offset. If the + firmware volume is sticky write, the caller must ensure that + all the bits of the specified range to write are in the + EFI_FVB_ERASE_POLARITY state before calling the Write() + function, or else the result will be unpredictable. This + unpredictability arises because, for a sticky-write firmware + volume, a write may negate a bit in the EFI_FVB_ERASE_POLARITY + state but cannot flip it back again. Before calling the + Write() function, it is recommended for the caller to first call + the EraseBlocks() function to erase the specified block to + write. A block erase cycle will transition bits from the + (NOT)EFI_FVB_ERASE_POLARITY state back to the + EFI_FVB_ERASE_POLARITY state. Implementations should be + mindful that the firmware volume might be in the WriteDisabled + state. If it is in this state, the Write() function must + return the status code EFI_ACCESS_DENIED without modifying the + contents of the firmware volume. The Write() function must + also prevent spanning block boundaries. If a write is + requested that spans a block boundary, the write must store up + to the boundary but not beyond. The output parameter NumBytes + must be set to correctly indicate the number of bytes actually + written. The caller must be aware that a write may be + partially completed. All writes, partial or otherwise, must be + fully flushed to the hardware before the Write() service + returns. + + @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL instanc= e. + + @param Lba The starting logical block index to write to. + + @param Offset Offset into the block at which to begin writing. + + @param NumBytes The pointer to a UINTN. At entry, *NumBytes + contains the total size of the buffer. At + exit, *NumBytes contains the total number of + bytes actually written. + + @param Buffer The pointer to a caller-allocated buffer that + contains the source for the write. + + @retval EFI_SUCCESS The firmware volume was written successfully= . + + @retval EFI_BAD_BUFFER_SIZE The write was attempted across an + LBA boundary. On output, NumBytes + contains the total number of bytes + actually written. + + @retval EFI_ACCESS_DENIED The firmware volume is in the + WriteDisabled state. + + @retval EFI_DEVICE_ERROR The block device is malfunctioning + and could not be written. + + +**/ +STATIC +EFI_STATUS +OpTeeRpmbFvbWrite ( + IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + IN EFI_LBA Lba, + IN UINTN Offset, + IN OUT UINTN *NumBytes, + IN UINT8 *Buffer + ) +{ + MEM_INSTANCE *Instance; + EFI_STATUS Status =3D EFI_SUCCESS; + VOID *Base; + + Instance =3D INSTANCE_FROM_FVB_THIS(This); + if (!Instance->Initialized) { + Instance->Initialize (Instance); + } + Base =3D (VOID *)Instance->MemBaseAddress + Lba * Instance->BlockSize + = Offset; + Status =3D 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 EFI_SUCCESS; +} + +/** + 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 =3D INSTANCE_FROM_FVB_THIS(This); + + VA_START (Args, This); + for (Start =3D VA_ARG (Args, EFI_LBA); + Start !=3D EFI_LBA_LIST_TERMINATOR; + Start =3D VA_ARG (Args, EFI_LBA)) { + NumLba =3D VA_ARG (Args, UINTN); + if (NumLba =3D=3D 0 || Start + NumLba > Instance->NBlocks) { + return EFI_INVALID_PARAMETER; + } + NumBytes =3D NumLba * Instance->BlockSize; + Base =3D (VOID *)Instance->MemBaseAddress + Start * Instance->BlockSiz= e; + Buf =3D AllocatePool(NumLba * Instance->BlockSize); + if (!Buf) { [SAMI] if (Buf =3D=3D NULL) { [/SAMI] + return EFI_DEVICE_ERROR; + } + SetMem64 (Buf, NumLba * Instance->BlockSize, ~0UL); + // Write the device + Status =3D 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 content= s + into memory before we register the Fvb protocol. + + @param Instace Address to copy flash contents to + + @retval 0 on success, OP-TEE error on failure +**/ +STATIC +VOID +ReadEntireFlash ( + MEM_INSTANCE *Instance + ) +{ + UINTN ReadAddr; + + UINTN StorageFtwWorkingSize =3D PcdGet32(PcdFlashNvStorageFtwWorkingSize= ); + UINTN StorageVariableSize =3D PcdGet32(PcdFlashNvStorageVariableSize); + UINTN StorageFtwSpareSize =3D PcdGet32(PcdFlashNvStorageFtwSpareSize); + + ReadAddr =3D Instance->MemBaseAddress; + // There's no need to check if the read failed here. The upper EDK2 laye= rs + // will initialize the flash correctly if the in-memory copy is wrong + ReadWriteRpmb(SP_SVC_RPMB_READ, ReadAddr, StorageVariableSize + + StorageFtwWorkingSize + StorageFtwSpareSize , 0); +} + + +STATIC +EFI_STATUS +EFIAPI +ValidateFvHeader ( + IN EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader + ) +{ + UINT16 Checksum; + VARIABLE_STORE_HEADER *VariableStoreHeader; + UINTN VariableStoreLength; + UINTN FvLength; + + FvLength =3D PcdGet32(PcdFlashNvStorageVariableSize) + + PcdGet32(PcdFlashNvStorageFtwWorkingSize) + + PcdGet32(PcdFlashNvStorageFtwSpareSize); + + // Verify the header revision, header signature, length + // Length of FvBlock cannot be 2**64-1 + // HeaderLength cannot be an odd number + // + if ( (FwVolHeader->Revision !=3D EFI_FVH_REVISION) + || (FwVolHeader->Signature !=3D EFI_FVH_SIGNATURE) + || (FwVolHeader->FvLength !=3D FvLength) + ) + { + DEBUG ((DEBUG_INFO, "%a: No Firmware Volume header present\n", + __FUNCTION__)); + return EFI_NOT_FOUND; + } + + // Check the Firmware Volume Guid + if (!CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid)= ) { + DEBUG ((DEBUG_INFO, "%a: Firmware Volume Guid non-compatible\n", + __FUNCTION__)); + return EFI_NOT_FOUND; + } + + // Verify the header checksum + Checksum =3D CalculateSum16((UINT16*)FwVolHeader, FwVolHeader->HeaderLen= gth); + if (Checksum !=3D 0) { + DEBUG ((DEBUG_INFO, "%a: FV checksum is invalid (Checksum:0x%X)\n", + __FUNCTION__, Checksum)); + return EFI_VOLUME_CORRUPTED; + } + + VariableStoreHeader =3D (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_NOT_FOUND; + } + + VariableStoreLength =3D PcdGet32 (PcdFlashNvStorageVariableSize) - + FwVolHeader->HeaderLength; + if (VariableStoreHeader->Size !=3D VariableStoreLength) { + DEBUG ((DEBUG_INFO, "%a: Variable Store Length does not match\n", + __FUNCTION__)); + return EFI_NOT_FOUND; + } + + return EFI_SUCCESS; + +} + +STATIC +EFI_STATUS +InitializeFvAndVariableStoreHeaders ( + MEM_INSTANCE *Instance + ) +{ + EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader; + VARIABLE_STORE_HEADER *VariableStoreHeader; + EFI_STATUS Status =3D EFI_SUCCESS; + UINTN HeadersLength; + VOID* Headers; + + HeadersLength =3D sizeof(EFI_FIRMWARE_VOLUME_HEADER) + + sizeof(EFI_FV_BLOCK_MAP_ENTRY) + + sizeof(VARIABLE_STORE_HEADER); + Headers =3D AllocateZeroPool(HeadersLength); [SAMI] Error handling for allocation failure is needed here. [/SAMI] + + // + // EFI_FIRMWARE_VOLUME_HEADER + // + FirmwareVolumeHeader =3D (EFI_FIRMWARE_VOLUME_HEADER*)Headers; + CopyGuid (&FirmwareVolumeHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid= ); + FirmwareVolumeHeader->FvLength =3D + PcdGet32(PcdFlashNvStorageVariableSize) + + PcdGet32(PcdFlashNvStorageFtwWorkingSize) + + PcdGet32(PcdFlashNvStorageFtwSpareSize); + FirmwareVolumeHeader->Signature =3D EFI_FVH_SIGNATURE; + FirmwareVolumeHeader->Attributes =3D EFI_FVB2_READ_ENABLED_CAP | + EFI_FVB2_READ_STATUS | + EFI_FVB2_STICKY_WRITE | + EFI_FVB2_MEMORY_MAPPED | + EFI_FVB2_ERASE_POLARITY | + EFI_FVB2_WRITE_STATUS | + EFI_FVB2_WRITE_ENABLED_CAP; + + FirmwareVolumeHeader->HeaderLength =3D sizeof(EFI_FIRMWARE_VOLUME_HEADER= ) + + sizeof(EFI_FV_BLOCK_MAP_ENTRY); + FirmwareVolumeHeader->Revision =3D EFI_FVH_REVISION; + FirmwareVolumeHeader->BlockMap[0].NumBlocks =3D Instance->NBlocks; + FirmwareVolumeHeader->BlockMap[0].Length =3D Instance->BlockSize; + FirmwareVolumeHeader->BlockMap[1].NumBlocks =3D 0; + FirmwareVolumeHeader->BlockMap[1].Length =3D 0; + FirmwareVolumeHeader->Checksum =3D CalculateCheckSum16 ( + (UINT16*)FirmwareVolumeHeader, + FirmwareVolumeHeader->HeaderLength); + + // + // VARIABLE_STORE_HEADER + // + VariableStoreHeader =3D (VARIABLE_STORE_HEADER*)((UINTN)Headers + + FirmwareVolumeHeader->Hea= derLength); + CopyGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGui= d); + VariableStoreHeader->Size =3D PcdGet32(PcdFlashNvStorageVariableSize) - + FirmwareVolumeHeader->HeaderLength; + VariableStoreHeader->Format =3D VARIABLE_STORE_FORMATTED; + VariableStoreHeader->State =3D VARIABLE_STORE_HEALTHY; + + Status =3D ReadWriteRpmb(SP_SVC_RPMB_WRITE, (UINTN) Headers, HeadersLeng= th, 0); + if (EFI_ERROR (Status)) { + goto Exit; + } + // Install the combined header in memory + CopyMem ((VOID*) Instance->MemBaseAddress, Headers, HeadersLength); + +Exit: + FreePool (Headers); + return Status; +} + +STATIC +EFI_STATUS +EFIAPI +FvbInitialize ( + MEM_INSTANCE *Instance + ) +{ + EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + EFI_STATUS Status; + + 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) =3D=3D + PcdGet64 (PcdFlashNvStorageFtwWorkingBase64)); + ASSERT (PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) + + PcdGet32 (PcdFlashNvStorageFtwWorkingSize) =3D=3D + 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->BlockSiz= e > 0)); + ASSERT ((PcdGet32 (PcdFlashNvStorageFtwSpareSize) > 0) && + (PcdGet32 (PcdFlashNvStorageFtwSpareSize) / Instance->BlockSize = > 0)); + + // Ensure the Variable areas are aligned on block size boundaries + ASSERT ((PcdGet64 (PcdFlashNvStorageVariableBase64) % Instance->BlockSiz= e) =3D=3D 0); + ASSERT ((PcdGet64 (PcdFlashNvStorageFtwWorkingBase64) % Instance->BlockS= ize) =3D=3D 0); + ASSERT ((PcdGet64 (PcdFlashNvStorageFtwSpareBase64) % Instance->BlockSiz= e) =3D=3D 0); + + // Read the file from disk and copy it to memory + ReadEntireFlash (Instance); + + FwVolHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *) Instance->MemBaseAddress; + Status =3D ValidateFvHeader(FwVolHeader); + if (EFI_ERROR (Status)) { + // There is no valid header, so time to install one. + DEBUG ((DEBUG_INFO, "%a: The FVB Header is not valid.\n", __FUNCTION__= )); + + // Reset memory + SetMem64 ((VOID *)Instance->MemBaseAddress, Instance->NBlocks * Instan= ce->BlockSize, ~0UL); + DEBUG ((DEBUG_INFO, "%a: Erasing Flash.\n", __FUNCTION__)); + Status =3D 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 =3D InitializeFvAndVariableStoreHeaders (Instance); + if (EFI_ERROR (Status)) { + return Status; + } + } else { + DEBUG ((DEBUG_INFO, "%a: Found valid FVB Header.\n", __FUNCTION__)); + } + Instance->Initialized =3D TRUE; + + return Status; +} + +EFI_STATUS +EFIAPI +OpTeeRpmbFvbInit ( + IN EFI_HANDLE ImageHandle, + IN EFI_MM_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + VOID *Addr; + UINTN FvLength; + UINTN NBlocks; + + FvLength =3D PcdGet32(PcdFlashNvStorageVariableSize) + + PcdGet32(PcdFlashNvStorageFtwWorkingSize) + + PcdGet32(PcdFlashNvStorageFtwSpareSize); + + NBlocks =3D EFI_SIZE_TO_PAGES(ALIGN_VARIABLE(FvLength)); + Addr =3D AllocatePages(NBlocks); + ASSERT (Addr !=3D NULL); + if (Addr =3D=3D NULL) { [SAMI] ASSERT (Addr !=3D NULL); could be removed from the line above an ins= tead ASSERT (0); could be added here. [/SAMI] + return EFI_OUT_OF_RESOURCES; + } + + SetMem (&mInstance, sizeof (mInstance), 0); + + mInstance.FvbProtocol.GetPhysicalAddress =3D OpTeeRpmbFvbGetPhysicalAddr= ess; + mInstance.FvbProtocol.GetAttributes =3D OpTeeRpmbFvbGetAttributes; + mInstance.FvbProtocol.SetAttributes =3D OpTeeRpmbFvbSetAttributes; + mInstance.FvbProtocol.GetBlockSize =3D OpTeeRpmbFvbGetBlockSize; + mInstance.FvbProtocol.EraseBlocks =3D OpTeeRpmbFvbErase; + mInstance.FvbProtocol.Write =3D OpTeeRpmbFvbWrite; + mInstance.FvbProtocol.Read =3D OpTeeRpmbFvbRead; + + mInstance.MemBaseAddress =3D (EFI_PHYSICAL_ADDRESS) Addr; + mInstance.Signature =3D FLASH_SIGNATURE; + mInstance.Initialize =3D FvbInitialize; + mInstance.BlockSize =3D EFI_PAGE_SIZE; + mInstance.NBlocks =3D NBlocks; + + // The Pcd is user defined, so make sure we don't overflow + if (mInstance.MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageV= ariableSize)) { + return EFI_INVALID_PARAMETER; + } + + if (mInstance.MemBaseAddress > MAX_UINT64 - PcdGet32 (PcdFlashNvStorageV= ariableSize) - + PcdGet32 (PcdFlashNvStorageFtwWorkingSize)) { + return EFI_INVALID_PARAMETER; + } + + // Update the defined PCDs related to Variable Storage + PatchPcdSet64 (PcdFlashNvStorageVariableBase64, mInstance.MemBaseAddress= ); + PatchPcdSet64 (PcdFlashNvStorageFtwWorkingBase64, mInstance.MemBaseAddre= ss + + PcdGet32 (PcdFlashNvStorageVariableSize)); + PatchPcdSet64 (PcdFlashNvStorageFtwSpareBase64, mInstance.MemBaseAddress= + + PcdGet32 (PcdFlashNvStorageVariableSize) + + PcdGet32 (PcdFlashNvStorageFtwWorkingSize)); + + Status =3D gMmst->MmInstallProtocolInterface ( + &mInstance.Handle, + &gEfiSmmFirmwareVolumeBlockProtocolGuid, + EFI_NATIVE_INTERFACE, + &mInstance.FvbProtocol + ); + ASSERT_EFI_ERROR (Status); + + DEBUG ((DEBUG_INFO, "%a: Register OP-TEE RPMB Fvb\n", __FUNCTION__)); + DEBUG ((DEBUG_INFO, "%a: Using NV store FV in-memory copy at 0x%lx\n", + __FUNCTION__, PatchPcdGet64 (PcdFlashNvStorageVariableBase64))); + + return Status; +} diff --git a/Drivers/OpTeeRpmb/OpTeeRpmbFvb.h b/Drivers/OpTeeRpmb/OpTeeRpmb= Fvb.h new file mode 100644 index 000000000000..fa5848f24c83 --- /dev/null +++ b/Drivers/OpTeeRpmb/OpTeeRpmbFvb.h @@ -0,0 +1,52 @@ +/** @file + + Copyright (c) 2020, Linaro Ltd. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef OPTEE_RPMB_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 inst= ance + @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 all= ocated memory + @param[in] BlockSize Blocksize + @param[in] NBlocks Number of allocated blocks +**/ +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 --=20 2.30.0