From 0ecb4e163e16325868fbbbe8a4122968fcecab59 Mon Sep 17 00:00:00 2001 From: Marius Tache <102153746+marius-alex-tache@users.noreply.github.com> Date: Wed, 9 Aug 2023 16:31:26 +0300 Subject: [PATCH] [K32W0] SDK 2.6.12 changes (#28489) * k32w0: Re-use Thread task for BLE processing Signed-off-by: Doru Gucea * k32w0: Use generic FreeRTOS functions Avoid using messaging/allocation functions specific to K32W0-SDK and use instead generic FreeRTOS functions. This opens the path for a common BLE Manager between K32W0/K32W1. Signed-off-by: Doru Gucea * k32w0: event queues: use generic FreeRTOS functions Signed-off-by: Doru Gucea * k32w0: avoid useless advertising restarting There is no need to restart advertising after a connect event. Signed-off-by: Doru Gucea * [K32W0] Place BLE common code in a single file Only specific BLE initialization code is placed under k32w0 folder. Signed-off-by: Doru Gucea * [K32W0] Place specific initialization code in an abstract method Signed-off-by: Doru Gucea * [K32W0] Avoid useless stop of ble advertising Signed-off-by: Doru Gucea * [K32W0] Remove unused function Signed-off-by: Doru Gucea * k32w0: remove useless controller code NVIC Priority set is done inside the controller library. Signed-off-by: Doru Gucea * [K32W0] Small fixes - return codes; - comments. Signed-off-by: Doru Gucea * [K32W0] Add LP API header The LP API was not included in BleManagerImpl when building in low power mode. Signed-off-by: Marius Tache * [K32W0] Clear unsupported thread metrics Thread metrics optional fields should call ClearValue explicitly, to make sure no garbage is returned in the response message. Signed-off-by: Marius Tache * [K32W0] Disable CHIP_DEVICE_CONFIG_BLE_SET_PHY_2M_REQ for lock/contact sensor This define enables/disables the Gap_LeSetPhy request to switch to 2M. It is disabled here for interoperability reasons just to be extra cautious. Both devices may send a Link Layer control procedure in parallel resulting in a LPM Error Transaction Collision. If the peer device doesn't accept our reject command, this can result in a BLE connection timeout. Signed-off-by: Marius Tache * [K32W0] FRO 32K mode should be used with 32Mhz cpu clock Signed-off-by: Marius Tache * [K32W0] Remove OTA API dependency in factory data provider If factory data is used, then it is expected that the internal flash section is written, so the factory data provider can memcpy directly, without additional checks that were previously done in OtaUtils. Using the OTA API for reading internal flash data just seems unnatural. In the absence of another API, just memcpy directly assuming the section was written. Signed-off-by: Marius Tache * [K32W0] Rename factory data flag CONFIG_CHIP_K32W0_REAL_FACTORY_DATA renamed to CONFIG_CHIP_LOAD_REAL_FACTORY_DATA. Also replaced format string in factory data provider logs. Signed-off-by: Marius Tache * [K32W0] Rename K32W0FactoryDataProvider to FactoryDataProvider Signed-off-by: Marius Tache * [K32W0] Move FactoryDataProvider to K32W common area Update #include statements to use an absolute path. Signed-off-by: Marius Tache * [K32W0] Add FactoryDataProviderImpl FactoryDataProviderImpl has two main features: - CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER - enables application factory data provider - CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR - enables factory data OTA Enclose the corresponding functions in their respective flags. Applications should instantiate a FactoryDataProviderImpl instance, which can be default or custom. Signed-off-by: Marius Tache * [K32W0] Add support for kSoftwareUpdateCompleted boot reason A new K32WConfig key is introduced: kConfigKey_SoftwareUpdateCompleted This key is stored in OTA HandleApply, before the device is reset. Upon initialization, if the reset is caused by a system reset (ResetMCU), then if this key exists, the boot reason is kSoftwareUpdateCompleted. Signed-off-by: Marius Tache * [K32W0] POWER_GetResetCause() should be called once for each startup, and its return value should be processed bit by bit * [K32W0] the priority is watchdog reset, when software reset and watchdog reset are set at the same time in POWER_GetResetCause() * [K32W0] Remove ble connections state Other changes: * Set fast advertising flag when advertising is stopped * Add device connected state Signed-off-by: Marius Tache * [K32W0] Remove unused members Signed-off-by: Marius Tache * [K32W0] Move global variables to class members Add HandleForceDisconnect method. Signed-off-by: Marius Tache * [K32W0] Event queue should be emptied in DoBleProcessing Signed-off-by: Marius Tache * [K32W0] Cancel BLE advertising timer upon connection close event Signed-off-by: Marius Tache * [K32W0] Schedule stop advertising from Matter task Stop advertising was wrongly scheduled from the timer service daemon task, which has the highest priority. This caused BLE controller task to be preempted when doing the switch from fast to slow advertising mode, which caused some events to not be captured on time, resulting in a failed advertising stop. Stop advertising is now scheduled to run from Matter task. Signed-off-by: Marius Tache * [K32W0] Add instructions to overwrite board configuration files The example uses template/reference board configuration files. To overwrite the board configuration files, set `override_is_DK6=false` in the `k32w0_sdk` target from the app `BUILD.gn`: ``` k32w0_sdk("sdk") { override_is_DK6 = false ... } ``` This variable will be used by `k32w0_sdk.gni` to overwrite `chip_with_DK6` option, thus the reference board configuration files will no longer be used. Signed-off-by: Marius Tache * [K32W0] Restructure RAM storage RAM storage class was moved to k32w0 folder. RamStorageKey files were removed and implementation was moved inside RamStorage. Signed-off-by: Marius Tache * [K32W0] Add extendedSearch option Increase number of KVS keys to 200. Signed-off-by: Marius Tache * [K32W0] Remove unused ksdk_mbedtls file Not in the scope of the ticket. Signed-off-by: Marius Tache * [K32W0] Extended search should be taken into account when factory resetting If extended search was enabled for a RAM storage instance, then factory reset should remove all PDM ids used, starting with the base one. Signed-off-by: Marius Tache * [K32W0] Update SDK version in README files Signed-off-by: Marius Tache * [K32W0] Set rotating device id unique id length to max by default Signed-off-by: Marius Tache * [K32W0] Use west to get K32W0 SDK * [K32W0] Remove deprecated function pointer Signed-off-by: Marius Tache * [NXP] Bump ot-nxp to latest Signed-off-by: Marius Tache * Restyled by whitespace Restyled by clang-format Restyled by gn Restyled by prettier-markdown Restyled by prettier-yaml * [K32W0] update cPWR_UsePowerDownMode to chip_with_low_power update cPWR_UsePowerDownMode usage to a more generic chip_with_low_power in order to be able to be used by multiple platforms Signed-off-by: Marius Vilvoi * [K32W0] Remove unused flag in README files Signed-off-by: Marius Tache * [K32W0] Remove redundant header file Signed-off-by: Marius Tache * [K32W0] Update path for building K32W041 as this missing files are only under the K32W061 board * [K32W0] Update docker image version in examples job Signed-off-by: Marius Tache * Restyled by whitespace Restyled by gn Restyled by prettier-markdown * [K32W0] Update documentation for reference apps The user can specify a custom SDK by setting NXP_K32W0_SDK_ROOT. If such an env variabile is not defined, then the gn env will implicitly set it to the SDK found in the repo: third_party/nxp/k32w0_sdk/repo/core Signed-off-by: Marius Tache * Restyled by gn * Restyled by prettier-markdown * [K32W0] BLE processing should be done under the corresponding flag Signed-off-by: Marius Tache --------- Signed-off-by: Doru Gucea Signed-off-by: Marius Tache Signed-off-by: Marius Vilvoi Co-authored-by: Doru Gucea Co-authored-by: tanyue518 Co-authored-by: Gabriel Couturier Co-authored-by: Restyled.io Co-authored-by: Marius Vilvoi --- .github/workflows/examples-k32w.yaml | 2 +- .../nxp/k32w/k32w0/README.md | 63 +- .../k32w/k32w0/include/CHIPProjectConfig.h | 18 +- .../nxp/k32w/k32w0/include/FreeRTOSConfig.h | 4 +- .../nxp/k32w/k32w0/main/AppTask.cpp | 50 +- .../nxp/k32w/k32w0/main/include/AppEvent.h | 4 +- .../nxp/k32w/k32w0/main/include/AppTask.h | 8 +- .../nxp/k32w/k32w0/main/main.cpp | 10 +- .../lighting-app/nxp/k32w/k32w0/README.md | 69 +- .../k32w/k32w0/include/CHIPProjectConfig.h | 6 +- .../nxp/k32w/k32w0/main/AppTask.cpp | 24 +- .../nxp/k32w/k32w0/main/include/AppTask.h | 8 +- examples/lock-app/nxp/k32w/k32w0/README.md | 62 +- .../k32w/k32w0/include/CHIPProjectConfig.h | 18 +- .../nxp/k32w/k32w0/include/FreeRTOSConfig.h | 4 +- .../lock-app/nxp/k32w/k32w0/main/AppTask.cpp | 35 +- .../nxp/k32w/k32w0/main/include/AppEvent.h | 4 +- .../nxp/k32w/k32w0/main/include/AppTask.h | 8 +- .../lock-app/nxp/k32w/k32w0/main/main.cpp | 12 +- .../k32w/k32w0/app/support/FreeRtosHooks.c | 4 +- .../common/CustomFactoryDataProvider.cpp | 4 +- .../k32w0/common/CustomFactoryDataProvider.h | 4 +- .../platform/nxp/k32w/k32w0/common/README.md | 24 +- .../nxp/k32w/k32w0/scripts/sign-outdir.py | 5 +- .../nxp/k32w/common/BLEManagerCommon.cpp | 1418 ++++++ .../nxp/k32w/common/BLEManagerCommon.h | 238 + .../CHIPDevicePlatformRamStorageConfig.h | 9 +- .../FactoryDataProvider.cpp} | 267 +- .../FactoryDataProvider.h} | 40 +- .../nxp/k32w/common/K32W_OTA_README.md | 14 +- .../nxp/k32w/common/OTAImageProcessorImpl.cpp | 4 + .../nxp/k32w/common/RamStorageKey.cpp | 45 - src/platform/nxp/k32w/common/RamStorageKey.h | 42 - .../nxp/k32w/k32w0/BLEManagerImpl.cpp | 1614 +----- src/platform/nxp/k32w/k32w0/BLEManagerImpl.h | 235 +- src/platform/nxp/k32w/k32w0/BUILD.gn | 11 +- .../nxp/k32w/k32w0/CHIPDevicePlatformConfig.h | 10 + .../k32w/k32w0/ConfigurationManagerImpl.cpp | 95 +- .../nxp/k32w/k32w0/ConfigurationManagerImpl.h | 7 +- .../k32w/k32w0/DiagnosticDataProviderImpl.cpp | 4 +- .../k32w/k32w0/FactoryDataProviderImpl.cpp | 183 + .../nxp/k32w/k32w0/FactoryDataProviderImpl.h | 59 + src/platform/nxp/k32w/k32w0/K32W0Config.cpp | 1 + src/platform/nxp/k32w/k32w0/K32W0Config.h | 4 +- .../k32w/k32w0/KeyValueStoreManagerImpl.cpp | 20 +- .../nxp/k32w/k32w0/KeyValueStoreManagerImpl.h | 2 +- src/platform/nxp/k32w/k32w0/LowPowerHooks.cpp | 2 +- .../k32w/k32w0/OTAFactoryDataProcessor.cpp | 18 +- .../nxp/k32w/k32w0/OTAFactoryDataProcessor.h | 8 +- .../nxp/k32w/k32w0/PlatformManagerImpl.cpp | 4 +- .../nxp/k32w/{common => k32w0}/RamStorage.cpp | 53 +- .../nxp/k32w/{common => k32w0}/RamStorage.h | 27 +- .../nxp/k32w/k32w0/ThreadStackManagerImpl.cpp | 12 +- src/platform/nxp/k32w/k32w0/args.gni | 6 + .../nxp/k32w/k32w0/crypto/ksdk_mbedtls.c | 4324 ----------------- third_party/nxp/k32w0_sdk/k32w0_sdk.gni | 83 +- third_party/nxp/k32w0_sdk/repo/.gitignore | 2 + .../nxp/k32w0_sdk/repo/manifest/west.yml | 43 + third_party/openthread/ot-nxp | 2 +- 59 files changed, 2632 insertions(+), 6724 deletions(-) create mode 100644 src/platform/nxp/k32w/common/BLEManagerCommon.cpp create mode 100644 src/platform/nxp/k32w/common/BLEManagerCommon.h rename src/platform/nxp/k32w/{k32w0/K32W0FactoryDataProvider.cpp => common/FactoryDataProvider.cpp} (51%) rename src/platform/nxp/k32w/{k32w0/K32W0FactoryDataProvider.h => common/FactoryDataProvider.h} (85%) delete mode 100644 src/platform/nxp/k32w/common/RamStorageKey.cpp delete mode 100644 src/platform/nxp/k32w/common/RamStorageKey.h create mode 100644 src/platform/nxp/k32w/k32w0/FactoryDataProviderImpl.cpp create mode 100644 src/platform/nxp/k32w/k32w0/FactoryDataProviderImpl.h rename src/platform/nxp/k32w/{common => k32w0}/RamStorage.cpp (74%) rename src/platform/nxp/k32w/{common => k32w0}/RamStorage.h (68%) delete mode 100644 src/platform/nxp/k32w/k32w0/crypto/ksdk_mbedtls.c create mode 100644 third_party/nxp/k32w0_sdk/repo/.gitignore create mode 100644 third_party/nxp/k32w0_sdk/repo/manifest/west.yml diff --git a/.github/workflows/examples-k32w.yaml b/.github/workflows/examples-k32w.yaml index 19b772bd52ab6c..1c82c8bfb0dde0 100644 --- a/.github/workflows/examples-k32w.yaml +++ b/.github/workflows/examples-k32w.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-k32w:1 + image: ghcr.io/project-chip/chip-build-k32w:5 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/examples/contact-sensor-app/nxp/k32w/k32w0/README.md b/examples/contact-sensor-app/nxp/k32w/k32w0/README.md index af98333cb8b99f..9f92bc0d795142 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w0/README.md +++ b/examples/contact-sensor-app/nxp/k32w/k32w0/README.md @@ -20,7 +20,8 @@ network. - [Bluetooth LE Rendezvous](#bluetooth-le-rendezvous) - [Device UI](#device-ui) - [Building](#building) - - [Known issues buiulding](#known-issues-building) + - [Overwrite board config files](#overwrite-board-config-files) + - [Known issues building](#known-issues-building) - [Manufacturing data](#manufacturing-data) - [Flashing and debugging](#flashing-and-debugging) - [Pigweed Tokenizer](#pigweed-tokenizer) @@ -176,19 +177,43 @@ contact status. In order to build the Project CHIP example, we recommend using a Linux distribution (the demo-application was compiled on Ubuntu 20.04). -- Download - [K32W061DK6 SDK 2.6.11](https://cache.nxp.com/lgfiles/bsps/SDK_2_6_11_K32W061DK6.zip). - -- Start building the application either with Secure Element or without +- Start building the application either with Secure Element or without, SDK is + downloaded with west tool. - without Secure Element ``` - user@ubuntu:~/Desktop/git/connectedhomeip$ export NXP_K32W0_SDK_ROOT=/home/user/Desktop/SDK_2_6_11_K32W061DK6/ - user@ubuntu:~/Desktop/git/connectedhomeip$ ./third_party/nxp/k32w0_sdk/sdk_fixes/patch_k32w_sdk.sh user@ubuntu:~/Desktop/git/connectedhomeip$ source ./scripts/activate.sh + user@ubuntu:~/Desktop/git/connectedhomeip$ cd third_party/nxp/k32w0_sdk/repo + user@ubuntu:~/Desktop/git/connectedhomeip/third_party/nxp/k32w0_sdk/repo$ west init -l manifest --mf west.yml + user@ubuntu:~/Desktop/git/connectedhomeip/third_party/nxp/k32w0_sdk/repo$ west update + ``` + + In case there are local modification to the already installed git NXP SDK: + Use the below west `forall` command instead of the west init command to + reset the west workspace. Warning: all local changes will be lost after + running this command. + + ```bash + user@ubuntu:~/Desktop/git/connectedhomeip$ cd third_party/nxp/k32w0_sdk/repo + user@ubuntu:~/Desktop/git/connectedhomeip/third_party/nxp/k32w0_sdk/repo$west forall -c "git reset --hard && git clean -xdf" -a + ``` + + Build the application + + Prior to building, the user can specify a custom `SDK` path by setting + `NXP_K32W0_SDK_ROOT`: + + ``` + user@ubuntu:~/Desktop/git/connectedhomeip$ export NXP_K32W0_SDK_ROOT=$(pwd)/third_party/nxp/k32w0_sdk/repo/core + ``` + + If the environment variable `NXP_K32W0_SDK_ROOT` is not set, it will default + to the `SDK` found in `third_party/nxp/k32w0_sdk/repo/core`. + + ``` user@ubuntu:~/Desktop/git/connectedhomeip$ cd examples/contact-sensor-app/nxp/k32w/k32w0 - user@ubuntu:~/Desktop/git/connectedhomeip/examples/contact-sensor-app/nxp/k32w/k32w0$ gn gen out/debug --args="k32w0_sdk_root=\"${NXP_K32W0_SDK_ROOT}\" chip_with_OM15082=1 chip_with_ot_cli=0 is_debug=false chip_crypto=\"platform\" chip_with_se05x=0 chip_pw_tokenizer_logging=true" + user@ubuntu:~/Desktop/git/connectedhomeip/examples/contact-sensor-app/nxp/k32w/k32w0$ gn gen out/debug --args="chip_with_OM15082=1 chip_with_ot_cli=0 is_debug=false chip_crypto=\"platform\" chip_with_se05x=0 chip_pw_tokenizer_logging=true" user@ubuntu:~/Desktop/git/connectedhomeip/examples/contact-sensor-app/nxp/k32w/k32w0$ ninja -C out/debug ``` @@ -202,8 +227,7 @@ Secure Element. These can be changed if building without Secure Element - K32W041AM flavor Exactly the same steps as above but set argument build_for_k32w041am=1 in - the gn command and use - [K32W041AMDK6 SDK 2.6.11](https://cache.nxp.com/lgfiles/bsps/SDK_2_6_11_K32W041AMDK6.zip). + the gn command. Also, in case the OM15082 Expansion Board is not attached to the DK6 board, the build argument (chip_with_OM15082) inside the gn build instruction should be set @@ -232,6 +256,23 @@ pycryptodome 3.9.8 The resulting output file can be found in out/debug/chip-k32w0x-contact-example. +### Overwrite board config files + +The example uses template/reference board configuration files. + +To overwrite the board configuration files, set `override_is_DK6=false` in the +`k32w0_sdk` target from the app `BUILD.gn`: + +``` +k32w0_sdk("sdk") { + override_is_DK6 = false + ... +} +``` + +This variable will be used by `k32w0_sdk.gni` to overwrite `chip_with_DK6` +option, thus the reference board configuration files will no longer be used. + ### Known issues building - When using Secure element and cross-compiling on Linux, log messages from @@ -274,7 +315,7 @@ CHIPProjectConfig.h. Regarding factory data provider, there are two options: -- use the default factory data provider: `K32W0FactoryDataProvider` by setting +- use the default factory data provider: `FactoryDataProviderImpl` by setting `chip_with_factory_data=1` in the gn build command. - use a custom factory data provider: please see [Guide for implementing a custom factory data provider](../../../../platform/nxp/k32w/k32w0/common/README.md). diff --git a/examples/contact-sensor-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h b/examples/contact-sensor-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h index 71960deda7e3a5..03e638f54cbf13 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h +++ b/examples/contact-sensor-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h @@ -37,11 +37,11 @@ // Use hard-coded test certificates already embedded in generic chip code => set it to 0 // Use real/development certificates => set it to 1 + file the provisioning section from // the internal flash -#ifndef CONFIG_CHIP_K32W0_REAL_FACTORY_DATA -#define CONFIG_CHIP_K32W0_REAL_FACTORY_DATA 0 +#ifndef CONFIG_CHIP_LOAD_REAL_FACTORY_DATA +#define CONFIG_CHIP_LOAD_REAL_FACTORY_DATA 0 #endif -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA // Enable usage of custom factory data provider #ifndef CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER @@ -222,6 +222,18 @@ #define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 +/** + * CHIP_DEVICE_CONFIG_BLE_SET_PHY_2M_REQ + * + * This define enables/disables the Gap_LeSetPhy request to switch to 2M. + * It is disabled here for interoperability reasons just to be extra cautious. + * Both devices may send a Link Layer control procedure in parallel resulting in a + * LPM Error Transaction Collision. + * If the peer device doesn't accept our reject command, this can result in a BLE + * connection timeout. + */ +#define CHIP_DEVICE_CONFIG_BLE_SET_PHY_2M_REQ 0 + /** * CHIP_DEVICE_CONFIG_INIT_OTA_DELAY * diff --git a/examples/contact-sensor-app/nxp/k32w/k32w0/include/FreeRTOSConfig.h b/examples/contact-sensor-app/nxp/k32w/k32w0/include/FreeRTOSConfig.h index aaf62544a61edb..ea5259b3af043c 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w0/include/FreeRTOSConfig.h +++ b/examples/contact-sensor-app/nxp/k32w/k32w0/include/FreeRTOSConfig.h @@ -41,7 +41,7 @@ #define configUSE_PREEMPTION 1 -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) #define configUSE_TICKLESS_IDLE 1 #else #define configUSE_TICKLESS_IDLE 0 @@ -51,7 +51,7 @@ #define configTICK_RATE_HZ ((TickType_t) 100) #define configMAX_PRIORITIES (8) -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(configUSE_TICKLESS_IDLE) && (configUSE_TICKLESS_IDLE == 1) #define configMINIMAL_STACK_SIZE ((unsigned short) 610) #else #define configMINIMAL_STACK_SIZE ((unsigned short) 450) diff --git a/examples/contact-sensor-app/nxp/k32w/k32w0/main/AppTask.cpp b/examples/contact-sensor-app/nxp/k32w/k32w0/main/AppTask.cpp index ecd120d9020f17..fbd0a6877e3a45 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w0/main/AppTask.cpp +++ b/examples/contact-sensor-app/nxp/k32w/k32w0/main/AppTask.cpp @@ -65,7 +65,7 @@ TimerHandle_t sFunctionTimer; // FreeRTOS app sw timer. static QueueHandle_t sAppEventQueue; -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) static LEDWidget sStatusLED; static LEDWidget sContactSensorLED; #endif @@ -85,6 +85,9 @@ using namespace chip; using namespace chip::app; AppTask AppTask::sAppTask; +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA +static AppTask::FactoryDataProvider sFactoryDataProvider; +#endif static Identify gIdentify = { chip::EndpointId{ 1 }, AppTask::OnIdentifyStart, AppTask::OnIdentifyStop, Clusters::Identify::IdentifyTypeEnum::kVisibleIndicator }; @@ -99,7 +102,7 @@ static BDXDownloader gDownloader; constexpr uint16_t requestedOtaBlockSize = 1024; #endif -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA && CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR CHIP_ERROR CustomFactoryDataRestoreMechanism(void) { K32W_LOG("This is a custom factory data restore mechanism."); @@ -134,7 +137,7 @@ static void CheckOtaEntry() if (ota_entries.ota_state == otaApplied) { K32W_LOG("OTA successfully applied"); -#if CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA && CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR // If this point is reached, it means OTA_CommitCustomEntries was successfully called. // Delete the factory data backup to stop doing a restore when the factory data provider // is initialized. This ensures that both the factory data and app were updated, otherwise @@ -177,26 +180,27 @@ CHIP_ERROR AppTask::Init() #endif // Initialize device attestation config -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA - // Initialize factory data provider - ReturnErrorOnFailure(AppTask::FactoryDataProvider::GetDefaultInstance().Init()); - AppTask::FactoryDataProvider::GetDefaultInstance().RegisterRestoreMechanism(CustomFactoryDataRestoreMechanism); - SetDeviceInstanceInfoProvider(&AppTask::FactoryDataProvider::GetDefaultInstance()); - SetDeviceAttestationCredentialsProvider(&AppTask::FactoryDataProvider::GetDefaultInstance()); - SetCommissionableDataProvider(&AppTask::FactoryDataProvider::GetDefaultInstance()); +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA +#if CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR + sFactoryDataProvider.RegisterRestoreMechanism(CustomFactoryDataRestoreMechanism); +#endif + ReturnErrorOnFailure(sFactoryDataProvider.Init()); + SetDeviceInstanceInfoProvider(&sFactoryDataProvider); + SetDeviceAttestationCredentialsProvider(&sFactoryDataProvider); + SetCommissionableDataProvider(&sFactoryDataProvider); #else #ifdef ENABLE_HSM_DEVICE_ATTESTATION SetDeviceAttestationCredentialsProvider(Examples::GetExampleSe05xDACProvider()); #else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); #endif -#endif // CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#endif // CONFIG_CHIP_LOAD_REAL_FACTORY_DATA // QR code will be used with CHIP Tool AppTask::PrintOnboardingInfo(); /* HW init leds */ -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) LED_Init(); /* start with all LEDS turnedd off */ @@ -323,7 +327,7 @@ void AppTask::AppTaskMain(void * pvParameter) { TickType_t xTicksToWait = pdMS_TO_TICKS(10); -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) xTicksToWait = portMAX_DELAY; #endif @@ -361,7 +365,7 @@ void AppTask::AppTaskMain(void * pvParameter) // // Otherwise, blink the LED ON for a very short time. -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) if (sAppTask.mFunction != Function::kFactoryReset && sAppTask.mFunction != Function::kIdentify) { if (sIsThreadProvisioned) @@ -513,7 +517,7 @@ void AppTask::ResetActionEventHandler(void * aGenericEvent) sAppTask.CancelTimer(); sAppTask.mFunction = Function::kNoneSelected; -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) /* restore initial state for the LED indicating contact state */ if (!ContactSensorMgr().IsContactClosed()) { @@ -541,7 +545,7 @@ void AppTask::ResetActionEventHandler(void * aGenericEvent) sAppTask.mFunction = Function::kFactoryReset; /* LEDs will start blinking to signal that a Factory Reset was scheduled */ -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) sStatusLED.Set(false); sContactSensorLED.Set(false); @@ -639,7 +643,7 @@ void AppTask::BleStartAdvertising(intptr_t arg) if (ConnectivityMgr().IsBLEAdvertisingEnabled()) { ConnectivityMgr().SetBLEAdvertisingEnabled(false); -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) sStatusLED.Set(false); #endif K32W_LOG("Stopped BLE Advertising!"); @@ -650,7 +654,7 @@ void AppTask::BleStartAdvertising(intptr_t arg) if (chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() == CHIP_NO_ERROR) { -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) sStatusLED.Set(true); #endif K32W_LOG("Started BLE Advertising!"); @@ -750,14 +754,14 @@ void AppTask::OnStateChanged(ContactSensorManager::State aState) if (ContactSensorManager::State::kContactClosed == aState) { K32W_LOG("Contact state changed to closed.") -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) sContactSensorLED.Set(true); #endif } else if (ContactSensorManager::State::kContactOpened == aState) { K32W_LOG("Contact state changed to opened.") -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) sContactSensorLED.Set(false); #endif } @@ -781,7 +785,7 @@ void AppTask::OnIdentifyStart(Identify * identify) } K32W_LOG("Identify process has started. Status LED should blink every 0.5 seconds."); sAppTask.mFunction = Function::kIdentify; -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) sStatusLED.Set(false); sStatusLED.Blink(500); #endif @@ -831,7 +835,7 @@ void AppTask::PostEvent(const AppEvent * aEvent) void AppTask::DispatchEvent(AppEvent * aEvent) { -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) /* specific processing for events sent from App_PostCallbackMessage (see main.cpp) */ if (aEvent->Type == AppEvent::kEventType_Lp) { @@ -879,7 +883,7 @@ void AppTask::UpdateDeviceStateInternal(intptr_t arg) /* get onoff attribute value */ (void) app::Clusters::BooleanState::Attributes::StateValue::Get(1, &stateValueAttrValue); -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) /* set the device state */ sContactSensorLED.Set(stateValueAttrValue); #endif diff --git a/examples/contact-sensor-app/nxp/k32w/k32w0/main/include/AppEvent.h b/examples/contact-sensor-app/nxp/k32w/k32w0/main/include/AppEvent.h index 3d7f4367ccaeb8..b8ae7e72540ef8 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w0/main/include/AppEvent.h +++ b/examples/contact-sensor-app/nxp/k32w/k32w0/main/include/AppEvent.h @@ -29,7 +29,7 @@ struct AppEvent kTimer, kContact, kInstall, -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) kEventType_Lp, #endif kOTAResume, @@ -56,7 +56,7 @@ struct AppEvent EventHandler Handler; -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) void * param; #endif }; diff --git a/examples/contact-sensor-app/nxp/k32w/k32w0/main/include/AppTask.h b/examples/contact-sensor-app/nxp/k32w/k32w0/main/include/AppTask.h index d8845b61ae45db..58effbdba14162 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w0/main/include/AppTask.h +++ b/examples/contact-sensor-app/nxp/k32w/k32w0/main/include/AppTask.h @@ -26,8 +26,8 @@ #include "CHIPProjectConfig.h" -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA -#include "K32W0FactoryDataProvider.h" +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA +#include #if CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER #include "CustomFactoryDataProvider.h" #endif @@ -50,11 +50,11 @@ class AppTask { public: -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA #if CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER using FactoryDataProvider = chip::DeviceLayer::CustomFactoryDataProvider; #else - using FactoryDataProvider = chip::DeviceLayer::K32W0FactoryDataProvider; + using FactoryDataProvider = chip::DeviceLayer::FactoryDataProviderImpl; #endif #endif diff --git a/examples/contact-sensor-app/nxp/k32w/k32w0/main/main.cpp b/examples/contact-sensor-app/nxp/k32w/k32w0/main/main.cpp index b00f65d0d5578d..56288842a3f5de 100644 --- a/examples/contact-sensor-app/nxp/k32w/k32w0/main/main.cpp +++ b/examples/contact-sensor-app/nxp/k32w/k32w0/main/main.cpp @@ -35,7 +35,7 @@ #include #endif -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) #include "fsl_gpio.h" #include "fsl_iocon.h" #include "gpio_pins.h" @@ -86,7 +86,7 @@ void APP_SetMaxTxPower() #endif /* low power requirements */ -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) extern "C" void setThreadInitialized(bool isInitialized); extern "C" bool isThreadInitialized(); #endif @@ -160,7 +160,7 @@ extern "C" void main_task(void const * argument) goto exit; } -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) setThreadInitialized(TRUE); #endif @@ -206,7 +206,7 @@ extern "C" void main_task(void const * argument) extern "C" void otSysEventSignalPending(void) { -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) /* make sure that 15.4 radio is initialized before waking up the Thread task */ if (isThreadInitialized()) #endif @@ -216,7 +216,7 @@ extern "C" void otSysEventSignalPending(void) } } -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) extern "C" void vOptimizeConsumption(void) { /* BUTTON2 change contact, BUTTON4 start adv/factoryreset */ diff --git a/examples/lighting-app/nxp/k32w/k32w0/README.md b/examples/lighting-app/nxp/k32w/k32w0/README.md index 674960ee0d560c..829d4bd1e70223 100644 --- a/examples/lighting-app/nxp/k32w/k32w0/README.md +++ b/examples/lighting-app/nxp/k32w/k32w0/README.md @@ -22,13 +22,14 @@ network. - [Bluetooth LE Rendezvous](#bluetooth-le-rendezvous) - [Device UI](#device-ui) - [Building](#building) - - [Known issues](#known-issues-building) + - [Overwrite board config files](#overwrite-board-config-files) + - [Known issues building](#known-issues-building) - [Manufacturing data](#manufacturing-data) - [Flashing and debugging](#flashing-and-debugging) - [Pigweed Tokenizer](#pigweed-tokenizer) - [Detokenizer script](#detokenizer-script) - [Notes](#notes) - - [Known issues](#known-issues-tokenizer) + - [Known issues tokenizer](#known-issues-tokenizer) - [NXP Ultrafast P256 ECC Library](#nxp-ultrafast-p256-ecc-library) - [Building steps](#building-steps) - [Tinycrypt ECC library](#tinycrypt-ecc-library) @@ -38,7 +39,7 @@ network. - [Writing the PSECT](#writing-the-psect) - [Writing the application](#writing-the-application) - [OTA Testing](#ota-testing) - - [Known issues](#known-issues-ota) + - [Known issues OTA](#known-issues-ota) ## Introduction @@ -191,23 +192,51 @@ effects: In order to build the Project CHIP example, we recommend using a Linux distribution (the demo-application was compiled on Ubuntu 20.04). -- Download - [K32W061DK6 SDK 2.6.11](https://cache.nxp.com/lgfiles/bsps/SDK_2_6_11_K32W061DK6.zip). - -- Start building the application either with Secure Element or without +- Start building the application either with Secure Element or without, SDK is + downloaded with west tool. - without Secure Element ``` -user@ubuntu:~/Desktop/git/connectedhomeip$ export NXP_K32W0_SDK_ROOT=/home/user/Desktop/SDK_2_6_11_K32W061DK6/ user@ubuntu:~/Desktop/git/connectedhomeip$ source ./scripts/activate.sh +user@ubuntu:~/Desktop/git/connectedhomeip$ cd third_party/nxp/k32w0_sdk/repo +user@ubuntu:~/Desktop/git/connectedhomeip/third_party/nxp/k32w0_sdk/repo$ west init -l manifest --mf west.yml +user@ubuntu:~/Desktop/git/connectedhomeip/third_party/nxp/k32w0_sdk/repo$ west update +``` + +In case there are local modification to the already installed git NXP SDK: Use +the below west `forall` command instead of the west init command to reset the +west workspace. Warning: all local changes will be lost after running this +command. + +```bash +user@ubuntu:~/Desktop/git/connectedhomeip$ cd third_party/nxp/k32w0_sdk/repo +user@ubuntu:~/Desktop/git/connectedhomeip/third_party/nxp/k32w0_sdk/repo$west forall -c "git reset --hard && git clean -xdf" -a +``` + +Build the application + +Prior to building, the user can specify a custom `SDK` path by setting +`NXP_K32W0_SDK_ROOT`: + +``` +user@ubuntu:~/Desktop/git/connectedhomeip$ export NXP_K32W0_SDK_ROOT=$(pwd)/third_party/nxp/k32w0_sdk/repo/core +``` + +If the environment variable `NXP_K32W0_SDK_ROOT` is not set, it will default to +the `SDK` found in `third_party/nxp/k32w0_sdk/repo/core`. + +``` user@ubuntu:~/Desktop/git/connectedhomeip$ cd examples/lighting-app/nxp/k32w/k32w0 -user@ubuntu:~/Desktop/git/connectedhomeip/examples/lighting-app/nxp/k32w/k32w0$ gn gen out/debug --args="k32w0_sdk_root=\"${NXP_K32W0_SDK_ROOT}\" chip_with_OM15082=1 chip_with_ot_cli=0 is_debug=false chip_crypto=\"platform\" chip_with_se05x=0 chip_pw_tokenizer_logging=true" +user@ubuntu:~/Desktop/git/connectedhomeip/examples/lighting-app/nxp/k32w/k32w0$ gn gen out/debug --args="chip_with_OM15082=1 chip_with_ot_cli=0 is_debug=false chip_crypto=\"platform\" chip_with_se05x=0 chip_pw_tokenizer_logging=true" user@ubuntu:~/Desktop/git/connectedhomeip/examples/lighting-app/nxp/k32w/k32w0$ ninja -C out/debug ``` - with Secure element + +``` Exactly the same steps as above but set chip_with_se05x=1 in the gn command and add argument chip_enable_ota_requestor=false +``` Note that option chip_enable_ota_requestor=false are required for building with Secure Element. These can be changed if building without Secure Element @@ -215,8 +244,7 @@ Secure Element. These can be changed if building without Secure Element - K32W041AM flavor Exactly the same steps as above but set argument build_for_k32w041am=1 in - the gn command and use - [K32W041AMDK6 SDK 2.6.11](https://cache.nxp.com/lgfiles/bsps/SDK_2_6_11_K32W041AMDK6.zip). + the gn command. Also, in case the OM15082 Expansion Board is not attached to the DK6 board, the build argument (chip_with_OM15082) inside the gn build instruction should be set @@ -245,6 +273,23 @@ pycryptodome 3.9.8 The resulting output file can be found in out/debug/chip-k32w0x-light-example. +### Overwrite board config files + +The example uses template/reference board configuration files. + +To overwrite the board configuration files, set `override_is_DK6=false` in the +`k32w0_sdk` target from the app `BUILD.gn`: + +``` +k32w0_sdk("sdk") { + override_is_DK6 = false + ... +} +``` + +This variable will be used by `k32w0_sdk.gni` to overwrite `chip_with_DK6` +option, thus the reference board configuration files will no longer be used. + ## Known issues building - When using Secure element and cross-compiling on Linux, log messages from @@ -287,7 +332,7 @@ CHIPProjectConfig.h. Regarding factory data provider, there are two options: -- use the default factory data provider: `K32W0FactoryDataProvider` by setting +- use the default factory data provider: `FactoryDataProviderImpl` by setting `chip_with_factory_data=1` in the gn build command. - use a custom factory data provider: please see [Guide for implementing a custom factory data provider](../../../../platform/nxp/k32w/k32w0/common/README.md). diff --git a/examples/lighting-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h b/examples/lighting-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h index c994886a68215a..f56764b2cb731b 100644 --- a/examples/lighting-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h +++ b/examples/lighting-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h @@ -37,11 +37,11 @@ // Use hard-coded test certificates already embedded in generic chip code => set it to 0 // Use real/development certificates => set it to 1 + file the provisioning section from // the internal flash -#ifndef CONFIG_CHIP_K32W0_REAL_FACTORY_DATA -#define CONFIG_CHIP_K32W0_REAL_FACTORY_DATA 0 +#ifndef CONFIG_CHIP_LOAD_REAL_FACTORY_DATA +#define CONFIG_CHIP_LOAD_REAL_FACTORY_DATA 0 #endif -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA // Enable usage of custom factory data provider #ifndef CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER diff --git a/examples/lighting-app/nxp/k32w/k32w0/main/AppTask.cpp b/examples/lighting-app/nxp/k32w/k32w0/main/AppTask.cpp index d2bdbe55c0d2cc..5f67ac9f58b91c 100644 --- a/examples/lighting-app/nxp/k32w/k32w0/main/AppTask.cpp +++ b/examples/lighting-app/nxp/k32w/k32w0/main/AppTask.cpp @@ -87,6 +87,9 @@ using namespace chip; using namespace chip::app; AppTask AppTask::sAppTask; +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA +static AppTask::FactoryDataProvider sFactoryDataProvider; +#endif // This key is for testing/certification only and should not be used in production devices. // For production devices this key must be provided from factory data. @@ -110,7 +113,7 @@ static BDXDownloader gDownloader; constexpr uint16_t requestedOtaBlockSize = 1024; #endif -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA && CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR CHIP_ERROR CustomFactoryDataRestoreMechanism(void) { K32W_LOG("This is a custom factory data restore mechanism."); @@ -145,7 +148,7 @@ static void CheckOtaEntry() if (ota_entries.ota_state == otaApplied) { K32W_LOG("OTA successfully applied"); -#if CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA && CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR // If this point is reached, it means OTA_CommitCustomEntries was successfully called. // Delete the factory data backup to stop doing a restore when the factory data provider // is initialized. This ensures that both the factory data and app were updated, otherwise @@ -182,20 +185,21 @@ CHIP_ERROR AppTask::Init() #endif // Initialize device attestation config -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA - // Initialize factory data provider - ReturnErrorOnFailure(AppTask::FactoryDataProvider::GetDefaultInstance().Init()); - AppTask::FactoryDataProvider::GetDefaultInstance().RegisterRestoreMechanism(CustomFactoryDataRestoreMechanism); - SetDeviceInstanceInfoProvider(&AppTask::FactoryDataProvider::GetDefaultInstance()); - SetDeviceAttestationCredentialsProvider(&AppTask::FactoryDataProvider::GetDefaultInstance()); - SetCommissionableDataProvider(&AppTask::FactoryDataProvider::GetDefaultInstance()); +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA +#if CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR + sFactoryDataProvider.RegisterRestoreMechanism(CustomFactoryDataRestoreMechanism); +#endif + ReturnErrorOnFailure(sFactoryDataProvider.Init()); + SetDeviceInstanceInfoProvider(&sFactoryDataProvider); + SetDeviceAttestationCredentialsProvider(&sFactoryDataProvider); + SetCommissionableDataProvider(&sFactoryDataProvider); #else #ifdef ENABLE_HSM_DEVICE_ATTESTATION SetDeviceAttestationCredentialsProvider(Examples::GetExampleSe05xDACProvider()); #else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); #endif -#endif // CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#endif // CONFIG_CHIP_LOAD_REAL_FACTORY_DATA // QR code will be used with CHIP Tool AppTask::PrintOnboardingInfo(); diff --git a/examples/lighting-app/nxp/k32w/k32w0/main/include/AppTask.h b/examples/lighting-app/nxp/k32w/k32w0/main/include/AppTask.h index e91e3c5a303167..83dfd33da2abd9 100644 --- a/examples/lighting-app/nxp/k32w/k32w0/main/include/AppTask.h +++ b/examples/lighting-app/nxp/k32w/k32w0/main/include/AppTask.h @@ -26,8 +26,8 @@ #include "CHIPProjectConfig.h" -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA -#include "K32W0FactoryDataProvider.h" +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA +#include #if CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER #include "CustomFactoryDataProvider.h" #endif @@ -50,11 +50,11 @@ class AppTask { public: -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA #if CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER using FactoryDataProvider = chip::DeviceLayer::CustomFactoryDataProvider; #else - using FactoryDataProvider = chip::DeviceLayer::K32W0FactoryDataProvider; + using FactoryDataProvider = chip::DeviceLayer::FactoryDataProviderImpl; #endif #endif diff --git a/examples/lock-app/nxp/k32w/k32w0/README.md b/examples/lock-app/nxp/k32w/k32w0/README.md index 26ccf8fe663a11..b5fec55268371c 100644 --- a/examples/lock-app/nxp/k32w/k32w0/README.md +++ b/examples/lock-app/nxp/k32w/k32w0/README.md @@ -22,7 +22,8 @@ network. - [Bluetooth LE Rendezvous](#bluetooth-le-rendezvous) - [Device UI](#device-ui) - [Building](#building) - - [Known issues](#known-issues-building) + - [Overwrite board config files](#overwrite-board-config-files) + - [Known issues building](#known-issues-building) - [Manufacturing data](#manufacturing-data) - [Flashing and debugging](#flashing-and-debugging) - [Pigweed Tokenizer](#pigweed-tokenizer) @@ -35,7 +36,7 @@ network. - [Building steps](#building-steps-1) - [Low power](#low-power) - - [Known issues](#known-issues-low-power) + - [Known issues low power](#known-issues-low-power) @@ -172,19 +173,43 @@ will be initiated. In order to build the Project CHIP example, we recommend using a Linux distribution (the demo-application was compiled on Ubuntu 20.04). -- Download - [K32W061DK6 SDK 2.6.11](https://cache.nxp.com/lgfiles/bsps/SDK_2_6_11_K32W061DK6.zip). - -- Start building the application either with Secure Element or without +- Start building the application either with Secure Element or without, SDK is + downloaded with west tool. - without Secure Element ``` -user@ubuntu:~/Desktop/git/connectedhomeip$ export NXP_K32W0_SDK_ROOT=/home/user/Desktop/SDK_2_6_11_K32W061DK6/ -user@ubuntu:~/Desktop/git/connectedhomeip$ ./third_party/nxp/k32w0_sdk/sdk_fixes/patch_k32w_sdk.sh user@ubuntu:~/Desktop/git/connectedhomeip$ source ./scripts/activate.sh +user@ubuntu:~/Desktop/git/connectedhomeip$ cd third_party/nxp/k32w0_sdk/repo +user@ubuntu:~/Desktop/git/connectedhomeip/third_party/nxp/k32w0_sdk/repo$ west init -l manifest --mf west.yml +user@ubuntu:~/Desktop/git/connectedhomeip/third_party/nxp/k32w0_sdk/repo$ west update +``` + +In case there are local modification to the already installed git NXP SDK: Use +the below west `forall` command instead of the west init command to reset the +west workspace. Warning: all local changes will be lost after running this +command. + +```bash +user@ubuntu:~/Desktop/git/connectedhomeip$ cd third_party/nxp/k32w0_sdk/repo +user@ubuntu:~/Desktop/git/connectedhomeip/third_party/nxp/k32w0_sdk/repo$west forall -c "git reset --hard && git clean -xdf" -a +``` + +Build the application + +Prior to building, the user can specify a custom `SDK` path by setting +`NXP_K32W0_SDK_ROOT`: + +``` +user@ubuntu:~/Desktop/git/connectedhomeip$ export NXP_K32W0_SDK_ROOT=$(pwd)/third_party/nxp/k32w0_sdk/repo/core +``` + +If the environment variable `NXP_K32W0_SDK_ROOT` is not set, it will default to +the `SDK` found in `third_party/nxp/k32w0_sdk/repo/core`. + +``` user@ubuntu:~/Desktop/git/connectedhomeip$ cd examples/lock-app/nxp/k32w/k32w0 -user@ubuntu:~/Desktop/git/connectedhomeip/examples/lock-app/nxp/k32w/k32w0$ gn gen out/debug --args="k32w0_sdk_root=\"${NXP_K32W0_SDK_ROOT}\" chip_with_OM15082=1 chip_with_ot_cli=0 is_debug=false chip_crypto=\"platform\" chip_with_se05x=0 chip_pw_tokenizer_logging=true" +user@ubuntu:~/Desktop/git/connectedhomeip/examples/lock-app/nxp/k32w/k32w0$ gn gen out/debug --args="chip_with_OM15082=1 chip_with_ot_cli=0 is_debug=false chip_crypto=\"platform\" chip_with_se05x=0 chip_pw_tokenizer_logging=true" user@ubuntu:~/Desktop/git/connectedhomeip/examples/lock-app/nxp/k32w/k32w0$ ninja -C out/debug ``` @@ -218,6 +243,23 @@ pycryptodome 3.9.8 The resulting output file can be found in out/debug/chip-k32w0x-lock-example. +### Overwrite board config files + +The example uses template/reference board configuration files. + +To overwrite the board configuration files, set `override_is_DK6=false` in the +`k32w0_sdk` target from the app `BUILD.gn`: + +``` +k32w0_sdk("sdk") { + override_is_DK6 = false + ... +} +``` + +This variable will be used by `k32w0_sdk.gni` to overwrite `chip_with_DK6` +option, thus the reference board configuration files will no longer be used. + ## Known issues building - When using Secure element and cross-compiling on Linux, log messages from @@ -260,7 +302,7 @@ CHIPProjectConfig.h. Regarding factory data provider, there are two options: -- use the default factory data provider: `K32W0FactoryDataProvider` by setting +- use the default factory data provider: `FactoryDataProviderImpl` by setting `chip_with_factory_data=1` in the gn build command. - use a custom factory data provider: please see [Guide for implementing a custom factory data provider](../../../../platform/nxp/k32w/k32w0/common/README.md). diff --git a/examples/lock-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h b/examples/lock-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h index a25fa7e12f1498..0e087ffa3f3a1b 100644 --- a/examples/lock-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h +++ b/examples/lock-app/nxp/k32w/k32w0/include/CHIPProjectConfig.h @@ -37,11 +37,11 @@ // Use hard-coded test certificates already embedded in generic chip code => set it to 0 // Use real/development certificates => set it to 1 + file the provisioning section from // the internal flash -#ifndef CONFIG_CHIP_K32W0_REAL_FACTORY_DATA -#define CONFIG_CHIP_K32W0_REAL_FACTORY_DATA 0 +#ifndef CONFIG_CHIP_LOAD_REAL_FACTORY_DATA +#define CONFIG_CHIP_LOAD_REAL_FACTORY_DATA 0 #endif -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA // Enable usage of custom factory data provider #ifndef CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER @@ -200,6 +200,18 @@ #define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 +/** + * CHIP_DEVICE_CONFIG_BLE_SET_PHY_2M_REQ + * + * This define enables/disables the Gap_LeSetPhy request to switch to 2M. + * It is disabled here for interoperability reasons just to be extra cautious. + * Both devices may send a Link Layer control procedure in parallel resulting in a + * LPM Error Transaction Collision. + * If the peer device doesn't accept our reject command, this can result in a BLE + * connection timeout. + */ +#define CHIP_DEVICE_CONFIG_BLE_SET_PHY_2M_REQ 0 + /** * @def CHIP_IM_MAX_NUM_COMMAND_HANDLER * diff --git a/examples/lock-app/nxp/k32w/k32w0/include/FreeRTOSConfig.h b/examples/lock-app/nxp/k32w/k32w0/include/FreeRTOSConfig.h index 2b82b290a9b2cb..24779514ef875f 100644 --- a/examples/lock-app/nxp/k32w/k32w0/include/FreeRTOSConfig.h +++ b/examples/lock-app/nxp/k32w/k32w0/include/FreeRTOSConfig.h @@ -41,7 +41,7 @@ #define configUSE_PREEMPTION 1 -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) #define configUSE_TICKLESS_IDLE 1 #else #define configUSE_TICKLESS_IDLE 0 @@ -51,7 +51,7 @@ #define configTICK_RATE_HZ ((TickType_t) 100) #define configMAX_PRIORITIES (8) -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(configUSE_TICKLESS_IDLE) && (configUSE_TICKLESS_IDLE == 1) #define configMINIMAL_STACK_SIZE ((unsigned short) 250) #else #define configMINIMAL_STACK_SIZE ((unsigned short) 450) diff --git a/examples/lock-app/nxp/k32w/k32w0/main/AppTask.cpp b/examples/lock-app/nxp/k32w/k32w0/main/AppTask.cpp index b4e793a525d8d4..9e6afc3e77b6f1 100644 --- a/examples/lock-app/nxp/k32w/k32w0/main/AppTask.cpp +++ b/examples/lock-app/nxp/k32w/k32w0/main/AppTask.cpp @@ -55,7 +55,7 @@ TimerHandle_t sFunctionTimer; // FreeRTOS app sw timer. static QueueHandle_t sAppEventQueue; -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) static LEDWidget sStatusLED; static LEDWidget sLockLED; #endif @@ -73,6 +73,9 @@ using namespace ::chip::Credentials; using namespace ::chip::DeviceLayer; AppTask AppTask::sAppTask; +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA +static AppTask::FactoryDataProvider sFactoryDataProvider; +#endif CHIP_ERROR AppTask::StartAppTask() { @@ -96,25 +99,25 @@ CHIP_ERROR AppTask::Init() PlatformMgr().ScheduleWork(InitServer, 0); // Initialize device attestation config -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA // Initialize factory data provider - ReturnErrorOnFailure(AppTask::FactoryDataProvider::GetDefaultInstance().Init()); - SetDeviceInstanceInfoProvider(&AppTask::FactoryDataProvider::GetDefaultInstance()); - SetDeviceAttestationCredentialsProvider(&AppTask::FactoryDataProvider::GetDefaultInstance()); - SetCommissionableDataProvider(&AppTask::FactoryDataProvider::GetDefaultInstance()); + ReturnErrorOnFailure(sFactoryDataProvider.Init()); + SetDeviceInstanceInfoProvider(&sFactoryDataProvider); + SetDeviceAttestationCredentialsProvider(&sFactoryDataProvider); + SetCommissionableDataProvider(&sFactoryDataProvider); #else #ifdef ENABLE_HSM_DEVICE_ATTESTATION SetDeviceAttestationCredentialsProvider(Examples::GetExampleSe05xDACProvider()); #else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); #endif -#endif // CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#endif // CONFIG_CHIP_LOAD_REAL_FACTORY_DATA // QR code will be used with CHIP Tool AppTask::PrintOnboardingInfo(); /* HW init leds */ -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) LED_Init(); /* start with all LEDS turnedd off */ @@ -222,7 +225,7 @@ void AppTask::AppTaskMain(void * pvParameter) { TickType_t xTicksToWait = pdMS_TO_TICKS(10); -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) xTicksToWait = portMAX_DELAY; #endif @@ -260,7 +263,7 @@ void AppTask::AppTaskMain(void * pvParameter) // // Otherwise, blink the LED ON for a very short time. -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) if (sAppTask.mFunction != kFunction_FactoryReset) { if (sIsThreadProvisioned) @@ -419,7 +422,7 @@ void AppTask::ResetActionEventHandler(void * aGenericEvent) sAppTask.CancelTimer(); sAppTask.mFunction = kFunction_NoneSelected; -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) /* restore initial state for the LED indicating Lock state */ if (BoltLockMgr().IsUnlocked()) { @@ -447,7 +450,7 @@ void AppTask::ResetActionEventHandler(void * aGenericEvent) sAppTask.mFunction = kFunction_FactoryReset; /* LEDs will start blinking to signal that a Factory Reset was scheduled */ -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) sStatusLED.Set(false); sLockLED.Set(false); @@ -676,7 +679,7 @@ void AppTask::ActionInitiated(BoltLockManager::Action_t aAction, int32_t aActor) sAppTask.mFunction = kFunctionLockUnlock; -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) sLockLED.Blink(50, 50); #endif } @@ -689,14 +692,14 @@ void AppTask::ActionCompleted(BoltLockManager::Action_t aAction) if (aAction == BoltLockManager::LOCK_ACTION) { K32W_LOG("Lock Action has been completed") -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) sLockLED.Set(true); #endif } else if (aAction == BoltLockManager::UNLOCK_ACTION) { K32W_LOG("Unlock Action has been completed") -#if !cPWR_UsePowerDownMode +#if !defined(chip_with_low_power) || (chip_with_low_power == 0) sLockLED.Set(false); #endif } @@ -733,7 +736,7 @@ void AppTask::PostEvent(const AppEvent * aEvent) void AppTask::DispatchEvent(AppEvent * aEvent) { -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) /* specific processing for events sent from App_PostCallbackMessage (see main.cpp) */ if (aEvent->Type == AppEvent::kEventType_Lp) { diff --git a/examples/lock-app/nxp/k32w/k32w0/main/include/AppEvent.h b/examples/lock-app/nxp/k32w/k32w0/main/include/AppEvent.h index 051eb627991917..864628869959f6 100644 --- a/examples/lock-app/nxp/k32w/k32w0/main/include/AppEvent.h +++ b/examples/lock-app/nxp/k32w/k32w0/main/include/AppEvent.h @@ -29,7 +29,7 @@ struct AppEvent kEventType_Timer, kEventType_Lock, kEventType_Install, -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) kEventType_Lp, #endif }; @@ -56,7 +56,7 @@ struct AppEvent EventHandler Handler; -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) void * param; #endif }; diff --git a/examples/lock-app/nxp/k32w/k32w0/main/include/AppTask.h b/examples/lock-app/nxp/k32w/k32w0/main/include/AppTask.h index 2e1194ed36c721..cbaa5757374497 100644 --- a/examples/lock-app/nxp/k32w/k32w0/main/include/AppTask.h +++ b/examples/lock-app/nxp/k32w/k32w0/main/include/AppTask.h @@ -26,8 +26,8 @@ #include "CHIPProjectConfig.h" -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA -#include "K32W0FactoryDataProvider.h" +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA +#include #if CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER #include "CustomFactoryDataProvider.h" #endif @@ -41,11 +41,11 @@ class AppTask { public: -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA #if CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER using FactoryDataProvider = chip::DeviceLayer::CustomFactoryDataProvider; #else - using FactoryDataProvider = chip::DeviceLayer::K32W0FactoryDataProvider; + using FactoryDataProvider = chip::DeviceLayer::FactoryDataProviderImpl; #endif #endif diff --git a/examples/lock-app/nxp/k32w/k32w0/main/main.cpp b/examples/lock-app/nxp/k32w/k32w0/main/main.cpp index 795cd3b9fcb09b..7cb5057175b37b 100644 --- a/examples/lock-app/nxp/k32w/k32w0/main/main.cpp +++ b/examples/lock-app/nxp/k32w/k32w0/main/main.cpp @@ -35,7 +35,7 @@ #include #endif -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) #include "fsl_gpio.h" #include "fsl_iocon.h" #include "gpio_pins.h" @@ -46,7 +46,7 @@ using namespace ::chip::Inet; using namespace ::chip::DeviceLayer; using namespace ::chip::Logging; -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) #include "Keyboard.h" #include "OtaSupport.h" #include "PWR_Configuration.h" @@ -67,7 +67,7 @@ extern InitFunc __init_array_end; extern "C" void sched_enable(); /* low power requirements */ -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) extern "C" void setThreadInitialized(bool isInitialized); extern "C" bool isThreadInitialized(); #endif @@ -133,7 +133,7 @@ extern "C" void main_task(void const * argument) goto exit; } -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) setThreadInitialized(TRUE); #endif @@ -172,7 +172,7 @@ extern "C" void main_task(void const * argument) extern "C" void otSysEventSignalPending(void) { -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) /* make sure that 15.4 radio is initialized before waking up the Thread task */ if (isThreadInitialized()) #endif @@ -182,7 +182,7 @@ extern "C" void otSysEventSignalPending(void) } } -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) extern "C" void vOptimizeConsumption(void) { /* BUTTON2 change contact, BUTTON4 start adv/factoryreset */ diff --git a/examples/platform/nxp/k32w/k32w0/app/support/FreeRtosHooks.c b/examples/platform/nxp/k32w/k32w0/app/support/FreeRtosHooks.c index 8a05dca08621e5..4d9b19781f1c92 100644 --- a/examples/platform/nxp/k32w/k32w0/app/support/FreeRtosHooks.c +++ b/examples/platform/nxp/k32w/k32w0/app/support/FreeRtosHooks.c @@ -112,7 +112,7 @@ void freertos_mbedtls_mutex_free(void) mbedtls_threading_free_alt(); } -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) && (configUSE_TICKLESS_IDLE != 0) +#if (configUSE_TICKLESS_IDLE != 0) /* * Setup the systick timer to generate the tick interrupts at the required @@ -239,7 +239,7 @@ void vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime) OSA_InterruptEnable(); } -#endif /* (cPWR_UsePowerDownMode) && (configUSE_TICKLESS_IDLE != 0) */ +#endif /* (configUSE_TICKLESS_IDLE != 0) */ static void BOARD_ActionOnIdle(void) { diff --git a/examples/platform/nxp/k32w/k32w0/common/CustomFactoryDataProvider.cpp b/examples/platform/nxp/k32w/k32w0/common/CustomFactoryDataProvider.cpp index 249eddf975713f..18e809509fc803 100644 --- a/examples/platform/nxp/k32w/k32w0/common/CustomFactoryDataProvider.cpp +++ b/examples/platform/nxp/k32w/k32w0/common/CustomFactoryDataProvider.cpp @@ -32,7 +32,7 @@ CustomFactoryDataProvider & CustomFactoryDataProvider::GetDefaultInstance() CHIP_ERROR CustomFactoryDataProvider::SetCustomIds() { - static_assert(CustomFactoryIds::kCustomMaxId == K32W0FactoryDataProvider::kNumberOfIds, + static_assert(CustomFactoryIds::kCustomMaxId == FactoryDataProvider::kNumberOfIds, "kNumberOfIds is computed based on CHIP_DEVICE_CONFIG_CUSTOM_PROVIDER_NUMBER_IDS."); maxLengths[CustomFactoryIds::kCustomId1] = kMaxLengthCustomId1; maxLengths[CustomFactoryIds::kCustomId2] = kMaxLengthCustomId2; @@ -47,7 +47,7 @@ CHIP_ERROR CustomFactoryDataProvider::ParseFunctionExample() MutableByteSpan buffer(data_buf); memset(buffer.data(), 0, buffer.size()); uint16_t userDataSize = 0; - // A user can use K32W0FactoryDataProvider::SearchForId to read an id from internal + // A user can use FactoryDataProvider::SearchForId to read an id from internal // flash factory data section. ReturnErrorOnFailure(SearchForId(CustomFactoryIds::kCustomId1, buffer.data(), buffer.size(), userDataSize)); diff --git a/examples/platform/nxp/k32w/k32w0/common/CustomFactoryDataProvider.h b/examples/platform/nxp/k32w/k32w0/common/CustomFactoryDataProvider.h index 5a8fc5e0507fc0..9edd603b4677c8 100644 --- a/examples/platform/nxp/k32w/k32w0/common/CustomFactoryDataProvider.h +++ b/examples/platform/nxp/k32w/k32w0/common/CustomFactoryDataProvider.h @@ -16,7 +16,7 @@ */ #pragma once -#include "K32W0FactoryDataProvider.h" +#include namespace chip { namespace DeviceLayer { @@ -27,7 +27,7 @@ namespace DeviceLayer { * provider based on this example. */ -class CustomFactoryDataProvider : public K32W0FactoryDataProvider +class CustomFactoryDataProvider : public FactoryDataProviderImpl { public: /* Custom IDs should start from FactoryDataId::kMaxId, which is diff --git a/examples/platform/nxp/k32w/k32w0/common/README.md b/examples/platform/nxp/k32w/k32w0/common/README.md index 442529562babd2..459f62f049e337 100644 --- a/examples/platform/nxp/k32w/k32w0/common/README.md +++ b/examples/platform/nxp/k32w/k32w0/common/README.md @@ -4,20 +4,18 @@ orphan: true ## Usage of custom Factory Data Provider -`K32W0FactoryDataProvider` is the default factory data provider. It implements -three interfaces from common Matter stack: +`FactoryDataProviderImpl` is the default factory data provider. It is an +extension of `FactoryDataProvider` K32W common class, which implements the +following interfaces: - CommissionableDataProvider - DeviceAttestationCredentialsProvider - DeviceInstanceInfoProvider -A user can inherit `K32W0FactoryDataProvider` to provide additional -functionality (such as parsing custom factory data fields) that is customer -specific. Additionally, each method from the above three interfaces could be -overwritten in the custom provider, but the current platform provider -implementation should be enough for most use cases. +A user can inherit `FactoryDataProviderImpl` to provide additional functionality +(such as parsing custom factory data fields) that is customer specific. -What **MUST** be done to enable usage of a custom factory provider: +What **shall** be done to enable usage of a custom factory provider: - Set `use_custom_factory_provider=1`. This option is only available when factory data is used (`chip_with_factory_data=1`). An assert will be raised @@ -43,7 +41,7 @@ What **MUST** be done to enable usage of a custom factory provider: Note that new flags were introduced: - `CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER`: select between using - `K32W0FactoryDataProvider` or `CustomFactoryDataProvider` when + `FactoryDataProviderImpl` or `CustomFactoryDataProvider` when registering the provider. - `CHIP_DEVICE_CONFIG_CUSTOM_PROVIDER_NUMBER_IDS`: set the number of custom IDs (which are different than the default IDs). If this macro is @@ -51,12 +49,12 @@ What **MUST** be done to enable usage of a custom factory provider: - The default IDs are validated directly in `SearchForId`, but custom IDs should set their maximum lengths through `SetCustomIds` method. -- `K32W0FactoryDataProvider::kNumberOfIds` is computed at compile time and - should represent the number of IDs (custom + default). Custom IDs should - start from `FactoryDataId::kMaxId`, which is the next valid ID. IDs +- `FactoryDataProvider::kNumberOfIds` is computed at compile time and should + represent the number of IDs (custom + default). Custom IDs should start from + `FactoryDataId::kMaxId`, which is the next valid ID. IDs `[1, FactoryDataId::kMaxId - 1]` are reserved for default factory data IDs. Please refer to `CustomFactoryDataProvider` for a minimal example of a custom factory data provider and note that its implementation is just an example of how to integrate a custom provider into the application, while still using the -default implementation provided by `K32W0FactoryDataProvider`. +default implementation provided by `FactoryDataProviderImpl`. diff --git a/examples/platform/nxp/k32w/k32w0/scripts/sign-outdir.py b/examples/platform/nxp/k32w/k32w0/scripts/sign-outdir.py index 0c4a0b34a9dc17..577cc2424fd5b9 100644 --- a/examples/platform/nxp/k32w/k32w0/scripts/sign-outdir.py +++ b/examples/platform/nxp/k32w/k32w0/scripts/sign-outdir.py @@ -1,7 +1,10 @@ import os import subprocess -sign_images_path = os.environ["NXP_K32W0_SDK_ROOT"] + "/tools/imagetool/sign_images.sh" +if os.environ["NXP_K32W0_SDK_ROOT"] != "": + sign_images_path = os.environ["NXP_K32W0_SDK_ROOT"] + "/tools/imagetool/sign_images.sh" +else: + sign_images_path = os.getcwd() + "/../../../../../../third_party/nxp/k32w0_sdk/repo/core/tools/imagetool/sign_images.sh" # Give execute permission if needed if os.access(sign_images_path, os.X_OK) is False: diff --git a/src/platform/nxp/k32w/common/BLEManagerCommon.cpp b/src/platform/nxp/k32w/common/BLEManagerCommon.cpp new file mode 100644 index 00000000000000..05b878bfd3d202 --- /dev/null +++ b/src/platform/nxp/k32w/common/BLEManagerCommon.cpp @@ -0,0 +1,1418 @@ +/* + * + * Copyright (c) 2020-2021 Project CHIP Authors + * Copyright (c) 2020 Nest Labs, Inc. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Provides an implementation of the BLEManager singleton object + * for the K32W platforms. + */ + +/* this file behaves like a config.h, comes first */ +#include + +#include + +#include + +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + +#include + +#include "board.h" +#include "gatt_db_app_interface.h" +#include "gatt_db_handles.h" +#include "stdio.h" +#include "timers.h" + +#if defined(CPU_JN518X) && defined(chip_with_low_power) && (chip_with_low_power == 1) +#include "PWR_Configuration.h" +#endif + +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING +#include +#include +#endif + +/******************************************************************************* + * Local data types + *******************************************************************************/ +extern "C" bool_t Ble_ConfigureHostStackConfig(void); + +#if defined(chip_with_low_power) && (chip_with_low_power == 1) +extern "C" void PWR_DisallowDeviceToSleep(void); +extern "C" void PWR_AllowDeviceToSleep(void); +#endif + +using namespace ::chip; +using namespace ::chip::Ble; + +namespace chip { +namespace DeviceLayer { +namespace Internal { + +namespace { +/******************************************************************************* + * Macros & Constants definitions + *******************************************************************************/ +/* Timeout of BLE commands */ +#define CHIP_BLE_KW_EVNT_TIMEOUT 1000 / portTICK_PERIOD_MS + +/** BLE advertisement state changed */ +#define CHIP_BLE_KW_EVNT_ADV_CHANGED 0x0001 +/** BLE advertisement command failed */ +#define CHIP_BLE_KW_EVNT_ADV_FAILED 0x0002 +/** BLE advertisement setup failed */ +#define CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED 0x0004 +/** BLE advertisement parameters setup complete */ +#define CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE 0x0008 +/** BLE advertisement data setup complete */ +#define CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE 0x0010 +/** BLE random address set */ +#define CHIP_BLE_KW_EVNT_RND_ADDR_SET 0x0020 +/** BLE Initialization complete */ +#define CHIP_BLE_KW_EVNT_INIT_COMPLETE 0x0040 +/** BLE Received a handle value confirmation from the client */ +#define CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED 0x0080 +/** BLE send indication failed */ +#define CHIP_BLE_KW_EVNT_INDICATION_FAILED 0x0100 +/** TX Power Level Set */ +#define CHIP_BLE_KW_EVNT_POWER_LEVEL_SET 0x0200 +/** Maximal time of connection without activity */ +#define CHIP_BLE_KW_CONN_TIMEOUT 60000 +/** Maximum number of pending BLE events */ +#define CHIP_BLE_EVENT_QUEUE_MAX_ENTRIES 10 + +#define LOOP_EV_BLE (0x08) + +/* controller task configuration */ +#define CONTROLLER_TASK_PRIORITY (6U) +#define CONTROLLER_TASK_STACK_SIZE (gControllerTaskStackSize_c / sizeof(StackType_t)) + +/* host task configuration */ +#define HOST_TASK_PRIORITY (4U) +#define HOST_TASK_STACK_SIZE (gHost_TaskStackSize_c / sizeof(StackType_t)) + +/* advertising configuration */ +#define BLEKW_ADV_MAX_NO (2) +#define BLEKW_SCAN_RSP_MAX_NO (2) +#define BLEKW_MAX_ADV_DATA_LEN (31) +#define CHIP_ADV_SHORT_UUID_LEN (2) + +/* FreeRTOS sw timer */ +TimerHandle_t sbleAdvTimeoutTimer; + +/* Queue used to synchronize asynchronous messages from the KW BLE tasks */ +QueueHandle_t sBleEventQueue; + +/* Used to manage asynchronous events from BLE Stack: e.g.: GAP setup finished */ +EventGroupHandle_t sEventGroup; + +TimerHandle_t connectionTimeout; + +const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; +const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, + 0x9D, 0x11 } }; +const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, + 0x9D, 0x12 } }; + +#if defined(chip_with_low_power) && (chip_with_low_power == 1) +static bool bleAppStopInProgress; +#endif + +BLEManagerCommon * sImplInstance; + +} // namespace + +CHIP_ERROR BLEManagerCommon::_Init() +{ + CHIP_ERROR err = CHIP_NO_ERROR; + EventBits_t eventBits; + uint16_t attChipRxHandle[1] = { (uint16_t) value_chipoble_rx }; + +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + uint16_t attChipC3Handle[1] = { (uint16_t) value_chipoble_c3 }; +#endif + + mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; + + // Check if BLE stack is initialized + VerifyOrExit(!mFlags.Has(Flags::kK32WBLEStackInitialized), err = CHIP_ERROR_INCORRECT_STATE); + + // Initialize the Chip BleLayer. + err = BleLayer::Init(this, this, &DeviceLayer::SystemLayer()); + SuccessOrExit(err); + + /* Initialization of message wait events - + * used for receiving BLE Stack events */ + sEventGroup = xEventGroupCreate(); + VerifyOrExit(sEventGroup != NULL, err = CHIP_ERROR_INCORRECT_STATE); + + /* Prepare callback input queue.*/ + sBleEventQueue = xQueueCreate(CHIP_BLE_EVENT_QUEUE_MAX_ENTRIES, sizeof(blekw_msg_t *)); + VerifyOrExit(sBleEventQueue != NULL, err = CHIP_ERROR_INCORRECT_STATE); + + /* Create the connection timeout timer. */ + connectionTimeout = + xTimerCreate("bleTimeoutTmr", pdMS_TO_TICKS(CHIP_BLE_KW_CONN_TIMEOUT), pdFALSE, (void *) 0, blekw_connection_timeout_cb); + VerifyOrExit(connectionTimeout != NULL, err = CHIP_ERROR_INCORRECT_STATE); + + /* BLE platform code initialization */ + SuccessOrExit(err = InitHostController(&blekw_generic_cb)); + + sImplInstance = GetImplInstance(); + + /* Register the GATT server callback */ + VerifyOrExit(GattServer_RegisterCallback(blekw_gatt_server_cb) == gBleSuccess_c, err = CHIP_ERROR_INCORRECT_STATE); + + /* Wait until BLE Stack is ready */ + eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_INIT_COMPLETE, pdTRUE, pdTRUE, CHIP_BLE_KW_EVNT_TIMEOUT); + VerifyOrExit(eventBits & CHIP_BLE_KW_EVNT_INIT_COMPLETE, err = CHIP_ERROR_INCORRECT_STATE); + +#if defined(CPU_JN518X) && defined(chip_with_low_power) && (chip_with_low_power == 1) + PWR_ChangeDeepSleepMode(cPWR_PowerDown_RamRet); +#endif + + GattServer_RegisterHandlesForWriteNotifications(1, attChipRxHandle); +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + VerifyOrExit(GattServer_RegisterHandlesForReadNotifications(1, attChipC3Handle) == gBleSuccess_c, + err = CHIP_ERROR_INCORRECT_STATE); +#endif + + mFlags.Set(Flags::kK32WBLEStackInitialized); + mFlags.Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? true : false); + mFlags.Set(Flags::kFastAdvertisingEnabled); + + // Create FreeRTOS sw timer for BLE timeouts and interval change. + sbleAdvTimeoutTimer = xTimerCreate("BleAdvTimer", // Just a text name, not used by the RTOS kernel + pdMS_TO_TICKS(100), // == default timer period (mS) + false, // no timer reload (==one-shot) + (void *) this, // init timer id = ble obj context + BleAdvTimeoutHandler // timer callback handler + ); + VerifyOrExit(sbleAdvTimeoutTimer != NULL, err = CHIP_ERROR_INCORRECT_STATE); + +exit: + return err; +} + +uint16_t BLEManagerCommon::_NumConnections(void) +{ + return static_cast(mDeviceConnected == true); +} + +bool BLEManagerCommon::_IsAdvertisingEnabled(void) +{ + return mFlags.Has(Flags::kAdvertisingEnabled); +} + +bool BLEManagerCommon::_IsAdvertising(void) +{ + return mFlags.Has(Flags::kAdvertising); +} + +CHIP_ERROR BLEManagerCommon::_SetAdvertisingEnabled(bool val) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); + + if (mFlags.Has(Flags::kAdvertisingEnabled) != val) + { + mFlags.Set(Flags::kAdvertisingEnabled, val); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + } + +exit: + return err; +} + +CHIP_ERROR BLEManagerCommon::_SetAdvertisingMode(BLEAdvertisingMode mode) +{ + switch (mode) + { + case BLEAdvertisingMode::kFastAdvertising: + mFlags.Set(Flags::kFastAdvertisingEnabled); + break; + case BLEAdvertisingMode::kSlowAdvertising: { + // We are in FreeRTOS timer service context, which is a default daemon task and has + // the highest priority. Stop advertising should be scheduled to run from Matter task. + mFlags.Clear(Flags::kFastAdvertisingEnabled); + PlatformMgr().ScheduleWork(StopAdvertisingPriorToSwitchingMode, 0); + break; + } + default: + return CHIP_ERROR_INVALID_ARGUMENT; + } + mFlags.Set(Flags::kRestartAdvertising); + PlatformMgr().ScheduleWork(DriveBLEState, 0); + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLEManagerCommon::_GetDeviceName(char * buf, size_t bufSize) +{ + if (strlen(mDeviceName) >= bufSize) + { + return CHIP_ERROR_BUFFER_TOO_SMALL; + } + strcpy(buf, mDeviceName); + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLEManagerCommon::_SetDeviceName(const char * deviceName) +{ + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported) + { + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; + } + if (deviceName != NULL && deviceName[0] != 0) + { + if (strlen(deviceName) >= kMaxDeviceNameLength) + { + return CHIP_ERROR_INVALID_ARGUMENT; + } + memset(mDeviceName, 0, kMaxDeviceNameLength); + strcpy(mDeviceName, deviceName); + mFlags.Set(Flags::kDeviceNameSet); + ChipLogProgress(DeviceLayer, "Setting device name to : \"%s\"", deviceName); + } + else + { + mDeviceName[0] = 0; + mFlags.Clear(Flags::kDeviceNameSet); + } + + return CHIP_NO_ERROR; +} + +void BLEManagerCommon::_OnPlatformEvent(const ChipDeviceEvent * event) +{ + switch (event->Type) + { + case DeviceEventType::kCHIPoBLESubscribe: + ChipDeviceEvent connEstEvent; + + HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; + PlatformMgr().PostEventOrDie(&connEstEvent); + break; + + case DeviceEventType::kCHIPoBLEUnsubscribe: + HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + break; + + case DeviceEventType::kCHIPoBLEWriteReceived: + HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, + PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); + break; + + case DeviceEventType::kCHIPoBLEConnectionError: + HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason); + break; + + case DeviceEventType::kCHIPoBLEIndicateConfirm: + HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); + break; + + default: + break; + } +} + +bool BLEManagerCommon::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) +{ + ChipLogProgress(DeviceLayer, "BLEManagerCommon::SubscribeCharacteristic() not supported"); + return false; +} + +bool BLEManagerCommon::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) +{ + ChipLogProgress(DeviceLayer, "BLEManagerCommon::UnsubscribeCharacteristic() not supported"); + return false; +} + +bool BLEManagerCommon::CloseConnection(BLE_CONNECTION_OBJECT conId) +{ + return blekw_stop_connection_internal(conId); +} + +uint16_t BLEManagerCommon::GetMTU(BLE_CONNECTION_OBJECT conId) const +{ + uint16_t tempMtu = 0; + (void) Gatt_GetMtu(conId, &tempMtu); + + return tempMtu; +} + +bool BLEManagerCommon::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, + PacketBufferHandle pBuf) +{ + ChipLogProgress(DeviceLayer, "BLEManagerCommon::SendWriteRequest() not supported"); + return false; +} + +bool BLEManagerCommon::SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, + PacketBufferHandle pBuf) +{ + ChipLogProgress(DeviceLayer, "BLEManagerCommon::SendReadRequest() not supported"); + return false; +} + +bool BLEManagerCommon::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, + const ChipBleUUID * svcId, const ChipBleUUID * charId) +{ + ChipLogProgress(DeviceLayer, "BLEManagerCommon::SendReadResponse() not supported"); + return false; +} + +void BLEManagerCommon::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) +{ + BLEMgrImpl().CloseConnection(conId); +} + +bool BLEManagerCommon::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, + PacketBufferHandle data) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + uint16_t cId = (UUIDsMatch(&ChipUUID_CHIPoBLEChar_TX, charId) ? value_chipoble_tx : 0); + ChipDeviceEvent event; + + if (cId != 0) + { + if (blekw_send_event(conId, cId, data->Start(), data->DataLength()) != BLE_OK) + { + err = CHIP_ERROR_SENDING_BLOCKED; + } + else + { + event.Type = DeviceEventType::kCHIPoBLEIndicateConfirm; + event.CHIPoBLEIndicateConfirm.ConId = conId; + err = PlatformMgr().PostEvent(&event); + } + + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "BLEManagerCommon::SendIndication() failed: %s", ErrorStr(err)); + return false; + } + return true; + } + return false; +} + +BLEManagerCommon::ble_err_t BLEManagerCommon::blekw_send_event(int8_t connection_handle, uint16_t handle, uint8_t * data, + uint32_t len) +{ + EventBits_t eventBits; + +#if CHIP_DEVICE_CHIP0BLE_DEBUG + ChipLogProgress(DeviceLayer, "Trying to send event."); +#endif + + if (connection_handle < 0 || handle <= 0) + { + ChipLogProgress(DeviceLayer, "BLE Event - Bad Handle"); + return BLE_E_FAIL; + } + + if (len > 0 && data == NULL) + { + ChipLogProgress(DeviceLayer, "BLE Event - Invalid Data"); + return BLE_E_FAIL; + } + + /************* Send the indication *************/ + xEventGroupClearBits(sEventGroup, CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED | CHIP_BLE_KW_EVNT_INDICATION_FAILED); + + if (GattServer_SendInstantValueIndication(connection_handle, handle, len, data) != gBleSuccess_c) + { + ChipLogProgress(DeviceLayer, "BLE Event - Can't sent indication"); + return BLE_E_FAIL; + } + + /* Wait until BLE Stack is ready */ + eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED | CHIP_BLE_KW_EVNT_INDICATION_FAILED, pdTRUE, + pdFALSE, CHIP_BLE_KW_EVNT_TIMEOUT); + + if (eventBits & CHIP_BLE_KW_EVNT_INDICATION_FAILED) + { + ChipLogProgress(DeviceLayer, "BLE Event - Sent Failed"); + return BLE_E_FAIL; + } + +#if CHIP_DEVICE_CHIP0BLE_DEBUG + ChipLogProgress(DeviceLayer, "BLE Event - Sent :-) "); +#endif + + return BLE_OK; +} +/******************************************************************************* + * Private functions + *******************************************************************************/ + +BLEManagerCommon::ble_err_t BLEManagerCommon::blekw_start_advertising(gapAdvertisingParameters_t * adv_params, + gapAdvertisingData_t * adv, gapScanResponseData_t * scnrsp) +{ + EventBits_t eventBits; + + /************* Set the advertising parameters *************/ + xEventGroupClearBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE); + + /* Set the advertising parameters */ + if (Gap_SetAdvertisingParameters(adv_params) != gBleSuccess_c) + { + vTaskDelay(1); + + /* Retry, just to make sure before giving up and sending an error. */ + if (Gap_SetAdvertisingParameters(adv_params) != gBleSuccess_c) + { + return BLE_E_SET_ADV_PARAMS; + } + } + + eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE, + pdTRUE, pdFALSE, CHIP_BLE_KW_EVNT_TIMEOUT); + + if (!(eventBits & CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE)) + { + return BLE_E_ADV_PARAMS_FAILED; + } + + /************* Set the advertising data *************/ + xEventGroupClearBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE); + + /* Set the advertising data */ + if (Gap_SetAdvertisingData(adv, scnrsp) != gBleSuccess_c) + { + return BLE_E_SET_ADV_DATA; + } + + eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE, + pdTRUE, pdFALSE, CHIP_BLE_KW_EVNT_TIMEOUT); + + if (!(eventBits & CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE)) + { + return BLE_E_ADV_SETUP_FAILED; + } + + /************* Start the advertising *************/ + xEventGroupClearBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED); + + if (gBleSuccess_c != Gap_CreateRandomDeviceAddress(NULL, NULL)) + { + return BLE_E_SET_ADV_PARAMS; + } + + eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_RND_ADDR_SET, pdTRUE, pdTRUE, CHIP_BLE_KW_EVNT_TIMEOUT); + + if (!(eventBits & CHIP_BLE_KW_EVNT_RND_ADDR_SET)) + { + return BLE_E_ADV_PARAMS_FAILED; + } + + /* Start the advertising */ + if (Gap_StartAdvertising(blekw_gap_advertising_cb, blekw_gap_connection_cb) != gBleSuccess_c) + { + return BLE_E_START_ADV; + } + +#if defined(chip_with_low_power) && (chip_with_low_power == 1) + PWR_DisallowDeviceToSleep(); +#endif + + eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED, pdTRUE, pdFALSE, + CHIP_BLE_KW_EVNT_TIMEOUT); + if (!(eventBits & CHIP_BLE_KW_EVNT_ADV_CHANGED)) + { +#if defined(chip_with_low_power) && (chip_with_low_power == 1) + PWR_AllowDeviceToSleep(); +#endif + return BLE_E_START_ADV_FAILED; + } + +#if defined(chip_with_low_power) && (chip_with_low_power == 1) + PWR_AllowDeviceToSleep(); +#endif + + return BLE_OK; +} + +BLEManagerCommon::ble_err_t BLEManagerCommon::blekw_stop_advertising(void) +{ + EventBits_t eventBits; + bleResult_t res; + + xEventGroupClearBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED); + + /* Stop the advertising data */ + res = Gap_StopAdvertising(); + if (res != gBleSuccess_c) + { + ChipLogProgress(DeviceLayer, "Failed to stop advertising %d", res); + return BLE_E_STOP; + } + + eventBits = xEventGroupWaitBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED, pdTRUE, pdFALSE, + CHIP_BLE_KW_EVNT_TIMEOUT); + + if (eventBits & CHIP_BLE_KW_EVNT_ADV_FAILED) + { + ChipLogProgress(DeviceLayer, "Stop advertising flat out failed."); + return BLE_E_ADV_FAILED; + } + else if (!(eventBits & CHIP_BLE_KW_EVNT_ADV_CHANGED)) + { + ChipLogProgress(DeviceLayer, "Stop advertising event timeout."); + return BLE_E_ADV_CHANGED; + } + + return BLE_OK; +} + +CHIP_ERROR BLEManagerCommon::ConfigureAdvertisingData(void) +{ + ble_err_t err; + CHIP_ERROR chipErr; + uint16_t discriminator; + uint16_t advInterval = 0; + gapAdvertisingData_t adv = { 0 }; + gapAdStructure_t adv_data[BLEKW_ADV_MAX_NO] = { { 0 } }; + gapAdStructure_t scan_rsp_data[BLEKW_SCAN_RSP_MAX_NO] = { { 0 } }; + uint8_t advPayload[BLEKW_MAX_ADV_DATA_LEN] = { 0 }; + gapScanResponseData_t scanRsp = { 0 }; + gapAdvertisingParameters_t adv_params = { 0 }; + uint8_t chipAdvDataFlags = (gLeGeneralDiscoverableMode_c | gBrEdrNotSupported_c); + uint8_t chipOverBleService[2]; + ChipBLEDeviceIdentificationInfo mDeviceIdInfo = { 0 }; + uint8_t mDeviceIdInfoLength = 0; + + chipErr = GetCommissionableDataProvider()->GetSetupDiscriminator(discriminator); + if (chipErr != CHIP_NO_ERROR) + { + return chipErr; + } + + if (!mFlags.Has(Flags::kDeviceNameSet)) + { + memset(mDeviceName, 0, kMaxDeviceNameLength); + snprintf(mDeviceName, kMaxDeviceNameLength, "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, discriminator); + } + + /**************** Prepare advertising data *******************************************/ + adv.cNumAdStructures = BLEKW_ADV_MAX_NO; + + chipErr = ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo); + SuccessOrExit(chipErr); + mDeviceIdInfoLength = sizeof(mDeviceIdInfo); + + if ((mDeviceIdInfoLength + CHIP_ADV_SHORT_UUID_LEN + 1) > BLEKW_MAX_ADV_DATA_LEN) + { + return CHIP_ERROR_INCORRECT_STATE; + } + + adv_data[0].length = 0x02; + adv_data[0].adType = gAdFlags_c; + adv_data[0].aData = (uint8_t *) (&chipAdvDataFlags); + + adv_data[1].length = static_cast(mDeviceIdInfoLength + CHIP_ADV_SHORT_UUID_LEN + 1); + adv_data[1].adType = gAdServiceData16bit_c; + memcpy(advPayload, ShortUUID_CHIPoBLEService, CHIP_ADV_SHORT_UUID_LEN); + memcpy(&advPayload[CHIP_ADV_SHORT_UUID_LEN], (void *) &mDeviceIdInfo, mDeviceIdInfoLength); + adv_data[1].aData = advPayload; + + adv.aAdStructures = adv_data; + +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + ReturnErrorOnFailure(EncodeAdditionalDataTlv()); +#endif + + /**************** Prepare scan response data *******************************************/ + scanRsp.cNumAdStructures = BLEKW_SCAN_RSP_MAX_NO; + + scan_rsp_data[0].length = static_cast(strlen(mDeviceName) + 1); + scan_rsp_data[0].adType = gAdCompleteLocalName_c; + scan_rsp_data[0].aData = (uint8_t *) mDeviceName; + + scan_rsp_data[1].length = sizeof(chipOverBleService) + 1; + scan_rsp_data[1].adType = gAdComplete16bitServiceList_c; + chipOverBleService[0] = ShortUUID_CHIPoBLEService[0]; + chipOverBleService[1] = ShortUUID_CHIPoBLEService[1]; + scan_rsp_data[1].aData = (uint8_t *) chipOverBleService; + + scanRsp.aAdStructures = scan_rsp_data; + + /**************** Prepare advertising parameters *************************************/ + if (mFlags.Has(Flags::kFastAdvertisingEnabled)) + { + advInterval = CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX; + } + else + { + advInterval = CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX; + } + advInterval = (uint16_t)(advInterval * 0.625F); + + adv_params.minInterval = adv_params.maxInterval = advInterval; + adv_params.advertisingType = gAdvConnectableUndirected_c; + adv_params.ownAddressType = gBleAddrTypeRandom_c; + adv_params.peerAddressType = gBleAddrTypePublic_c; + memset(adv_params.peerAddress, 0, gcBleDeviceAddressSize_c); + adv_params.channelMap = (gapAdvertisingChannelMapFlags_t)(gAdvChanMapFlag37_c | gAdvChanMapFlag38_c | gAdvChanMapFlag39_c); + adv_params.filterPolicy = gProcessAll_c; + + err = blekw_start_advertising(&adv_params, &adv, &scanRsp); + if (err == BLE_OK) + { + ChipLogProgress(DeviceLayer, "Started Advertising at %d ms", advInterval); + } + else + { + ChipLogProgress(DeviceLayer, "Advertising error 0x%x!", err); + mFlags.Clear(Flags::kAdvertising); + return CHIP_ERROR_INCORRECT_STATE; + } + +exit: + return chipErr; +} + +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING +CHIP_ERROR BLEManagerCommon::EncodeAdditionalDataTlv() +{ + CHIP_ERROR err = CHIP_NO_ERROR; + BitFlags dataFields; + AdditionalDataPayloadGeneratorParams params; + +#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) + uint8_t rotatingDeviceIdUniqueId[ConfigurationManager::kRotatingDeviceIDUniqueIDLength] = {}; + MutableByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId); + + err = DeviceLayer::GetDeviceInstanceInfoProvider()->GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan); + SuccessOrExit(err); + err = ConfigurationMgr().GetLifetimeCounter(params.rotatingDeviceIdLifetimeCounter); + SuccessOrExit(err); + params.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueIdSpan; + dataFields.Set(AdditionalDataFields::RotatingDeviceId); +#endif /* CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) */ + err = AdditionalDataPayloadGenerator().generateAdditionalDataPayload(params, sImplInstance->c3AdditionalDataBufferHandle, + dataFields); + +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "Failed to generate TLV encoded Additional Data (%s)", __func__); + } + + return err; +} + +void BLEManagerCommon::HandleC3ReadRequest(blekw_msg_t * msg) +{ + bleResult_t result; + blekw_att_read_data_t * att_rd_data = (blekw_att_read_data_t *) msg->data.data; + deviceId_t deviceId = att_rd_data->device_id; + uint16_t handle = att_rd_data->handle; + uint16_t length = sImplInstance->c3AdditionalDataBufferHandle->DataLength(); + const uint8_t * data = (const uint8_t *) sImplInstance->c3AdditionalDataBufferHandle->Start(); + + result = GattDb_WriteAttribute(handle, length, data); + if (result != gBleSuccess_c) + { + ChipLogError(DeviceLayer, "Failed to write C3 characteristic: %d", result); + } + + result = GattServer_SendAttributeReadStatus(deviceId, handle, gAttErrCodeNoError_c); + if (result != gBleSuccess_c) + { + ChipLogError(DeviceLayer, "Failed to send response to C3 read request: %d", result); + } +} +#endif /* CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING */ + +CHIP_ERROR BLEManagerCommon::StartAdvertising(void) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + mFlags.Set(Flags::kAdvertising); + mFlags.Clear(Flags::kRestartAdvertising); + + if (mFlags.Has(Flags::kFastAdvertisingEnabled)) + { + StartBleAdvTimeoutTimer(CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_TIMEOUT); + } + + err = ConfigureAdvertisingData(); + + if (err == CHIP_NO_ERROR) + /* schedule NFC emulation stop */ + { + ChipDeviceEvent advChange; + advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; + advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Started; + err = PlatformMgr().PostEvent(&advChange); + } + + return err; +} + +CHIP_ERROR BLEManagerCommon::StopAdvertising(void) +{ + CHIP_ERROR error = CHIP_NO_ERROR; + + if (mFlags.Has(Flags::kAdvertising)) + { + mFlags.Clear(Flags::kAdvertising); + mFlags.Clear(Flags::kRestartAdvertising); + + if (!mDeviceConnected) + { + ble_err_t err = blekw_stop_advertising(); + VerifyOrReturnError(err == BLE_OK, CHIP_ERROR_INCORRECT_STATE); + CancelBleAdvTimeoutTimer(); + } + +#if CONFIG_CHIP_NFC_COMMISSIONING + /* schedule NFC emulation stop */ + ChipDeviceEvent advChange; + advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; + advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Stopped; + error = PlatformMgr().PostEvent(&advChange); +#endif + } + + return error; +} + +void BLEManagerCommon::DriveBLEState(void) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + // Check if BLE stack is initialized + VerifyOrExit(mFlags.Has(Flags::kK32WBLEStackInitialized), err = CHIP_ERROR_INCORRECT_STATE); + + // Start advertising if needed... + if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled)) + { + // Start/re-start advertising if not already started, or if there is a pending change + // to the advertising configuration. + if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kRestartAdvertising)) + { + err = StartAdvertising(); + SuccessOrExit(err); + } + } + // Otherwise, stop advertising if it is enabled. + else if (mFlags.Has(Flags::kAdvertising)) + { + err = StopAdvertising(); + SuccessOrExit(err); + // Reset to fast advertising mode only if SetBLEAdvertisingEnabled(false) was called (usually from app). + mFlags.Set(Flags::kFastAdvertisingEnabled); + } + +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err)); + mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; + } +} + +void BLEManagerCommon::DriveBLEState(intptr_t arg) +{ + sImplInstance->DriveBLEState(); +} + +void BLEManagerCommon::StopAdvertisingPriorToSwitchingMode(intptr_t arg) +{ + if (CHIP_NO_ERROR != sImplInstance->StopAdvertising()) + { + ChipLogProgress(DeviceLayer, "Failed to stop advertising"); + } +} + +void BLEManagerCommon::DoBleProcessing(void) +{ + blekw_msg_t * msg = NULL; + + while ((xQueueReceive(sBleEventQueue, &msg, 0) == pdTRUE) && msg) + { + if (msg->type == BLE_KW_MSG_ERROR) + { + if (msg->data.u8 == BLE_KW_MSG_2M_UPGRADE_ERROR) + { + ChipLogProgress(DeviceLayer, + "Warning. BLE is using 1Mbps. Couldn't upgrade to 2Mbps, " + "maybe the peer is missing 2Mbps support."); + } + else + { + ChipLogProgress(DeviceLayer, "BLE Error: %d.\n", msg->data.u8); + } + } + else if (msg->type == BLE_KW_MSG_CONNECTED) + { + sImplInstance->HandleConnectEvent(msg); + } + else if (msg->type == BLE_KW_MSG_DISCONNECTED) + { + sImplInstance->HandleConnectionCloseEvent(msg); + } + else if (msg->type == BLE_KW_MSG_MTU_CHANGED) + { + blekw_start_connection_timeout(); + ChipLogProgress(DeviceLayer, "BLE MTU size has been changed to %d.", msg->data.u16); + } + else if (msg->type == BLE_KW_MSG_ATT_WRITTEN || msg->type == BLE_KW_MSG_ATT_LONG_WRITTEN || + msg->type == BLE_KW_MSG_ATT_CCCD_WRITTEN) + { + sImplInstance->HandleWriteEvent(msg); + } + else if (msg->type == BLE_KW_MSG_ATT_READ) + { +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + blekw_att_read_data_t * att_rd_data = (blekw_att_read_data_t *) msg->data.data; + if (value_chipoble_c3 == att_rd_data->handle) + sImplInstance->HandleC3ReadRequest(msg); +#endif + } + else if (msg->type == BLE_KW_MSG_FORCE_DISCONNECT) + { + sImplInstance->HandleForceDisconnect(); + } + + /* Free the message from the queue */ + free(msg); + msg = NULL; + } +} + +void BLEManagerCommon::HandleConnectEvent(blekw_msg_t * msg) +{ + uint8_t deviceId = msg->data.u8; + ChipLogProgress(DeviceLayer, "BLE is connected with device: %d.\n", deviceId); + +#if gClkUseFro32K && defined(chip_with_low_power) && (chip_with_low_power == 1) + PWR_DisallowDeviceToSleep(); +#endif + + mDeviceId = deviceId; + mDeviceConnected = true; + + blekw_start_connection_timeout(); + PlatformMgr().ScheduleWork(DriveBLEState, 0); +} + +void BLEManagerCommon::HandleConnectionCloseEvent(blekw_msg_t * msg) +{ + uint8_t deviceId = msg->data.u8; + ChipLogProgress(DeviceLayer, "BLE is disconnected with device: %d.\n", deviceId); + +#if gClkUseFro32K && defined(chip_with_low_power) && (chip_with_low_power == 1) + PWR_AllowDeviceToSleep(); +#endif + + mDeviceConnected = false; + + ChipDeviceEvent event; + event.Type = DeviceEventType::kCHIPoBLEConnectionError; + event.CHIPoBLEConnectionError.ConId = deviceId; + event.CHIPoBLEConnectionError.Reason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED; + + CancelBleAdvTimeoutTimer(); + + PlatformMgr().PostEventOrDie(&event); + mFlags.Set(Flags::kRestartAdvertising); + mFlags.Set(Flags::kFastAdvertisingEnabled); + PlatformMgr().ScheduleWork(DriveBLEState, 0); +} + +void BLEManagerCommon::HandleWriteEvent(blekw_msg_t * msg) +{ + blekw_att_written_data_t * att_wr_data = (blekw_att_written_data_t *) msg->data.data; + attErrorCode_t status = gAttErrCodeNoError_c; + +#if CHIP_DEVICE_CHIP0BLE_DEBUG + ChipLogProgress(DeviceLayer, "Attribute write request(device: %d,handle: %d).", att_wr_data->device_id, att_wr_data->handle); +#endif + + blekw_start_connection_timeout(); + + if (value_chipoble_rx == att_wr_data->handle) + { + sImplInstance->HandleRXCharWrite(msg); + } + else if (cccd_chipoble_tx == att_wr_data->handle) + { + sImplInstance->HandleTXCharCCCDWrite(msg); + } + + /* TODO: do we need to send the status also for CCCD_WRITTEN? */ + if (msg->type != BLE_KW_MSG_ATT_CCCD_WRITTEN) + { + bleResult_t res = GattServer_SendAttributeWrittenStatus(att_wr_data->device_id, att_wr_data->handle, status); + + if (res != gBleSuccess_c) + { + ChipLogProgress(DeviceLayer, "GattServer_SendAttributeWrittenStatus returned %d", res); + } + } +} + +void BLEManagerCommon::HandleTXCharCCCDWrite(blekw_msg_t * msg) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + blekw_att_written_data_t * att_wr_data = (blekw_att_written_data_t *) msg->data.data; + ChipDeviceEvent event; + + VerifyOrExit(att_wr_data->length != 0, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(att_wr_data->data != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + +#if CHIP_DEVICE_CHIP0BLE_DEBUG + ChipLogProgress(DeviceLayer, "CHIPoBLE %s received", *att_wr_data->data ? "subscribe" : "unsubscribe"); +#endif + + if (*att_wr_data->data) + { + if (!mDeviceSubscribed) + { + mDeviceSubscribed = true; + event.Type = DeviceEventType::kCHIPoBLESubscribe; + event.CHIPoBLESubscribe.ConId = att_wr_data->device_id; + err = PlatformMgr().PostEvent(&event); + } + } + else + { + mDeviceSubscribed = false; + event.Type = DeviceEventType::kCHIPoBLEUnsubscribe; + event.CHIPoBLESubscribe.ConId = att_wr_data->device_id; + err = PlatformMgr().PostEvent(&event); + } + +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "HandleTXCharCCCDWrite() failed: %s", ErrorStr(err)); + } +} + +void BLEManagerCommon::HandleRXCharWrite(blekw_msg_t * msg) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + System::PacketBufferHandle buf; + blekw_att_written_data_t * att_wr_data = (blekw_att_written_data_t *) msg->data.data; + + VerifyOrExit(att_wr_data->length != 0, err = CHIP_ERROR_INCORRECT_STATE); + VerifyOrExit(att_wr_data->data != nullptr, err = CHIP_ERROR_INCORRECT_STATE); + + // Copy the data to a PacketBuffer. + buf = System::PacketBufferHandle::NewWithData(att_wr_data->data, att_wr_data->length); + VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY); + +#if CHIP_DEVICE_CHIP0BLE_DEBUG + ChipLogDetail(DeviceLayer, + "Write request/command received for" + "CHIPoBLE RX characteristic (con %u, len %u)", + att_wr_data->device_id, buf->DataLength()); +#endif + + // Post an event to the CHIP queue to deliver the data into the CHIP stack. + { + ChipDeviceEvent event; + event.Type = DeviceEventType::kCHIPoBLEWriteReceived; + event.CHIPoBLEWriteReceived.ConId = att_wr_data->device_id; + event.CHIPoBLEWriteReceived.Data = std::move(buf).UnsafeRelease(); + err = PlatformMgr().PostEvent(&event); + } +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "HandleRXCharWrite() failed: %s", ErrorStr(err)); + } +} + +void BLEManagerCommon::HandleForceDisconnect() +{ + ChipLogProgress(DeviceLayer, "BLE connection timeout: Forcing disconnection."); + + /* Set the advertising parameters */ + if (Gap_Disconnect(mDeviceId) != gBleSuccess_c) + { + ChipLogProgress(DeviceLayer, "Gap_Disconnect() failed."); + } +} + +/******************************************************************************* + * BLE stack callbacks + *******************************************************************************/ +void BLEManagerCommon::blekw_generic_cb(gapGenericEvent_t * pGenericEvent) +{ + /* Call BLE Conn Manager */ + BleConnManager_GenericEvent(pGenericEvent); + + switch (pGenericEvent->eventType) + { + case gInternalError_c: + /* Notify the CHIP that the BLE hardware report fail */ + ChipLogProgress(DeviceLayer, "BLE Internal Error: Code 0x%04X, Source 0x%08X, HCI OpCode %d.\n", + pGenericEvent->eventData.internalError.errorCode, pGenericEvent->eventData.internalError.errorSource, + pGenericEvent->eventData.internalError.hciCommandOpcode); + if ((gHciUnsupportedRemoteFeature_c == pGenericEvent->eventData.internalError.errorCode) && + (gLeSetPhy_c == pGenericEvent->eventData.internalError.errorSource)) + { + (void) blekw_msg_add_u8(BLE_KW_MSG_ERROR, BLE_KW_MSG_2M_UPGRADE_ERROR); + } + else + { + (void) blekw_msg_add_u8(BLE_KW_MSG_ERROR, BLE_INTERNAL_ERROR); + } + break; + + case gAdvertisingSetupFailed_c: + xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED); + break; + + case gAdvertisingParametersSetupComplete_c: + xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE); + break; + + case gAdvertisingDataSetupComplete_c: + xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE); + break; + + case gRandomAddressReady_c: + Gap_SetRandomAddress(pGenericEvent->eventData.addrReady.aAddress); + break; + + case gRandomAddressSet_c: + xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_RND_ADDR_SET); + break; + +#if BLE_HIGH_TX_POWER + case gTxPowerLevelSetComplete_c: + if (gBleSuccess_c == pGenericEvent->eventData.txPowerLevelSetStatus) + { + xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_POWER_LEVEL_SET); + } + break; +#endif + + case gInitializationComplete_c: + /* Common GAP configuration */ + BleConnManager_GapCommonConfig(); + + /* Set the local synchronization event */ + xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_INIT_COMPLETE); + break; + default: + break; + } +} + +void BLEManagerCommon::blekw_gap_advertising_cb(gapAdvertisingEvent_t * pAdvertisingEvent) +{ + if (pAdvertisingEvent->eventType == gAdvertisingStateChanged_c) + { + /* Set the local synchronization event */ + xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_CHANGED); + } + else + { + /* The advertisement start failed */ + ChipLogProgress(DeviceLayer, "Advertising failed: event=%d reason=0x%04X\n", pAdvertisingEvent->eventType, + pAdvertisingEvent->eventData.failReason); + + /* Set the local synchronization event */ + xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_ADV_FAILED); + } +} + +void BLEManagerCommon::blekw_gap_connection_cb(deviceId_t deviceId, gapConnectionEvent_t * pConnectionEvent) +{ + /* Call BLE Conn Manager */ + BleConnManager_GapPeripheralEvent(deviceId, pConnectionEvent); + + if (pConnectionEvent->eventType == gConnEvtConnected_c) + { +#if CHIP_DEVICE_CONFIG_BLE_SET_PHY_2M_REQ + ChipLogProgress(DeviceLayer, "BLE K32W: Trying to set the PHY to 2M"); + + (void) Gap_LeSetPhy(FALSE, deviceId, 0, gConnPhyUpdateReqTxPhySettings_c, gConnPhyUpdateReqRxPhySettings_c, + (uint16_t) gConnPhyUpdateReqPhyOptions_c); +#endif + + /* Notify App Task that the BLE is connected now */ + (void) blekw_msg_add_u8(BLE_KW_MSG_CONNECTED, (uint8_t) deviceId); +#if defined(chip_with_low_power) && (chip_with_low_power == 1) + PWR_AllowDeviceToSleep(); +#endif + } + else if (pConnectionEvent->eventType == gConnEvtDisconnected_c) + { + blekw_stop_connection_timeout(); + + /* Notify App Task that the BLE is disconnected now */ + (void) blekw_msg_add_u8(BLE_KW_MSG_DISCONNECTED, (uint8_t) deviceId); + +#if defined(chip_with_low_power) && (chip_with_low_power == 1) + if (bleAppStopInProgress == TRUE) + { + bleAppStopInProgress = FALSE; + PWR_AllowDeviceToSleep(); + } +#endif + } + else if (pConnectionEvent->eventType == gConnEvtPairingRequest_c) + { + /* Reject request for pairing */ + Gap_RejectPairing(deviceId, gPairingNotSupported_c); + } + else if (pConnectionEvent->eventType == gConnEvtAuthenticationRejected_c) + { + ChipLogProgress(DeviceLayer, "BLE Authentication rejected (reason:%d).\n", + pConnectionEvent->eventData.authenticationRejectedEvent.rejectReason); + } +} + +void BLEManagerCommon::blekw_connection_timeout_cb(TimerHandle_t timer) +{ + (void) blekw_msg_add_u8(BLE_KW_MSG_FORCE_DISCONNECT, 0); +} + +void BLEManagerCommon::blekw_start_connection_timeout(void) +{ + xTimerReset(connectionTimeout, 0); +} + +void BLEManagerCommon::blekw_stop_connection_timeout(void) +{ + ChipLogProgress(DeviceLayer, "Stopped connectionTimeout timer."); + xTimerStop(connectionTimeout, 0); +} + +void BLEManagerCommon::blekw_gatt_server_cb(deviceId_t deviceId, gattServerEvent_t * pServerEvent) +{ + switch (pServerEvent->eventType) + { + case gEvtMtuChanged_c: { + uint16_t tempMtu = 0; + + (void) Gatt_GetMtu(deviceId, &tempMtu); + blekw_msg_add_u16(BLE_KW_MSG_MTU_CHANGED, tempMtu); + break; + } + + case gEvtAttributeWritten_c: + blekw_msg_add_att_written(BLE_KW_MSG_ATT_WRITTEN, deviceId, pServerEvent->eventData.attributeWrittenEvent.handle, + pServerEvent->eventData.attributeWrittenEvent.aValue, + pServerEvent->eventData.attributeWrittenEvent.cValueLength); + break; + + case gEvtLongCharacteristicWritten_c: + blekw_msg_add_att_written(BLE_KW_MSG_ATT_LONG_WRITTEN, deviceId, pServerEvent->eventData.longCharWrittenEvent.handle, + pServerEvent->eventData.longCharWrittenEvent.aValue, + pServerEvent->eventData.longCharWrittenEvent.cValueLength); + break; + + case gEvtAttributeRead_c: + blekw_msg_add_att_read(BLE_KW_MSG_ATT_READ, deviceId, pServerEvent->eventData.attributeReadEvent.handle); + break; + + case gEvtCharacteristicCccdWritten_c: { + uint16_t cccd_val = pServerEvent->eventData.charCccdWrittenEvent.newCccd; + + blekw_msg_add_att_written(BLE_KW_MSG_ATT_CCCD_WRITTEN, deviceId, pServerEvent->eventData.charCccdWrittenEvent.handle, + (uint8_t *) &cccd_val, 2); + break; + } + + case gEvtHandleValueConfirmation_c: + /* Set the local synchronization event */ + xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED); + break; + + case gEvtError_c: + if (pServerEvent->eventData.procedureError.procedureType == gSendIndication_c) + { + /* Set the local synchronization event */ + xEventGroupSetBits(sEventGroup, CHIP_BLE_KW_EVNT_INDICATION_FAILED); + } + else + { + ChipLogProgress(DeviceLayer, "BLE Gatt Server Error: Code 0x%04X, Source %d.\n", + pServerEvent->eventData.procedureError.error, pServerEvent->eventData.procedureError.procedureType); + + /* Notify CHIP BLE App Task that the BLE hardware report fail */ + (void) blekw_msg_add_u8(BLE_KW_MSG_ERROR, BLE_INTERNAL_GATT_ERROR); + } + break; + + default: + break; + } +} +/******************************************************************************* + * Add to message queue functions + *******************************************************************************/ +CHIP_ERROR BLEManagerCommon::blekw_msg_add_att_written(blekw_msg_type_t type, uint8_t device_id, uint16_t handle, uint8_t * data, + uint16_t length) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + blekw_msg_t * msg = NULL; + blekw_att_written_data_t * att_wr_data; + + /* Allocate a buffer with enough space to store the packet */ + msg = (blekw_msg_t *) malloc(sizeof(blekw_msg_t) + sizeof(blekw_att_written_data_t) + length); + VerifyOrExit(msg, err = CHIP_ERROR_NO_MEMORY); + + msg->type = type; + msg->length = sizeof(blekw_att_written_data_t) + length; + att_wr_data = (blekw_att_written_data_t *) msg->data.data; + att_wr_data->device_id = device_id; + att_wr_data->handle = handle; + att_wr_data->length = length; + FLib_MemCpy(att_wr_data->data, data, length); + + VerifyOrExit(xQueueSend(sBleEventQueue, &msg, 0) == pdTRUE, err = CHIP_ERROR_NO_MEMORY); + otTaskletsSignalPending(NULL); + +exit: + return err; +} + +CHIP_ERROR BLEManagerCommon::blekw_msg_add_att_read(blekw_msg_type_t type, uint8_t device_id, uint16_t handle) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + blekw_msg_t * msg = NULL; + blekw_att_read_data_t * att_rd_data; + + /* Allocate a buffer with enough space to store the packet */ + msg = (blekw_msg_t *) malloc(sizeof(blekw_msg_t) + sizeof(blekw_att_read_data_t)); + VerifyOrExit(msg, err = CHIP_ERROR_NO_MEMORY); + + msg->type = type; + msg->length = sizeof(blekw_att_read_data_t); + att_rd_data = (blekw_att_read_data_t *) msg->data.data; + att_rd_data->device_id = device_id; + att_rd_data->handle = handle; + + VerifyOrExit(xQueueSend(sBleEventQueue, &msg, 0) == pdTRUE, err = CHIP_ERROR_NO_MEMORY); + otTaskletsSignalPending(NULL); + +exit: + return err; +} + +CHIP_ERROR BLEManagerCommon::blekw_msg_add_u8(blekw_msg_type_t type, uint8_t data) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + blekw_msg_t * msg = NULL; + + /* Allocate a buffer with enough space to store the packet */ + msg = (blekw_msg_t *) malloc(sizeof(blekw_msg_t)); + VerifyOrExit(msg, err = CHIP_ERROR_NO_MEMORY); + + msg->type = type; + msg->length = 0; + msg->data.u8 = data; + + VerifyOrExit(xQueueSend(sBleEventQueue, &msg, 0) == pdTRUE, err = CHIP_ERROR_NO_MEMORY); + otTaskletsSignalPending(NULL); + +exit: + return err; +} + +CHIP_ERROR BLEManagerCommon::blekw_msg_add_u16(blekw_msg_type_t type, uint16_t data) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + blekw_msg_t * msg = NULL; + + /* Allocate a buffer with enough space to store the packet */ + msg = (blekw_msg_t *) malloc(sizeof(blekw_msg_t)); + VerifyOrExit(msg, err = CHIP_ERROR_NO_MEMORY); + + msg->type = type; + msg->length = 0; + msg->data.u16 = data; + + VerifyOrExit(xQueueSend(sBleEventQueue, &msg, 0) == pdTRUE, err = CHIP_ERROR_NO_MEMORY); + otTaskletsSignalPending(NULL); + +exit: + return err; +} + +void BLEManagerCommon::BleAdvTimeoutHandler(TimerHandle_t xTimer) +{ + if (BLEMgrImpl().mFlags.Has(Flags::kFastAdvertisingEnabled)) + { + ChipLogDetail(DeviceLayer, "Start slow advertisement"); + BLEMgr().SetAdvertisingMode(BLEAdvertisingMode::kSlowAdvertising); + } +} + +void BLEManagerCommon::CancelBleAdvTimeoutTimer(void) +{ + if (xTimerStop(sbleAdvTimeoutTimer, 0) == pdFAIL) + { + ChipLogError(DeviceLayer, "Failed to stop BledAdv timeout timer"); + } +} + +void BLEManagerCommon::StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs) +{ + if (xTimerIsTimerActive(sbleAdvTimeoutTimer)) + { + CancelBleAdvTimeoutTimer(); + } + + // timer is not active, change its period to required value (== restart). + // FreeRTOS- Block for a maximum of 100 ticks if the change period command + // cannot immediately be sent to the timer command queue. + if (xTimerChangePeriod(sbleAdvTimeoutTimer, aTimeoutInMs / portTICK_PERIOD_MS, 100) != pdPASS) + { + ChipLogError(DeviceLayer, "Failed to start BledAdv timeout timer"); + } +} + +bool BLEManagerCommon::blekw_stop_connection_internal(BLE_CONNECTION_OBJECT conId) +{ + ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (con %u)", conId); + + if (Gap_Disconnect(conId) != gBleSuccess_c) + { + ChipLogProgress(DeviceLayer, "Gap_Disconnect() failed."); + return false; + } +#if defined(chip_with_low_power) && (chip_with_low_power == 1) + else + { + bleAppStopInProgress = TRUE; + PWR_DisallowDeviceToSleep(); + } +#endif + + return true; +} + +} // namespace Internal +} // namespace DeviceLayer +} // namespace chip +#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/nxp/k32w/common/BLEManagerCommon.h b/src/platform/nxp/k32w/common/BLEManagerCommon.h new file mode 100644 index 00000000000000..d8a6561e50b380 --- /dev/null +++ b/src/platform/nxp/k32w/common/BLEManagerCommon.h @@ -0,0 +1,238 @@ +/* + * + * Copyright (c) 2020-2021 Project CHIP Authors + * Copyright (c) 2020 Nest Labs, Inc. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Provides an implementation of the BLEManager singleton object + * for the K32W platforms. + */ + +#pragma once + +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + +#include "fsl_os_abstraction.h" + +#include "ble_conn_manager.h" +#include "ble_general.h" +#include "ble_host_task_config.h" +#include "ble_host_tasks.h" +#include "gap_interface.h" +#include "gatt_db_dynamic.h" +#include "gatt_server_interface.h" + +#include "FreeRTOS.h" +#include "event_groups.h" +#include "timers.h" + +namespace chip { +namespace DeviceLayer { +namespace Internal { + +typedef void (*ble_generic_cb_fp)(gapGenericEvent_t * pGenericEvent); + +using namespace chip::Ble; + +/** + * Base class for different platform implementations (K32W0 and K32W1 for now). + */ +class BLEManagerCommon : public BLEManager, protected BleLayer, private BlePlatformDelegate, private BleApplicationDelegate +{ +protected: + // ===== Members that implement the BLEManager internal interface. + + CHIP_ERROR _Init(void); + CHIP_ERROR _Shutdown() { return CHIP_NO_ERROR; } + CHIPoBLEServiceMode _GetCHIPoBLEServiceMode(void); + CHIP_ERROR _SetCHIPoBLEServiceMode(CHIPoBLEServiceMode val); + bool _IsAdvertisingEnabled(void); + CHIP_ERROR _SetAdvertisingEnabled(bool val); + bool _IsAdvertising(void); + CHIP_ERROR _SetAdvertisingMode(BLEAdvertisingMode mode); + CHIP_ERROR _GetDeviceName(char * buf, size_t bufSize); + CHIP_ERROR _SetDeviceName(const char * deviceName); + uint16_t _NumConnections(void); + void _OnPlatformEvent(const ChipDeviceEvent * event); + + // ===== Members that implement virtual methods on BlePlatformDelegate. + + bool SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, + const Ble::ChipBleUUID * charId) override; + bool UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, + const Ble::ChipBleUUID * charId) override; + bool CloseConnection(BLE_CONNECTION_OBJECT conId) override; + uint16_t GetMTU(BLE_CONNECTION_OBJECT conId) const override; + bool SendIndication(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, + System::PacketBufferHandle pBuf) override; + bool SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, + System::PacketBufferHandle pBuf) override; + bool SendReadRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, + System::PacketBufferHandle pBuf) override; + bool SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const Ble::ChipBleUUID * svcId, + const Ble::ChipBleUUID * charId) override; + + // ===== Members that implement virtual methods on BleApplicationDelegate. + + void NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) override; + + // ===== Private members reserved for use by this class only. + + enum class Flags : uint8_t + { + kAdvertisingEnabled = 0x0001, + kFastAdvertisingEnabled = 0x0002, + kAdvertising = 0x0004, + kRestartAdvertising = 0x0008, + kK32WBLEStackInitialized = 0x0010, + kDeviceNameSet = 0x0020, + }; + BitFlags mFlags; + + enum + { + kMaxDeviceNameLength = 16, + kUnusedIndex = 0xFF, + }; + + typedef enum + { + BLE_KW_MSG_ERROR = 0x01, + BLE_KW_MSG_CONNECTED, + BLE_KW_MSG_DISCONNECTED, + BLE_KW_MSG_MTU_CHANGED, + BLE_KW_MSG_ATT_WRITTEN, + BLE_KW_MSG_ATT_LONG_WRITTEN, + BLE_KW_MSG_ATT_READ, + BLE_KW_MSG_ATT_CCCD_WRITTEN, + BLE_KW_MSG_FORCE_DISCONNECT, + } blekw_msg_type_t; + + typedef struct hk_ble_kw_msg_s + { + blekw_msg_type_t type; + uint16_t length; + union + { + uint8_t u8; + uint16_t u16; + uint32_t u32; + uint8_t data[1]; + char * str; + } data; + } blekw_msg_t; + + typedef enum ble_err_t + { + BLE_OK = 0, + BLE_INTERNAL_GATT_ERROR, + BLE_E_SET_ADV_PARAMS, + BLE_E_ADV_PARAMS_FAILED, + BLE_E_SET_ADV_DATA, + BLE_E_ADV_CHANGED, + BLE_E_ADV_FAILED, + BLE_E_ADV_SETUP_FAILED, + BLE_E_START_ADV, + BLE_E_STOP, + BLE_E_FAIL, + BLE_E_START_ADV_FAILED, + BLE_KW_MSG_2M_UPGRADE_ERROR, + BLE_INTERNAL_ERROR, + } ble_err_t; + + typedef struct ble_att_written_data_s + { + uint8_t device_id; + uint16_t handle; + uint16_t length; + uint8_t data[1]; + } blekw_att_written_data_t; + + typedef struct hk_ble_att_read_data_s + { + uint8_t device_id; + uint16_t handle; + } blekw_att_read_data_t; + + CHIPoBLEServiceMode mServiceMode; + char mDeviceName[kMaxDeviceNameLength + 1]; +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + chip::System::PacketBufferHandle c3AdditionalDataBufferHandle; +#endif + uint8_t mDeviceId; + bool mDeviceSubscribed = false; + bool mDeviceConnected = false; + + void DriveBLEState(void); + CHIP_ERROR ConfigureAdvertising(void); + CHIP_ERROR ConfigureAdvertisingData(void); + CHIP_ERROR StartAdvertising(void); + CHIP_ERROR StopAdvertising(void); + + void HandleConnectEvent(blekw_msg_t * msg); + void HandleConnectionCloseEvent(blekw_msg_t * msg); + void HandleWriteEvent(blekw_msg_t * msg); + void HandleRXCharWrite(blekw_msg_t * msg); + void HandleTXCharCCCDWrite(blekw_msg_t * msg); + void HandleForceDisconnect(); + +#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING + CHIP_ERROR EncodeAdditionalDataTlv(); + void HandleC3ReadRequest(blekw_msg_t * msg); +#endif + BLEManagerCommon::ble_err_t blekw_send_event(int8_t connection_handle, uint16_t handle, uint8_t * data, uint32_t len); + + static void DriveBLEState(intptr_t arg); + static void StopAdvertisingPriorToSwitchingMode(intptr_t arg); + static void BleAdvTimeoutHandler(TimerHandle_t xTimer); + static void CancelBleAdvTimeoutTimer(void); + static void StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs); + + static void blekw_connection_timeout_cb(TimerHandle_t timer); + static void blekw_generic_cb(gapGenericEvent_t * pGenericEvent); + static void blekw_gatt_server_cb(deviceId_t deviceId, gattServerEvent_t * pServerEvent); + static CHIP_ERROR blekw_msg_add_u8(blekw_msg_type_t type, uint8_t data); + static CHIP_ERROR blekw_msg_add_u16(blekw_msg_type_t type, uint16_t data); + static CHIP_ERROR blekw_msg_add_att_written(blekw_msg_type_t type, uint8_t device_id, uint16_t handle, uint8_t * data, + uint16_t length); + static CHIP_ERROR blekw_msg_add_att_read(blekw_msg_type_t type, uint8_t device_id, uint16_t handle); + static BLEManagerCommon::ble_err_t blekw_start_advertising(gapAdvertisingParameters_t * adv_params, gapAdvertisingData_t * adv, + gapScanResponseData_t * scnrsp); + static BLEManagerCommon::ble_err_t blekw_stop_advertising(void); + static void blekw_gap_advertising_cb(gapAdvertisingEvent_t * pAdvertisingEvent); + static void blekw_gap_connection_cb(deviceId_t deviceId, gapConnectionEvent_t * pConnectionEvent); + static void blekw_start_connection_timeout(void); + static void blekw_stop_connection_timeout(void); + static bool blekw_stop_connection_internal(BLE_CONNECTION_OBJECT conId); + +public: + virtual CHIP_ERROR InitHostController(ble_generic_cb_fp cb_fp) = 0; + virtual BLEManagerCommon * GetImplInstance() = 0; + void DoBleProcessing(void); +}; + +inline BLEManager::CHIPoBLEServiceMode BLEManagerCommon::_GetCHIPoBLEServiceMode(void) +{ + return mServiceMode; +} + +} // namespace Internal +} // namespace DeviceLayer +} // namespace chip + +#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/nxp/k32w/common/CHIPDevicePlatformRamStorageConfig.h b/src/platform/nxp/k32w/common/CHIPDevicePlatformRamStorageConfig.h index b55e8fccc38fc8..58c1c73bba5b73 100644 --- a/src/platform/nxp/k32w/common/CHIPDevicePlatformRamStorageConfig.h +++ b/src/platform/nxp/k32w/common/CHIPDevicePlatformRamStorageConfig.h @@ -108,6 +108,9 @@ * @def kNvmId_KvsValues * * PDM ID used for KVS values RAM storage. + * KVS buffer can become quite big, so this PDM + * id is used as base id for subsequent PDM ids + * used to store data in chunks of PDM page size. */ #ifndef kNvmId_KvsValues #define kNvmId_KvsValues (uint16_t) 0x6001 @@ -132,13 +135,13 @@ #define kNvmId_ApplicationBase (uint16_t) 0xA000 #endif -#if CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#if CONFIG_CHIP_LOAD_REAL_FACTORY_DATA /** * @def kNvmId_FactoryDataBackup * - * PDM ID used for factory data backup in K32W0FactoryDataProvider. + * PDM ID used for factory data backup in FactoryDataProvider. */ #ifndef kNvmId_FactoryDataBackup #define kNvmId_FactoryDataBackup (uint16_t) 0x7000 #endif -#endif // CONFIG_CHIP_K32W0_REAL_FACTORY_DATA +#endif // CONFIG_CHIP_LOAD_REAL_FACTORY_DATA diff --git a/src/platform/nxp/k32w/k32w0/K32W0FactoryDataProvider.cpp b/src/platform/nxp/k32w/common/FactoryDataProvider.cpp similarity index 51% rename from src/platform/nxp/k32w/k32w0/K32W0FactoryDataProvider.cpp rename to src/platform/nxp/k32w/common/FactoryDataProvider.cpp index 53533218cccf72..5e99042ba4f0ed 100644 --- a/src/platform/nxp/k32w/k32w0/K32W0FactoryDataProvider.cpp +++ b/src/platform/nxp/k32w/common/FactoryDataProvider.cpp @@ -15,7 +15,7 @@ * limitations under the License. */ -#if (!CONFIG_CHIP_K32W0_REAL_FACTORY_DATA || !(defined CONFIG_CHIP_K32W0_REAL_FACTORY_DATA)) +#if (!CONFIG_CHIP_LOAD_REAL_FACTORY_DATA || !(defined CONFIG_CHIP_LOAD_REAL_FACTORY_DATA)) #include #include #include @@ -29,11 +29,7 @@ #include #include #include - -#include "K32W0FactoryDataProvider.h" -extern "C" { -#include "Flash_Adapter.h" -} +#include #include @@ -43,63 +39,17 @@ namespace DeviceLayer { static constexpr size_t kSpake2pSerializedVerifier_MaxBase64Len = BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_VerifierSerialized_Length) + 1; static constexpr size_t kSpake2pSalt_MaxBase64Len = BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length) + 1; -static constexpr size_t kMaxKeyLen = 32; - -OtaUtils_EEPROM_ReadData pFunctionEepromRead = (OtaUtils_EEPROM_ReadData) K32W0FactoryDataProvider::ReadDataMemcpy; - -uint32_t K32W0FactoryDataProvider::kFactoryDataStart = (uint32_t) __FACTORY_DATA_START; -uint32_t K32W0FactoryDataProvider::kFactoryDataSize = (uint32_t) __FACTORY_DATA_SIZE; -uint32_t K32W0FactoryDataProvider::kFactoryDataPayloadStart = kFactoryDataStart + sizeof(K32W0FactoryDataProvider::Header); - -uint8_t K32W0FactoryDataProvider::ReadDataMemcpy(uint16_t num, uint32_t src, uint8_t * dst) -{ - memcpy(dst, (void *) (src), num); - return 0; -} -K32W0FactoryDataProvider & K32W0FactoryDataProvider::GetDefaultInstance() -{ - static K32W0FactoryDataProvider sInstance; - return sInstance; -} +uint32_t FactoryDataProvider::kFactoryDataStart = (uint32_t) __FACTORY_DATA_START; +uint32_t FactoryDataProvider::kFactoryDataSize = (uint32_t) __FACTORY_DATA_SIZE; +uint32_t FactoryDataProvider::kFactoryDataPayloadStart = kFactoryDataStart + sizeof(FactoryDataProvider::Header); -extern "C" WEAK CHIP_ERROR FactoryDataDefaultRestoreMechanism() -{ - CHIP_ERROR error = CHIP_NO_ERROR; - uint16_t backupLength = 0; - -#if CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR - // Check if PDM id related to factory data backup exists. - // If it does, it means an external event (such as a power loss) - // interrupted the factory data update process and the section - // from internal flash is most likely erased and should be restored. - if (PDM_bDoesDataExist(kNvmId_FactoryDataBackup, &backupLength)) - { - chip::Platform::ScopedMemoryBuffer buffer; - buffer.Calloc(K32W0FactoryDataProvider::kFactoryDataSize); - ReturnErrorCodeIf(buffer.Get() == nullptr, CHIP_ERROR_NO_MEMORY); - - auto status = PDM_eReadDataFromRecord(kNvmId_FactoryDataBackup, (void *) buffer.Get(), - K32W0FactoryDataProvider::kFactoryDataSize, &backupLength); - ReturnErrorCodeIf(PDM_E_STATUS_OK != status, CHIP_FACTORY_DATA_PDM_RESTORE); - - error = K32W0FactoryDataProvider::GetDefaultInstance().UpdateData(buffer.Get()); - if (error == CHIP_NO_ERROR) - { - ChipLogProgress(DeviceLayer, "Factory data was restored successfully"); - } - } -#endif - - return error; -} - -K32W0FactoryDataProvider::K32W0FactoryDataProvider() +FactoryDataProvider::FactoryDataProvider() { maxLengths[FactoryDataId::kVerifierId] = kSpake2pSerializedVerifier_MaxBase64Len; maxLengths[FactoryDataId::kSaltId] = kSpake2pSalt_MaxBase64Len; maxLengths[FactoryDataId::kIcId] = sizeof(uint32_t); - maxLengths[FactoryDataId::kDacPrivateKeyId] = kMaxKeyLen; + maxLengths[FactoryDataId::kDacPrivateKeyId] = Crypto::kP256_PrivateKey_Length; maxLengths[FactoryDataId::kDacCertificateId] = Credentials::kMaxDERCertLength; maxLengths[FactoryDataId::kPaiCertificateId] = Credentials::kMaxDERCertLength; maxLengths[FactoryDataId::kDiscriminatorId] = sizeof(uint32_t); @@ -117,150 +67,61 @@ K32W0FactoryDataProvider::K32W0FactoryDataProvider() maxLengths[FactoryDataId::kPartNumber] = ConfigurationManager::kMaxPartNumberLength; maxLengths[FactoryDataId::kProductURL] = ConfigurationManager::kMaxProductURLLength; maxLengths[FactoryDataId::kProductLabel] = ConfigurationManager::kMaxProductLabelLength; - - RegisterRestoreMechanism(FactoryDataDefaultRestoreMechanism); } -CHIP_ERROR K32W0FactoryDataProvider::Init() -{ - CHIP_ERROR error = CHIP_NO_ERROR; - uint32_t sum = 0; - - ReturnErrorOnFailure(SetCustomIds()); - - for (uint8_t i = 1; i < K32W0FactoryDataProvider::kNumberOfIds; i++) - { - sum += maxLengths[i]; - } - - if (sum > kFactoryDataSize) - { - ChipLogError(DeviceLayer, "Max size of factory data: %" PRIu32 " is bigger than reserved factory data size: %" PRIu32, sum, - kFactoryDataSize); - } - - VerifyOrReturnError(mRestoreMechanisms.size() > 0, CHIP_FACTORY_DATA_RESTORE_MECHANISM); - - for (auto & restore : mRestoreMechanisms) - { - error = restore(); - if (error != CHIP_NO_ERROR) - { - continue; - } - - error = Validate(); - if (error != CHIP_NO_ERROR) - { - continue; - } +FactoryDataProvider::~FactoryDataProvider() {} - break; - } - - if (error != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Factory data init failed with: %s", ErrorStr(error)); - } - else - { -#if CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR - PDM_vDeleteDataRecord(kNvmId_FactoryDataBackup); -#endif - } - - return error; -} - -CHIP_ERROR K32W0FactoryDataProvider::Validate() +CHIP_ERROR FactoryDataProvider::Validate() { - uint8_t sha256Output[SHA256_HASH_SIZE] = { 0 }; + uint8_t output[Crypto::kSHA256_Hash_Length] = { 0 }; - auto status = OtaUtils_ReadFromInternalFlash((uint16_t) sizeof(Header), kFactoryDataStart, (uint8_t *) &mHeader, NULL, - pFunctionEepromRead); - ReturnErrorCodeIf(gOtaUtilsSuccess_c != status, CHIP_FACTORY_DATA_HEADER_READ); + memcpy(&mHeader, (void *) kFactoryDataStart, sizeof(Header)); ReturnErrorCodeIf(mHeader.hashId != kHashId, CHIP_FACTORY_DATA_HASH_ID); - SHA256_Hash((uint8_t *) kFactoryDataPayloadStart, mHeader.size, sha256Output); - ReturnErrorCodeIf(memcmp(sha256Output, mHeader.hash, kHashLen) != 0, CHIP_FACTORY_DATA_SHA_CHECK); - - return CHIP_NO_ERROR; -} - -void K32W0FactoryDataProvider::RegisterRestoreMechanism(RestoreMechanism restore) -{ - mRestoreMechanisms.insert(mRestoreMechanisms.end(), restore); -} - -CHIP_ERROR K32W0FactoryDataProvider::UpdateData(uint8_t * pBuf) -{ - NV_Init(); - - auto status = NV_FlashEraseSector(kFactoryDataStart, kFactoryDataSize); - ReturnErrorCodeIf(status != kStatus_FLASH_Success, CHIP_FACTORY_DATA_FLASH_ERASE); - - Header * header = (Header *) pBuf; - status = NV_FlashProgramUnaligned(kFactoryDataStart, sizeof(Header) + header->size, pBuf); - ReturnErrorCodeIf(status != kStatus_FLASH_Success, CHIP_FACTORY_DATA_FLASH_PROGRAM); + ReturnErrorOnFailure(Crypto::Hash_SHA256((uint8_t *) kFactoryDataPayloadStart, mHeader.size, output)); + ReturnErrorCodeIf(memcmp(output, mHeader.hash, kHashLen) != 0, CHIP_FACTORY_DATA_SHA_CHECK); return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::SearchForId(uint8_t searchedType, uint8_t * pBuf, size_t bufLength, uint16_t & length, - uint32_t * offset) +CHIP_ERROR FactoryDataProvider::SearchForId(uint8_t searchedType, uint8_t * pBuf, size_t bufLength, uint16_t & length, + uint32_t * offset) { - CHIP_ERROR err = CHIP_ERROR_NOT_FOUND; - uint32_t addr = kFactoryDataPayloadStart; - uint8_t type = 0; + uint32_t addr = kFactoryDataPayloadStart; + uint8_t type = 0; while (addr < (kFactoryDataPayloadStart + mHeader.size)) { - if (gOtaUtilsSuccess_c != OtaUtils_ReadFromInternalFlash((uint16_t) sizeof(type), addr, &type, NULL, pFunctionEepromRead) || - gOtaUtilsSuccess_c != - OtaUtils_ReadFromInternalFlash((uint16_t) sizeof(length), addr + 1, (uint8_t *) &length, NULL, pFunctionEepromRead)) - break; + memcpy(&type, (void *) addr, sizeof(type)); + memcpy(&length, (void *) (addr + 1), sizeof(length)); if (searchedType == type) { - if ((type >= K32W0FactoryDataProvider::kNumberOfIds) || (length > maxLengths[type])) + if ((type >= FactoryDataProvider::kNumberOfIds) || (length > maxLengths[type])) { ChipLogError(DeviceLayer, "Failed validity check for factory data with: id=%d, length=%d", type, length); break; } - if (bufLength < length) - { - err = CHIP_ERROR_BUFFER_TOO_SMALL; - } - else - { - if (gOtaUtilsSuccess_c != - OtaUtils_ReadFromInternalFlash(length, addr + kValueOffset, pBuf, NULL, pFunctionEepromRead)) - break; + ReturnErrorCodeIf(bufLength < length, CHIP_ERROR_BUFFER_TOO_SMALL); + memcpy(pBuf, (void *) (addr + kValueOffset), length); - if (offset) - *offset = (addr - kFactoryDataPayloadStart); - err = CHIP_NO_ERROR; - } - break; + if (offset) + *offset = (addr - kFactoryDataPayloadStart); + + return CHIP_NO_ERROR; } else { - /* Jump past 2 bytes of length and then use length to jump to next data */ + /* Jump past 3 bytes of length and then use length to jump to next data */ addr = addr + kValueOffset + length; } } - return err; -} - -CHIP_ERROR K32W0FactoryDataProvider::SetCustomIds() -{ - ChipLogError(DeviceLayer, "SetCustomIds() is not implemented for default FactoryDataProvider"); - return CHIP_NO_ERROR; + return CHIP_ERROR_NOT_FOUND; } -CHIP_ERROR K32W0FactoryDataProvider::GetCertificationDeclaration(MutableByteSpan & outBuffer) +CHIP_ERROR FactoryDataProvider::GetCertificationDeclaration(MutableByteSpan & outBuffer) { uint16_t declarationSize = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kCertDeclarationId, outBuffer.data(), outBuffer.size(), declarationSize)); @@ -269,12 +130,12 @@ CHIP_ERROR K32W0FactoryDataProvider::GetCertificationDeclaration(MutableByteSpan return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetFirmwareInformation(MutableByteSpan & out_firmware_info_buffer) +CHIP_ERROR FactoryDataProvider::GetFirmwareInformation(MutableByteSpan & out_firmware_info_buffer) { return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & outBuffer) +CHIP_ERROR FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & outBuffer) { uint16_t certificateSize = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kDacCertificateId, outBuffer.data(), outBuffer.size(), certificateSize)); @@ -282,7 +143,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) +CHIP_ERROR FactoryDataProvider::GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) { uint16_t certificateSize = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kPaiCertificateId, outBuffer.data(), outBuffer.size(), certificateSize)); @@ -290,34 +151,12 @@ CHIP_ERROR K32W0FactoryDataProvider::GetProductAttestationIntermediateCert(Mutab return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) +CHIP_ERROR FactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) { - Crypto::P256ECDSASignature signature; - Crypto::P256Keypair keypair; - Crypto::P256SerializedKeypair serializedKeypair; - - VerifyOrReturnError(IsSpanUsable(outSignBuffer), CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(IsSpanUsable(messageToSign), CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(outSignBuffer.size() >= signature.Capacity(), CHIP_ERROR_BUFFER_TOO_SMALL); - - /* Get private key of DAC certificate from reserved section */ - uint8_t keyBuf[kMaxKeyLen]; - MutableByteSpan dacPrivateKeySpan(keyBuf); - uint16_t keySize = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kDacPrivateKeyId, dacPrivateKeySpan.data(), dacPrivateKeySpan.size(), keySize)); - dacPrivateKeySpan.reduce_size(keySize); - - /* Only the private key is used when signing */ - ReturnErrorOnFailure(serializedKeypair.SetLength(Crypto::kP256_PublicKey_Length + dacPrivateKeySpan.size())); - memcpy(serializedKeypair.Bytes() + Crypto::kP256_PublicKey_Length, dacPrivateKeySpan.data(), dacPrivateKeySpan.size()); - - ReturnErrorOnFailure(keypair.Deserialize(serializedKeypair)); - ReturnErrorOnFailure(keypair.ECDSA_sign_msg(messageToSign.data(), messageToSign.size(), signature)); - - return CopySpanToMutableSpan(ByteSpan{ signature.ConstBytes(), signature.Length() }, outSignBuffer); + return SignWithDacKey(messageToSign, outSignBuffer); } -CHIP_ERROR K32W0FactoryDataProvider::GetSetupDiscriminator(uint16_t & setupDiscriminator) +CHIP_ERROR FactoryDataProvider::GetSetupDiscriminator(uint16_t & setupDiscriminator) { uint32_t discriminator = 0; uint16_t temp = 0; @@ -328,12 +167,12 @@ CHIP_ERROR K32W0FactoryDataProvider::GetSetupDiscriminator(uint16_t & setupDiscr return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::SetSetupDiscriminator(uint16_t setupDiscriminator) +CHIP_ERROR FactoryDataProvider::SetSetupDiscriminator(uint16_t setupDiscriminator) { return CHIP_ERROR_NOT_IMPLEMENTED; } -CHIP_ERROR K32W0FactoryDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount) +CHIP_ERROR FactoryDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount) { uint16_t temp = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kIcId, (uint8_t *) &iterationCount, sizeof(iterationCount), temp)); @@ -341,7 +180,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetSpake2pIterationCount(uint32_t & iterati return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) +CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) { char saltB64[kSpake2pSalt_MaxBase64Len] = { 0 }; uint16_t saltB64Len = 0; @@ -356,7 +195,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) +CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) { char verifierB64[kSpake2pSerializedVerifier_MaxBase64Len] = { 0 }; uint16_t verifierB64Len = 0; @@ -370,7 +209,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifi return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetSetupPasscode(uint32_t & setupPasscode) +CHIP_ERROR FactoryDataProvider::GetSetupPasscode(uint32_t & setupPasscode) { uint16_t length = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kSetupPasscodeId, (uint8_t *) &setupPasscode, sizeof(setupPasscode), length)); @@ -378,12 +217,12 @@ CHIP_ERROR K32W0FactoryDataProvider::GetSetupPasscode(uint32_t & setupPasscode) return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::SetSetupPasscode(uint32_t setupPasscode) +CHIP_ERROR FactoryDataProvider::SetSetupPasscode(uint32_t setupPasscode) { return CHIP_ERROR_NOT_IMPLEMENTED; } -CHIP_ERROR K32W0FactoryDataProvider::GetVendorName(char * buf, size_t bufSize) +CHIP_ERROR FactoryDataProvider::GetVendorName(char * buf, size_t bufSize) { uint16_t length = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kVendorNameId, (uint8_t *) buf, bufSize, length)); @@ -392,7 +231,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetVendorName(char * buf, size_t bufSize) return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetVendorId(uint16_t & vendorId) +CHIP_ERROR FactoryDataProvider::GetVendorId(uint16_t & vendorId) { uint16_t length = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kVidId, (uint8_t *) &vendorId, sizeof(vendorId), length)); @@ -400,7 +239,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetVendorId(uint16_t & vendorId) return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetProductName(char * buf, size_t bufSize) +CHIP_ERROR FactoryDataProvider::GetProductName(char * buf, size_t bufSize) { uint16_t length = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kProductNameId, (uint8_t *) buf, bufSize, length)); @@ -409,7 +248,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetProductName(char * buf, size_t bufSize) return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetProductId(uint16_t & productId) +CHIP_ERROR FactoryDataProvider::GetProductId(uint16_t & productId) { uint16_t length = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kPidId, (uint8_t *) &productId, sizeof(productId), length)); @@ -417,7 +256,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetProductId(uint16_t & productId) return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetPartNumber(char * buf, size_t bufSize) +CHIP_ERROR FactoryDataProvider::GetPartNumber(char * buf, size_t bufSize) { uint16_t length = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kPartNumber, (uint8_t *) buf, bufSize, length)); @@ -426,7 +265,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetPartNumber(char * buf, size_t bufSize) return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetProductURL(char * buf, size_t bufSize) +CHIP_ERROR FactoryDataProvider::GetProductURL(char * buf, size_t bufSize) { uint16_t length = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kProductURL, (uint8_t *) buf, bufSize, length)); @@ -435,7 +274,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetProductURL(char * buf, size_t bufSize) return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetProductLabel(char * buf, size_t bufSize) +CHIP_ERROR FactoryDataProvider::GetProductLabel(char * buf, size_t bufSize) { uint16_t length = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kProductLabel, (uint8_t *) buf, bufSize, length)); @@ -444,7 +283,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetProductLabel(char * buf, size_t bufSize) return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) +CHIP_ERROR FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) { uint16_t length = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kSerialNumberId, (uint8_t *) buf, bufSize, length)); @@ -453,7 +292,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) +CHIP_ERROR FactoryDataProvider::GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) { uint16_t length = 0; uint8_t date[ConfigurationManager::kMaxManufacturingDateLength]; @@ -478,7 +317,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetManufacturingDate(uint16_t & year, uint8 return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetHardwareVersion(uint16_t & hardwareVersion) +CHIP_ERROR FactoryDataProvider::GetHardwareVersion(uint16_t & hardwareVersion) { uint16_t length = 0; ReturnErrorOnFailure( @@ -487,7 +326,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetHardwareVersion(uint16_t & hardwareVersi return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetHardwareVersionString(char * buf, size_t bufSize) +CHIP_ERROR FactoryDataProvider::GetHardwareVersionString(char * buf, size_t bufSize) { uint16_t length = 0; ReturnErrorOnFailure(SearchForId(FactoryDataId::kHardwareVersionStrId, (uint8_t *) buf, bufSize, length)); @@ -496,7 +335,7 @@ CHIP_ERROR K32W0FactoryDataProvider::GetHardwareVersionString(char * buf, size_t return CHIP_NO_ERROR; } -CHIP_ERROR K32W0FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) +CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) { CHIP_ERROR err = CHIP_ERROR_NOT_IMPLEMENTED; #if CHIP_ENABLE_ROTATING_DEVICE_ID diff --git a/src/platform/nxp/k32w/k32w0/K32W0FactoryDataProvider.h b/src/platform/nxp/k32w/common/FactoryDataProvider.h similarity index 85% rename from src/platform/nxp/k32w/k32w0/K32W0FactoryDataProvider.h rename to src/platform/nxp/k32w/common/FactoryDataProvider.h index 2cbfeb664dc7fa..db10a8f6accb23 100644 --- a/src/platform/nxp/k32w/k32w0/K32W0FactoryDataProvider.h +++ b/src/platform/nxp/k32w/common/FactoryDataProvider.h @@ -19,17 +19,12 @@ #include #include #include - -#include "CHIPPlatformConfig.h" -#include "K32W0Config.h" -#include #include -#include "OtaUtils.h" -#include "SecLib.h" - #include +#include "CHIPPlatformConfig.h" + /* Grab symbol for the base address from the linker file. */ extern uint32_t __FACTORY_DATA_START[]; extern uint32_t __FACTORY_DATA_SIZE[]; @@ -57,9 +52,9 @@ namespace DeviceLayer { * and Device Instance Info. */ -class K32W0FactoryDataProvider : public DeviceInstanceInfoProvider, - public CommissionableDataProvider, - public Credentials::DeviceAttestationCredentialsProvider +class FactoryDataProvider : public DeviceInstanceInfoProvider, + public CommissionableDataProvider, + public Credentials::DeviceAttestationCredentialsProvider { public: struct Header @@ -112,24 +107,11 @@ class K32W0FactoryDataProvider : public DeviceInstanceInfoProvider, static constexpr uint32_t kHashLen = 4; static constexpr size_t kHashId = 0xCE47BA5E; - typedef otaUtilsResult_t (*OtaUtils_EEPROM_ReadData)(uint16_t nbBytes, uint32_t address, uint8_t * pInbuf); - - using RestoreMechanism = CHIP_ERROR (*)(void); - - static uint8_t ReadDataMemcpy(uint16_t num, uint32_t src, uint8_t * dst); - static K32W0FactoryDataProvider & GetDefaultInstance(); + FactoryDataProvider(); + virtual ~FactoryDataProvider(); - K32W0FactoryDataProvider(); - - CHIP_ERROR Init(); - CHIP_ERROR Validate(); - void RegisterRestoreMechanism(RestoreMechanism mechanism); - CHIP_ERROR UpdateData(uint8_t * pBuf); - CHIP_ERROR SearchForId(uint8_t searchedType, uint8_t * pBuf, size_t bufLength, uint16_t & length, uint32_t * offset = nullptr); - - // Custom factory data providers must implement this method in order to define - // their own custom IDs. - virtual CHIP_ERROR SetCustomIds(); + virtual CHIP_ERROR Init() = 0; + virtual CHIP_ERROR SignWithDacKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) = 0; // ===== Members functions that implement the CommissionableDataProvider CHIP_ERROR GetSetupDiscriminator(uint16_t & setupDiscriminator) override; @@ -162,9 +144,11 @@ class K32W0FactoryDataProvider : public DeviceInstanceInfoProvider, CHIP_ERROR GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) override; protected: + CHIP_ERROR Validate(); + CHIP_ERROR SearchForId(uint8_t searchedType, uint8_t * pBuf, size_t bufLength, uint16_t & length, uint32_t * offset = nullptr); + uint16_t maxLengths[kNumberOfIds]; Header mHeader; - std::vector mRestoreMechanisms; }; } // namespace DeviceLayer diff --git a/src/platform/nxp/k32w/common/K32W_OTA_README.md b/src/platform/nxp/k32w/common/K32W_OTA_README.md index 97c73ec9e5a7a2..4f2ba7b6e52960 100644 --- a/src/platform/nxp/k32w/common/K32W_OTA_README.md +++ b/src/platform/nxp/k32w/common/K32W_OTA_README.md @@ -124,13 +124,19 @@ implementation. The OTA image should be generated with the Prior to factory data update, the old factory data is backed up in external flash. If anything interrupts the update (e.g. power loss), there is a slight chance the internal flash factory data section is erased and has to be restored -at next boot. The `K32W0FactoryDataProvider` offers a default restore mechanism -and support for registering additional restore mechanisms or overwriting the -default one. +at next boot. The `FactoryDataProvider` offers a default restore mechanism and +support for registering additional restore mechanisms or overwriting the default +one. Restore mechanisms are just functions that have this signature: `CHIP_ERROR (*)(void)`. Any such function can be registered through -`K32W0FactoryDataProvider::RegisterRestoreMechanism`. +`FactoryDataProvider::RegisterRestoreMechanism`. + +The default restore mechanism is implemented as a weak function: +`FactoryDataDefaultRestoreMechanism`. It is registered in +`FactoryDataProvider::Init`, before factory data validation, and it can be +overwritten at application level. When doing the actual restore, the mechanisms +are called in the order they were registered. The default restore mechanism is implemented as a weak function: `FactoryDataDefaultRestoreMechanism`. It is registered in diff --git a/src/platform/nxp/k32w/common/OTAImageProcessorImpl.cpp b/src/platform/nxp/k32w/common/OTAImageProcessorImpl.cpp index b87ef560aa5841..69317d7c0cbf6f 100644 --- a/src/platform/nxp/k32w/common/OTAImageProcessorImpl.cpp +++ b/src/platform/nxp/k32w/common/OTAImageProcessorImpl.cpp @@ -17,7 +17,9 @@ */ #include +#include #include +#include #include #include @@ -377,6 +379,8 @@ void OTAImageProcessorImpl::HandleApply(intptr_t context) imageProcessor->mAccumulator.Clear(); + ConfigurationManagerImpl().StoreSoftwareUpdateCompleted(); + // Set the necessary information to inform the SSBL that a new image is available // and trigger the actual device reboot after some time, to take into account // queued actions, e.g. sending events to a subscription diff --git a/src/platform/nxp/k32w/common/RamStorageKey.cpp b/src/platform/nxp/k32w/common/RamStorageKey.cpp deleted file mode 100644 index 131559e9a39c30..00000000000000 --- a/src/platform/nxp/k32w/common/RamStorageKey.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -namespace chip::DeviceLayer::Internal { - -RamStorageKey::RamStorageKey(RamStorage * storage, uint8_t keyId, uint8_t pdmId) -{ - mStorage = storage; - mId = GetPdmId(keyId, pdmId); -} - -CHIP_ERROR RamStorageKey::Read(uint8_t * buf, uint16_t & sizeToRead) const -{ - return mStorage->Read(mId, 0, buf, &sizeToRead); -} - -CHIP_ERROR RamStorageKey::Write(const uint8_t * buf, uint16_t length) -{ - return mStorage->Write(mId, buf, length); -} - -CHIP_ERROR RamStorageKey::Delete() -{ - return mStorage->Delete(mId, -1); -} - -} // namespace chip::DeviceLayer::Internal diff --git a/src/platform/nxp/k32w/common/RamStorageKey.h b/src/platform/nxp/k32w/common/RamStorageKey.h deleted file mode 100644 index e1596eeec1ec85..00000000000000 --- a/src/platform/nxp/k32w/common/RamStorageKey.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#pragma once - -#include - -namespace chip { -namespace DeviceLayer { -namespace Internal { - -class RamStorageKey -{ -public: - RamStorageKey(RamStorage * storage, uint8_t keyId, uint8_t pdmId); - CHIP_ERROR Read(uint8_t * buf, uint16_t & sizeToRead) const; - CHIP_ERROR Write(const uint8_t * buf, uint16_t length); - CHIP_ERROR Delete(); - - static uint16_t GetPdmId(uint8_t keyId, uint8_t pdmId) { return static_cast(keyId) << 8 | pdmId; } - -private: - RamStorage * mStorage; - uint16_t mId; -}; - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/nxp/k32w/k32w0/BLEManagerImpl.cpp b/src/platform/nxp/k32w/k32w0/BLEManagerImpl.cpp index 7ae29b191578fe..a7bc09d524360e 100644 --- a/src/platform/nxp/k32w/k32w0/BLEManagerImpl.cpp +++ b/src/platform/nxp/k32w/k32w0/BLEManagerImpl.cpp @@ -1,7 +1,6 @@ /* * - * Copyright (c) 2020-2021 Project CHIP Authors - * Copyright (c) 2020 Nest Labs, Inc. + * Copyright (c) 2021-2023 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,181 +16,50 @@ * limitations under the License. */ -/** - * @file - * Provides an implementation of the BLEManager singleton object - * for the K32W platforms. - */ - /* this file behaves like a config.h, comes first */ #include -#include - -#include - -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - -#include - -#include "board.h" -#include "fsl_xcvr.h" -#include "gatt_db_app_interface.h" -#include "gatt_db_handles.h" -#include "stdio.h" -#include "timers.h" - -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) #include "PWR_Configuration.h" +#include "PWR_Interface.h" #endif -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -#include -#include -#endif +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + +/* controller task configuration */ +#define CONTROLLER_TASK_PRIORITY (6U) +#define CONTROLLER_TASK_STACK_SIZE (gControllerTaskStackSize_c / sizeof(StackType_t)) -/******************************************************************************* - * Local data types - *******************************************************************************/ -extern "C" bool_t Ble_ConfigureHostStackConfig(void); extern "C" void (*pfBLE_SignalFromISR)(void); -extern "C" bool_t Ble_CheckMemoryStorage(void); extern osaEventId_t gHost_TaskEvent; +osaEventId_t mControllerTaskEvent; extern msgQueue_t gApp2Host_TaskQueue; extern msgQueue_t gHci2Host_TaskQueue; -using namespace ::chip; -using namespace ::chip::Ble; +#include + +extern "C" bool_t Ble_ConfigureHostStackConfig(void); namespace chip { namespace DeviceLayer { namespace Internal { -namespace { -/******************************************************************************* - * Macros & Constants definitions - *******************************************************************************/ -/* Timeout of BLE commands */ -#define CHIP_BLE_KW_EVNT_TIMEOUT 1000 - -/** BLE advertisement state changed */ -#define CHIP_BLE_KW_EVNT_ADV_CHANGED 0x0001 -/** BLE advertisement command failed */ -#define CHIP_BLE_KW_EVNT_ADV_FAILED 0x0002 -/** BLE advertisement setup failed */ -#define CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED 0x0004 -/** BLE advertisement parameters setup complete */ -#define CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE 0x0008 -/** BLE advertisement data setup complete */ -#define CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE 0x0010 -/** BLE random address set */ -#define CHIP_BLE_KW_EVNT_RND_ADDR_SET 0x0020 -/** BLE Initialization complete */ -#define CHIP_BLE_KW_EVNT_INIT_COMPLETE 0x0040 -/** BLE Received a handle value confirmation from the client */ -#define CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED 0x0080 -/** BLE send indication failed */ -#define CHIP_BLE_KW_EVNT_INDICATION_FAILED 0x0100 -/** Maximal time of connection without activity */ -#define CHIP_BLE_KW_CONN_TIMEOUT 60000 - -#define LOOP_EV_BLE (0x08) - -/* controller task configuration */ -#define CONTROLLER_TASK_PRIORITY (6U) -#define CONTROLLER_TASK_STACK_SIZE (gControllerTaskStackSize_c / sizeof(StackType_t)) - -/* host task configuration */ -#define HOST_TASK_PRIORITY (4U) -#define HOST_TASK_STACK_SIZE (gHost_TaskStackSize_c / sizeof(StackType_t)) - -/* ble app task configuration */ -#define CHIP_DEVICE_CONFIG_BLE_APP_TASK_PRIORITY (HOST_TASK_PRIORITY - 1) -#define CHIP_DEVICE_CONFIG_BLE_APP_TASK_STACK_SIZE (1024) - -/* advertising configuration */ -#define BLEKW_ADV_MAX_NO (2) -#define BLEKW_SCAN_RSP_MAX_NO (2) -#define BLEKW_MAX_ADV_DATA_LEN (31) -#define CHIP_ADV_SHORT_UUID_LEN (2) - -/* FreeRTOS sw timer */ -TimerHandle_t sbleAdvTimeoutTimer; - -/* Message list used to synchronize asynchronous messages from the KW BLE tasks */ -anchor_t blekw_msg_list; - -/* Used to manage asynchronous events from BLE Stack: e.g.: GAP setup finished */ -osaEventId_t event_msg; - -osaEventId_t mControllerTaskEvent; -TimerHandle_t connectionTimeout; - -/* Used by BLE App Task to handle asynchronous GATT events */ -EventGroupHandle_t bleAppTaskLoopEvent; - -/* keep the device ID of the connected peer */ -uint8_t g_device_id; - -const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_RX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x11 } }; -const ChipBleUUID ChipUUID_CHIPoBLEChar_TX = { { 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, - 0x9D, 0x12 } }; - -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) -static bool bleAppStopInProgress; -#endif -} // namespace - BLEManagerImpl BLEManagerImpl::sInstance; -CHIP_ERROR BLEManagerImpl::_Init() +BLEManagerCommon * BLEManagerImpl::GetImplInstance() +{ + return &BLEManagerImpl::sInstance; +} +CHIP_ERROR BLEManagerImpl::InitHostController(ble_generic_cb_fp cb_fp) { CHIP_ERROR err = CHIP_NO_ERROR; - osaEventFlags_t flags; - BaseType_t bleAppCreated = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; - uint16_t attChipRxHandle[1] = { (uint16_t) value_chipoble_rx }; - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - uint16_t attChipC3Handle[1] = { (uint16_t) value_chipoble_c3 }; -#endif - - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Enabled; - - // Check if BLE stack is initialized - VerifyOrExit(!mFlags.Has(Flags::kK32WBLEStackInitialized), err = CHIP_ERROR_INCORRECT_STATE); - - // Initialize the Chip BleLayer. - err = BleLayer::Init(this, this, &DeviceLayer::SystemLayer()); - SuccessOrExit(err); - - /* Initialization of message wait events - - * used for receiving BLE Stack events */ - event_msg = OSA_EventCreate(TRUE); - VerifyOrExit(event_msg != NULL, err = CHIP_ERROR_INCORRECT_STATE); pfBLE_SignalFromISR = BLE_SignalFromISRCallback; /* Set the config structure to the host stack */ VerifyOrExit(Ble_ConfigureHostStackConfig() == TRUE, err = CHIP_ERROR_INCORRECT_STATE); - /* Prepare callback input queue.*/ - MSG_InitQueue(&blekw_msg_list); - - /* Create the connection timeout timer. */ - connectionTimeout = - xTimerCreate("bleTimeoutTmr", pdMS_TO_TICKS(CHIP_BLE_KW_CONN_TIMEOUT), pdFALSE, (void *) 0, blekw_connection_timeout_cb); - - /* Create BLE App Task */ - bleAppTaskLoopEvent = xEventGroupCreate(); - VerifyOrExit(bleAppTaskLoopEvent != NULL, err = CHIP_ERROR_INCORRECT_STATE); - bleAppCreated = xTaskCreate(bleAppTask, CHIP_DEVICE_CONFIG_BLE_APP_TASK_NAME, - CHIP_DEVICE_CONFIG_BLE_APP_TASK_STACK_SIZE / sizeof(StackType_t), this, - CHIP_DEVICE_CONFIG_BLE_APP_TASK_PRIORITY, NULL); - VerifyOrExit(bleAppCreated == pdPASS, err = CHIP_ERROR_INCORRECT_STATE); - /* BLE Radio Init */ VerifyOrExit(XCVR_Init(BLE_MODE, DR_2MBPS) == gXcvrSuccess_c, err = CHIP_ERROR_INCORRECT_STATE); @@ -202,365 +70,47 @@ CHIP_ERROR BLEManagerImpl::_Init() VerifyOrExit(blekw_host_init() == CHIP_NO_ERROR, err = CHIP_ERROR_INCORRECT_STATE); /* BLE Host Stack Init */ - Ble_HostInitialize(blekw_generic_cb, (hciHostToControllerInterface_t) Hci_SendPacketToController); - - /* Register the GATT server callback */ - VerifyOrExit(GattServer_RegisterCallback(blekw_gatt_server_cb) == gBleSuccess_c, err = CHIP_ERROR_INCORRECT_STATE); - - /* Wait until BLE Stack is ready */ - VerifyOrExit(OSA_EventWait(event_msg, CHIP_BLE_KW_EVNT_INIT_COMPLETE, TRUE, CHIP_BLE_KW_EVNT_TIMEOUT, &flags) == - osaStatus_Success, - err = CHIP_ERROR_INCORRECT_STATE); - -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) - PWR_ChangeDeepSleepMode(cPWR_PowerDown_RamRet); -#endif - - GattServer_RegisterHandlesForWriteNotifications(1, attChipRxHandle); -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - GattServer_RegisterHandlesForReadNotifications(1, attChipC3Handle); -#endif - - mFlags.Set(Flags::kK32WBLEStackInitialized); - mFlags.Set(Flags::kAdvertisingEnabled, CHIP_DEVICE_CONFIG_CHIPOBLE_ENABLE_ADVERTISING_AUTOSTART ? true : false); - mFlags.Set(Flags::kFastAdvertisingEnabled); + VerifyOrExit(Ble_HostInitialize(cb_fp, Hci_SendPacketToController) == gBleSuccess_c, err = CHIP_ERROR_INCORRECT_STATE); - // Create FreeRTOS sw timer for BLE timeouts and interval change. - sbleAdvTimeoutTimer = xTimerCreate("BleAdvTimer", // Just a text name, not used by the RTOS kernel - 1, // == default timer period (mS) - false, // no timer reload (==one-shot) - (void *) this, // init timer id = ble obj context - BleAdvTimeoutHandler // timer callback handler - ); - VerifyOrExit(sbleAdvTimeoutTimer != NULL, err = CHIP_ERROR_INCORRECT_STATE); exit: return err; } -uint16_t BLEManagerImpl::_NumConnections(void) -{ - uint16_t numCons = 0; - for (uint16_t i = 0; i < kMaxConnections; i++) - { - if (mBleConnections[i].allocated) - { - numCons++; - } - } - - return numCons; -} - -bool BLEManagerImpl::_IsAdvertisingEnabled(void) -{ - return mFlags.Has(Flags::kAdvertisingEnabled); -} - -bool BLEManagerImpl::_IsAdvertising(void) -{ - return mFlags.Has(Flags::kAdvertising); -} - -bool BLEManagerImpl::RemoveConnection(uint8_t connectionHandle) -{ - CHIPoBLEConState * bleConnState = GetConnectionState(connectionHandle, true); - bool status = false; - - if (bleConnState != NULL) - { - memset(bleConnState, 0, sizeof(CHIPoBLEConState)); - status = true; - } - - return status; -} - -void BLEManagerImpl::AddConnection(uint8_t connectionHandle) -{ - CHIPoBLEConState * bleConnState = GetConnectionState(connectionHandle, true); - - if (bleConnState != NULL) - { - memset(bleConnState, 0, sizeof(CHIPoBLEConState)); - bleConnState->allocated = 1; - bleConnState->connectionHandle = connectionHandle; - } -} - -BLEManagerImpl::CHIPoBLEConState * BLEManagerImpl::GetConnectionState(uint8_t connectionHandle, bool allocate) +/* Called by BLE when a connect is received */ +void BLEManagerImpl::BLE_SignalFromISRCallback(void) { - uint8_t freeIndex = kMaxConnections; - - for (uint8_t i = 0; i < kMaxConnections; i++) - { - if (mBleConnections[i].allocated == 1) - { - if (mBleConnections[i].connectionHandle == connectionHandle) - { - return &mBleConnections[i]; - } - } - - else if (i < freeIndex) - { - freeIndex = i; - } - } - - if (allocate) - { - if (freeIndex < kMaxConnections) - { - return &mBleConnections[freeIndex]; - } - - ChipLogError(DeviceLayer, "Failed to allocate CHIPoBLEConState"); - } - - return NULL; +#if defined(chip_with_low_power) + PWR_DisallowDeviceToSleep(); +#endif } -CHIP_ERROR BLEManagerImpl::_SetAdvertisingEnabled(bool val) +void BLEManagerImpl::Host_Task(osaTaskParam_t argument) { - CHIP_ERROR err = CHIP_NO_ERROR; - - VerifyOrExit(mServiceMode != ConnectivityManager::kCHIPoBLEServiceMode_NotSupported, err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); - - if (mFlags.Has(Flags::kAdvertisingEnabled) != val) - { - mFlags.Set(Flags::kAdvertisingEnabled, val); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - } - -exit: - return err; + Host_TaskHandler((void *) NULL); } -CHIP_ERROR BLEManagerImpl::_SetAdvertisingMode(BLEAdvertisingMode mode) +CHIP_ERROR BLEManagerImpl::blekw_host_init(void) { - switch (mode) + /* Initialization of task related */ + gHost_TaskEvent = OSA_EventCreate(TRUE); + if (!gHost_TaskEvent) { - case BLEAdvertisingMode::kFastAdvertising: - mFlags.Set(Flags::kFastAdvertisingEnabled, true); - break; - case BLEAdvertisingMode::kSlowAdvertising: - mFlags.Set(Flags::kFastAdvertisingEnabled, false); - break; - default: - return CHIP_ERROR_INVALID_ARGUMENT; + return CHIP_ERROR_NO_MEMORY; } - mFlags.Set(Flags::kRestartAdvertising); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - return CHIP_NO_ERROR; -} -CHIP_ERROR BLEManagerImpl::_GetDeviceName(char * buf, size_t bufSize) -{ - if (strlen(mDeviceName) >= bufSize) - { - return CHIP_ERROR_BUFFER_TOO_SMALL; - } - strcpy(buf, mDeviceName); - return CHIP_NO_ERROR; -} + /* Initialization of task message queue */ + MSG_InitQueue(&gApp2Host_TaskQueue); + MSG_InitQueue(&gHci2Host_TaskQueue); -CHIP_ERROR BLEManagerImpl::_SetDeviceName(const char * deviceName) -{ - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_NotSupported) - { - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; - } - if (deviceName != NULL && deviceName[0] != 0) - { - if (strlen(deviceName) >= kMaxDeviceNameLength) - { - return CHIP_ERROR_INVALID_ARGUMENT; - } - memset(mDeviceName, 0, kMaxDeviceNameLength); - strcpy(mDeviceName, deviceName); - mFlags.Set(Flags::kDeviceNameSet); - ChipLogProgress(DeviceLayer, "Setting device name to : \"%s\"", deviceName); - } - else + /* Task creation */ + if (pdPASS != xTaskCreate(Host_Task, "hostTask", HOST_TASK_STACK_SIZE, (void *) 0, HOST_TASK_PRIORITY, NULL)) { - mDeviceName[0] = 0; - mFlags.Clear(Flags::kDeviceNameSet); + return CHIP_ERROR_NO_MEMORY; } return CHIP_NO_ERROR; } -void BLEManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) -{ - switch (event->Type) - { - case DeviceEventType::kCHIPoBLESubscribe: - ChipDeviceEvent connEstEvent; - - HandleSubscribeReceived(event->CHIPoBLESubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); - connEstEvent.Type = DeviceEventType::kCHIPoBLEConnectionEstablished; - PlatformMgr().PostEventOrDie(&connEstEvent); - break; - - case DeviceEventType::kCHIPoBLEUnsubscribe: - HandleUnsubscribeReceived(event->CHIPoBLEUnsubscribe.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); - break; - - case DeviceEventType::kCHIPoBLEWriteReceived: - HandleWriteReceived(event->CHIPoBLEWriteReceived.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_RX, - PacketBufferHandle::Adopt(event->CHIPoBLEWriteReceived.Data)); - break; - - case DeviceEventType::kCHIPoBLEConnectionError: - HandleConnectionError(event->CHIPoBLEConnectionError.ConId, event->CHIPoBLEConnectionError.Reason); - break; - - case DeviceEventType::kCHIPoBLEIndicateConfirm: - HandleIndicationConfirmation(event->CHIPoBLEIndicateConfirm.ConId, &CHIP_BLE_SVC_ID, &ChipUUID_CHIPoBLEChar_TX); - break; - - default: - break; - } -} - -bool BLEManagerImpl::SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) -{ - ChipLogProgress(DeviceLayer, "BLEManagerImpl::SubscribeCharacteristic() not supported"); - return false; -} - -bool BLEManagerImpl::UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId) -{ - ChipLogProgress(DeviceLayer, "BLEManagerImpl::UnsubscribeCharacteristic() not supported"); - return false; -} - -bool BLEManagerImpl::CloseConnection(BLE_CONNECTION_OBJECT conId) -{ - return blekw_stop_connection_internal(conId); -} - -uint16_t BLEManagerImpl::GetMTU(BLE_CONNECTION_OBJECT conId) const -{ - uint16_t tempMtu = 0; - (void) Gatt_GetMtu(conId, &tempMtu); - - return tempMtu; -} - -bool BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf) -{ - ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendWriteRequest() not supported"); - return false; -} - -bool BLEManagerImpl::SendReadRequest(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle pBuf) -{ - ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendReadRequest() not supported"); - return false; -} - -bool BLEManagerImpl::SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, - const ChipBleUUID * svcId, const ChipBleUUID * charId) -{ - ChipLogProgress(DeviceLayer, "BLEManagerImpl::SendReadResponse() not supported"); - return false; -} - -void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) -{ - BLEMgrImpl().blekw_stop_connection_internal(conId); - BLEMgrImpl().RemoveConnection(conId); -} - -bool BLEManagerImpl::SendIndication(BLE_CONNECTION_OBJECT conId, const ChipBleUUID * svcId, const ChipBleUUID * charId, - PacketBufferHandle data) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - uint16_t cId = (UUIDsMatch(&ChipUUID_CHIPoBLEChar_TX, charId) ? value_chipoble_tx : 0); - ChipDeviceEvent event; - - if (cId != 0) - { - if (blekw_send_event(conId, cId, data->Start(), data->DataLength()) != BLE_OK) - { - err = CHIP_ERROR_SENDING_BLOCKED; - } - else - { - event.Type = DeviceEventType::kCHIPoBLEIndicateConfirm; - event.CHIPoBLEIndicateConfirm.ConId = conId; - err = PlatformMgr().PostEvent(&event); - } - - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "BLEManagerImpl::SendIndication() failed: %s", ErrorStr(err)); - return false; - } - return true; - } - return false; -} - -BLEManagerImpl::ble_err_t BLEManagerImpl::blekw_send_event(int8_t connection_handle, uint16_t handle, uint8_t * data, uint32_t len) -{ - osaEventFlags_t event_mask; - -#if CHIP_DEVICE_CHIP0BLE_DEBUG - ChipLogProgress(DeviceLayer, "Trying to send event."); -#endif - - if (connection_handle < 0 || handle <= 0) - { - ChipLogProgress(DeviceLayer, "BLE Event - Bad Handle"); - return BLE_E_FAIL; - } - - if (len > 0 && data == NULL) - { - ChipLogProgress(DeviceLayer, "BLE Event - Invalid Data"); - return BLE_E_FAIL; - } - - /************* Send the indication *************/ - if (OSA_EventClear(event_msg, CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED | CHIP_BLE_KW_EVNT_INDICATION_FAILED) != osaStatus_Success) - { - ChipLogProgress(DeviceLayer, "BLE Event - Can't clear OSA Events"); - return BLE_E_FAIL; - } - - if (GattServer_SendInstantValueIndication(connection_handle, handle, len, data) != gBleSuccess_c) - { - ChipLogProgress(DeviceLayer, "BLE Event - Can't sent indication"); - return BLE_E_FAIL; - } - - if (OSA_EventWait(event_msg, CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED | CHIP_BLE_KW_EVNT_INDICATION_FAILED, FALSE, - CHIP_BLE_KW_EVNT_TIMEOUT, &event_mask) != osaStatus_Success) - { - ChipLogProgress(DeviceLayer, "BLE Event - OSA Event failed"); - return BLE_E_FAIL; - } - - if (event_mask & CHIP_BLE_KW_EVNT_INDICATION_FAILED) - { - ChipLogProgress(DeviceLayer, "BLE Event - Sent Failed"); - return BLE_E_FAIL; - } - -#if CHIP_DEVICE_CHIP0BLE_DEBUG - ChipLogProgress(DeviceLayer, "BLE Event - Sent :-) "); -#endif - - return BLE_OK; -} -/******************************************************************************* - * Private functions - *******************************************************************************/ CHIP_ERROR BLEManagerImpl::blekw_controller_init(void) { mControllerTaskEvent = OSA_EventCreate(TRUE); @@ -580,26 +130,6 @@ CHIP_ERROR BLEManagerImpl::blekw_controller_init(void) return CHIP_ERROR_NO_MEMORY; } - /* Setup Interrupt priorities of Interrupt handlers that are used - * in application to meet requirements of FreeRTOS */ - - // BLE_DP_IRQHandler - NVIC_SetPriority(BLE_DP_IRQn, configMAX_PRIORITIES - 1); - // BLE_DP0_IRQHandler - NVIC_SetPriority(BLE_DP0_IRQn, configMAX_PRIORITIES - 1); - // BLE_DP1_IRQHandler - NVIC_SetPriority(BLE_DP1_IRQn, configMAX_PRIORITIES - 1); - // BLE_DP2_IRQHandler - NVIC_SetPriority(BLE_DP2_IRQn, configMAX_PRIORITIES - 1); - // BLE_LL_ALL_IRQHandler - NVIC_SetPriority(BLE_LL_ALL_IRQn, configMAX_PRIORITIES - 1); - - /* Check for available memory storage */ - if (!Ble_CheckMemoryStorage()) - { - return CHIP_ERROR_NO_MEMORY; - } - /* BLE Controller Init */ if (osaStatus_Success != Controller_Init(Ble_HciRecv)) { @@ -609,1072 +139,8 @@ CHIP_ERROR BLEManagerImpl::blekw_controller_init(void) return CHIP_NO_ERROR; } -void BLEManagerImpl::Host_Task(osaTaskParam_t argument) -{ - Host_TaskHandler((void *) NULL); -} - -CHIP_ERROR BLEManagerImpl::blekw_host_init(void) -{ - /* Initialization of task related */ - gHost_TaskEvent = OSA_EventCreate(TRUE); - if (!gHost_TaskEvent) - { - return CHIP_ERROR_NO_MEMORY; - } - - /* Initialization of task message queue */ - MSG_InitQueue(&gApp2Host_TaskQueue); - MSG_InitQueue(&gHci2Host_TaskQueue); - - /* Task creation */ - if (pdPASS != xTaskCreate(Host_Task, "hostTask", HOST_TASK_STACK_SIZE, (void *) 0, HOST_TASK_PRIORITY, NULL)) - { - return CHIP_ERROR_NO_MEMORY; - } - - return CHIP_NO_ERROR; -} - -BLEManagerImpl::ble_err_t BLEManagerImpl::blekw_start_advertising(gapAdvertisingParameters_t * adv_params, - gapAdvertisingData_t * adv, gapScanResponseData_t * scnrsp) -{ - osaEventFlags_t event_mask; - - /************* Set the advertising parameters *************/ - OSA_EventClear(event_msg, (CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE)); - - /* Set the advertising parameters */ - if (Gap_SetAdvertisingParameters(adv_params) != gBleSuccess_c) - { - vTaskDelay(1); - - /* Retry, just to make sure before giving up and sending an error. */ - if (Gap_SetAdvertisingParameters(adv_params) != gBleSuccess_c) - { - return BLE_E_SET_ADV_PARAMS; - } - } - - if (OSA_EventWait(event_msg, (CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE), FALSE, - CHIP_BLE_KW_EVNT_TIMEOUT, &event_mask) != osaStatus_Success) - { - return BLE_E_ADV_PARAMS_FAILED; - } - - if (event_mask & CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED) - { - return BLE_E_ADV_PARAMS_FAILED; - } - - /************* Set the advertising data *************/ - OSA_EventClear(event_msg, (CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE)); - - /* Set the advertising data */ - if (Gap_SetAdvertisingData(adv, scnrsp) != gBleSuccess_c) - { - return BLE_E_SET_ADV_DATA; - } - - if (OSA_EventWait(event_msg, (CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED | CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE), FALSE, - CHIP_BLE_KW_EVNT_TIMEOUT, &event_mask) != osaStatus_Success) - { - return BLE_E_ADV_SETUP_FAILED; - } - - if (event_mask & CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED) - { - return BLE_E_ADV_SETUP_FAILED; - } - - /************* Start the advertising *************/ - OSA_EventClear(event_msg, (CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED)); +} // namespace Internal +} // namespace DeviceLayer +} // namespace chip - if (gBleSuccess_c != Gap_CreateRandomDeviceAddress(NULL, NULL)) - { - return BLE_E_SET_ADV_PARAMS; - } - - if (OSA_EventWait(event_msg, CHIP_BLE_KW_EVNT_RND_ADDR_SET, FALSE, CHIP_BLE_KW_EVNT_TIMEOUT, &event_mask) != osaStatus_Success) - { - return BLE_E_ADV_PARAMS_FAILED; - } - - /* Start the advertising */ - if (Gap_StartAdvertising(blekw_gap_advertising_cb, blekw_gap_connection_cb) != gBleSuccess_c) - { - return BLE_E_START_ADV; - } - -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) - PWR_DisallowDeviceToSleep(); -#endif - - if (OSA_EventWait(event_msg, (CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED), FALSE, CHIP_BLE_KW_EVNT_TIMEOUT, - &event_mask) != osaStatus_Success) - { -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) - PWR_AllowDeviceToSleep(); -#endif - return BLE_E_START_ADV_FAILED; - } - - if (event_mask & CHIP_BLE_KW_EVNT_ADV_FAILED) - { -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) - PWR_AllowDeviceToSleep(); -#endif - return BLE_E_START_ADV_FAILED; - } - -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) - PWR_AllowDeviceToSleep(); -#endif - - return BLE_OK; -} - -BLEManagerImpl::ble_err_t BLEManagerImpl::blekw_stop_advertising(void) -{ - osaEventFlags_t event_mask; - bleResult_t res; - - OSA_EventClear(event_msg, (CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED)); - - /* Stop the advertising data */ - res = Gap_StopAdvertising(); - if (res != gBleSuccess_c) - { - ChipLogProgress(DeviceLayer, "Failed to stop advertising %d", res); - return BLE_E_STOP; - } - - if (OSA_EventWait(event_msg, (CHIP_BLE_KW_EVNT_ADV_CHANGED | CHIP_BLE_KW_EVNT_ADV_FAILED), FALSE, CHIP_BLE_KW_EVNT_TIMEOUT, - &event_mask) != osaStatus_Success) - { - ChipLogProgress(DeviceLayer, "Stop advertising event timeout."); - return BLE_E_ADV_CHANGED; - } - - if (event_mask & CHIP_BLE_KW_EVNT_ADV_FAILED) - { - ChipLogProgress(DeviceLayer, "Stop advertising flat out failed."); - return BLE_E_ADV_FAILED; - } - - return BLE_OK; -} - -CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) -{ - ble_err_t err; - CHIP_ERROR chipErr; - uint16_t discriminator; - uint16_t advInterval = 0; - gapAdvertisingData_t adv = { 0 }; - gapAdStructure_t adv_data[BLEKW_ADV_MAX_NO] = { { 0 } }; - gapAdStructure_t scan_rsp_data[BLEKW_SCAN_RSP_MAX_NO] = { { 0 } }; - uint8_t advPayload[BLEKW_MAX_ADV_DATA_LEN] = { 0 }; - gapScanResponseData_t scanRsp = { 0 }; - gapAdvertisingParameters_t adv_params = { 0 }; - uint8_t chipAdvDataFlags = (gLeGeneralDiscoverableMode_c | gBrEdrNotSupported_c); - uint8_t chipOverBleService[2]; - ChipBLEDeviceIdentificationInfo mDeviceIdInfo = { 0 }; - uint8_t mDeviceIdInfoLength = 0; - - chipErr = GetCommissionableDataProvider()->GetSetupDiscriminator(discriminator); - if (chipErr != CHIP_NO_ERROR) - { - return chipErr; - } - - if (!mFlags.Has(Flags::kDeviceNameSet)) - { - memset(mDeviceName, 0, kMaxDeviceNameLength); - snprintf(mDeviceName, kMaxDeviceNameLength, "%s%04u", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, discriminator); - } - - /**************** Prepare advertising data *******************************************/ - adv.cNumAdStructures = BLEKW_ADV_MAX_NO; - - chipErr = ConfigurationMgr().GetBLEDeviceIdentificationInfo(mDeviceIdInfo); - SuccessOrExit(chipErr); - mDeviceIdInfoLength = sizeof(mDeviceIdInfo); - - if ((mDeviceIdInfoLength + CHIP_ADV_SHORT_UUID_LEN + 1) > BLEKW_MAX_ADV_DATA_LEN) - { - return CHIP_ERROR_INCORRECT_STATE; - } - - adv_data[0].length = 0x02; - adv_data[0].adType = gAdFlags_c; - adv_data[0].aData = (uint8_t *) (&chipAdvDataFlags); - - adv_data[1].length = static_cast(mDeviceIdInfoLength + CHIP_ADV_SHORT_UUID_LEN + 1); - adv_data[1].adType = gAdServiceData16bit_c; - memcpy(advPayload, ShortUUID_CHIPoBLEService, CHIP_ADV_SHORT_UUID_LEN); - memcpy(&advPayload[CHIP_ADV_SHORT_UUID_LEN], (void *) &mDeviceIdInfo, mDeviceIdInfoLength); - adv_data[1].aData = advPayload; - - adv.aAdStructures = adv_data; - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - ReturnErrorOnFailure(EncodeAdditionalDataTlv()); -#endif - - /**************** Prepare scan response data *******************************************/ - scanRsp.cNumAdStructures = BLEKW_SCAN_RSP_MAX_NO; - - scan_rsp_data[0].length = static_cast(strlen(mDeviceName) + 1); - scan_rsp_data[0].adType = gAdCompleteLocalName_c; - scan_rsp_data[0].aData = (uint8_t *) mDeviceName; - - scan_rsp_data[1].length = sizeof(chipOverBleService) + 1; - scan_rsp_data[1].adType = gAdComplete16bitServiceList_c; - chipOverBleService[0] = ShortUUID_CHIPoBLEService[0]; - chipOverBleService[1] = ShortUUID_CHIPoBLEService[1]; - scan_rsp_data[1].aData = (uint8_t *) chipOverBleService; - - scanRsp.aAdStructures = scan_rsp_data; - - /**************** Prepare advertising parameters *************************************/ - if (mFlags.Has(Flags::kFastAdvertisingEnabled)) - { - advInterval = CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_INTERVAL_MAX; - } - else - { - advInterval = CHIP_DEVICE_CONFIG_BLE_SLOW_ADVERTISING_INTERVAL_MAX; - } - advInterval = (uint16_t)(advInterval * 0.625F); - - adv_params.minInterval = adv_params.maxInterval = advInterval; - adv_params.advertisingType = gAdvConnectableUndirected_c; - adv_params.ownAddressType = gBleAddrTypeRandom_c; - adv_params.peerAddressType = gBleAddrTypePublic_c; - memset(adv_params.peerAddress, 0, gcBleDeviceAddressSize_c); - adv_params.channelMap = (gapAdvertisingChannelMapFlags_t)(gAdvChanMapFlag37_c | gAdvChanMapFlag38_c | gAdvChanMapFlag39_c); - adv_params.filterPolicy = gProcessAll_c; - - err = blekw_start_advertising(&adv_params, &adv, &scanRsp); - if (err == BLE_OK) - { - ChipLogProgress(DeviceLayer, "Started Advertising at %d ms", advInterval); - } - else - { - ChipLogProgress(DeviceLayer, "Advertising error 0x%x!", err); - mFlags.Clear(Flags::kAdvertising); - return CHIP_ERROR_INCORRECT_STATE; - } - -exit: - return chipErr; -} - -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING -CHIP_ERROR BLEManagerImpl::EncodeAdditionalDataTlv() -{ - CHIP_ERROR err = CHIP_NO_ERROR; - BitFlags dataFields; - AdditionalDataPayloadGeneratorParams params; - -#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) - uint8_t rotatingDeviceIdUniqueId[ConfigurationManager::kRotatingDeviceIDUniqueIDLength] = {}; - MutableByteSpan rotatingDeviceIdUniqueIdSpan(rotatingDeviceIdUniqueId); - - err = DeviceLayer::GetDeviceInstanceInfoProvider()->GetRotatingDeviceIdUniqueId(rotatingDeviceIdUniqueIdSpan); - SuccessOrExit(err); - err = ConfigurationMgr().GetLifetimeCounter(params.rotatingDeviceIdLifetimeCounter); - SuccessOrExit(err); - params.rotatingDeviceIdUniqueId = rotatingDeviceIdUniqueIdSpan; - dataFields.Set(AdditionalDataFields::RotatingDeviceId); -#endif /* CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) */ - err = - AdditionalDataPayloadGenerator().generateAdditionalDataPayload(params, sInstance.c3AdditionalDataBufferHandle, dataFields); - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Failed to generate TLV encoded Additional Data (%s)", __func__); - } - - return err; -} - -void BLEManagerImpl::HandleC3ReadRequest(blekw_msg_t * msg) -{ - bleResult_t result; - blekw_att_read_data_t * att_rd_data = (blekw_att_read_data_t *) msg->data.data; - deviceId_t deviceId = att_rd_data->device_id; - uint16_t handle = att_rd_data->handle; - uint16_t length = sInstance.c3AdditionalDataBufferHandle->DataLength(); - const uint8_t * data = (const uint8_t *) sInstance.c3AdditionalDataBufferHandle->Start(); - - result = GattDb_WriteAttribute(handle, length, data); - if (result != gBleSuccess_c) - { - ChipLogError(DeviceLayer, "Failed to write C3 characteristic: %d", result); - } - - result = GattServer_SendAttributeReadStatus(deviceId, handle, gAttErrCodeNoError_c); - if (result != gBleSuccess_c) - { - ChipLogError(DeviceLayer, "Failed to send response to C3 read request: %d", result); - } -} -#endif /* CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING */ - -CHIP_ERROR BLEManagerImpl::StartAdvertising(void) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - mFlags.Set(Flags::kAdvertising); - mFlags.Clear(Flags::kRestartAdvertising); - - if (mFlags.Has(Flags::kFastAdvertisingEnabled)) - { - StartBleAdvTimeoutTimer(CHIP_DEVICE_CONFIG_BLE_FAST_ADVERTISING_TIMEOUT); - } - - err = ConfigureAdvertisingData(); - - if (err == CHIP_NO_ERROR) - /* schedule NFC emulation stop */ - { - ChipDeviceEvent advChange; - advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; - advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Started; - err = PlatformMgr().PostEvent(&advChange); - } - - return err; -} - -CHIP_ERROR BLEManagerImpl::StopAdvertising(void) -{ - ble_err_t err; - CHIP_ERROR error = CHIP_NO_ERROR; - - if (mFlags.Has(Flags::kAdvertising)) - { - mFlags.Clear(Flags::kAdvertising); - mFlags.Clear(Flags::kFastAdvertisingEnabled); - mFlags.Clear(Flags::kRestartAdvertising); - - err = blekw_stop_advertising(); - if (err != BLE_OK) - { - return CHIP_ERROR_INCORRECT_STATE; - } - else - { - /* schedule NFC emulation stop */ - { - ChipDeviceEvent advChange; - advChange.Type = DeviceEventType::kCHIPoBLEAdvertisingChange; - advChange.CHIPoBLEAdvertisingChange.Result = kActivity_Stopped; - error = PlatformMgr().PostEvent(&advChange); - } - } - } - CancelBleAdvTimeoutTimer(); - - return error; -} - -void BLEManagerImpl::DriveBLEState(void) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - - // Check if BLE stack is initialized - VerifyOrExit(mFlags.Has(Flags::kK32WBLEStackInitialized), /* */); - - // Start advertising if needed... - if (mServiceMode == ConnectivityManager::kCHIPoBLEServiceMode_Enabled && mFlags.Has(Flags::kAdvertisingEnabled)) - { - // Start/re-start advertising if not already started, or if there is a pending change - // to the advertising configuration. - if (!mFlags.Has(Flags::kAdvertising) || mFlags.Has(Flags::kRestartAdvertising)) - { - err = StartAdvertising(); - SuccessOrExit(err); - } - } - // Otherwise, stop advertising if it is enabled. - else if (mFlags.Has(Flags::kAdvertising)) - { - err = StopAdvertising(); - SuccessOrExit(err); - ChipLogProgress(DeviceLayer, "Stopped Advertising"); - } - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "Disabling CHIPoBLE service due to error: %s", ErrorStr(err)); - mServiceMode = ConnectivityManager::kCHIPoBLEServiceMode_Disabled; - } -} - -void BLEManagerImpl::DriveBLEState(intptr_t arg) -{ - sInstance.DriveBLEState(); -} - -/******************************************************************************* - * BLE App Task Processing - *******************************************************************************/ -void BLEManagerImpl::bleAppTask(void * p_arg) -{ - while (true) - { - xEventGroupWaitBits(bleAppTaskLoopEvent, LOOP_EV_BLE, true, false, portMAX_DELAY); - - if (MSG_Pending(&blekw_msg_list)) - { - /* There is message from the BLE tasks to solve */ - blekw_msg_t * msg = (blekw_msg_t *) MSG_DeQueue(&blekw_msg_list); - - assert(msg != NULL); - - if (msg->type == BLE_KW_MSG_ERROR) - { - if (msg->data.u8 == BLE_KW_MSG_2M_UPGRADE_ERROR) - { - ChipLogProgress(DeviceLayer, - "Warning. BLE is using 1Mbps. Couldn't upgrade to 2Mbps, " - "maybe the peer is missing 2Mbps support."); - } - else - { - ChipLogProgress(DeviceLayer, "BLE Error: %d.\n", msg->data.u8); - } - } - else if (msg->type == BLE_KW_MSG_CONNECTED) - { - sInstance.HandleConnectEvent(msg); - } - else if (msg->type == BLE_KW_MSG_DISCONNECTED) - { - sInstance.HandleConnectionCloseEvent(msg); - } - else if (msg->type == BLE_KW_MSG_MTU_CHANGED) - { - blekw_start_connection_timeout(); - ChipLogProgress(DeviceLayer, "BLE MTU size has been changed to %d.", msg->data.u16); - } - else if (msg->type == BLE_KW_MSG_ATT_WRITTEN || msg->type == BLE_KW_MSG_ATT_LONG_WRITTEN || - msg->type == BLE_KW_MSG_ATT_CCCD_WRITTEN) - { - sInstance.HandleWriteEvent(msg); - } - else if (msg->type == BLE_KW_MSG_ATT_READ) - { -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - blekw_att_read_data_t * att_rd_data = (blekw_att_read_data_t *) msg->data.data; - if (value_chipoble_c3 == att_rd_data->handle) - sInstance.HandleC3ReadRequest(msg); -#endif - } - else if (msg->type == BLE_KW_MSG_FORCE_DISCONNECT) - { - ChipLogProgress(DeviceLayer, "BLE connection timeout: Forcing disconnection."); - - /* Set the advertising parameters */ - if (Gap_Disconnect(g_device_id) != gBleSuccess_c) - { - ChipLogProgress(DeviceLayer, "Gap_Disconnect() failed."); - } - sInstance.RemoveConnection(g_device_id); - } - - /* Freed the message from the queue */ - MSG_Free(msg); - } - } -} - -void BLEManagerImpl::HandleConnectEvent(blekw_msg_t * msg) -{ - uint8_t device_id_loc = msg->data.u8; - ChipLogProgress(DeviceLayer, "BLE is connected with device: %d.\n", device_id_loc); - -#if gClkUseFro32K -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) - PWR_DisallowDeviceToSleep(); -#endif -#endif - - g_device_id = device_id_loc; - blekw_start_connection_timeout(); - sInstance.AddConnection(device_id_loc); - mFlags.Set(Flags::kRestartAdvertising); - PlatformMgr().ScheduleWork(DriveBLEState, 0); -} - -void BLEManagerImpl::HandleConnectionCloseEvent(blekw_msg_t * msg) -{ - uint8_t device_id_loc = msg->data.u8; - ChipLogProgress(DeviceLayer, "BLE is disconnected with device: %d.\n", device_id_loc); - -#if gClkUseFro32K -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) - PWR_AllowDeviceToSleep(); -#endif -#endif - - if (sInstance.RemoveConnection(device_id_loc)) - { - ChipDeviceEvent event; - event.Type = DeviceEventType::kCHIPoBLEConnectionError; - event.CHIPoBLEConnectionError.ConId = device_id_loc; - event.CHIPoBLEConnectionError.Reason = BLE_ERROR_REMOTE_DEVICE_DISCONNECTED; - - PlatformMgr().PostEventOrDie(&event); - mFlags.Set(Flags::kRestartAdvertising); - mFlags.Set(Flags::kFastAdvertisingEnabled); - PlatformMgr().ScheduleWork(DriveBLEState, 0); - } -} - -void BLEManagerImpl::HandleWriteEvent(blekw_msg_t * msg) -{ - blekw_att_written_data_t * att_wr_data = (blekw_att_written_data_t *) msg->data.data; - attErrorCode_t status = gAttErrCodeNoError_c; - -#if CHIP_DEVICE_CHIP0BLE_DEBUG - ChipLogProgress(DeviceLayer, "Attribute write request(device: %d,handle: %d).", att_wr_data->device_id, att_wr_data->handle); -#endif - - blekw_start_connection_timeout(); - - if (value_chipoble_rx == att_wr_data->handle) - { - sInstance.HandleRXCharWrite(msg); - } - else if (cccd_chipoble_tx == att_wr_data->handle) - { - sInstance.HandleTXCharCCCDWrite(msg); - } - - /* TODO: do we need to send the status also for CCCD_WRITTEN? */ - if (msg->type != BLE_KW_MSG_ATT_CCCD_WRITTEN) - { - bleResult_t res = GattServer_SendAttributeWrittenStatus(att_wr_data->device_id, att_wr_data->handle, status); - - if (res != gBleSuccess_c) - { - ChipLogProgress(DeviceLayer, "GattServer_SendAttributeWrittenStatus returned %d", res); - } - } -} - -void BLEManagerImpl::HandleTXCharCCCDWrite(blekw_msg_t * msg) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - CHIPoBLEConState * bleConnState; - bool indicationsEnabled; - ChipDeviceEvent event; - blekw_att_written_data_t * att_wr_data = (blekw_att_written_data_t *) msg->data.data; - uint16_t writeLen = att_wr_data->length; - uint8_t * data = att_wr_data->data; - - VerifyOrExit(writeLen != 0, err = CHIP_ERROR_INCORRECT_STATE); - bleConnState = GetConnectionState(att_wr_data->device_id, false); - VerifyOrExit(bleConnState != NULL, err = CHIP_ERROR_NO_MEMORY); - - /* Determine if the client is enabling or disabling indications. - * TODO: Check the indications corresponding bit - */ - indicationsEnabled = (*data); - -#if CHIP_DEVICE_CHIP0BLE_DEBUG - ChipLogProgress(DeviceLayer, "CHIPoBLE %s received", indicationsEnabled ? "subscribe" : "unsubscribe"); -#endif - - if (indicationsEnabled) - { - // If indications are not already enabled for the connection... - if (!bleConnState->subscribed) - { - bleConnState->subscribed = 1; - /* Post an event to the CHIP queue to process either a CHIPoBLE - * Subscribe or Unsubscribe based on whether the client - * is enabling or disabling indications. */ - { - event.Type = DeviceEventType::kCHIPoBLESubscribe; - event.CHIPoBLESubscribe.ConId = att_wr_data->device_id; - err = PlatformMgr().PostEvent(&event); - } - } - } - else - { - bleConnState->subscribed = 0; - event.Type = DeviceEventType::kCHIPoBLEUnsubscribe; - event.CHIPoBLESubscribe.ConId = att_wr_data->device_id; - err = PlatformMgr().PostEvent(&event); - } - -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "HandleTXCharCCCDWrite() failed: %s", ErrorStr(err)); - } -} - -void BLEManagerImpl::HandleRXCharWrite(blekw_msg_t * msg) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - System::PacketBufferHandle buf; - blekw_att_written_data_t * att_wr_data = (blekw_att_written_data_t *) msg->data.data; - uint16_t writeLen = att_wr_data->length; - uint8_t * data = att_wr_data->data; - - // Copy the data to a PacketBuffer. - buf = System::PacketBufferHandle::New(writeLen); - VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY); - VerifyOrExit(buf->AvailableDataLength() >= writeLen, err = CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(buf->Start(), data, writeLen); - buf->SetDataLength(writeLen); - -#if CHIP_DEVICE_CHIP0BLE_DEBUG - ChipLogDetail(DeviceLayer, - "Write request/command received for" - "CHIPoBLE RX characteristic (con %u, len %u)", - att_wr_data->device_id, buf->DataLength()); -#endif - - // Post an event to the CHIP queue to deliver the data into the CHIP stack. - { - ChipDeviceEvent event; - event.Type = DeviceEventType::kCHIPoBLEWriteReceived; - event.CHIPoBLEWriteReceived.ConId = att_wr_data->device_id; - event.CHIPoBLEWriteReceived.Data = std::move(buf).UnsafeRelease(); - err = PlatformMgr().PostEvent(&event); - } -exit: - if (err != CHIP_NO_ERROR) - { - ChipLogError(DeviceLayer, "HandleRXCharWrite() failed: %s", ErrorStr(err)); - } -} -/******************************************************************************* - * BLE stack callbacks - *******************************************************************************/ -void BLEManagerImpl::blekw_generic_cb(gapGenericEvent_t * pGenericEvent) -{ - /* Call BLE Conn Manager */ - BleConnManager_GenericEvent(pGenericEvent); - - switch (pGenericEvent->eventType) - { - case gInternalError_c: - /* Notify the CHIP that the BLE hardware report fail */ - ChipLogProgress(DeviceLayer, "BLE Internal Error: Code 0x%04X, Source 0x%08X, HCI OpCode %d.\n", - pGenericEvent->eventData.internalError.errorCode, pGenericEvent->eventData.internalError.errorSource, - pGenericEvent->eventData.internalError.hciCommandOpcode); - if ((gHciUnsupportedRemoteFeature_c == pGenericEvent->eventData.internalError.errorCode) && - (gLeSetPhy_c == pGenericEvent->eventData.internalError.errorSource)) - { - (void) blekw_msg_add_u8(BLE_KW_MSG_ERROR, BLE_KW_MSG_2M_UPGRADE_ERROR); - } - else - { - (void) blekw_msg_add_u8(BLE_KW_MSG_ERROR, BLE_INTERNAL_ERROR); - } - break; - - case gAdvertisingSetupFailed_c: - OSA_EventSet(event_msg, CHIP_BLE_KW_EVNT_ADV_SETUP_FAILED); - break; - - case gAdvertisingParametersSetupComplete_c: - OSA_EventSet(event_msg, CHIP_BLE_KW_EVNT_ADV_PAR_SETUP_COMPLETE); - break; - - case gAdvertisingDataSetupComplete_c: - OSA_EventSet(event_msg, CHIP_BLE_KW_EVNT_ADV_DAT_SETUP_COMPLETE); - break; - - case gRandomAddressReady_c: - Gap_SetRandomAddress(pGenericEvent->eventData.addrReady.aAddress); - break; - - case gRandomAddressSet_c: - OSA_EventSet(event_msg, CHIP_BLE_KW_EVNT_RND_ADDR_SET); - break; - - case gInitializationComplete_c: - /* Common GAP configuration */ - BleConnManager_GapCommonConfig(); - - /* Set the local synchronization event */ - OSA_EventSet(event_msg, CHIP_BLE_KW_EVNT_INIT_COMPLETE); - break; - default: - break; - } -} - -void BLEManagerImpl::blekw_gap_advertising_cb(gapAdvertisingEvent_t * pAdvertisingEvent) -{ - if (pAdvertisingEvent->eventType == gAdvertisingStateChanged_c) - { - /* Set the local synchronization event */ - OSA_EventSet(event_msg, CHIP_BLE_KW_EVNT_ADV_CHANGED); - } - else - { - /* The advertisement start failed */ - ChipLogProgress(DeviceLayer, "Advertising failed: event=%d reason=0x%04X\n", pAdvertisingEvent->eventType, - pAdvertisingEvent->eventData.failReason); - - /* Set the local synchronization event */ - OSA_EventSet(event_msg, CHIP_BLE_KW_EVNT_ADV_FAILED); - } -} - -void BLEManagerImpl::blekw_gap_connection_cb(deviceId_t deviceId, gapConnectionEvent_t * pConnectionEvent) -{ - /* Call BLE Conn Manager */ - BleConnManager_GapPeripheralEvent(deviceId, pConnectionEvent); - - if (pConnectionEvent->eventType == gConnEvtConnected_c) - { -#if CHIP_DEVICE_CONFIG_BLE_SET_PHY_2M_REQ - ChipLogProgress(DeviceLayer, "BLE K32W: Trying to set the PHY to 2M"); - - (void) Gap_LeSetPhy(FALSE, deviceId, 0, gConnPhyUpdateReqTxPhySettings_c, gConnPhyUpdateReqRxPhySettings_c, - (uint16_t) gConnPhyUpdateReqPhyOptions_c); -#endif - - /* Notify App Task that the BLE is connected now */ - (void) blekw_msg_add_u8(BLE_KW_MSG_CONNECTED, (uint8_t) deviceId); -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) - PWR_AllowDeviceToSleep(); -#endif - } - else if (pConnectionEvent->eventType == gConnEvtDisconnected_c) - { - blekw_stop_connection_timeout(); - - /* Notify App Task that the BLE is disconnected now */ - (void) blekw_msg_add_u8(BLE_KW_MSG_DISCONNECTED, (uint8_t) deviceId); - -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) - if (bleAppStopInProgress == TRUE) - { - bleAppStopInProgress = FALSE; - PWR_AllowDeviceToSleep(); - } -#endif - } - else if (pConnectionEvent->eventType == gConnEvtPairingRequest_c) - { - /* Reject request for pairing */ - Gap_RejectPairing(deviceId, gPairingNotSupported_c); - } - else if (pConnectionEvent->eventType == gConnEvtAuthenticationRejected_c) - { - ChipLogProgress(DeviceLayer, "BLE Authentication rejected (reason:%d).\n", - pConnectionEvent->eventData.authenticationRejectedEvent.rejectReason); - } -} - -/* Called by BLE when a connect is received */ -void BLEManagerImpl::BLE_SignalFromISRCallback(void) -{ -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) - PWR_DisallowDeviceToSleep(); -#endif /* cPWR_UsePowerDownMode */ -} - -void BLEManagerImpl::blekw_connection_timeout_cb(TimerHandle_t timer) -{ - (void) blekw_msg_add_u8(BLE_KW_MSG_FORCE_DISCONNECT, 0); -} - -void BLEManagerImpl::blekw_start_connection_timeout(void) -{ - xTimerReset(connectionTimeout, 0); -} - -void BLEManagerImpl::blekw_stop_connection_timeout(void) -{ - ChipLogProgress(DeviceLayer, "Stopped connectionTimeout timer."); - xTimerStop(connectionTimeout, 0); -} - -void BLEManagerImpl::blekw_gatt_server_cb(deviceId_t deviceId, gattServerEvent_t * pServerEvent) -{ - switch (pServerEvent->eventType) - { - case gEvtMtuChanged_c: { - uint16_t tempMtu = 0; - - (void) Gatt_GetMtu(deviceId, &tempMtu); - blekw_msg_add_u16(BLE_KW_MSG_MTU_CHANGED, tempMtu); - break; - } - - case gEvtAttributeWritten_c: - blekw_msg_add_att_written(BLE_KW_MSG_ATT_WRITTEN, deviceId, pServerEvent->eventData.attributeWrittenEvent.handle, - pServerEvent->eventData.attributeWrittenEvent.aValue, - pServerEvent->eventData.attributeWrittenEvent.cValueLength); - break; - - case gEvtLongCharacteristicWritten_c: - blekw_msg_add_att_written(BLE_KW_MSG_ATT_LONG_WRITTEN, deviceId, pServerEvent->eventData.longCharWrittenEvent.handle, - pServerEvent->eventData.longCharWrittenEvent.aValue, - pServerEvent->eventData.longCharWrittenEvent.cValueLength); - break; - - case gEvtAttributeRead_c: - blekw_msg_add_att_read(BLE_KW_MSG_ATT_READ, deviceId, pServerEvent->eventData.attributeReadEvent.handle); - break; - - case gEvtCharacteristicCccdWritten_c: { - uint16_t cccd_val = pServerEvent->eventData.charCccdWrittenEvent.newCccd; - - blekw_msg_add_att_written(BLE_KW_MSG_ATT_CCCD_WRITTEN, deviceId, pServerEvent->eventData.charCccdWrittenEvent.handle, - (uint8_t *) &cccd_val, 2); - break; - } - - case gEvtHandleValueConfirmation_c: - /* Set the local synchronization event */ - OSA_EventSet(event_msg, CHIP_BLE_KW_EVNT_INDICATION_CONFIRMED); - break; - - case gEvtError_c: - if (pServerEvent->eventData.procedureError.procedureType == gSendIndication_c) - { - /* Set the local synchronization event */ - OSA_EventSet(event_msg, CHIP_BLE_KW_EVNT_INDICATION_FAILED); - } - else - { - ChipLogProgress(DeviceLayer, "BLE Gatt Server Error: Code 0x%04X, Source %d.\n", - pServerEvent->eventData.procedureError.error, pServerEvent->eventData.procedureError.procedureType); - - /* Notify CHIP BLE App Task that the BLE hardware report fail */ - (void) blekw_msg_add_u8(BLE_KW_MSG_ERROR, BLE_INTERNAL_GATT_ERROR); - } - break; - - default: - break; - } -} -/******************************************************************************* - * Add to message queue functions - *******************************************************************************/ -CHIP_ERROR BLEManagerImpl::blekw_msg_add_att_written(blekw_msg_type_t type, uint8_t device_id, uint16_t handle, uint8_t * data, - uint16_t length) -{ - blekw_msg_t * msg = NULL; - blekw_att_written_data_t * att_wr_data; - - /* Allocate a buffer with enough space to store the packet */ - msg = (blekw_msg_t *) MSG_Alloc(sizeof(blekw_msg_t) + sizeof(blekw_att_written_data_t) + length); - - if (!msg) - { - return CHIP_ERROR_NO_MEMORY; - assert(0); - } - - msg->type = type; - msg->length = sizeof(blekw_att_written_data_t) + length; - att_wr_data = (blekw_att_written_data_t *) msg->data.data; - att_wr_data->device_id = device_id; - att_wr_data->handle = handle; - att_wr_data->length = length; - FLib_MemCpy(att_wr_data->data, data, length); - - /* Put message in the queue */ - if (gListOk_c != MSG_Queue(&blekw_msg_list, msg)) - { - assert(0); - } - - /* Notify BLE-APP Task to serve the BLE subsystem */ - blekw_new_data_received_notification(LOOP_EV_BLE); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::blekw_msg_add_att_read(blekw_msg_type_t type, uint8_t device_id, uint16_t handle) -{ - blekw_msg_t * msg = NULL; - blekw_att_read_data_t * att_rd_data; - - /* Allocate a buffer with enough space to store the packet */ - msg = (blekw_msg_t *) MSG_Alloc(sizeof(blekw_msg_t) + sizeof(blekw_att_read_data_t)); - - if (!msg) - { - return CHIP_ERROR_NO_MEMORY; - assert(0); - } - - msg->type = type; - msg->length = sizeof(blekw_att_read_data_t); - att_rd_data = (blekw_att_read_data_t *) msg->data.data; - att_rd_data->device_id = device_id; - att_rd_data->handle = handle; - - /* Put message in the queue */ - if (gListOk_c != MSG_Queue(&blekw_msg_list, msg)) - { - assert(0); - } - - /* Notify BLE-APP Task to serve the BLE subsystem */ - blekw_new_data_received_notification(LOOP_EV_BLE); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::blekw_msg_add_u8(blekw_msg_type_t type, uint8_t data) -{ - blekw_msg_t * msg = NULL; - - /* Allocate a buffer with enough space to store the packet */ - msg = (blekw_msg_t *) MSG_Alloc(sizeof(blekw_msg_t)); - - if (!msg) - { - return CHIP_ERROR_NO_MEMORY; - } - - msg->type = type; - msg->length = 0; - msg->data.u8 = data; - - /* Put message in the queue */ - MSG_Queue(&blekw_msg_list, msg); - - /* Notify BLE-APP Task to serve the BLE subsystem */ - blekw_new_data_received_notification(LOOP_EV_BLE); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR BLEManagerImpl::blekw_msg_add_u16(blekw_msg_type_t type, uint16_t data) -{ - blekw_msg_t * msg = NULL; - - /* Allocate a buffer with enough space to store the packet */ - msg = (blekw_msg_t *) MSG_Alloc(sizeof(blekw_msg_t)); - - if (!msg) - { - return CHIP_ERROR_NO_MEMORY; - } - - msg->type = type; - msg->length = 0; - msg->data.u16 = data; - - /* Put message in the queue */ - MSG_Queue(&blekw_msg_list, msg); - - /* Notify BLE-APP Task to serve the BLE subsystem */ - blekw_new_data_received_notification(LOOP_EV_BLE); - - return CHIP_NO_ERROR; -} - -/******************************************************************************* - * FreeRTOS Task Management Functions - *******************************************************************************/ -void BLEManagerImpl::blekw_new_data_received_notification(uint32_t mask) -{ - portBASE_TYPE taskToWake = pdFALSE; - - if (__get_IPSR()) - { - if (xEventGroupSetBitsFromISR(bleAppTaskLoopEvent, mask, &taskToWake) == pdPASS) - { - /* If xHigherPriorityTaskWoken is now set to pdTRUE then a context - switch should be requested. The macro used is port specific and will - be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to - the documentation page for the port being used. */ - portYIELD_FROM_ISR(taskToWake); - } - } - else - { - xEventGroupSetBits(bleAppTaskLoopEvent, mask); - } -} - -void BLEManagerImpl::BleAdvTimeoutHandler(TimerHandle_t xTimer) -{ - // If stop advertising fails (timeout on event wait), then - // rearm the timer as fast as possible to retry. - // Once stop advertising is successful, slow advertising can start. - auto err = sInstance.StopAdvertising(); - if (err != CHIP_NO_ERROR) - { - ChipLogDetail(DeviceLayer, "Stop advertising failed. Retrying..."); - StartBleAdvTimeoutTimer(portTICK_PERIOD_MS); - return; - } - - sInstance.mFlags.Clear(Flags::kFastAdvertisingEnabled); - ChipLogDetail(DeviceLayer, "Start slow advertisement"); - sInstance.StartAdvertising(); -} - -void BLEManagerImpl::CancelBleAdvTimeoutTimer(void) -{ - if (xTimerStop(sbleAdvTimeoutTimer, 0) == pdFAIL) - { - ChipLogError(DeviceLayer, "Failed to stop BledAdv timeout timer"); - } -} - -void BLEManagerImpl::StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs) -{ - if (xTimerIsTimerActive(sbleAdvTimeoutTimer)) - { - CancelBleAdvTimeoutTimer(); - } - - // timer is not active, change its period to required value (== restart). - // FreeRTOS- Block for a maximum of 100 ticks if the change period command - // cannot immediately be sent to the timer command queue. - if (xTimerChangePeriod(sbleAdvTimeoutTimer, aTimeoutInMs / portTICK_PERIOD_MS, 100) != pdPASS) - { - ChipLogError(DeviceLayer, "Failed to start BledAdv timeout timer"); - } -} - -bool BLEManagerImpl::blekw_stop_connection_internal(BLE_CONNECTION_OBJECT conId) -{ - ChipLogProgress(DeviceLayer, "Closing BLE GATT connection (con %u)", conId); - - if (Gap_Disconnect(conId) != gBleSuccess_c) - { - ChipLogProgress(DeviceLayer, "Gap_Disconnect() failed."); - return false; - } -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) - else - { - bleAppStopInProgress = TRUE; - PWR_DisallowDeviceToSleep(); - } -#endif - - return true; -} - -} // namespace Internal -} // namespace DeviceLayer -} // namespace chip -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE +#endif /* CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE */ diff --git a/src/platform/nxp/k32w/k32w0/BLEManagerImpl.h b/src/platform/nxp/k32w/k32w0/BLEManagerImpl.h index f946ef9a9a562c..52fd69007d9aa0 100644 --- a/src/platform/nxp/k32w/k32w0/BLEManagerImpl.h +++ b/src/platform/nxp/k32w/k32w0/BLEManagerImpl.h @@ -1,7 +1,6 @@ /* * - * Copyright (c) 2020-2021 Project CHIP Authors - * Copyright (c) 2020 Nest Labs, Inc. + * Copyright (c) 2021-2023 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -17,33 +16,20 @@ * limitations under the License. */ -/** - * @file - * Provides an implementation of the BLEManager singleton object - * for the K32W platforms. - */ - #pragma once #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include "Messaging.h" - -#include "fsl_os_abstraction.h" - -#include "ble_conn_manager.h" #include "ble_controller_task_config.h" #include "ble_general.h" #include "ble_host_task_config.h" -#include "ble_host_tasks.h" #include "controller_interface.h" -#include "gap_interface.h" -#include "gatt_db_dynamic.h" -#include "gatt_server_interface.h" -#include "FreeRTOS.h" -#include "event_groups.h" -#include "timers.h" +#include + +/* host task configuration */ +#define HOST_TASK_PRIORITY (4U) +#define HOST_TASK_STACK_SIZE (gHost_TaskStackSize_c / sizeof(StackType_t)) namespace chip { namespace DeviceLayer { @@ -51,214 +37,29 @@ namespace Internal { using namespace chip::Ble; -/** - * Concrete implementation of the BLEManager singleton object for the K32W platforms. - */ -class BLEManagerImpl final : public BLEManager, private BleLayer, private BlePlatformDelegate, private BleApplicationDelegate +class BLEManagerImpl : public BLEManagerCommon { +public: // Allow the BLEManager interface class to delegate method calls to // the implementation methods provided by this class. friend BLEManager; -private: - // ===== Members that implement the BLEManager internal interface. - - CHIP_ERROR _Init(void); - void _Shutdown() {} - bool _IsAdvertisingEnabled(void); - CHIP_ERROR _SetAdvertisingEnabled(bool val); - bool _IsAdvertising(void); - CHIP_ERROR _SetAdvertisingMode(BLEAdvertisingMode mode); - CHIP_ERROR _GetDeviceName(char * buf, size_t bufSize); - CHIP_ERROR _SetDeviceName(const char * deviceName); - uint16_t _NumConnections(void); - void _OnPlatformEvent(const ChipDeviceEvent * event); - BleLayer * _GetBleLayer(void); - - // ===== Members that implement virtual methods on BlePlatformDelegate. - - bool SubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, - const Ble::ChipBleUUID * charId) override; - bool UnsubscribeCharacteristic(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, - const Ble::ChipBleUUID * charId) override; - bool CloseConnection(BLE_CONNECTION_OBJECT conId) override; - uint16_t GetMTU(BLE_CONNECTION_OBJECT conId) const override; - bool SendIndication(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, - System::PacketBufferHandle pBuf) override; - bool SendWriteRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, - System::PacketBufferHandle pBuf) override; - bool SendReadRequest(BLE_CONNECTION_OBJECT conId, const Ble::ChipBleUUID * svcId, const Ble::ChipBleUUID * charId, - System::PacketBufferHandle pBuf) override; - bool SendReadResponse(BLE_CONNECTION_OBJECT conId, BLE_READ_REQUEST_CONTEXT requestContext, const Ble::ChipBleUUID * svcId, - const Ble::ChipBleUUID * charId) override; - - // ===== Members that implement virtual methods on BleApplicationDelegate. - - void NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) override; - - // ===== Members for internal use by the following friends. - - friend BLEManager & BLEMgr(void); - friend BLEManagerImpl & BLEMgrImpl(void); + CHIP_ERROR InitHostController(ble_generic_cb_fp cb_fp) override; + BLEManagerCommon * GetImplInstance() override; +private: static BLEManagerImpl sInstance; - // ===== Private members reserved for use by this class only. - - enum class Flags : uint8_t - { - kAdvertisingEnabled = 0x0001, - kFastAdvertisingEnabled = 0x0002, - kAdvertising = 0x0004, - kRestartAdvertising = 0x0008, - kK32WBLEStackInitialized = 0x0010, - kDeviceNameSet = 0x0020, - }; - BitFlags mFlags; - - enum - { - kMaxConnections = BLE_LAYER_NUM_BLE_ENDPOINTS, - kMaxDeviceNameLength = 32, - kUnusedIndex = 0xFF, - }; - - typedef enum - { - BLE_KW_MSG_ERROR = 0x01, - BLE_KW_MSG_CONNECTED, - BLE_KW_MSG_DISCONNECTED, - BLE_KW_MSG_MTU_CHANGED, - BLE_KW_MSG_ATT_WRITTEN, - BLE_KW_MSG_ATT_LONG_WRITTEN, - BLE_KW_MSG_ATT_READ, - BLE_KW_MSG_ATT_CCCD_WRITTEN, - BLE_KW_MSG_FORCE_DISCONNECT, - } blekw_msg_type_t; - - typedef struct hk_ble_kw_msg_s - { - blekw_msg_type_t type; - uint16_t length; - union - { - uint8_t u8; - uint16_t u16; - uint32_t u32; - uint8_t data[1]; - char * str; - } data; - } blekw_msg_t; - - typedef enum ble_err_t - { - BLE_OK = 0, - BLE_INTERNAL_GATT_ERROR, - BLE_E_SET_ADV_PARAMS, - BLE_E_ADV_PARAMS_FAILED, - BLE_E_SET_ADV_DATA, - BLE_E_ADV_CHANGED, - BLE_E_ADV_FAILED, - BLE_E_ADV_SETUP_FAILED, - BLE_E_START_ADV, - BLE_E_STOP, - BLE_E_FAIL, - BLE_E_START_ADV_FAILED, - BLE_INTERNAL_ERROR, - BLE_KW_MSG_2M_UPGRADE_ERROR, - } ble_err_t; - - typedef struct ble_att_written_data_s - { - uint8_t device_id; - uint16_t handle; - uint16_t length; - uint8_t data[1]; - } blekw_att_written_data_t; - - typedef struct hk_ble_att_read_data_s - { - uint8_t device_id; - uint16_t handle; - } blekw_att_read_data_t; - - struct CHIPoBLEConState - { - uint16_t mtu : 10; - uint16_t allocated : 1; - uint16_t subscribed : 1; - uint16_t unused : 4; - uint8_t connectionHandle; - uint8_t bondingHandle; - }; - CHIPoBLEConState mBleConnections[kMaxConnections]; - - CHIPoBLEServiceMode mServiceMode; - uint16_t mNumGAPCons; - uint8_t mAdvHandle; - char mDeviceName[kMaxDeviceNameLength + 1]; -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - chip::System::PacketBufferHandle c3AdditionalDataBufferHandle; -#endif - - void DriveBLEState(void); - CHIP_ERROR ConfigureAdvertising(void); - CHIP_ERROR StartAdvertising(void); - CHIP_ERROR StopAdvertising(void); - void HandleSoftDeviceBLEEvent(const ChipDeviceEvent * event); - void HandleConnectEvent(blekw_msg_t * msg); - void HandleConnectionCloseEvent(blekw_msg_t * msg); - void HandleWriteEvent(blekw_msg_t * msg); - void HandleRXCharWrite(blekw_msg_t * msg); - void HandleTXCharCCCDWrite(blekw_msg_t * msg); - CHIP_ERROR HandleGAPConnect(const ChipDeviceEvent * event); - CHIP_ERROR HandleGAPDisconnect(const ChipDeviceEvent * event); - CHIP_ERROR HandleRXCharWrite(const ChipDeviceEvent * event); - CHIP_ERROR HandleTXCharCCCDWrite(const ChipDeviceEvent * event); - CHIP_ERROR HandleTXComplete(const ChipDeviceEvent * event); - CHIP_ERROR SetSubscribed(uint16_t conId); - bool UnsetSubscribed(uint16_t conId); - bool IsSubscribed(uint16_t conId); - CHIP_ERROR ConfigureAdvertisingData(void); -#if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING - CHIP_ERROR EncodeAdditionalDataTlv(); - void HandleC3ReadRequest(blekw_msg_t * msg); -#endif - BLEManagerImpl::ble_err_t blekw_send_event(int8_t connection_handle, uint16_t handle, uint8_t * data, uint32_t len); - bool RemoveConnection(uint8_t connectionHandle); - void AddConnection(uint8_t connectionHandle); - BLEManagerImpl::CHIPoBLEConState * GetConnectionState(uint8_t connectionHandle, bool allocate); - - static void DriveBLEState(intptr_t arg); - - static void BLE_SignalFromISRCallback(void); - static void blekw_connection_timeout_cb(TimerHandle_t timer); - static CHIP_ERROR blekw_msg_add_u8(blekw_msg_type_t type, uint8_t data); - static void blekw_new_data_received_notification(uint32_t mask); - static void BleAdvTimeoutHandler(TimerHandle_t xTimer); - static void CancelBleAdvTimeoutTimer(void); - static void StartBleAdvTimeoutTimer(uint32_t aTimeoutInMs); - static CHIP_ERROR blekw_controller_init(void); static CHIP_ERROR blekw_host_init(void); static void Host_Task(osaTaskParam_t argument); - static void blekw_generic_cb(gapGenericEvent_t * pGenericEvent); - static void blekw_gatt_server_cb(deviceId_t deviceId, gattServerEvent_t * pServerEvent); - static CHIP_ERROR blekw_msg_add_u16(blekw_msg_type_t type, uint16_t data); - static CHIP_ERROR blekw_msg_add_att_written(blekw_msg_type_t type, uint8_t device_id, uint16_t handle, uint8_t * data, - uint16_t length); - static CHIP_ERROR blekw_msg_add_att_read(blekw_msg_type_t type, uint8_t device_id, uint16_t handle); - static BLEManagerImpl::ble_err_t blekw_start_advertising(gapAdvertisingParameters_t * adv_params, gapAdvertisingData_t * adv, - gapScanResponseData_t * scnrsp); - static BLEManagerImpl::ble_err_t blekw_stop_advertising(void); - static void blekw_gap_advertising_cb(gapAdvertisingEvent_t * pAdvertisingEvent); - static void blekw_gap_connection_cb(deviceId_t deviceId, gapConnectionEvent_t * pConnectionEvent); - static void blekw_start_connection_timeout(void); - static void blekw_stop_connection_timeout(void); + static void BLE_SignalFromISRCallback(void); + static CHIP_ERROR blekw_controller_init(void); - static void bleAppTask(void * p_arg); + BleLayer * _GetBleLayer(void); -public: - static bool blekw_stop_connection_internal(BLE_CONNECTION_OBJECT conId); + // ===== Members for internal use by the following friends. + friend BLEManager & BLEMgr(void); + friend BLEManagerImpl & BLEMgrImpl(void); }; /** @@ -292,4 +93,4 @@ inline BleLayer * BLEManagerImpl::_GetBleLayer() } // namespace DeviceLayer } // namespace chip -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE +#endif /* CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE */ diff --git a/src/platform/nxp/k32w/k32w0/BUILD.gn b/src/platform/nxp/k32w/k32w0/BUILD.gn index 9e2a205d8e0ba6..7c9d11aaa4433b 100644 --- a/src/platform/nxp/k32w/k32w0/BUILD.gn +++ b/src/platform/nxp/k32w/k32w0/BUILD.gn @@ -27,8 +27,8 @@ if (chip_enable_openthread) { static_library("k32w0") { sources = [ "../../../SingletonConfigurationManager.cpp", - "../common/RamStorage.cpp", - "../common/RamStorageKey.cpp", + "../common/BLEManagerCommon.cpp", + "../common/BLEManagerCommon.h", "BLEManagerImpl.cpp", "BLEManagerImpl.h", "CHIPDevicePlatformConfig.h", @@ -50,6 +50,7 @@ static_library("k32w0") { "NFCManagerImpl.h", "PlatformManagerImpl.cpp", "PlatformManagerImpl.h", + "RamStorage.cpp", "SystemTimeSupport.cpp", "ble_function_mux.c", ] @@ -59,14 +60,12 @@ static_library("k32w0") { "${chip_root}/src/credentials/examples/DeviceAttestationCredsExample.h", "${chip_root}/src/credentials/examples/ExampleDACs.h", "${chip_root}/src/credentials/examples/ExamplePAI.h", - "../common/RamStorage.h", - "../common/RamStorageKey.h", ] if (chip_with_factory_data == 1) { sources += [ - "K32W0FactoryDataProvider.cpp", - "K32W0FactoryDataProvider.h", + "../common/FactoryDataProvider.cpp", + "FactoryDataProviderImpl.cpp", ] public += [ "${chip_root}/src/credentials/CHIPCert.h", diff --git a/src/platform/nxp/k32w/k32w0/CHIPDevicePlatformConfig.h b/src/platform/nxp/k32w/k32w0/CHIPDevicePlatformConfig.h index 310a175fcf4cbf..0f6258fe9cd824 100644 --- a/src/platform/nxp/k32w/k32w0/CHIPDevicePlatformConfig.h +++ b/src/platform/nxp/k32w/k32w0/CHIPDevicePlatformConfig.h @@ -37,6 +37,16 @@ #define CHIP_DEVICE_CHIP0BLE_DEBUG 0 #endif +/** + * @def CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID_LENGTH + * + * Set unique id to maximum length if not defined to ensure the actual unique + * id is retrieved instead of the default one (if factory data read fails). + */ +#ifndef CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID_LENGTH +#define CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID_LENGTH 32 +#endif + // ========== Platform-specific Configuration ========= // These are configuration options that are unique to the K32W platform. diff --git a/src/platform/nxp/k32w/k32w0/ConfigurationManagerImpl.cpp b/src/platform/nxp/k32w/k32w0/ConfigurationManagerImpl.cpp index b27bdec546e4d0..d7e9088f322143 100644 --- a/src/platform/nxp/k32w/k32w0/ConfigurationManagerImpl.cpp +++ b/src/platform/nxp/k32w/k32w0/ConfigurationManagerImpl.cpp @@ -40,8 +40,6 @@ namespace DeviceLayer { using namespace ::chip::DeviceLayer::Internal; -// TODO: Define a Singleton instance of CHIP Group Key Store here - ConfigurationManagerImpl & ConfigurationManagerImpl::GetDefaultInstance() { static ConfigurationManagerImpl sInstance; @@ -51,49 +49,40 @@ ConfigurationManagerImpl & ConfigurationManagerImpl::GetDefaultInstance() CHIP_ERROR ConfigurationManagerImpl::Init() { CHIP_ERROR err; - uint32_t rebootCount = 0; + uint8_t rebootCause = POWER_GetResetCause(); if (K32WConfig::ConfigValueExists(K32WConfig::kCounterKey_RebootCount)) { - err = GetRebootCount(rebootCount); - SuccessOrExit(err); - - err = StoreRebootCount(rebootCount + 1); - SuccessOrExit(err); + uint32_t rebootCount = 0; + SuccessOrExit(err = GetRebootCount(rebootCount)); + SuccessOrExit(err = StoreRebootCount(rebootCount + 1)); } else { // The first boot after factory reset of the Node. - err = StoreRebootCount(0); - SuccessOrExit(err); + SuccessOrExit(err = StoreRebootCount(0)); } if (!K32WConfig::ConfigValueExists(K32WConfig::kCounterKey_TotalOperationalHours)) { - err = StoreTotalOperationalHours(0); - SuccessOrExit(err); - } - - if (!K32WConfig::ConfigValueExists(K32WConfig::kCounterKey_BootReason)) - { - err = StoreBootReason(to_underlying(BootReasonType::kUnspecified)); - SuccessOrExit(err); + SuccessOrExit(err = StoreTotalOperationalHours(0)); } - rebootCause = POWER_GetResetCause(); + SuccessOrExit(err = DetermineBootReason(rebootCause)); // Initialize the generic implementation base class. err = Internal::GenericConfigurationManagerImpl::Init(); SuccessOrExit(err); - // TODO: Initialize the global GroupKeyStore object here - - err = CHIP_NO_ERROR; - exit: return err; } +CHIP_ERROR ConfigurationManagerImpl::StoreSoftwareUpdateCompleted() +{ + return WriteConfigValue(K32WConfig::kConfigKey_SoftwareUpdateCompleted, true); +} + CHIP_ERROR ConfigurationManagerImpl::GetRebootCount(uint32_t & rebootCount) { return ReadConfigValue(K32WConfig::kCounterKey_RebootCount, rebootCount); @@ -116,31 +105,7 @@ CHIP_ERROR ConfigurationManagerImpl::StoreTotalOperationalHours(uint32_t totalOp CHIP_ERROR ConfigurationManagerImpl::GetBootReason(uint32_t & bootReason) { - bootReason = to_underlying(BootReasonType::kUnspecified); - // rebootCause is obtained at bootup. - if (rebootCause == RESET_UNDEFINED) - { - bootReason = to_underlying(BootReasonType::kUnspecified); - } - else if ((rebootCause == RESET_POR) || (rebootCause == RESET_EXT_PIN)) - { - bootReason = to_underlying(BootReasonType::kPowerOnReboot); - } - else if (rebootCause == RESET_BOR) - { - bootReason = to_underlying(BootReasonType::kBrownOutReset); - } - else if (rebootCause == RESET_SW_REQ) - { - bootReason = to_underlying(BootReasonType::kSoftwareReset); - } - else if (rebootCause == RESET_WDT) - { - bootReason = to_underlying(BootReasonType::kSoftwareWatchdogReset); - /* Reboot can be due to hardware or software watchdog */ - } - - return CHIP_NO_ERROR; + return ReadConfigValue(K32WConfig::kCounterKey_BootReason, bootReason); } CHIP_ERROR ConfigurationManagerImpl::StoreBootReason(uint32_t bootReason) @@ -275,6 +240,40 @@ CHIP_ERROR ConfigurationManagerImpl::WriteConfigValueBin(Key key, const uint8_t void ConfigurationManagerImpl::RunConfigUnitTest(void) {} +CHIP_ERROR ConfigurationManagerImpl::DetermineBootReason(uint8_t rebootCause) +{ + BootReasonType bootReason = BootReasonType::kUnspecified; + + if ((rebootCause & RESET_POR) || (rebootCause & RESET_EXT_PIN)) + { + bootReason = BootReasonType::kPowerOnReboot; + } + else if (rebootCause & RESET_BOR) + { + bootReason = BootReasonType::kBrownOutReset; + } + else if (rebootCause & RESET_WDT) + { + /* Reboot can be due to hardware or software watchdog */ + bootReason = BootReasonType::kHardwareWatchdogReset; + } + else if (rebootCause & RESET_SW_REQ) + { + if (K32WConfig::ConfigValueExists(K32WConfig::kConfigKey_SoftwareUpdateCompleted)) + { + bootReason = BootReasonType::kSoftwareUpdateCompleted; + } + else + { + bootReason = BootReasonType::kSoftwareReset; + } + } + + K32WConfig::ClearConfigValue(K32WConfig::kConfigKey_SoftwareUpdateCompleted); + + return StoreBootReason(to_underlying(bootReason)); +} + void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) { CHIP_ERROR err; diff --git a/src/platform/nxp/k32w/k32w0/ConfigurationManagerImpl.h b/src/platform/nxp/k32w/k32w0/ConfigurationManagerImpl.h index 4807162ee00ba9..8fded100d00a87 100644 --- a/src/platform/nxp/k32w/k32w0/ConfigurationManagerImpl.h +++ b/src/platform/nxp/k32w/k32w0/ConfigurationManagerImpl.h @@ -39,10 +39,9 @@ class ConfigurationManagerImpl final : public Internal::GenericConfigurationMana public: // This returns an instance of this class. static ConfigurationManagerImpl & GetDefaultInstance(); + CHIP_ERROR StoreSoftwareUpdateCompleted(); -private: // ===== Members that implement the ConfigurationManager public interface. - CHIP_ERROR Init(void) override; CHIP_ERROR GetPrimaryWiFiMACAddress(uint8_t * buf) override; bool CanFactoryReset(void) override; @@ -59,8 +58,8 @@ class ConfigurationManagerImpl final : public Internal::GenericConfigurationMana CHIP_ERROR StoreUniqueId(const char * uniqueId, size_t uniqueIdLen) override; CHIP_ERROR GenerateUniqueId(char * buf, size_t bufSize) override; +private: // NOTE: Other public interface methods are implemented by GenericConfigurationManagerImpl<>. - // ===== Members that implement the GenericConfigurationManagerImpl protected interface. CHIP_ERROR ReadConfigValue(Key key, bool & val) override; CHIP_ERROR ReadConfigValue(Key key, uint32_t & val) override; @@ -76,7 +75,7 @@ class ConfigurationManagerImpl final : public Internal::GenericConfigurationMana void RunConfigUnitTest(void) override; // ===== Private members reserved for use by this class only. - uint8_t rebootCause; + CHIP_ERROR DetermineBootReason(uint8_t rebootCause); static void DoFactoryReset(intptr_t arg); }; diff --git a/src/platform/nxp/k32w/k32w0/DiagnosticDataProviderImpl.cpp b/src/platform/nxp/k32w/k32w0/DiagnosticDataProviderImpl.cpp index 96b8e663fe15aa..4331e007c4b07c 100644 --- a/src/platform/nxp/k32w/k32w0/DiagnosticDataProviderImpl.cpp +++ b/src/platform/nxp/k32w/k32w0/DiagnosticDataProviderImpl.cpp @@ -117,8 +117,8 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetThreadMetrics(ThreadMetrics ** threadM thread->stackFreeMinimum.Emplace(taskStatusArray[x].usStackHighWaterMark); /* Unsupported metrics */ - // thread->stackSize; - // thread->stackFreeCurrent; + thread->stackFreeCurrent.ClearValue(); + thread->stackSize.ClearValue(); thread->Next = head; head = thread; diff --git a/src/platform/nxp/k32w/k32w0/FactoryDataProviderImpl.cpp b/src/platform/nxp/k32w/k32w0/FactoryDataProviderImpl.cpp new file mode 100644 index 00000000000000..026aceb5dfad27 --- /dev/null +++ b/src/platform/nxp/k32w/k32w0/FactoryDataProviderImpl.cpp @@ -0,0 +1,183 @@ +/* + * + * Copyright (c) 2023 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#if CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR +extern "C" { +#include "Flash_Adapter.h" +} +extern "C" WEAK CHIP_ERROR FactoryDataDefaultRestoreMechanism(); +#endif + +namespace chip { +namespace DeviceLayer { + +FactoryDataProviderImpl::FactoryDataProviderImpl() +{ +#if CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR + RegisterRestoreMechanism(FactoryDataDefaultRestoreMechanism); +#endif +} + +CHIP_ERROR FactoryDataProviderImpl::Init() +{ + CHIP_ERROR error = CHIP_NO_ERROR; + uint32_t sum = 0; + +#if CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER + ReturnErrorOnFailure(SetCustomIds()); +#endif + + for (uint8_t i = 1; i < FactoryDataProvider::kNumberOfIds; i++) + { + sum += maxLengths[i]; + } + + if (sum > kFactoryDataSize) + { + ChipLogError(DeviceLayer, "Max size of factory data: %lu is bigger than reserved factory data size: %lu", sum, + kFactoryDataSize); + } + +#if CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR + error = ValidateWithRestore(); +#else + error = Validate(); +#endif + if (error != CHIP_NO_ERROR) + { + ChipLogError(DeviceLayer, "Factory data init failed with: %s", ErrorStr(error)); + } + + return error; +} + +CHIP_ERROR FactoryDataProviderImpl::SignWithDacKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) +{ + Crypto::P256ECDSASignature signature; + Crypto::P256Keypair keypair; + Crypto::P256SerializedKeypair serializedKeypair; + + VerifyOrReturnError(IsSpanUsable(outSignBuffer), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(IsSpanUsable(messageToSign), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(outSignBuffer.size() >= signature.Capacity(), CHIP_ERROR_BUFFER_TOO_SMALL); + + /* Get private key of DAC certificate from reserved section */ + uint8_t keyBuf[Crypto::kP256_PrivateKey_Length]; + MutableByteSpan dacPrivateKeySpan(keyBuf); + uint16_t keySize = 0; + ReturnErrorOnFailure(SearchForId(FactoryDataId::kDacPrivateKeyId, dacPrivateKeySpan.data(), dacPrivateKeySpan.size(), keySize)); + dacPrivateKeySpan.reduce_size(keySize); + + /* Only the private key is used when signing */ + ReturnErrorOnFailure(serializedKeypair.SetLength(Crypto::kP256_PublicKey_Length + dacPrivateKeySpan.size())); + memcpy(serializedKeypair.Bytes() + Crypto::kP256_PublicKey_Length, dacPrivateKeySpan.data(), dacPrivateKeySpan.size()); + + ReturnErrorOnFailure(keypair.Deserialize(serializedKeypair)); + ReturnErrorOnFailure(keypair.ECDSA_sign_msg(messageToSign.data(), messageToSign.size(), signature)); + + // TODO: sanitize temporary buffers used to store the private key, so it doesn't leak on the stack? + + return CopySpanToMutableSpan(ByteSpan{ signature.ConstBytes(), signature.Length() }, outSignBuffer); +} + +#if CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR +extern "C" WEAK CHIP_ERROR FactoryDataDefaultRestoreMechanism() +{ + CHIP_ERROR error = CHIP_NO_ERROR; + uint16_t backupLength = 0; + + // Check if PDM id related to factory data backup exists. + // If it does, it means an external event (such as a power loss) + // interrupted the factory data update process and the section + // from internal flash is most likely erased and should be restored. + if (PDM_bDoesDataExist(kNvmId_FactoryDataBackup, &backupLength)) + { + chip::Platform::ScopedMemoryBuffer buffer; + buffer.Calloc(FactoryDataProvider::kFactoryDataSize); + ReturnErrorCodeIf(buffer.Get() == nullptr, CHIP_ERROR_NO_MEMORY); + + auto status = PDM_eReadDataFromRecord(kNvmId_FactoryDataBackup, (void *) buffer.Get(), + FactoryDataProvider::kFactoryDataSize, &backupLength); + ReturnErrorCodeIf(PDM_E_STATUS_OK != status, CHIP_FACTORY_DATA_PDM_RESTORE); + + error = FactoryDataProviderImpl::UpdateData(buffer.Get()); + if (error == CHIP_NO_ERROR) + { + ChipLogProgress(DeviceLayer, "Factory data was restored successfully"); + } + } + + return error; +} + +CHIP_ERROR FactoryDataProviderImpl::ValidateWithRestore() +{ + CHIP_ERROR error = CHIP_NO_ERROR; + + VerifyOrReturnError(mRestoreMechanisms.size() > 0, CHIP_FACTORY_DATA_RESTORE_MECHANISM); + + for (auto & restore : mRestoreMechanisms) + { + error = restore(); + if (error != CHIP_NO_ERROR) + { + continue; + } + + error = Validate(); + if (error != CHIP_NO_ERROR) + { + continue; + } + + break; + } + + if (error == CHIP_NO_ERROR) + { + PDM_vDeleteDataRecord(kNvmId_FactoryDataBackup); + } + + return error; +} + +CHIP_ERROR FactoryDataProviderImpl::UpdateData(uint8_t * pBuf) +{ + NV_Init(); + + auto status = NV_FlashEraseSector(kFactoryDataStart, kFactoryDataSize); + ReturnErrorCodeIf(status != kStatus_FLASH_Success, CHIP_FACTORY_DATA_FLASH_ERASE); + + Header * header = (Header *) pBuf; + status = NV_FlashProgramUnaligned(kFactoryDataStart, sizeof(Header) + header->size, pBuf); + ReturnErrorCodeIf(status != kStatus_FLASH_Success, CHIP_FACTORY_DATA_FLASH_PROGRAM); + + return CHIP_NO_ERROR; +} + +void FactoryDataProviderImpl::RegisterRestoreMechanism(RestoreMechanism restore) +{ + mRestoreMechanisms.insert(mRestoreMechanisms.end(), restore); +} +#endif // CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/nxp/k32w/k32w0/FactoryDataProviderImpl.h b/src/platform/nxp/k32w/k32w0/FactoryDataProviderImpl.h new file mode 100644 index 00000000000000..f8d51573f6c488 --- /dev/null +++ b/src/platform/nxp/k32w/k32w0/FactoryDataProviderImpl.h @@ -0,0 +1,59 @@ +/* + * + * Copyright (c) 2023 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include +#include + +namespace chip { +namespace DeviceLayer { + +/** + * This class provides K32W0 specific factory data features. + * CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER - application defined factory data provider + * CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR - enables factory data OTA + */ + +class FactoryDataProviderImpl : public FactoryDataProvider +{ +public: + FactoryDataProviderImpl(); + + CHIP_ERROR Init() override; + CHIP_ERROR SignWithDacKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) override; + +#if CHIP_DEVICE_CONFIG_USE_CUSTOM_PROVIDER + virtual ~FactoryDataProviderImpl() {} + // Custom factory data providers must implement this method in order to define + // their own custom IDs. + virtual CHIP_ERROR SetCustomIds() = 0; +#endif + +#if CONFIG_CHIP_K32W0_OTA_FACTORY_DATA_PROCESSOR + using RestoreMechanism = CHIP_ERROR (*)(void); + + static CHIP_ERROR UpdateData(uint8_t * pBuf); + CHIP_ERROR ValidateWithRestore(); + void RegisterRestoreMechanism(RestoreMechanism mechanism); + +private: + std::vector mRestoreMechanisms; +#endif +}; + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/nxp/k32w/k32w0/K32W0Config.cpp b/src/platform/nxp/k32w/k32w0/K32W0Config.cpp index e1427b32c63813..a346d18d69c90c 100644 --- a/src/platform/nxp/k32w/k32w0/K32W0Config.cpp +++ b/src/platform/nxp/k32w/k32w0/K32W0Config.cpp @@ -62,6 +62,7 @@ const K32WConfig::Key K32WConfig::kConfigKey_RegulatoryLocation{ &K32WConfig::sC const K32WConfig::Key K32WConfig::kConfigKey_CountryCode{ &K32WConfig::sConfigStorage, kKeyId_Config, 0x08 }; const K32WConfig::Key K32WConfig::kConfigKey_UniqueId{ &K32WConfig::sConfigStorage, kKeyId_Config, 0x0A }; const K32WConfig::Key K32WConfig::kConfigKey_SoftwareVersion{ &K32WConfig::sConfigStorage, kKeyId_Config, 0x0B }; +const K32WConfig::Key K32WConfig::kConfigKey_SoftwareUpdateCompleted{ &K32WConfig::sConfigStorage, kKeyId_Config, 0x0C }; const K32WConfig::Key K32WConfig::kCounterKey_RebootCount{ &K32WConfig::sCounterStorage, kKeyId_Counter, 0x00 }; const K32WConfig::Key K32WConfig::kCounterKey_UpTime{ &K32WConfig::sCounterStorage, kKeyId_Counter, 0x01 }; diff --git a/src/platform/nxp/k32w/k32w0/K32W0Config.h b/src/platform/nxp/k32w/k32w0/K32W0Config.h index 6e2ec0f850d6be..e364c045c25b1c 100644 --- a/src/platform/nxp/k32w/k32w0/K32W0Config.h +++ b/src/platform/nxp/k32w/k32w0/K32W0Config.h @@ -20,8 +20,7 @@ #include #include -#include -#include +#include namespace chip { namespace DeviceLayer { @@ -74,6 +73,7 @@ class K32WConfig static const Key kConfigKey_CountryCode; static const Key kConfigKey_UniqueId; static const Key kConfigKey_SoftwareVersion; + static const Key kConfigKey_SoftwareUpdateCompleted; // CHIP Counter Keys static const Key kCounterKey_RebootCount; diff --git a/src/platform/nxp/k32w/k32w0/KeyValueStoreManagerImpl.cpp b/src/platform/nxp/k32w/k32w0/KeyValueStoreManagerImpl.cpp index 46ad467ca470ba..8b3e7491eec3bb 100644 --- a/src/platform/nxp/k32w/k32w0/KeyValueStoreManagerImpl.cpp +++ b/src/platform/nxp/k32w/k32w0/KeyValueStoreManagerImpl.cpp @@ -25,17 +25,16 @@ #include #include -#include -#include #include #include +#include #include namespace chip { namespace DeviceLayer { namespace PersistedStorage { -constexpr size_t kMaxNumberOfKeys = 150; +constexpr size_t kMaxNumberOfKeys = 200; constexpr size_t kMaxKeyValueBytes = 255; Internal::RamStorage KeyValueStoreManagerImpl::sKeysStorage = { kNvmId_KvsKeys }; @@ -54,7 +53,7 @@ uint16_t GetStringKeyId(const char * key, uint16_t * freeId) for (keyId = 0; keyId < kMaxNumberOfKeys; keyId++) { uint16_t keyStringSize = kMaxKeyValueBytes; - pdmInternalId = Internal::RamStorageKey::GetPdmId(kKeyId_KvsKeys, keyId); + pdmInternalId = Internal::RamStorageKey::GetInternalId(kKeyId_KvsKeys, keyId); err = KeyValueStoreManagerImpl::sKeysStorage.Read(pdmInternalId, 0, (uint8_t *) keyString, &keyStringSize); if (err == CHIP_NO_ERROR) @@ -82,7 +81,8 @@ CHIP_ERROR KeyValueStoreManagerImpl::Init() { ChipLogProgress(DeviceLayer, "Cannot init KVS keys storage with id: %d. Error: %s", kNvmId_KvsKeys, ErrorStr(err)); } - err = sValuesStorage.Init(Internal::RamStorage::kRamBufferInitialSize); + // Set values storage to max RAM buffer size as a temporary fix for TC-RR-1.1. + err = sValuesStorage.Init(kRamBufferMaxAllocSize, true); if (err != CHIP_NO_ERROR) { ChipLogProgress(DeviceLayer, "Cannot init KVS values storage with id: %d. Error: %s", kNvmId_KvsValues, ErrorStr(err)); @@ -106,7 +106,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t if (keyId < kMaxNumberOfKeys) { // This is the ID of the actual data - pdmInternalId = Internal::RamStorageKey::GetPdmId(kKeyId_KvsValues, keyId); + pdmInternalId = Internal::RamStorageKey::GetInternalId(kKeyId_KvsValues, keyId); ChipLogProgress(DeviceLayer, "KVS, get the value of Matter key [%s] with PDM id: %i", key, pdmInternalId); err = KeyValueStoreManagerImpl::sValuesStorage.Read(pdmInternalId, 0, (uint8_t *) value, &valueSize); *read_bytes_size = valueSize; @@ -140,7 +140,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, keyId = freeKeyId; } - pdmInternalId = Internal::RamStorageKey::GetPdmId(kKeyId_KvsValues, keyId); + pdmInternalId = Internal::RamStorageKey::GetInternalId(kKeyId_KvsValues, keyId); ChipLogProgress(DeviceLayer, "KVS, save in flash the value of the Matter key [%s] with PDM id: %i", key, pdmInternalId); err = sValuesStorage.Write(pdmInternalId, (uint8_t *) value, value_size); @@ -150,7 +150,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, { if (putKey) { - pdmInternalId = Internal::RamStorageKey::GetPdmId(kKeyId_KvsKeys, keyId); + pdmInternalId = Internal::RamStorageKey::GetInternalId(kKeyId_KvsKeys, keyId); ChipLogProgress(DeviceLayer, "KVS, save in flash the Matter key [%s] with PDM id: %i and length %d", key, pdmInternalId, strlen(key) + 1); @@ -185,7 +185,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) if (keyId < kMaxNumberOfKeys) { // entry exists so we can remove it - pdmInternalId = Internal::RamStorageKey::GetPdmId(kKeyId_KvsKeys, keyId); + pdmInternalId = Internal::RamStorageKey::GetInternalId(kKeyId_KvsKeys, keyId); ChipLogProgress(DeviceLayer, "KVS, delete from flash the Matter key [%s] with PDM id: %i", key, pdmInternalId); err = sKeysStorage.Delete(pdmInternalId, -1); @@ -193,7 +193,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) /* also delete the 'key string' from flash */ if (err == CHIP_NO_ERROR) { - pdmInternalId = Internal::RamStorageKey::GetPdmId(kKeyId_KvsValues, keyId); + pdmInternalId = Internal::RamStorageKey::GetInternalId(kKeyId_KvsValues, keyId); ChipLogProgress(DeviceLayer, "KVS, delete from flash the value of the Matter key [%s] with PDM id: %i", key, pdmInternalId); diff --git a/src/platform/nxp/k32w/k32w0/KeyValueStoreManagerImpl.h b/src/platform/nxp/k32w/k32w0/KeyValueStoreManagerImpl.h index db9036eb3586e2..a83a29b8a2e3ef 100644 --- a/src/platform/nxp/k32w/k32w0/KeyValueStoreManagerImpl.h +++ b/src/platform/nxp/k32w/k32w0/KeyValueStoreManagerImpl.h @@ -24,7 +24,7 @@ #pragma once -#include +#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/nxp/k32w/k32w0/LowPowerHooks.cpp b/src/platform/nxp/k32w/k32w0/LowPowerHooks.cpp index eb980e179882b1..a9bbcac8613d8f 100644 --- a/src/platform/nxp/k32w/k32w0/LowPowerHooks.cpp +++ b/src/platform/nxp/k32w/k32w0/LowPowerHooks.cpp @@ -20,7 +20,7 @@ * Provides a glue layer between Matter and NXP-SDK Low Power */ -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) #include #include diff --git a/src/platform/nxp/k32w/k32w0/OTAFactoryDataProcessor.cpp b/src/platform/nxp/k32w/k32w0/OTAFactoryDataProcessor.cpp index 8a3a9b7b661779..dbf7d09c892de4 100644 --- a/src/platform/nxp/k32w/k32w0/OTAFactoryDataProcessor.cpp +++ b/src/platform/nxp/k32w/k32w0/OTAFactoryDataProcessor.cpp @@ -27,8 +27,6 @@ namespace chip { -static OtaUtils_EEPROM_ReadData pFunctionEepromRead = (OtaUtils_EEPROM_ReadData) FactoryProvider::ReadDataMemcpy; - CHIP_ERROR OTAFactoryDataProcessor::Init() { mAccumulator.Init(mLength); @@ -81,7 +79,7 @@ CHIP_ERROR OTAFactoryDataProcessor::ApplyAction() SuccessOrExit(error = Update((uint8_t) Tags::kPaiCertificateId, mPayload.mCertPai)); SuccessOrExit(error = Update((uint8_t) Tags::kCertDeclarationId, mPayload.mCertDeclaration)); - error = FactoryProvider::GetDefaultInstance().UpdateData(mFactoryData); + error = FactoryProviderImpl::UpdateData(mFactoryData); exit: if (error != CHIP_NO_ERROR) @@ -99,7 +97,7 @@ CHIP_ERROR OTAFactoryDataProcessor::ApplyAction() CHIP_ERROR OTAFactoryDataProcessor::AbortAction() { ReturnErrorOnFailure(Restore()); - ReturnErrorOnFailure(FactoryProvider::GetDefaultInstance().UpdateData(mFactoryData)); + ReturnErrorOnFailure(FactoryProviderImpl::UpdateData(mFactoryData)); PDM_vDeleteDataRecord(kNvmId_FactoryDataBackup); @@ -158,20 +156,12 @@ CHIP_ERROR OTAFactoryDataProcessor::Update(uint8_t tag, Optional & opt CHIP_ERROR OTAFactoryDataProcessor::Read() { FactoryProvider::Header header; - auto status = OtaUtils_ReadFromInternalFlash(sizeof(FactoryProvider::Header), FactoryProvider::kFactoryDataStart, - (uint8_t *) &header, NULL, pFunctionEepromRead); + memcpy(&header, (void *) FactoryProvider::kFactoryDataStart, sizeof(FactoryProvider::Header)); mFactoryData = static_cast(chip::Platform::MemoryAlloc(FactoryProvider::kFactoryDataSize)); ReturnErrorCodeIf(mFactoryData == nullptr, CHIP_FACTORY_DATA_NULL); memset(mFactoryData, 0, FactoryProvider::kFactoryDataSize); - - status = OtaUtils_ReadFromInternalFlash(sizeof(FactoryProvider::Header) + header.size, FactoryProvider::kFactoryDataStart, - mFactoryData, NULL, pFunctionEepromRead); - if (status != gOtaUtilsSuccess_c) - { - ClearBuffer(); - return CHIP_FACTORY_DATA_INTERNAL_FLASH_READ; - } + memcpy(mFactoryData, (void *) FactoryProvider::kFactoryDataStart, sizeof(FactoryProvider::Header) + header.size); return CHIP_NO_ERROR; } diff --git a/src/platform/nxp/k32w/k32w0/OTAFactoryDataProcessor.h b/src/platform/nxp/k32w/k32w0/OTAFactoryDataProcessor.h index e40e81f199c1ac..8682d0bcc1e9dc 100644 --- a/src/platform/nxp/k32w/k32w0/OTAFactoryDataProcessor.h +++ b/src/platform/nxp/k32w/k32w0/OTAFactoryDataProcessor.h @@ -21,13 +21,15 @@ #include #include #include +#include #include -#include +#include namespace chip { -using FactoryProvider = DeviceLayer::K32W0FactoryDataProvider; -using Tags = FactoryProvider::FactoryDataId; +using FactoryProvider = DeviceLayer::FactoryDataProvider; +using FactoryProviderImpl = DeviceLayer::FactoryDataProviderImpl; +using Tags = FactoryProvider::FactoryDataId; /** * OTA custom payload that uses Matter TLVs. diff --git a/src/platform/nxp/k32w/k32w0/PlatformManagerImpl.cpp b/src/platform/nxp/k32w/k32w0/PlatformManagerImpl.cpp index 05e53f40bd044a..198f9318ba41fb 100644 --- a/src/platform/nxp/k32w/k32w0/PlatformManagerImpl.cpp +++ b/src/platform/nxp/k32w/k32w0/PlatformManagerImpl.cpp @@ -56,7 +56,7 @@ namespace DeviceLayer { PlatformManagerImpl PlatformManagerImpl::sInstance; -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) extern "C" void InitLowPower(); #endif @@ -97,7 +97,7 @@ CHIP_ERROR PlatformManagerImpl::InitBoardFwk(void) BOARD_ADCWakeupInit(); #endif -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) /* Low Power Init */ InitLowPower(); #endif diff --git a/src/platform/nxp/k32w/common/RamStorage.cpp b/src/platform/nxp/k32w/k32w0/RamStorage.cpp similarity index 74% rename from src/platform/nxp/k32w/common/RamStorage.cpp rename to src/platform/nxp/k32w/k32w0/RamStorage.cpp index d02537ff6f4be5..db7ab50a0f1247 100644 --- a/src/platform/nxp/k32w/common/RamStorage.cpp +++ b/src/platform/nxp/k32w/k32w0/RamStorage.cpp @@ -18,7 +18,7 @@ #include #include -#include +#include #include "pdm_ram_storage_glue.h" @@ -39,13 +39,41 @@ #define ot_free(...) #endif +#if PDM_SAVE_IDLE +// Segment data size is: D_SEGMENT_MEMORY_SIZE (4096) - D_PDM_NVM_SEGMENT_HEADER_SIZE (size of internal header). +// Subtract 64 to have more margin. +#define PDM_SEGMENT_SIZE (4096 - 64) +#endif + namespace chip::DeviceLayer::Internal { -CHIP_ERROR RamStorage::Init(uint16_t aInitialSize) +RamStorageKey::RamStorageKey(RamStorage * storage, uint8_t keyId, uint8_t internalId) +{ + mStorage = storage; + mId = GetInternalId(keyId, internalId); +} + +CHIP_ERROR RamStorageKey::Read(uint8_t * buf, uint16_t & sizeToRead) const +{ + return mStorage->Read(mId, 0, buf, &sizeToRead); +} + +CHIP_ERROR RamStorageKey::Write(const uint8_t * buf, uint16_t length) +{ + return mStorage->Write(mId, buf, length); +} + +CHIP_ERROR RamStorageKey::Delete() +{ + return mStorage->Delete(mId, -1); +} + +CHIP_ERROR RamStorage::Init(uint16_t aInitialSize, bool extendedSearch) { CHIP_ERROR err; - mBuffer = getRamBuffer(mPdmId, aInitialSize); + mBuffer = getRamBuffer(mPdmId, aInitialSize, extendedSearch); + mExtendedSearch = extendedSearch; return mBuffer ? CHIP_NO_ERROR : CHIP_ERROR_NO_MEMORY; } @@ -124,8 +152,25 @@ CHIP_ERROR RamStorage::Delete(uint16_t aKey, int aIndex) void RamStorage::OnFactoryReset() { + uint16_t i = 0; + uint16_t length; + mutex_lock(mBuffer, osaWaitForever_c); - PDM_vDeleteDataRecord(mPdmId); + // Have to cover the extended search case, in which a large RAM + // buffer is saved at multiple PDM ids. + if (mExtendedSearch) + { + while (PDM_bDoesDataExist(mPdmId + i, &length)) + { + ChipLogProgress(DeviceLayer, "Ram Storage: delete PDM id: %x", mPdmId + i); + PDM_vDeleteDataRecord(mPdmId + i); + i++; + } + } + else + { + PDM_vDeleteDataRecord(mPdmId); + } mutex_unlock(mBuffer); FreeBuffer(); } diff --git a/src/platform/nxp/k32w/common/RamStorage.h b/src/platform/nxp/k32w/k32w0/RamStorage.h similarity index 68% rename from src/platform/nxp/k32w/common/RamStorage.h rename to src/platform/nxp/k32w/k32w0/RamStorage.h index 767f850c250046..5b244b69df2bad 100644 --- a/src/platform/nxp/k32w/common/RamStorage.h +++ b/src/platform/nxp/k32w/k32w0/RamStorage.h @@ -26,9 +26,31 @@ namespace chip { namespace DeviceLayer { namespace Internal { +class RamStorage; + +/** + * + * This class describes a RAM storage key wrapper. + */ +struct RamStorageKey +{ + RamStorageKey(RamStorage * storage, uint8_t keyId, uint8_t internalId); + + CHIP_ERROR Read(uint8_t * buf, uint16_t & sizeToRead) const; + CHIP_ERROR Write(const uint8_t * buf, uint16_t length); + CHIP_ERROR Delete(); + + static uint16_t GetInternalId(uint8_t keyId, uint8_t internalId) { return static_cast(keyId) << 8 | internalId; } + +private: + RamStorage * mStorage; + uint16_t mId; +}; + /** * - * All ram storage operations should be managed by this class. + * This class manages a RAM buffer and its operations. + * All operations on the buffer are protected by a mutex. */ class RamStorage { @@ -39,7 +61,7 @@ class RamStorage RamStorage(uint16_t aPdmId) : mPdmId(aPdmId), mBuffer(nullptr) {} - CHIP_ERROR Init(uint16_t aInitialSize); + CHIP_ERROR Init(uint16_t aInitialSize, bool extendedSearch = false); void FreeBuffer(); Buffer * GetBuffer() const { return mBuffer; } CHIP_ERROR Read(uint16_t aKey, int aIndex, uint8_t * aValue, uint16_t * aValueLength) const; @@ -53,6 +75,7 @@ class RamStorage uint16_t mPdmId; Buffer * mBuffer; + bool mExtendedSearch; }; } // namespace Internal diff --git a/src/platform/nxp/k32w/k32w0/ThreadStackManagerImpl.cpp b/src/platform/nxp/k32w/k32w0/ThreadStackManagerImpl.cpp index d525fc4a1e3ee7..e67680554fc0a9 100644 --- a/src/platform/nxp/k32w/k32w0/ThreadStackManagerImpl.cpp +++ b/src/platform/nxp/k32w/k32w0/ThreadStackManagerImpl.cpp @@ -36,7 +36,7 @@ #include -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) extern "C" bool isThreadInitialized(); #endif @@ -68,8 +68,16 @@ CHIP_ERROR ThreadStackManagerImpl::InitThreadStack(otInstance * otInst) void ThreadStackManagerImpl::ProcessThreadActivity() { + /* reuse thread task for ble processing. + * by doing this, we avoid allocating a new stack for short-lived + * BLE processing (e.g.: only during Matter commissioning) + */ +#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE + auto * bleManager = &chip::DeviceLayer::Internal::BLEMgrImpl(); + bleManager->DoBleProcessing(); +#endif -#if defined(cPWR_UsePowerDownMode) && (cPWR_UsePowerDownMode) +#if defined(chip_with_low_power) && (chip_with_low_power == 1) if (isThreadInitialized()) #endif { diff --git a/src/platform/nxp/k32w/k32w0/args.gni b/src/platform/nxp/k32w/k32w0/args.gni index 0364287bd8196c..59a41ae6931585 100644 --- a/src/platform/nxp/k32w/k32w0/args.gni +++ b/src/platform/nxp/k32w/k32w0/args.gni @@ -18,6 +18,12 @@ import("//build_overrides/openthread.gni") chip_device_platform = "k32w0" +if (getenv("NXP_K32W0_SDK_ROOT") == "") { + k32w0_sdk_root = "${chip_root}/third_party/nxp/k32w0_sdk/repo/core" +} else { + k32w0_sdk_root = getenv("NXP_K32W0_SDK_ROOT") +} + lwip_platform = "k32w0" chip_inet_config_enable_ipv4 = false diff --git a/src/platform/nxp/k32w/k32w0/crypto/ksdk_mbedtls.c b/src/platform/nxp/k32w/k32w0/crypto/ksdk_mbedtls.c deleted file mode 100644 index 14f1070097393d..00000000000000 --- a/src/platform/nxp/k32w/k32w0/crypto/ksdk_mbedtls.c +++ /dev/null @@ -1,4324 +0,0 @@ -/* - * Copyright 2015-2016, Freescale Semiconductor, Inc. - * Copyright 2017 NXP - * All rights reserved. - * - * - * SPDX-License-Identifier: BSD-3-Clause - */ - -#include "SecLib.h" - -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif - -#include "fsl_common.h" - -#if defined(FSL_FEATURE_SOC_LTC_COUNT) && (FSL_FEATURE_SOC_LTC_COUNT > 0) -#include "fsl_ltc.h" -#endif -#if defined(FSL_FEATURE_SOC_CAAM_COUNT) && (FSL_FEATURE_SOC_CAAM_COUNT > 0) -#include "fsl_caam.h" -#endif -#if defined(FSL_FEATURE_SOC_CAU3_COUNT) && (FSL_FEATURE_SOC_CAU3_COUNT > 0) -#include "fsl_cau3.h" -#endif -#if defined(FSL_FEATURE_SOC_DCP_COUNT) && (FSL_FEATURE_SOC_DCP_COUNT > 0) -#include "fsl_dcp.h" -#endif -#if defined(FSL_FEATURE_SOC_HASHCRYPT_COUNT) && (FSL_FEATURE_SOC_HASHCRYPT_COUNT > 0) -#include "fsl_hashcrypt.h" -#endif -#if defined(FSL_FEATURE_SOC_TRNG_COUNT) && (FSL_FEATURE_SOC_TRNG_COUNT > 0) -#if defined CPU_JN518X -#include "fsl_rng.h" -#else -#include "fsl_trng.h" -#endif -#elif defined(FSL_FEATURE_SOC_RNG_COUNT) && (FSL_FEATURE_SOC_RNG_COUNT > 0) -#include "fsl_rnga.h" -#elif defined(FSL_FEATURE_SOC_LPC_RNG1_COUNT) && (FSL_FEATURE_SOC_LPC_RNG1_COUNT > 0) -#include "fsl_rng.h" -#endif - -#define CLEAN_RETURN(value) \ - { \ - ret = value; \ - goto cleanup; \ - } - -/******************************************************************************/ -/*************************** CAAM *********************************************/ -/******************************************************************************/ -#if defined(FSL_FEATURE_SOC_CAAM_COUNT) && (FSL_FEATURE_SOC_CAAM_COUNT > 0) && defined(CRYPTO_USE_DRIVER_CAAM) -static caam_handle_t s_caamHandle = { .jobRing = kCAAM_JobRing0 }; -#endif - -/******************************************************************************/ -/*************************** CAU3 *********************************************/ -/******************************************************************************/ -#if defined(FSL_FEATURE_SOC_CAU3_COUNT) && (FSL_FEATURE_SOC_CAU3_COUNT > 0) -static cau3_handle_t s_cau3Handle = { .taskDone = MBEDTLS_CAU3_COMPLETION_SIGNAL, .keySlot = kCAU3_KeySlot0 }; -#endif - -/******************************************************************************/ -/**************************** DCP *********************************************/ -/******************************************************************************/ -#if defined(FSL_FEATURE_SOC_DCP_COUNT) && (FSL_FEATURE_SOC_DCP_COUNT > 0) -static dcp_handle_t s_dcpHandle = { .channel = kDCP_Channel0, .keySlot = kDCP_KeySlot0, .swapConfig = kDCP_NoSwap }; -#endif - -/******************************************************************************/ -/************************* Key slot management ********************************/ -/******************************************************************************/ -#if (defined(FSL_FEATURE_SOC_CAU3_COUNT) && (FSL_FEATURE_SOC_CAU3_COUNT > 0)) || (defined(MBEDTLS_FREESCALE_DCP_AES)) -static const void * s_mbedtlsCtx[4] = { 0 }; - -static void crypto_attach_ctx_to_key_slot(const void * ctx, uint8_t keySlot) -{ - s_mbedtlsCtx[keySlot] = ctx; -} - -static void crypto_detach_ctx_from_key_slot(const void * ctx) -{ - for (int i = 0; i < 4; i++) - { - if (ctx == s_mbedtlsCtx[i]) - { - s_mbedtlsCtx[i] = NULL; - break; - } - } -} - -static bool crypto_key_is_loaded(const void * ctx) -{ - bool ret = false; - for (int i = 0; i < 4; i++) - { - if (ctx == s_mbedtlsCtx[i]) - { - ret = true; - break; - } - } - return ret; -} -#endif - -#if defined(MBEDTLS_SHA1_ALT) || defined(MBEDTLS_SHA256_ALT) -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize(void * v, size_t n) -{ - volatile unsigned char * p = v; - while (n--) - *p++ = 0; -} -#endif /* MBEDTLS_SHA1_ALT || MBEDTLS_SHA256_ALT */ - -/******************************************************************************/ -/******************** CRYPTO_InitHardware **************************************/ -/******************************************************************************/ -/*! - * @brief Application init for various Crypto blocks. - * - * This function is provided to be called by MCUXpresso SDK applications. - * It calls basic init for Crypto Hw acceleration and Hw entropy modules. - */ -void CRYPTO_InitHardware(void) -{ -#if defined(FSL_FEATURE_SOC_LTC_COUNT) && (FSL_FEATURE_SOC_LTC_COUNT > 0) - /* Initialize LTC driver. - * This enables clocking and resets the module to a known state. */ - LTC_Init(LTC0); -#endif -#if defined(FSL_FEATURE_SOC_CAAM_COUNT) && (FSL_FEATURE_SOC_CAAM_COUNT > 0) && defined(CRYPTO_USE_DRIVER_CAAM) - /* Initialize CAAM driver. */ - caam_config_t caamConfig; - - CAAM_GetDefaultConfig(&caamConfig); - caamConfig.jobRingInterface[0] = &s_jrif0; - caamConfig.jobRingInterface[1] = &s_jrif1; - CAAM_Init(CAAM, &caamConfig); -#endif -#if defined(FSL_FEATURE_SOC_CAU3_COUNT) && (FSL_FEATURE_SOC_CAU3_COUNT > 0) - /* Initialize CAU3 */ - CAU3_Init(CAU3); -#endif -#if defined(FSL_FEATURE_SOC_DCP_COUNT) && (FSL_FEATURE_SOC_DCP_COUNT > 0) - /* Initialize DCP */ - dcp_config_t dcpConfig; - - DCP_GetDefaultConfig(&dcpConfig); - DCP_Init(DCP, &dcpConfig); -#endif -#if defined(FSL_FEATURE_SOC_CASPER_COUNT) && (FSL_FEATURE_SOC_CASPER_COUNT > 0) - /* Initialize CASPER */ - CASPER_Init(CASPER); -#endif -#if defined(FSL_FEATURE_SOC_HASHCRYPT_COUNT) && (FSL_FEATURE_SOC_HASHCRYPT_COUNT > 0) - /* Initialize HASHCRYPT */ - HASHCRYPT_Init(HASHCRYPT); -#endif - { /* Init RNG module.*/ -#if defined(FSL_FEATURE_SOC_TRNG_COUNT) && (FSL_FEATURE_SOC_TRNG_COUNT > 0) -#if defined CPU_JN518X -#if defined(RNG) -#define TRNG0 RNG -#endif -#else -#if defined(TRNG) -#define TRNG0 TRNG -#endif -#endif - trng_config_t trngConfig; - - TRNG_GetDefaultConfig(&trngConfig); - /* Set sample mode of the TRNG ring oscillator to Von Neumann, for better random data.*/ - /* Initialize TRNG */ - TRNG_Init(TRNG0, &trngConfig); -#elif defined(FSL_FEATURE_SOC_RNG_COUNT) && (FSL_FEATURE_SOC_RNG_COUNT > 0) - RNGA_Init(RNG); - RNGA_Seed(RNG, SIM->UIDL); -#endif - } -} - -/******************************************************************************/ -/*************************** DES **********************************************/ -/******************************************************************************/ - -#if defined(MBEDTLS_DES_C) - -#if defined(MBEDTLS_FREESCALE_LTC_DES) || defined(MBEDTLS_FREESCALE_MMCAU_DES) || defined(MBEDTLS_FREESCALE_CAAM_DES) || \ - defined(MBEDTLS_FREESCALE_CAU3_DES) - -#include "mbedtls/des.h" - -#if defined(MBEDTLS_FREESCALE_MMCAU_DES) -const unsigned char parityLookup[128] = { 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, - 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, - 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, - 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, - 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }; -#endif - -#if defined(MBEDTLS_FREESCALE_MMCAU_DES) || defined(MBEDTLS_FREESCALE_LTC_DES) || defined(MBEDTLS_FREESCALE_CAAM_DES) -/* - * DES key schedule (56-bit, encryption) - */ -int mbedtls_des_setkey_enc(mbedtls_des_context * ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE]) -{ -#if defined(MBEDTLS_FREESCALE_LTC_DES) || defined(MBEDTLS_FREESCALE_CAAM_DES) - memcpy(ctx->sk, key, MBEDTLS_DES_KEY_SIZE); -#elif defined(MBEDTLS_FREESCALE_MMCAU_DES) - int i; - unsigned char * sk_b = (unsigned char *) ctx->sk; - - /* fix key parity, if needed */ - for (i = 0; i < MBEDTLS_DES_KEY_SIZE; i++) - { - sk_b[i] = ((key[i] & 0xFE) | parityLookup[key[i] >> 1]); - } -#endif - ctx->mode = MBEDTLS_DES_ENCRYPT; - - return (0); -} - -/* - * DES key schedule (56-bit, decryption) - */ -int mbedtls_des_setkey_dec(mbedtls_des_context * ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE]) -{ -#if defined(MBEDTLS_FREESCALE_LTC_DES) || defined(MBEDTLS_FREESCALE_CAAM_DES) - memcpy(ctx->sk, key, MBEDTLS_DES_KEY_SIZE); -#elif defined(MBEDTLS_FREESCALE_MMCAU_DES) - int i; - unsigned char * sk_b = (unsigned char *) ctx->sk; - - /* fix key parity, if needed */ - for (i = 0; i < MBEDTLS_DES_KEY_SIZE; i++) - { - sk_b[i] = ((key[i] & 0xFE) | parityLookup[key[i] >> 1]); - } -#endif - ctx->mode = MBEDTLS_DES_DECRYPT; - - return (0); -} -#endif /* MBEDTLS_FREESCALE_MMCAU_DES || MBEDTLS_FREESCALE_LTC_DES || MBEDTLS_FREESCALE_CAAM_DES */ - -/* - * Triple-DES key schedule (112-bit, encryption) - */ -int mbedtls_des3_set2key_enc(mbedtls_des3_context * ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2]) -{ -#if defined(MBEDTLS_FREESCALE_LTC_DES) || defined(MBEDTLS_FREESCALE_CAAM_DES) || defined(MBEDTLS_FREESCALE_CAU3_DES) - memcpy(ctx->sk, key, MBEDTLS_DES_KEY_SIZE * 2); - memcpy(&ctx->sk[4], key, MBEDTLS_DES_KEY_SIZE); /* K3 = K1 */ -#if defined(MBEDTLS_FREESCALE_CAU3_DES) - crypto_detach_ctx_from_key_slot(ctx); -#endif -#elif defined(MBEDTLS_FREESCALE_MMCAU_DES) - int i; - unsigned char * sk_b = (unsigned char *) ctx->sk; - - /* fix key parity, if needed */ - for (i = 0; i < MBEDTLS_DES_KEY_SIZE * 2; i++) - { - sk_b[i] = ((key[i] & 0xFE) | parityLookup[key[i] >> 1]); - } - for (i = MBEDTLS_DES_KEY_SIZE * 2; i < MBEDTLS_DES_KEY_SIZE * 3; i++) - { - sk_b[i] = ((key[i - MBEDTLS_DES_KEY_SIZE * 2] & 0xFE) | parityLookup[key[i - MBEDTLS_DES_KEY_SIZE * 2] >> 1]); - } -#endif - ctx->mode = MBEDTLS_DES_ENCRYPT; - - return (0); -} - -/* - * Triple-DES key schedule (112-bit, decryption) - */ -int mbedtls_des3_set2key_dec(mbedtls_des3_context * ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2]) -{ -#if defined(MBEDTLS_FREESCALE_LTC_DES) || defined(MBEDTLS_FREESCALE_CAAM_DES) || defined(MBEDTLS_FREESCALE_CAU3_DES) - memcpy(ctx->sk, key, MBEDTLS_DES_KEY_SIZE * 2); - memcpy(&ctx->sk[4], key, MBEDTLS_DES_KEY_SIZE); /* K3 = K1 */ -#if defined(MBEDTLS_FREESCALE_CAU3_DES) - crypto_detach_ctx_from_key_slot(ctx); -#endif -#elif defined(MBEDTLS_FREESCALE_MMCAU_DES) - int i; - unsigned char * sk_b = (unsigned char *) ctx->sk; - - /* fix key parity, if needed */ - for (i = 0; i < MBEDTLS_DES_KEY_SIZE * 2; i++) - { - sk_b[i] = ((key[i] & 0xFE) | parityLookup[key[i] >> 1]); - } - for (i = MBEDTLS_DES_KEY_SIZE * 2; i < MBEDTLS_DES_KEY_SIZE * 3; i++) - { - sk_b[i] = ((key[i - MBEDTLS_DES_KEY_SIZE * 2] & 0xFE) | parityLookup[key[i - MBEDTLS_DES_KEY_SIZE * 2] >> 1]); - } -#endif - ctx->mode = MBEDTLS_DES_DECRYPT; - - return (0); -} - -/* - * Triple-DES key schedule (168-bit, encryption) - */ -int mbedtls_des3_set3key_enc(mbedtls_des3_context * ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3]) -{ -#if defined(MBEDTLS_FREESCALE_LTC_DES) || defined(MBEDTLS_FREESCALE_CAAM_DES) || defined(MBEDTLS_FREESCALE_CAU3_DES) - memcpy(ctx->sk, key, MBEDTLS_DES_KEY_SIZE * 3); -#if defined(MBEDTLS_FREESCALE_CAU3_DES) - crypto_detach_ctx_from_key_slot(ctx); -#endif -#elif defined(MBEDTLS_FREESCALE_MMCAU_DES) - int i; - unsigned char * sk_b = (unsigned char *) ctx->sk; - - /* fix key parity, if needed */ - for (i = 0; i < MBEDTLS_DES_KEY_SIZE * 3; i++) - { - sk_b[i] = ((key[i] & 0xFE) | parityLookup[key[i] >> 1]); - } -#endif - ctx->mode = MBEDTLS_DES_ENCRYPT; - - return (0); -} - -/* - * Triple-DES key schedule (168-bit, decryption) - */ -int mbedtls_des3_set3key_dec(mbedtls_des3_context * ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3]) -{ -#if defined(MBEDTLS_FREESCALE_LTC_DES) || defined(MBEDTLS_FREESCALE_CAAM_DES) || defined(MBEDTLS_FREESCALE_CAU3_DES) - memcpy(ctx->sk, key, MBEDTLS_DES_KEY_SIZE * 3); -#if defined(MBEDTLS_FREESCALE_CAU3_DES) - crypto_detach_ctx_from_key_slot(ctx); -#endif -#elif defined(MBEDTLS_FREESCALE_MMCAU_DES) - int i; - unsigned char * sk_b = (unsigned char *) ctx->sk; - - /* fix key parity, if needed */ - for (i = 0; i < MBEDTLS_DES_KEY_SIZE * 3; i++) - { - sk_b[i] = ((key[i] & 0xFE) | parityLookup[key[i] >> 1]); - } -#endif - ctx->mode = MBEDTLS_DES_DECRYPT; - return (0); -} - -#if defined(MBEDTLS_FREESCALE_LTC_DES) || defined(MBEDTLS_FREESCALE_MMCAU_DES) || defined(MBEDTLS_FREESCALE_CAAM_DES) -/* - * DES-ECB block encryption/decryption - */ -int mbedtls_des_crypt_ecb(mbedtls_des_context * ctx, const unsigned char input[8], unsigned char output[8]) -{ - uint8_t * key = (uint8_t *) ctx->sk; -#if defined(MBEDTLS_FREESCALE_LTC_DES) - if (ctx->mode == MBEDTLS_DES_ENCRYPT) - { - LTC_DES_EncryptEcb(LTC_INSTANCE, input, output, 8, key); - } - else - { - LTC_DES_DecryptEcb(LTC_INSTANCE, input, output, 8, key); - } -#elif defined(MBEDTLS_FREESCALE_MMCAU_DES) - if (ctx->mode == MBEDTLS_DES_ENCRYPT) - { - MMCAU_DES_EncryptEcb(input, key, output); - } - else - { - MMCAU_DES_DecryptEcb(input, key, output); - } -#elif defined(MBEDTLS_FREESCALE_CAAM_DES) - if (ctx->mode == MBEDTLS_DES_ENCRYPT) - { - CAAM_DES_EncryptEcb(CAAM_INSTANCE, &s_caamHandle, input, output, 8, key); - } - else - { - CAAM_DES_DecryptEcb(CAAM_INSTANCE, &s_caamHandle, input, output, 8, key); - } -#endif - return (0); -} -#endif /* MBEDTLS_FREESCALE_LTC_DES || MBEDTLS_FREESCALE_MMCAU_DES || MBEDTLS_FREESCALE_CAAM_DES */ - -/* - * 3DES-ECB block encryption/decryption - */ -int mbedtls_des3_crypt_ecb(mbedtls_des3_context * ctx, const unsigned char input[8], unsigned char output[8]) -{ - uint8_t * key = (uint8_t *) ctx->sk; -#if defined(MBEDTLS_FREESCALE_LTC_DES) - if (ctx->mode == MBEDTLS_DES_ENCRYPT) - { - LTC_DES3_EncryptEcb(LTC_INSTANCE, input, output, 8, key, key + 8, key + 16); - } - else - { - LTC_DES3_DecryptEcb(LTC_INSTANCE, input, output, 8, key, key + 8, key + 16); - } -#elif defined(MBEDTLS_FREESCALE_MMCAU_DES) - if (ctx->mode == MBEDTLS_DES_ENCRYPT) - { - MMCAU_DES_EncryptEcb(input, key, output); - MMCAU_DES_DecryptEcb(output, key + 8, output); - MMCAU_DES_EncryptEcb(output, key + 16, output); - } - else - { - MMCAU_DES_DecryptEcb(input, key + 16, output); - MMCAU_DES_EncryptEcb(output, key + 8, output); - MMCAU_DES_DecryptEcb(output, key, output); - } -#elif defined(MBEDTLS_FREESCALE_CAAM_DES) - if (ctx->mode == MBEDTLS_DES_ENCRYPT) - { - CAAM_DES3_EncryptEcb(CAAM_INSTANCE, &s_caamHandle, input, output, 8, key, key + 8, key + 16); - } - else - { - CAAM_DES3_DecryptEcb(CAAM_INSTANCE, &s_caamHandle, input, output, 8, key, key + 8, key + 16); - } -#elif defined(MBEDTLS_FREESCALE_CAU3_DES) - if (!crypto_key_is_loaded(ctx)) - { - CAU3_TDES_SetKey(CAU3, &s_cau3Handle, key, 24); - crypto_attach_ctx_to_key_slot(ctx, s_cau3Handle.keySlot); - } - - if (ctx->mode == MBEDTLS_DES_ENCRYPT) - { - CAU3_TDES_Encrypt(CAU3, &s_cau3Handle, input, output); - } - else - { - CAU3_TDES_Decrypt(CAU3, &s_cau3Handle, input, output); - } -#endif - return (0); -} - -#if defined(MBEDTLS_CIPHER_MODE_CBC) -/* - * DES-CBC buffer encryption/decryption - */ -#if defined(MBEDTLS_FREESCALE_LTC_DES) -int mbedtls_des_crypt_cbc(mbedtls_des_context * ctx, int mode, size_t length, unsigned char iv[8], const unsigned char * input, - unsigned char * output) -{ - unsigned char temp[8]; - uint8_t * key = (uint8_t *) ctx->sk; - - if (length % 8) - return (MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH); - - if (mode == MBEDTLS_DES_ENCRYPT) - { - LTC_DES_EncryptCbc(LTC_INSTANCE, input, output, length, iv, key); - memcpy(iv, output + length - 8, 8); - } - else /* MBEDTLS_DES_DECRYPT */ - { - memcpy(temp, input + length - 8, 8); - LTC_DES_DecryptCbc(LTC_INSTANCE, input, output, length, iv, key); - memcpy(iv, temp, 8); - } - return (0); -} - -/* - * 3DES-CBC buffer encryption/decryption - */ -int mbedtls_des3_crypt_cbc(mbedtls_des3_context * ctx, int mode, size_t length, unsigned char iv[8], const unsigned char * input, - unsigned char * output) -{ - unsigned char temp[8]; - uint8_t * key = (uint8_t *) ctx->sk; - - if (length % 8) - return (MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH); - - if (mode == MBEDTLS_DES_ENCRYPT) - { - LTC_DES3_EncryptCbc(LTC_INSTANCE, input, output, length, iv, key, key + 8, key + 16); - memcpy(iv, output + length - 8, 8); - } - else /* MBEDTLS_DES_DECRYPT */ - { - memcpy(temp, input + length - 8, 8); - LTC_DES3_DecryptCbc(LTC_INSTANCE, input, output, length, iv, key, key + 8, key + 16); - memcpy(iv, temp, 8); - } - - return (0); -} -#elif defined(MBEDTLS_FREESCALE_CAAM_DES) -int mbedtls_des_crypt_cbc(mbedtls_des_context * ctx, int mode, size_t length, unsigned char iv[8], const unsigned char * input, - unsigned char * output) -{ - unsigned char temp[8]; - uint8_t * key = (uint8_t *) ctx->sk; - - if (length % 8) - return (MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH); - - if (mode == MBEDTLS_DES_ENCRYPT) - { - CAAM_DES_EncryptCbc(CAAM_INSTANCE, &s_caamHandle, input, output, length, iv, key); - memcpy(iv, output + length - 8, 8); - } - else /* MBEDTLS_DES_DECRYPT */ - { - memcpy(temp, input + length - 8, 8); - CAAM_DES_DecryptCbc(CAAM_INSTANCE, &s_caamHandle, input, output, length, iv, key); - memcpy(iv, temp, 8); - } - return (0); -} - -/* - * 3DES-CBC buffer encryption/decryption - */ -int mbedtls_des3_crypt_cbc(mbedtls_des3_context * ctx, int mode, size_t length, unsigned char iv[8], const unsigned char * input, - unsigned char * output) -{ - unsigned char temp[8]; - uint8_t * key = (uint8_t *) ctx->sk; - - if (length % 8) - return (MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH); - - if (mode == MBEDTLS_DES_ENCRYPT) - { - CAAM_DES3_EncryptCbc(CAAM_INSTANCE, &s_caamHandle, input, output, length, iv, key, key + 8, key + 16); - memcpy(iv, output + length - 8, 8); - } - else /* MBEDTLS_DES_DECRYPT */ - { - memcpy(temp, input + length - 8, 8); - CAAM_DES3_DecryptCbc(CAAM_INSTANCE, &s_caamHandle, input, output, length, iv, key, key + 8, key + 16); - memcpy(iv, temp, 8); - } - - return (0); -} - -#endif /* MBEDTLS_FREESCALE_LTC_DES */ -#endif /* MBEDTLS_CIPHER_MODE_CBC */ - -#endif /*MBEDTLS_FREESCALE_LTC_DES || MBEDTLS_FREESCALE_MMCAU_DES || MBEDTLS_FREESCALE_CAAM_DES*/ - -#endif /* MBEDTLS_DES_C */ - -/******************************************************************************/ -/*************************** AES **********************************************/ -/******************************************************************************/ - -#if defined(MBEDTLS_AES_C) - -#if defined(MBEDTLS_FREESCALE_LTC_AES) || defined(MBEDTLS_FREESCALE_MMCAU_AES) || defined(MBEDTLS_FREESCALE_LPC_AES) || \ - defined(MBEDTLS_FREESCALE_CAU3_AES) || defined(MBEDTLS_FREESCALE_CAAM_AES) || defined(MBEDTLS_FREESCALE_DCP_AES) - -#include "mbedtls/aes.h" - -/* - * AES key schedule (encryption) - */ -int mbedtls_aes_setkey_enc(mbedtls_aes_context * ctx, const unsigned char * key, unsigned int keybits) -{ - uint32_t * RK; - -#ifdef MBEDTLS_AES_ALT_NO_192 - if (keybits == 192u) - { - return (MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE); - } -#endif - -#ifdef MBEDTLS_AES_ALT_NO_256 - if (keybits == 256u) - { - return (MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE); - } -#endif - -#if defined(MBEDTLS_FREESCALE_LTC_AES) || defined(MBEDTLS_FREESCALE_LPC_AES) || defined(MBEDTLS_FREESCALE_CAU3_AES) || \ - defined(MBEDTLS_FREESCALE_CAAM_AES) || defined(MBEDTLS_FREESCALE_DCP_AES) - const unsigned char * key_tmp = key; - ctx->rk = RK = ctx->buf; - memcpy(RK, key_tmp, keybits / 8); - -#if defined(MBEDTLS_FREESCALE_CAU3_AES) || defined(MBEDTLS_FREESCALE_DCP_AES) - crypto_detach_ctx_from_key_slot(ctx); -#endif /* MBEDTLS_FREESCALE_CAU3_AES || MBEDTLS_FREESCALE_DCP_AES */ - - switch (keybits) - { /* Set keysize in bytes.*/ - case 128: - ctx->nr = 16; - break; - case 192: - ctx->nr = 24; - break; - case 256: - ctx->nr = 32; - break; - default: - return (MBEDTLS_ERR_AES_INVALID_KEY_LENGTH); - } -#elif defined(MBEDTLS_FREESCALE_MMCAU_AES) - ctx->rk = RK = ctx->buf; - - switch (keybits) - { - case 128: - ctx->nr = 10; - break; - case 192: - ctx->nr = 12; - break; - case 256: - ctx->nr = 14; - break; - default: - return (MBEDTLS_ERR_AES_INVALID_KEY_LENGTH); - } - - MMCAU_AES_SetKey(key, keybits / 8, (uint8_t *) RK); -#endif - - return (0); -} - -/* - * AES key schedule (decryption) - */ -int mbedtls_aes_setkey_dec(mbedtls_aes_context * ctx, const unsigned char * key, unsigned int keybits) -{ - uint32_t * RK; - -#ifdef MBEDTLS_AES_ALT_NO_192 - if (keybits == 192u) - { - return (MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE); - } -#endif - -#ifdef MBEDTLS_AES_ALT_NO_256 - if (keybits == 256u) - { - return (MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE); - } -#endif - - ctx->rk = RK = ctx->buf; - -#if defined(MBEDTLS_FREESCALE_LTC_AES) || defined(MBEDTLS_FREESCALE_LPC_AES) || defined(MBEDTLS_FREESCALE_CAU3_AES) || \ - defined(MBEDTLS_FREESCALE_CAAM_AES) || defined(MBEDTLS_FREESCALE_DCP_AES) - const unsigned char * key_tmp = key; - memcpy(RK, key_tmp, keybits / 8); - -#if defined(MBEDTLS_FREESCALE_CAU3_AES) || defined(MBEDTLS_FREESCALE_DCP_AES) - crypto_detach_ctx_from_key_slot(ctx); -#endif /* MBEDTLS_FREESCALE_CAU3_AES || MBEDTLS_FREESCALE_DCP_AES */ - - switch (keybits) - { - case 128: - ctx->nr = 16; - break; - case 192: - ctx->nr = 24; - break; - case 256: - ctx->nr = 32; - break; - default: - return (MBEDTLS_ERR_AES_INVALID_KEY_LENGTH); - } -#elif defined(MBEDTLS_FREESCALE_MMCAU_AES) - ctx->rk = RK = ctx->buf; - - switch (keybits) - { - case 128: - ctx->nr = 10; - break; - case 192: - ctx->nr = 12; - break; - case 256: - ctx->nr = 14; - break; - default: - return (MBEDTLS_ERR_AES_INVALID_KEY_LENGTH); - } - - MMCAU_AES_SetKey(key, keybits / 8, (uint8_t *) RK); -#endif - - return 0; -} - -/* - * AES-ECB block encryption - */ -int mbedtls_internal_aes_encrypt(mbedtls_aes_context * ctx, const unsigned char input[16], unsigned char output[16]) -{ - uint8_t * key; - - key = (uint8_t *) ctx->rk; -#if defined(MBEDTLS_FREESCALE_LTC_AES) - LTC_AES_EncryptEcb(LTC_INSTANCE, input, output, 16, key, ctx->nr); -#elif defined(MBEDTLS_FREESCALE_MMCAU_AES) - MMCAU_AES_EncryptEcb(input, key, ctx->nr, output); -#elif defined(MBEDTLS_FREESCALE_CAU3_AES) - if (!crypto_key_is_loaded(ctx)) - { - CAU3_AES_SetKey(CAU3, &s_cau3Handle, key, ctx->nr); - crypto_attach_ctx_to_key_slot(ctx, s_cau3Handle.keySlot); - } - CAU3_AES_Encrypt(CAU3, &s_cau3Handle, input, output); -#elif defined(MBEDTLS_FREESCALE_LPC_AES) - AES_128_Encrypt(input, key, output); -#elif defined(MBEDTLS_FREESCALE_CAAM_AES) - CAAM_AES_EncryptEcb(CAAM_INSTANCE, &s_caamHandle, input, output, 16, key, ctx->nr); -#elif defined(MBEDTLS_FREESCALE_DCP_AES) - if (!crypto_key_is_loaded(ctx)) - { - DCP_AES_SetKey(DCP, &s_dcpHandle, key, ctx->nr); - crypto_attach_ctx_to_key_slot(ctx, s_dcpHandle.keySlot); - } - DCP_AES_EncryptEcb(DCP, &s_dcpHandle, input, output, 16); -#endif - - return (0); -} - -/* - * AES-ECB block decryption - */ -int mbedtls_internal_aes_decrypt(mbedtls_aes_context * ctx, const unsigned char input[16], unsigned char output[16]) -{ - uint8_t * key; - - key = (uint8_t *) ctx->rk; -#if defined(MBEDTLS_FREESCALE_LTC_AES) - LTC_AES_DecryptEcb(LTC_INSTANCE, input, output, 16, key, ctx->nr, kLTC_EncryptKey); -#elif defined(MBEDTLS_FREESCALE_MMCAU_AES) - MMCAU_AES_DecryptEcb(input, key, ctx->nr, output); -#elif defined(MBEDTLS_FREESCALE_CAU3_AES) - if (!crypto_key_is_loaded(ctx)) - { - CAU3_AES_SetKey(CAU3, &s_cau3Handle, key, ctx->nr); - crypto_attach_ctx_to_key_slot(ctx, s_cau3Handle.keySlot); - } - CAU3_AES_Decrypt(CAU3, &s_cau3Handle, input, output); -#elif defined(MBEDTLS_FREESCALE_LPC_AES) - AES_128_Decrypt(input, key, output); -#elif defined(MBEDTLS_FREESCALE_CAAM_AES) - CAAM_AES_DecryptEcb(CAAM_INSTANCE, &s_caamHandle, input, output, 16, key, ctx->nr); -#elif defined(MBEDTLS_FREESCALE_DCP_AES) - if (!crypto_key_is_loaded(ctx)) - { - DCP_AES_SetKey(DCP, &s_dcpHandle, key, ctx->nr); - crypto_attach_ctx_to_key_slot(ctx, s_dcpHandle.keySlot); - } - DCP_AES_DecryptEcb(DCP, &s_dcpHandle, input, output, 16); -#endif - - return (0); -} - -#if defined(MBEDTLS_CIPHER_MODE_CBC) -/* - * AES-CBC buffer encryption/decryption - */ -#if defined(MBEDTLS_FREESCALE_LTC_AES) -int mbedtls_aes_crypt_cbc(mbedtls_aes_context * ctx, int mode, size_t length, unsigned char iv[16], const unsigned char * input, - unsigned char * output) -{ - uint8_t * key = (uint8_t *) ctx->rk; - uint32_t keySize = ctx->nr; - - if (length % 16) - return (MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH); - - if (mode == MBEDTLS_AES_DECRYPT) - { - uint8_t tmp[16]; - memcpy(tmp, input + length - 16, 16); - LTC_AES_DecryptCbc(LTC_INSTANCE, input, output, length, iv, key, keySize, kLTC_EncryptKey); - memcpy(iv, tmp, 16); - } - else - { - LTC_AES_EncryptCbc(LTC_INSTANCE, input, output, length, iv, key, keySize); - memcpy(iv, output + length - 16, 16); - } - - return (0); -} -#elif defined(MBEDTLS_FREESCALE_LPC_AES) -int mbedtls_aes_crypt_cbc(mbedtls_aes_context * ctx, int mode, size_t length, unsigned char iv[16], const unsigned char * input, - unsigned char * output) -{ - uint8_t * key; - size_t keySize; - - if (length % 16) - return (MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH); - - key = (uint8_t *) ctx->rk; - keySize = (size_t) ctx->nr; - - if (mode == MBEDTLS_AES_DECRYPT) - { - uint8_t tmp[16]; - memcpy(tmp, input + length - 16, 16); - AES_128_CBC_Decrypt_And_Depad(tmp, length, iv, key, output); - memcpy(iv, tmp, 16); - } - else - { - AES_128_CBC_Encrypt(input, length, iv, key, output); - memcpy(iv, output + length - 16, 16); - } - - return (0); -} -#elif defined(MBEDTLS_FREESCALE_CAAM_AES) -int mbedtls_aes_crypt_cbc(mbedtls_aes_context * ctx, int mode, size_t length, unsigned char iv[16], const unsigned char * input, - unsigned char * output) -{ - uint8_t * key = (uint8_t *) ctx->rk; - uint32_t keySize = ctx->nr; - - if (length % 16) - return (MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH); - - if (mode == MBEDTLS_AES_DECRYPT) - { - uint8_t tmp[16]; - memcpy(tmp, input + length - 16, 16); - CAAM_AES_DecryptCbc(CAAM_INSTANCE, &s_caamHandle, input, output, length, iv, key, keySize); - memcpy(iv, tmp, 16); - } - else - { - CAAM_AES_EncryptCbc(CAAM_INSTANCE, &s_caamHandle, input, output, length, iv, key, keySize); - memcpy(iv, output + length - 16, 16); - } - - return (0); -} -#elif defined(MBEDTLS_FREESCALE_DCP_AES) -int mbedtls_aes_crypt_cbc(mbedtls_aes_context * ctx, int mode, size_t length, unsigned char iv[16], const unsigned char * input, - unsigned char * output) -{ - uint8_t * key; - - if (length % 16) - return (MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH); - - key = (uint8_t *) ctx->rk; - if (!crypto_key_is_loaded(ctx)) - { - DCP_AES_SetKey(DCP, &s_dcpHandle, key, ctx->nr); - crypto_attach_ctx_to_key_slot(ctx, s_dcpHandle.keySlot); - } - - if (mode == MBEDTLS_AES_DECRYPT) - { - uint8_t tmp[16]; - memcpy(tmp, input + length - 16, 16); - DCP_AES_DecryptCbc(DCP, &s_dcpHandle, input, output, length, iv); - memcpy(iv, tmp, 16); - } - else - { - DCP_AES_EncryptCbc(DCP, &s_dcpHandle, input, output, length, iv); - memcpy(iv, output + length - 16, 16); - } - - return (0); -} -#endif -#endif /* MBEDTLS_CIPHER_MODE_CBC */ - -#if defined(MBEDTLS_CIPHER_MODE_CFB) -#if defined(MBEDTLS_FREESCALE_LPC_AES) -/* - * AES-CFB128 buffer encryption/decryption - */ -int mbedtls_aes_crypt_cfb128(mbedtls_aes_context * ctx, int mode, size_t length, size_t * iv_off, unsigned char iv[16], - const unsigned char * input, unsigned char * output) -{ - uint8_t * key; - size_t keySize; - - key = (uint8_t *) ctx->rk; - keySize = (size_t) ctx->nr; - AES_SetKey(AES_INSTANCE, key, keySize); - - if (mode == MBEDTLS_AES_DECRYPT) - { - AES_DecryptCfb(AES_INSTANCE, input, output, length, iv); - } - else - { - AES_EncryptCfb(AES_INSTANCE, input, output, length, iv); - } - - return (0); -} - -/* - * AES-CFB8 buffer encryption/decryption - */ -int mbedtls_aes_crypt_cfb8(mbedtls_aes_context * ctx, int mode, size_t length, unsigned char iv[16], const unsigned char * input, - unsigned char * output) -{ - int status; - unsigned char c; - unsigned char ov[17]; - - while (length--) - { - memcpy(ov, iv, 16); - status = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, iv, iv); - if (status != 0) - { - return status; - } - - if (mode == MBEDTLS_AES_DECRYPT) - ov[16] = *input; - - c = *output++ = (unsigned char) (iv[0] ^ *input++); - - if (mode == MBEDTLS_AES_ENCRYPT) - ov[16] = c; - - memcpy(iv, ov + 1, 16); - } - - return (0); -} -#endif /* MBEDTLS_FREESCALE_LPC_AES */ -#endif /* MBEDTLS_CIPHER_MODE_CFB */ - -#if defined(MBEDTLS_CIPHER_MODE_CTR) -/* - * AES-CTR buffer encryption/decryption - */ -#if defined(MBEDTLS_FREESCALE_LTC_AES) -int mbedtls_aes_crypt_ctr(mbedtls_aes_context * ctx, size_t length, size_t * nc_off, unsigned char nonce_counter[16], - unsigned char stream_block[16], const unsigned char * input, unsigned char * output) -{ - uint8_t * key; - uint32_t keySize; - - key = (uint8_t *) ctx->rk; - keySize = ctx->nr; - LTC_AES_CryptCtr(LTC_INSTANCE, input, output, length, nonce_counter, key, keySize, stream_block, (uint32_t *) nc_off); - - return (0); -} -#elif defined(MBEDTLS_FREESCALE_LPC_AES) -int mbedtls_aes_crypt_ctr(mbedtls_aes_context * ctx, size_t length, size_t * nc_off, unsigned char nonce_counter[16], - unsigned char stream_block[16], const unsigned char * input, unsigned char * output) -{ - uint8_t * key; - size_t keySize; - - key = (uint8_t *) ctx->rk; - keySize = (size_t) ctx->nr; - - AES_128_CTR(input, length, nonce_counter, key, output); - - return (0); -} -#elif defined(MBEDTLS_FREESCALE_CAAM_AES) -int mbedtls_aes_crypt_ctr(mbedtls_aes_context * ctx, size_t length, size_t * nc_off, unsigned char nonce_counter[16], - unsigned char stream_block[16], const unsigned char * input, unsigned char * output) -{ - uint8_t * key; - uint32_t keySize; - - key = (uint8_t *) ctx->rk; - keySize = ctx->nr; - - CAAM_AES_CryptCtr(CAAM_INSTANCE, &s_caamHandle, input, output, length, nonce_counter, key, keySize, stream_block, nc_off); - - return (0); -} -#endif -#endif /* MBEDTLS_CIPHER_MODE_CTR */ - -#if defined(MBEDTLS_CIPHER_CMAC_ALT) && defined(MBEDTLS_CMAC_C) - -#include "mbedtls/cipher.h" -#include "mbedtls/cmac.h" - -#if defined(MBEDTLS_FREESCALE_CAU3_CIPHER_CMAC) -int mbedtls_cipher_cmac(const mbedtls_cipher_info_t * cipher_info, const unsigned char * key, size_t keylen, - const unsigned char * input, size_t ilen, unsigned char * output) -{ - mbedtls_cipher_context_t ctx; - int ret; - - if (cipher_info == NULL || key == NULL || input == NULL || output == NULL) - return (MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA); - - mbedtls_cipher_init(&ctx); - - if ((ret = mbedtls_cipher_setup(&ctx, cipher_info)) != 0) - goto exit; - - ret = mbedtls_cipher_cmac_starts(&ctx, key, keylen); - if (ret != 0) - goto exit; - - /* AES-CMAC-128 is directly supported by CAU3 firmware */ - if (cipher_info->type == MBEDTLS_CIPHER_AES_128_ECB) - { - status_t status; - uint8_t mac[16]; - - status = CAU3_AES_SetKey(CAU3, &s_cau3Handle, key, keylen / 8u); - if (status != kStatus_Success) - { - ret = MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA; - goto exit; - } - status = CAU3_AES_Cmac(CAU3, &s_cau3Handle, input, ilen, mac); - if (status != kStatus_Success) - { - ret = MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA; - goto exit; - } - memcpy(output, mac, 16); - } -#if defined(MBEDTLS_CIPHER_CMAC_TDES_ENABLED) || defined(MBEDTLS_CIPHER_CMAC_AES_256_ENABLED) - else if (cipher_info->type == MBEDTLS_CIPHER_AES_192_ECB) - { - /* CAU3 initial firmware does not support AES 192 */ - ret = MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA; - goto exit; - } - else - { - /* AES-CMAC-256 and TDES-CMAC. - * If both MBEDTLS_DES_C and MBEDTLS_CIPHER_CMAC_WANTS_AES_256 are undefined, - * this does not compile - */ - ret = mbedtls_cipher_cmac_update(&ctx, input, ilen); - if (ret != 0) - goto exit; - - ret = mbedtls_cipher_cmac_finish(&ctx, output); - } -#else - else - { - ret = MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA; - goto exit; - } -#endif /* MBEDTLS_CIPHER_CMAC_TDES_ENABLED || MBEDTLS_CIPHER_CMAC_AES_256_ENABLED */ - -exit: - mbedtls_cipher_free(&ctx); - - return (ret); -} -#endif /* MBEDTLS_FREESCALE_CAU3_CIPHER_CMAC */ -#endif /* MBEDTLS_CIPHER_CMAC_ALT && MBEDTLS_CMAC_C */ - -#if defined(MBEDTLS_CCM_C) - -#include "mbedtls/ccm.h" - -#define CCM_ENCRYPT 0 -#define CCM_DECRYPT 1 - -/* - * Authenticated encryption or decryption - */ -#if defined(MBEDTLS_FREESCALE_LTC_AES) -static int ccm_auth_crypt(mbedtls_ccm_context * ctx, int mode, size_t length, const unsigned char * iv, size_t iv_len, - const unsigned char * add, size_t add_len, const unsigned char * input, unsigned char * output, - unsigned char * tag, size_t tag_len) -{ - status_t status; - const uint8_t * key; - uint8_t keySize; - mbedtls_aes_context * aes_ctx; - - aes_ctx = (mbedtls_aes_context *) ctx->cipher_ctx.cipher_ctx; - key = (uint8_t *) aes_ctx->rk; - keySize = aes_ctx->nr; - if (mode == CCM_ENCRYPT) - { - status = LTC_AES_EncryptTagCcm(LTC_INSTANCE, input, output, length, iv, iv_len, add, add_len, key, keySize, tag, tag_len); - } - else - { - status = LTC_AES_DecryptTagCcm(LTC_INSTANCE, input, output, length, iv, iv_len, add, add_len, key, keySize, tag, tag_len); - } - - if (status == kStatus_InvalidArgument) - { - return MBEDTLS_ERR_CCM_BAD_INPUT; - } - else if (status != kStatus_Success) - { - return MBEDTLS_ERR_CCM_AUTH_FAILED; - } - - return (0); -} -#elif defined(MBEDTLS_FREESCALE_CAAM_AES) -static int ccm_auth_crypt(mbedtls_ccm_context * ctx, int mode, size_t length, const unsigned char * iv, size_t iv_len, - const unsigned char * add, size_t add_len, const unsigned char * input, unsigned char * output, - unsigned char * tag, size_t tag_len) -{ - status_t status; - const uint8_t * key; - uint8_t keySize; - mbedtls_aes_context * aes_ctx; - - aes_ctx = (mbedtls_aes_context *) ctx->cipher_ctx.cipher_ctx; - key = (uint8_t *) aes_ctx->rk; - keySize = aes_ctx->nr; - if (mode == CCM_ENCRYPT) - { - status = CAAM_AES_EncryptTagCcm(CAAM_INSTANCE, &s_caamHandle, input, output, length, iv, iv_len, add, add_len, key, keySize, - tag, tag_len); - } - else - { - status = CAAM_AES_DecryptTagCcm(CAAM_INSTANCE, &s_caamHandle, input, output, length, iv, iv_len, add, add_len, key, keySize, - tag, tag_len); - } - - if (status == kStatus_InvalidArgument) - { - return MBEDTLS_ERR_CCM_BAD_INPUT; - } - else if (status != kStatus_Success) - { - return MBEDTLS_ERR_CCM_AUTH_FAILED; - } - - return (0); -} -#endif /* MBEDTLS_FREESCALE_LTC_AES */ - -#if defined(MBEDTLS_FREESCALE_LTC_AES) || defined(MBEDTLS_FREESCALE_CAAM_AES) -/* - * Authenticated encryption - */ -int mbedtls_ccm_encrypt_and_tag(mbedtls_ccm_context * ctx, size_t length, const unsigned char * iv, size_t iv_len, - const unsigned char * add, size_t add_len, const unsigned char * input, unsigned char * output, - unsigned char * tag, size_t tag_len) -{ - return (ccm_auth_crypt(ctx, CCM_ENCRYPT, length, iv, iv_len, add, add_len, input, output, tag, tag_len)); -} - -/* - * Authenticated decryption - */ -int mbedtls_ccm_auth_decrypt(mbedtls_ccm_context * ctx, size_t length, const unsigned char * iv, size_t iv_len, - const unsigned char * add, size_t add_len, const unsigned char * input, unsigned char * output, - const unsigned char * tag, size_t tag_len) -{ - unsigned char tagCopy[16]; - unsigned char * actTag = NULL; - if (tag) - { - memcpy(tagCopy, tag, tag_len); - actTag = tagCopy; - } - return (ccm_auth_crypt(ctx, CCM_DECRYPT, length, iv, iv_len, add, add_len, input, output, actTag, tag_len)); -} -#endif /* MBEDTLS_FREESCALE_LTC_AES || MBEDTLS_FREESCALE_CAAM_AES */ -#endif /* MBEDTLS_CCM_C */ - -#if defined(MBEDTLS_GCM_C) -#if defined(MBEDTLS_FREESCALE_LTC_AES_GCM) - -#include "mbedtls/gcm.h" - -int mbedtls_gcm_crypt_and_tag(mbedtls_gcm_context * ctx, int mode, size_t length, const unsigned char * iv, size_t iv_len, - const unsigned char * add, size_t add_len, const unsigned char * input, unsigned char * output, - size_t tag_len, unsigned char * tag) -{ - status_t status; - uint8_t * key; - uint32_t keySize; - mbedtls_aes_context * aes_ctx; - - ctx->len = length; - ctx->add_len = add_len; - aes_ctx = (mbedtls_aes_context *) ctx->cipher_ctx.cipher_ctx; - key = (uint8_t *) aes_ctx->rk; - keySize = aes_ctx->nr; - if (mode == MBEDTLS_GCM_ENCRYPT) - { - status = LTC_AES_EncryptTagGcm(LTC_INSTANCE, input, output, length, iv, iv_len, add, add_len, key, keySize, tag, tag_len); - } - else - { - status = LTC_AES_DecryptTagGcm(LTC_INSTANCE, input, output, length, iv, iv_len, add, add_len, key, keySize, tag, tag_len); - } - - if (status == kStatus_InvalidArgument) - { - return MBEDTLS_ERR_GCM_BAD_INPUT; - } - else if (status != kStatus_Success) - { - return MBEDTLS_ERR_GCM_AUTH_FAILED; - } - - return 0; -} - -int mbedtls_gcm_auth_decrypt(mbedtls_gcm_context * ctx, size_t length, const unsigned char * iv, size_t iv_len, - const unsigned char * add, size_t add_len, const unsigned char * tag, size_t tag_len, - const unsigned char * input, unsigned char * output) -{ - unsigned char tag_copy[16]; - unsigned char * actTag = NULL; - if (tag) - { - memcpy(tag_copy, tag, tag_len); - actTag = tag_copy; - } - return (mbedtls_gcm_crypt_and_tag(ctx, MBEDTLS_GCM_DECRYPT, length, iv, iv_len, add, add_len, input, output, tag_len, actTag)); -} - -#elif defined(MBEDTLS_FREESCALE_LPC_AES_GCM) - -#include "mbedtls/gcm.h" - -int mbedtls_gcm_crypt_and_tag(mbedtls_gcm_context * ctx, int mode, size_t length, const unsigned char * iv, size_t iv_len, - const unsigned char * add, size_t add_len, const unsigned char * input, unsigned char * output, - size_t tag_len, unsigned char * tag) -{ - status_t status; - uint8_t * key; - size_t keySize; - mbedtls_aes_context * aes_ctx; - - ctx->len = length; - ctx->add_len = add_len; - aes_ctx = (mbedtls_aes_context *) ctx->cipher_ctx.cipher_ctx; - key = (uint8_t *) aes_ctx->rk; - keySize = (size_t) aes_ctx->nr; - - status = AES_SetKey(AES_INSTANCE, key, keySize); - if (status != kStatus_Success) - { - return MBEDTLS_ERR_GCM_BAD_INPUT; - } - - if (mode == MBEDTLS_GCM_ENCRYPT) - { - status = AES_EncryptTagGcm(AES_INSTANCE, input, output, length, iv, iv_len, add, add_len, tag, tag_len); - } - else - { - status = AES_DecryptTagGcm(AES_INSTANCE, input, output, length, iv, iv_len, add, add_len, tag, tag_len); - } - - if (status == kStatus_InvalidArgument) - { - return MBEDTLS_ERR_GCM_BAD_INPUT; - } - else if (status != kStatus_Success) - { - return MBEDTLS_ERR_GCM_AUTH_FAILED; - } - - return 0; -} - -int mbedtls_gcm_auth_decrypt(mbedtls_gcm_context * ctx, size_t length, const unsigned char * iv, size_t iv_len, - const unsigned char * add, size_t add_len, const unsigned char * tag, size_t tag_len, - const unsigned char * input, unsigned char * output) -{ - unsigned char tag_copy[16]; - - memcpy(tag_copy, tag, tag_len); - return ( - mbedtls_gcm_crypt_and_tag(ctx, MBEDTLS_GCM_DECRYPT, length, iv, iv_len, add, add_len, input, output, tag_len, tag_copy)); -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_AES_GCM) - -#include "mbedtls/gcm.h" - -int mbedtls_gcm_crypt_and_tag(mbedtls_gcm_context * ctx, int mode, size_t length, const unsigned char * iv, size_t iv_len, - const unsigned char * add, size_t add_len, const unsigned char * input, unsigned char * output, - size_t tag_len, unsigned char * tag) -{ - status_t status; - uint8_t * key; - uint32_t keySize; - mbedtls_aes_context * aes_ctx; - - ctx->len = length; - ctx->add_len = add_len; - aes_ctx = (mbedtls_aes_context *) ctx->cipher_ctx.cipher_ctx; - key = (uint8_t *) aes_ctx->rk; - keySize = aes_ctx->nr; - if (mode == MBEDTLS_GCM_ENCRYPT) - { - status = CAAM_AES_EncryptTagGcm(CAAM_INSTANCE, &s_caamHandle, input, output, length, iv, iv_len, add, add_len, key, keySize, - tag, tag_len); - } - else - { - status = CAAM_AES_DecryptTagGcm(CAAM_INSTANCE, &s_caamHandle, input, output, length, iv, iv_len, add, add_len, key, keySize, - tag, tag_len); - } - - if (status == kStatus_InvalidArgument) - { - return MBEDTLS_ERR_GCM_BAD_INPUT; - } - else if (status != kStatus_Success) - { - return MBEDTLS_ERR_GCM_AUTH_FAILED; - } - - return 0; -} - -int mbedtls_gcm_auth_decrypt(mbedtls_gcm_context * ctx, size_t length, const unsigned char * iv, size_t iv_len, - const unsigned char * add, size_t add_len, const unsigned char * tag, size_t tag_len, - const unsigned char * input, unsigned char * output) -{ - unsigned char tag_copy[16]; - unsigned char * actTag = NULL; - if (tag) - { - memcpy(tag_copy, tag, tag_len); - actTag = tag_copy; - } - return (mbedtls_gcm_crypt_and_tag(ctx, MBEDTLS_GCM_DECRYPT, length, iv, iv_len, add, add_len, input, output, tag_len, actTag)); -} -#endif -#endif /* MBEDTLS_GCM_C */ - -#endif /* MBEDTLS_FREESCALE_LTC_AES || MBEDTLS_FREESCALE_MMCAU_AES || MBEDTLS_FREESCALE_LPC_AES */ - -#endif /* MBEDTLS_AES_C */ - -/******************************************************************************/ -/*************************** PKHA *********************************************/ -/******************************************************************************/ - -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) || defined(MBEDTLS_FREESCALE_CAU3_PKHA) || defined(MBEDTLS_FREESCALE_CAAM_PKHA) - -#if defined(MBEDTLS_PLATFORM_C) -#include "mbedtls/platform.h" -#else -#include -#define mbedtls_calloc calloc -#define mbedtls_free free -#endif - -static void ltc_reverse_array(uint8_t * src, size_t src_len) -{ - int i; - - for (i = 0; i < src_len / 2; i++) - { - uint8_t tmp; - - tmp = src[i]; - src[i] = src[src_len - 1 - i]; - src[src_len - 1 - i] = tmp; - } -} - -#if defined(MBEDTLS_BIGNUM_C) - -#include "mbedtls/bignum.h" - -#if defined(MBEDTLS_FREESCALE_CAU3_PKHA) -#define LTC_PKHA_ModAdd CAU3_PKHA_ModAdd -#define LTC_PKHA_ModSub1 CAU3_PKHA_ModSub1 -#define LTC_PKHA_ModMul CAU3_PKHA_ModMul -#define LTC_PKHA_ModRed CAU3_PKHA_ModRed -#define LTC_PKHA_ModExp CAU3_PKHA_ModExp -#define LTC_PKHA_GCD CAU3_PKHA_ModGcd -#define LTC_PKHA_ModInv CAU3_PKHA_ModInv -#define LTC_PKHA_PrimalityTest CAU3_PKHA_PrimalityTest -#define LTC_INSTANCE ((CAU3_Type *) CAU3_BASE) - -#define kLTC_PKHA_IntegerArith kCAU3_PKHA_IntegerArith -#define kLTC_PKHA_NormalValue kCAU3_PKHA_NormalValue -#define kLTC_PKHA_TimingEqualized kCAU3_PKHA_TimingEqualized - -#define cau3_reverse_array ltc_reverse_array -#define cau3_get_from_mbedtls_mpi ltc_get_from_mbedtls_mpi -#endif - -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) -typedef uint16_t pkha_size_t; -#else -typedef size_t pkha_size_t; -#endif - -#if defined(MBEDTLS_MPI_ADD_ABS_ALT) - -/* Access to original version of mbedtls_mpi_add_abs function. */ -int mbedtls_mpi_add_abs_orig(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * B); - -/* - * Unsigned addition: X = |A| + |B| (HAC 14.7) - */ -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) || defined(MBEDTLS_FREESCALE_CAU3_PKHA) -int mbedtls_mpi_add_abs(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * B) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeB = mbedtls_mpi_size(B); - pkha_size_t sizeN = FREESCALE_PKHA_INT_MAX_BYTES; - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - /* - * Perform HW acceleration only if the size in bytes is less than maximum. - * Since modular add is used below, the result would be wrong - * if the real sum of operands exceeded LTC maximum number value. - */ - if ((sizeA < sizeN) && (sizeB < sizeN)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - uint8_t * N = mbedtls_calloc(4, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrA = N + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrB = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrB + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == N) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - memset(N, 0xFF, sizeN); - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - ltc_reverse_array(ptrA, sizeA); - - mbedtls_mpi_write_binary(B, ptrB, sizeB); - ltc_reverse_array(ptrB, sizeB); - - ret = (int) LTC_PKHA_ModAdd(LTC_INSTANCE, ptrA, sizeA, ptrB, sizeB, N, sizeN, ptrC, &sizeC, kLTC_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - ltc_reverse_array(ptrC, sizeC); - mbedtls_mpi_read_binary(X, ptrC, sizeC); - X->s = 1; - cleanup: - if (N) - { - mbedtls_free(N); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_add_abs_orig(X, A, B); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_PKHA) -int mbedtls_mpi_add_abs(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * B) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeB = mbedtls_mpi_size(B); - pkha_size_t sizeN = FREESCALE_PKHA_INT_MAX_BYTES; - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - /* - * Perform HW acceleration only if the size in bytes is less than maximum. - * Since modular add is used below, the result would be wrong - * if the real sum of operands exceeded CAAM maximum number value. - */ - if ((sizeA < sizeN) && (sizeB < sizeN)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - uint8_t * N = mbedtls_calloc(4, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrA = N + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrB = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrB + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == N) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - memset(N, 0xFF, sizeN); - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - mbedtls_mpi_write_binary(B, ptrB, sizeB); - - ret = (int) CAAM_PKHA_ModAdd(CAAM_INSTANCE, &s_caamHandle, ptrA, sizeA, ptrB, sizeB, N, sizeN, ptrC, &sizeC, - kCAAM_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - mbedtls_mpi_read_binary(X, ptrC, sizeC); - X->s = 1; - cleanup: - if (N) - { - mbedtls_free(N); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_add_abs_orig(X, A, B); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} -#endif /* MBEDTLS_FREESCALE_LTC_PKHA || MBEDTLS_FREESCALE_CAU3_PKHA */ -#endif /* MBEDTLS_MPI_ADD_ABS_ALT */ - -#if defined(MBEDTLS_MPI_SUB_ABS_ALT) - -/* Access to original version of mbedtls_mpi_sub_abs function. */ -int mbedtls_mpi_sub_abs_orig(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * B); - -/* - * Unsigned subtraction: X = |A| - |B| (HAC 14.9) - */ -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) || defined(MBEDTLS_FREESCALE_CAU3_PKHA) -int mbedtls_mpi_sub_abs(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * B) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeB = mbedtls_mpi_size(B); - pkha_size_t sizeN = FREESCALE_PKHA_INT_MAX_BYTES; - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - /* - * Perform HW acceleration only if |A| >= |B|. Since modular subtraction is used below, - * the result would be wrong if the real sum of operands exceeded maximum. - */ - if ((sizeA <= sizeN) && (sizeB <= sizeN) && (mbedtls_mpi_cmp_abs(A, B) >= 0)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - uint8_t * N = mbedtls_calloc(4, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrA = N + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrB = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrB + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == N) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - memset(N, 0xFF, sizeN); - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - ltc_reverse_array(ptrA, sizeA); - - mbedtls_mpi_write_binary(B, ptrB, sizeB); - ltc_reverse_array(ptrB, sizeB); - - ret = (int) LTC_PKHA_ModSub1(LTC_INSTANCE, ptrA, sizeA, ptrB, sizeB, N, sizeN, ptrC, &sizeC); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - ltc_reverse_array(ptrC, sizeC); - mbedtls_mpi_read_binary(X, ptrC, sizeC); - X->s = 1; - cleanup: - if (N) - { - mbedtls_free(N); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_sub_abs_orig(X, A, B); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_PKHA) -int mbedtls_mpi_sub_abs(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * B) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeB = mbedtls_mpi_size(B); - pkha_size_t sizeN = FREESCALE_PKHA_INT_MAX_BYTES; - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - /* - * Perform HW acceleration only if |A| >= |B|. Since modular subtraction is used below, - * the result would be wrong if the real sum of operands exceeded maximum. - */ - if ((sizeA <= sizeN) && (sizeB <= sizeN) && (mbedtls_mpi_cmp_abs(A, B) >= 0)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - uint8_t * N = mbedtls_calloc(4, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrA = N + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrB = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrB + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == N) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - memset(N, 0xFF, sizeN); - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - mbedtls_mpi_write_binary(B, ptrB, sizeB); - - ret = (int) CAAM_PKHA_ModSub1(CAAM_INSTANCE, &s_caamHandle, ptrA, sizeA, ptrB, sizeB, N, sizeN, ptrC, &sizeC); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - mbedtls_mpi_read_binary(X, ptrC, sizeC); - X->s = 1; - cleanup: - if (N) - { - mbedtls_free(N); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_sub_abs_orig(X, A, B); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} -#endif /* MBEDTLS_FREESCALE_LTC_PKHA || MBEDTLS_FREESCALE_CAU3_PKHA */ -#endif /* MBEDTLS_MPI_SUB_ABS_ALT */ - -#if defined(MBEDTLS_MPI_MUL_MPI_ALT) - -/* Access to original version of mbedtls_mpi_mul_mpi function. */ -int mbedtls_mpi_mul_mpi_orig(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * B); - -/* - * Baseline multiplication: X = A * B (HAC 14.12) - */ -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) || defined(MBEDTLS_FREESCALE_CAU3_PKHA) -int mbedtls_mpi_mul_mpi(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * B) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeB = mbedtls_mpi_size(B); - pkha_size_t sizeN = FREESCALE_PKHA_INT_MAX_BYTES; - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - /* - * Should be "if ((sizeA + sizeB) <= sizeN)", but if the multiplication result - * would be maximum LTC number (the same value as the modulus N below), - * zero would be returned instead, which is wrong value. - */ - if ((sizeA + sizeB) < sizeN) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - int sign = A->s * B->s; - - uint8_t * N = mbedtls_calloc(4, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrA = N + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrB = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrB + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == N) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - memset(N, 0xFF, sizeN); - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - ltc_reverse_array(ptrA, sizeA); - - mbedtls_mpi_write_binary(B, ptrB, sizeB); - ltc_reverse_array(ptrB, sizeB); - - /* - * Modular multiplication operation is used here. Since the modulus N is larger - * than the expected result of A * B, the effect is normal multiplication. - * TODO use PKHA MUL_IM_OM instead. - */ - ret = (int) LTC_PKHA_ModMul(LTC_INSTANCE, ptrA, sizeA, ptrB, sizeB, N, sizeN, ptrC, &sizeC, kLTC_PKHA_IntegerArith, - kLTC_PKHA_NormalValue, kLTC_PKHA_NormalValue, kLTC_PKHA_TimingEqualized); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - ltc_reverse_array(ptrC, sizeC); - mbedtls_mpi_read_binary(X, ptrC, sizeC); - X->s = sign; - cleanup: - if (N) - { - mbedtls_free(N); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_mul_mpi_orig(X, A, B); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_PKHA) -int mbedtls_mpi_mul_mpi(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * B) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeB = mbedtls_mpi_size(B); - pkha_size_t sizeN = FREESCALE_PKHA_INT_MAX_BYTES; - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - /* - * Should be "if ((sizeA + sizeB) <= sizeN)", but if the multiplication result - * would be maximum CAAM number (the same value as the modulus N below), - * zero would be returned instead, which is wrong value. - */ - if ((sizeA + sizeB) < sizeN) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - int sign = A->s * B->s; - - uint8_t * N = mbedtls_calloc(4, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrA = N + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrB = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrB + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == N) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - memset(N, 0xFF, sizeN); - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - mbedtls_mpi_write_binary(B, ptrB, sizeB); - - /* - * Modular multiplication operation is used here. Since the modulus N is larger - * than the expected result of A * B, the effect is normal multiplication. - * TODO use PKHA MUL_IM_OM instead. - */ - ret = (int) CAAM_PKHA_ModMul(CAAM_INSTANCE, &s_caamHandle, ptrA, sizeA, ptrB, sizeB, N, sizeN, ptrC, &sizeC, - kCAAM_PKHA_IntegerArith, kCAAM_PKHA_NormalValue, kCAAM_PKHA_NormalValue, - kCAAM_PKHA_TimingEqualized); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - mbedtls_mpi_read_binary(X, ptrC, sizeC); - X->s = sign; - cleanup: - if (N) - { - mbedtls_free(N); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_mul_mpi_orig(X, A, B); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} -#endif /* MBEDTLS_FREESCALE_LTC_PKHA || MBEDTLS_FREESCALE_CAU3_PKHA */ -#endif /* MBEDTLS_MPI_MUL_MPI_ALT */ - -#if defined(MBEDTLS_MPI_MOD_MPI_ALT) - -/* Access to original version of mbedtls_mpi_mod_mpi function. */ -int mbedtls_mpi_mod_mpi_orig(mbedtls_mpi * R, const mbedtls_mpi * A, const mbedtls_mpi * B); - -/* - * Modulo: R = A mod B - */ -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) || defined(MBEDTLS_FREESCALE_CAU3_PKHA) -int mbedtls_mpi_mod_mpi(mbedtls_mpi * R, const mbedtls_mpi * A, const mbedtls_mpi * B) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeB = mbedtls_mpi_size(B); - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - if ((sizeA <= FREESCALE_PKHA_INT_MAX_BYTES) && (sizeB <= FREESCALE_PKHA_INT_MAX_BYTES)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - int sign = A->s; - uint8_t * ptrA = mbedtls_calloc(3, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrB = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrB + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == ptrA) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - ltc_reverse_array(ptrA, sizeA); - - mbedtls_mpi_write_binary(B, ptrB, sizeB); - ltc_reverse_array(ptrB, sizeB); - - ret = (int) LTC_PKHA_ModRed(LTC_INSTANCE, ptrA, sizeA, ptrB, sizeB, ptrC, &sizeC, kLTC_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - ltc_reverse_array(ptrC, sizeC); - mbedtls_mpi_read_binary(R, ptrC, sizeC); - R->s = sign; - - while (mbedtls_mpi_cmp_int(R, 0) < 0) - mbedtls_mpi_add_mpi(R, R, B); /* MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( R, R, B ) ); */ - - while (mbedtls_mpi_cmp_mpi(R, B) >= 0) - mbedtls_mpi_sub_mpi(R, R, B); /* MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( R, R, B ) ); cleanup:*/ - cleanup: - if (ptrA) - { - mbedtls_free(ptrA); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_mod_mpi_orig(R, A, B); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_PKHA) -int mbedtls_mpi_mod_mpi(mbedtls_mpi * R, const mbedtls_mpi * A, const mbedtls_mpi * B) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeB = mbedtls_mpi_size(B); - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - if ((sizeA <= FREESCALE_PKHA_INT_MAX_BYTES) && (sizeB <= FREESCALE_PKHA_INT_MAX_BYTES)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - int sign = A->s; - uint8_t * ptrA = mbedtls_calloc(3, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrB = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrB + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == ptrA) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - mbedtls_mpi_write_binary(B, ptrB, sizeB); - - ret = (int) CAAM_PKHA_ModRed(CAAM_INSTANCE, &s_caamHandle, ptrA, sizeA, ptrB, sizeB, ptrC, &sizeC, kCAAM_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - mbedtls_mpi_read_binary(R, ptrC, sizeC); - R->s = sign; - - while (mbedtls_mpi_cmp_int(R, 0) < 0) - mbedtls_mpi_add_mpi(R, R, B); /* MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( R, R, B ) ); */ - - while (mbedtls_mpi_cmp_mpi(R, B) >= 0) - mbedtls_mpi_sub_mpi(R, R, B); /* MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( R, R, B ) ); cleanup:*/ - cleanup: - if (ptrA) - { - mbedtls_free(ptrA); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_mod_mpi_orig(R, A, B); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} -#endif /* MBEDTLS_FREESCALE_LTC_PKHA || MBEDTLS_FREESCALE_CAU3_PKHA */ -#endif /* MBEDTLS_MPI_MOD_MPI_ALT */ - -#if defined(MBEDTLS_MPI_EXP_MOD_ALT) - -/* Access to original version of mbedtls_mpi_exp_mod function. */ -int mbedtls_mpi_exp_mod_orig(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * E, const mbedtls_mpi * N, - mbedtls_mpi * _RR); - -/* - * Sliding-window exponentiation: X = A^E mod N (HAC 14.85) - */ -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) || defined(MBEDTLS_FREESCALE_CAU3_PKHA) -int mbedtls_mpi_exp_mod(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * E, const mbedtls_mpi * N, mbedtls_mpi * _RR) -{ - int ret; - pkha_size_t sizeE = mbedtls_mpi_size(E); - pkha_size_t sizeN = mbedtls_mpi_size(N); - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - if ((sizeE <= FREESCALE_PKHA_INT_MAX_BYTES) && (sizeN <= FREESCALE_PKHA_INT_MAX_BYTES)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - mbedtls_mpi * AA; // TODO rename etc. - - /* - * If number is greater than modulus, we must first reduce it due to LTC requirement - * on modular exponentiaton that it needs number less than modulus. - * We can take advantage of modular arithmetic rule that: A^B mod C = ( (A mod C)^B ) mod C. - * So we do (A mod N) first and if the size of A in bytes fits into LTC, it will be done in LTC - * (here LTC does not give size requirement on A versus N), otherwise it will be done in SW - * and since the size of N fits into LTC, the result of (A mod N) will also fit into LTC. - * Then we can do modular exponentiation in LTC. - */ - if (mbedtls_mpi_cmp_mpi(A, N) >= 0) - { - /* A >= N, perform X = (A mod N). */ - ret = mbedtls_mpi_mod_mpi(X, A, N); - - if (ret != kStatus_Success) - return (MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - /* Exponenciation will be performed with X. */ - AA = X; - } - else - { - /* Exponentiation will be performed with original A. */ - AA = (mbedtls_mpi *) A; - } - - pkha_size_t sizeA = mbedtls_mpi_size(AA); - uint8_t * ptrA = mbedtls_calloc(3, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrE = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrN = ptrE + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == ptrA) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - mbedtls_mpi_write_binary(AA, ptrA, sizeA); - ltc_reverse_array(ptrA, sizeA); - - mbedtls_mpi_write_binary(E, ptrE, sizeE); - ltc_reverse_array(ptrE, sizeE); - - mbedtls_mpi_write_binary(N, ptrN, sizeN); - ltc_reverse_array(ptrN, sizeN); - - ret = (int) LTC_PKHA_ModExp(LTC_INSTANCE, ptrA, sizeA, ptrN, sizeN, ptrE, sizeE, ptrN, &sizeN, kLTC_PKHA_IntegerArith, - kLTC_PKHA_NormalValue, kLTC_PKHA_TimingEqualized); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - ltc_reverse_array(ptrN, sizeN); - mbedtls_mpi_read_binary(X, ptrN, sizeN); - cleanup: - if (ptrA) - { - mbedtls_free(ptrA); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_exp_mod_orig(X, A, E, N, _RR); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_PKHA) -int mbedtls_mpi_exp_mod(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * E, const mbedtls_mpi * N, mbedtls_mpi * _RR) -{ - int ret; - pkha_size_t sizeE = mbedtls_mpi_size(E); - pkha_size_t sizeN = mbedtls_mpi_size(N); - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - if ((sizeE <= FREESCALE_PKHA_INT_MAX_BYTES) && (sizeN <= FREESCALE_PKHA_INT_MAX_BYTES)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - mbedtls_mpi * AA; // TODO rename etc. - - /* - * If number is greater than modulus, we must first reduce it due to CAAM requirement - * on modular exponentiaton that it needs number less than modulus. - * We can take advantage of modular arithmetic rule that: A^B mod C = ( (A mod C)^B ) mod C. - * So we do (A mod N) first and if the size of A in bytes fits into CAAM, it will be done in CAAM - * (here CAAM does not give size requirement on A versus N), otherwise it will be done in SW - * and since the size of N fits into CAAM, the result of (A mod N) will also fit into CAAM. - * Then we can do modular exponentiation in CAAM. - */ - if (mbedtls_mpi_cmp_mpi(A, N) >= 0) - { - /* A >= N, perform X = (A mod N). */ - ret = mbedtls_mpi_mod_mpi(X, A, N); - - if (ret != kStatus_Success) - return (MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - /* Exponenciation will be performed with X. */ - AA = X; - } - else - { - /* Exponentiation will be performed with original A. */ - AA = (mbedtls_mpi *) A; - } - - pkha_size_t sizeA = mbedtls_mpi_size(AA); - uint8_t * ptrA = mbedtls_calloc(3, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrE = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrN = ptrE + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == ptrA) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - mbedtls_mpi_write_binary(AA, ptrA, sizeA); - mbedtls_mpi_write_binary(E, ptrE, sizeE); - mbedtls_mpi_write_binary(N, ptrN, sizeN); - - ret = (int) CAAM_PKHA_ModExp(CAAM_INSTANCE, &s_caamHandle, ptrA, sizeA, ptrN, sizeN, ptrE, sizeE, ptrN, &sizeN, - kCAAM_PKHA_IntegerArith, kCAAM_PKHA_NormalValue, kCAAM_PKHA_TimingEqualized); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - mbedtls_mpi_read_binary(X, ptrN, sizeN); - cleanup: - if (ptrA) - { - mbedtls_free(ptrA); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_exp_mod_orig(X, A, E, N, _RR); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} -#endif /* MBEDTLS_FREESCALE_LTC_PKHA || MBEDTLS_FREESCALE_CAU3_PKHA */ -#endif /* MBEDTLS_MPI_EXP_MOD_ALT */ - -#if defined(MBEDTLS_MPI_GCD_ALT) - -/* Access to original version of mbedtls_mpi_gcd function. */ -int mbedtls_mpi_gcd_orig(mbedtls_mpi * G, const mbedtls_mpi * A, const mbedtls_mpi * B); - -/* - * Greatest common divisor: G = gcd(A, B) (HAC 14.54) - */ -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) || defined(MBEDTLS_FREESCALE_CAU3_PKHA) -int mbedtls_mpi_gcd(mbedtls_mpi * G, const mbedtls_mpi * A, const mbedtls_mpi * B) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeB = mbedtls_mpi_size(B); - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - if ((sizeA <= FREESCALE_PKHA_INT_MAX_BYTES) && (sizeB <= FREESCALE_PKHA_INT_MAX_BYTES)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - uint8_t * ptrA = mbedtls_calloc(3, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrB = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrB + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == ptrA) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - ltc_reverse_array(ptrA, sizeA); - - mbedtls_mpi_write_binary(B, ptrB, sizeB); - ltc_reverse_array(ptrB, sizeB); - - if (mbedtls_mpi_cmp_mpi(A, B) >= 0) - { - ret = (int) LTC_PKHA_ModRed(LTC_INSTANCE, ptrA, sizeA, ptrB, sizeB, ptrA, &sizeA, kLTC_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - } - - ret = (int) LTC_PKHA_GCD(LTC_INSTANCE, ptrA, sizeA, ptrB, sizeB, ptrC, &sizeC, kLTC_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - ltc_reverse_array(ptrC, sizeC); - mbedtls_mpi_read_binary(G, ptrC, sizeC); - cleanup: - if (ptrA) - { - mbedtls_free(ptrA); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_gcd_orig(G, A, B); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_PKHA) -int mbedtls_mpi_gcd(mbedtls_mpi * G, const mbedtls_mpi * A, const mbedtls_mpi * B) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeB = mbedtls_mpi_size(B); - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - if ((sizeA <= FREESCALE_PKHA_INT_MAX_BYTES) && (sizeB <= FREESCALE_PKHA_INT_MAX_BYTES)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - uint8_t * ptrA = mbedtls_calloc(3, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrB = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrB + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == ptrA) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - mbedtls_mpi_write_binary(B, ptrB, sizeB); - - if (mbedtls_mpi_cmp_mpi(A, B) >= 0) - { - ret = (int) CAAM_PKHA_ModRed(CAAM_INSTANCE, &s_caamHandle, ptrA, sizeA, ptrB, sizeB, ptrA, &sizeA, - kCAAM_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - } - - ret = (int) CAAM_PKHA_ModGcd(CAAM_INSTANCE, &s_caamHandle, ptrA, sizeA, ptrB, sizeB, ptrC, &sizeC, kCAAM_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - mbedtls_mpi_read_binary(G, ptrC, sizeC); - cleanup: - if (ptrA) - { - mbedtls_free(ptrA); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_gcd_orig(G, A, B); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} -#endif /* MBEDTLS_FREESCALE_LTC_PKHA || MBEDTLS_FREESCALE_CAU3_PKHA */ -#endif /* MBEDTLS_MPI_GCD_ALT */ - -#if defined(MBEDTLS_MPI_INV_MOD_ALT) - -/* Access to original version of mbedtls_mpi_inv_mod function. */ -int mbedtls_mpi_inv_mod_orig(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * N); - -/* - * Modular inverse: X = A^-1 mod N (HAC 14.61 / 14.64) - */ -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) || defined(MBEDTLS_FREESCALE_CAU3_PKHA) -int mbedtls_mpi_inv_mod(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * N) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeN = mbedtls_mpi_size(N); - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - if ((sizeA <= FREESCALE_PKHA_INT_MAX_BYTES) && (sizeN <= FREESCALE_PKHA_INT_MAX_BYTES)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - uint8_t * ptrA = mbedtls_calloc(3, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrN = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrN + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == ptrA) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - /* N cannot be negative */ - if (N->s < 0 || mbedtls_mpi_cmp_int(N, 0) == 0) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_BAD_INPUT_DATA); - } - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - ltc_reverse_array(ptrA, sizeA); - - mbedtls_mpi_write_binary(N, ptrN, sizeN); - ltc_reverse_array(ptrN, sizeN); - - if (mbedtls_mpi_cmp_mpi(A, N) >= 0) - { - ret = (int) LTC_PKHA_ModRed(LTC_INSTANCE, ptrA, sizeA, ptrN, sizeN, ptrA, &sizeA, kLTC_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - } - - ret = (int) LTC_PKHA_ModInv(LTC_INSTANCE, ptrA, sizeA, ptrN, sizeN, ptrC, &sizeC, kLTC_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - ltc_reverse_array(ptrC, sizeC); - mbedtls_mpi_read_binary(X, ptrC, sizeC); - cleanup: - if (ptrA) - { - mbedtls_free(ptrA); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_inv_mod_orig(X, A, N); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_PKHA) -int mbedtls_mpi_inv_mod(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * N) -{ - pkha_size_t sizeA = mbedtls_mpi_size(A); - pkha_size_t sizeN = mbedtls_mpi_size(N); - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - if ((sizeA <= FREESCALE_PKHA_INT_MAX_BYTES) && (sizeN <= FREESCALE_PKHA_INT_MAX_BYTES)) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - pkha_size_t sizeC; - uint8_t * ptrA = mbedtls_calloc(3, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrN = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrC = ptrN + FREESCALE_PKHA_INT_MAX_BYTES; - if (NULL == ptrA) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - /* N cannot be negative */ - if (N->s < 0 || mbedtls_mpi_cmp_int(N, 0) == 0) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_BAD_INPUT_DATA); - } - - mbedtls_mpi_write_binary(A, ptrA, sizeA); - mbedtls_mpi_write_binary(N, ptrN, sizeN); - - if (mbedtls_mpi_cmp_mpi(A, N) >= 0) - { - ret = (int) CAAM_PKHA_ModRed(CAAM_INSTANCE, &s_caamHandle, ptrA, sizeA, ptrN, sizeN, ptrA, &sizeA, - kCAAM_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - } - - ret = (int) CAAM_PKHA_ModInv(CAAM_INSTANCE, &s_caamHandle, ptrA, sizeA, ptrN, sizeN, ptrC, &sizeC, kCAAM_PKHA_IntegerArith); - - if (ret != kStatus_Success) - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - - mbedtls_mpi_read_binary(X, ptrC, sizeC); - cleanup: - if (ptrA) - { - mbedtls_free(ptrA); - } - return (ret); -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_inv_mod_orig(X, A, N); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} -#endif /* MBEDTLS_FREESCALE_LTC_PKHA || MBEDTLS_FREESCALE_CAU3_PKHA */ -#endif /* MBEDTLS_MPI_INV_MOD_ALT */ - -#if defined(MBEDTLS_MPI_IS_PRIME_ALT) - -/* Access to original version of mbedtls_mpi_is_prime function. */ -int mbedtls_mpi_is_prime_orig(const mbedtls_mpi * X, int (*f_rng)(void *, unsigned char *, size_t), void * p_rng); - -/* - * Pseudo-primality test: small factors, then Miller-Rabin - */ -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) || defined(MBEDTLS_FREESCALE_CAU3_PKHA) -int mbedtls_mpi_is_prime(const mbedtls_mpi * X, int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) -{ - pkha_size_t sizeX = mbedtls_mpi_size(X); - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - if (sizeX <= FREESCALE_PKHA_INT_MAX_BYTES) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - int random; - bool result = false; - uint8_t * ptrX = mbedtls_calloc(1, FREESCALE_PKHA_INT_MAX_BYTES); - if (NULL == ptrX) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - mbedtls_mpi_write_binary(X, ptrX, FREESCALE_PKHA_INT_MAX_BYTES); - ltc_reverse_array(ptrX, FREESCALE_PKHA_INT_MAX_BYTES); - - // Get the random seed number - f_rng(p_rng, (unsigned char *) (&random), sizeof(random)); - - ret = (int) LTC_PKHA_PrimalityTest(LTC_INSTANCE, (unsigned char *) &random, sizeof(random), (const uint8_t *) "1", 1u, ptrX, - sizeX, &result); - - if (ret != kStatus_Success) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - } - - if (result == false) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - } - cleanup: - if (ptrX) - { - mbedtls_free(ptrX); - } - return ret; -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_is_prime_orig(X, f_rng, p_rng); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_PKHA) -int mbedtls_mpi_is_prime(const mbedtls_mpi * X, int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) -{ - pkha_size_t sizeX = mbedtls_mpi_size(X); - -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - if (sizeX <= FREESCALE_PKHA_INT_MAX_BYTES) - { -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ - int ret; - int random; - bool result = false; - uint8_t * ptrX = mbedtls_calloc(1, FREESCALE_PKHA_INT_MAX_BYTES); - if (NULL == ptrX) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - mbedtls_mpi_write_binary(X, ptrX, FREESCALE_PKHA_INT_MAX_BYTES); - - // Get the random seed number - f_rng(p_rng, (unsigned char *) (&random), sizeof(random)); - - ret = (int) CAAM_PKHA_PrimalityTest(CAAM_INSTANCE, &s_caamHandle, (unsigned char *) &random, sizeof(random), - (const uint8_t *) "1", 1u, ptrX, sizeX, &result); - - if (ret != kStatus_Success) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - } - - if (result == false) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE); - } - cleanup: - if (ptrX) - { - mbedtls_free(ptrX); - } - return ret; -#if defined(FREESCALE_PKHA_LONG_OPERANDS_ENABLE) - } - else - { - return mbedtls_mpi_is_prime_orig(X, f_rng, p_rng); - } -#endif /* FREESCALE_PKHA_LONG_OPERANDS_ENABLE */ -} -#endif /* MBEDTLS_FREESCALE_LTC_PKHA || MBEDTLS_FREESCALE_CAU3_PKHA */ -#endif /* MBEDTLS_MPI_IS_PRIME_ALT */ - -#endif /* MBEDTLS_BIGNUM_C */ - -#if defined(MBEDTLS_ECP_C) - -#include "mbedtls/ecp.h" - -#define LTC_MAX_ECC (512) -#define CAAM_MAX_ECC (528) -#define CAU3_MAX_ECC (512) - -typedef enum -{ - kBigEndian = 0U, - kLittleEndian = 1U -} endian_t; - -/* convert from mbedtls_mpi to LTC or CAAM integer, as array of bytes of size sz. - * if mbedtls_mpi has less bytes than sz, add zero bytes at most significant byte positions. - * This is when for example modulus is 32 bytes (P-256 curve) - * and mbedtls_mpi has only 31 bytes, we add leading zeroes - * so that result array has 32 bytes, same as modulus (sz). - */ -#if defined(MBEDTLS_ECP_MUL_COMB_ALT) || defined(MBEDTLS_ECP_ADD_ALT) -static int get_and_extend_mbedtls_mpi(uint8_t * dst, const mbedtls_mpi * a, size_t sz, endian_t endian) -{ - size_t szbin; - int offset; - int ret; - - /* check how many bytes are in the mbedtls_mpi */ - szbin = mbedtls_mpi_size(a); - - /* compute offset from dst */ - offset = sz - szbin; - if (offset < 0) - offset = 0; - if (offset > sz) - offset = sz; - - /* add leading zeroes */ - if (offset) - memset(dst, 0, offset); - - /* convert mbedtls_mpi to array of bytes */ - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(a, dst + offset, szbin)); - - /* reverse array for LTC direct use */ - if (endian == kLittleEndian) - ltc_reverse_array(dst, sz); -cleanup: - return (ret); -} - -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) || defined(MBEDTLS_FREESCALE_CAU3_PKHA) -static int ltc_get_from_mbedtls_mpi(uint8_t * dst, const mbedtls_mpi * a, size_t sz) -{ - return get_and_extend_mbedtls_mpi(dst, a, sz, kLittleEndian); -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_PKHA) -static int caam_get_from_mbedtls_mpi(uint8_t * dst, const mbedtls_mpi * a, size_t sz) -{ - return get_and_extend_mbedtls_mpi(dst, a, sz, kBigEndian); -} -#endif /* MBEDTLS_FREESCALE_LTC_PKHA */ -#endif /* MBEDTLS_ECP_MUL_COMB_ALT || MBEDTLS_ECP_ADD_ALT */ - -/* - * Multiplication using the comb method, - * for curves in short Weierstrass form - */ -#if defined(MBEDTLS_ECP_MUL_COMB_ALT) -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) -int ecp_mul_comb(mbedtls_ecp_group * grp, mbedtls_ecp_point * R, const mbedtls_mpi * m, const mbedtls_ecp_point * P, - int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) -{ - int ret; - bool is_inf; - size_t size; - size_t size_bin; - int sign = m->s; - - ltc_pkha_ecc_point_t A; - ltc_pkha_ecc_point_t result; - - /* Allocate 7 elements with size of (LTC_MAX_ECC / 8) plus ptrE with size of FREESCALE_PKHA_INT_MAX_BYTES */ - uint8_t * ptrAX = mbedtls_calloc((7 * (LTC_MAX_ECC / 8)) + FREESCALE_PKHA_INT_MAX_BYTES, 1); - uint8_t * ptrAY = ptrAX + (LTC_MAX_ECC / 8); - uint8_t * ptrRX = ptrAY + (LTC_MAX_ECC / 8); - uint8_t * ptrRY = ptrRX + (LTC_MAX_ECC / 8); - uint8_t * ptrN = ptrRY + (LTC_MAX_ECC / 8); - uint8_t * ptrParamA = ptrN + (LTC_MAX_ECC / 8); - uint8_t * ptrParamB = ptrParamA + (LTC_MAX_ECC / 8); - uint8_t * ptrE = ptrParamB + (LTC_MAX_ECC / 8); - if (NULL == ptrAX) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - A.X = ptrAX; - A.Y = ptrAY; - result.X = ptrRX; - result.Y = ptrRY; - size = mbedtls_mpi_size(&grp->P); - if (mbedtls_mpi_size(&P->X) > (LTC_MAX_ECC / 8) || (mbedtls_mpi_get_bit(&grp->N, 0) != 1)) - { - CLEAN_RETURN(MBEDTLS_ERR_ECP_BAD_INPUT_DATA); - } - - /* Convert multi precision integers to arrays */ - MBEDTLS_MPI_CHK(ltc_get_from_mbedtls_mpi(A.X, &P->X, size)); - MBEDTLS_MPI_CHK(ltc_get_from_mbedtls_mpi(A.Y, &P->Y, size)); - MBEDTLS_MPI_CHK(ltc_get_from_mbedtls_mpi(ptrParamA, &grp->A, size)); - MBEDTLS_MPI_CHK(ltc_get_from_mbedtls_mpi(ptrParamB, &grp->B, size)); - - /* scalar multiplier integer of any size */ - size_bin = mbedtls_mpi_size(m); - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(m, ptrE, size_bin)); - ltc_reverse_array(ptrE, size_bin); - - /* modulus */ - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&grp->P, ptrN, size)); - ltc_reverse_array(ptrN, size); - - /* Multiply */ - LTC_PKHA_ECC_PointMul(LTC_INSTANCE, &A, ptrE, size_bin, ptrN, NULL, ptrParamA, ptrParamB, size, kLTC_PKHA_TimingEqualized, - kLTC_PKHA_IntegerArith, &result, &is_inf); - /* Convert result */ - ltc_reverse_array(ptrRX, size); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->X, ptrRX, size)); - ltc_reverse_array(ptrRY, size); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->Y, ptrRY, size)); - /* if the integer multiplier is negative, the computation happens with abs() value - * and the result (x,y) is changed to (x, -y) - */ - R->Y.s = sign; - MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&R->Z, 1)); - -cleanup: - if (ptrAX) - { - mbedtls_free(ptrAX); - } - return (ret); -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_PKHA) -int ecp_mul_comb(mbedtls_ecp_group * grp, mbedtls_ecp_point * R, const mbedtls_mpi * m, const mbedtls_ecp_point * P, - int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) -{ - int ret; - size_t size; - size_t size_bin; - int sign = m->s; - - caam_pkha_ecc_point_t A; - caam_pkha_ecc_point_t result; - - /* Allocate 7 elements with size of (CAAM_MAX_ECC / 8) plus ptrE with size of FREESCALE_PKHA_INT_MAX_BYTES */ - uint8_t * ptrAX = mbedtls_calloc((7 * (CAAM_MAX_ECC / 8)) + FREESCALE_PKHA_INT_MAX_BYTES, 1); - uint8_t * ptrAY = ptrAX + (CAAM_MAX_ECC / 8); - uint8_t * ptrRX = ptrAY + (CAAM_MAX_ECC / 8); - uint8_t * ptrRY = ptrRX + (CAAM_MAX_ECC / 8); - uint8_t * ptrN = ptrRY + (CAAM_MAX_ECC / 8); - uint8_t * ptrParamA = ptrN + (CAAM_MAX_ECC / 8); - uint8_t * ptrParamB = ptrParamA + (CAAM_MAX_ECC / 8); - uint8_t * ptrE = ptrParamB + (CAAM_MAX_ECC / 8); - if (NULL == ptrAX) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - A.X = ptrAX; - A.Y = ptrAY; - result.X = ptrRX; - result.Y = ptrRY; - size = mbedtls_mpi_size(&grp->P); - if (mbedtls_mpi_size(&P->X) > (CAAM_MAX_ECC / 8) || (mbedtls_mpi_get_bit(&grp->N, 0) != 1)) - { - CLEAN_RETURN(MBEDTLS_ERR_ECP_BAD_INPUT_DATA); - } - - /* Convert multi precision integers to arrays */ - MBEDTLS_MPI_CHK(caam_get_from_mbedtls_mpi(A.X, &P->X, size)); - MBEDTLS_MPI_CHK(caam_get_from_mbedtls_mpi(A.Y, &P->Y, size)); - MBEDTLS_MPI_CHK(caam_get_from_mbedtls_mpi(ptrParamA, &grp->A, size)); - MBEDTLS_MPI_CHK(caam_get_from_mbedtls_mpi(ptrParamB, &grp->B, size)); - - /* scalar multiplier integer of any size */ - size_bin = mbedtls_mpi_size(m); - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(m, ptrE, size_bin)); - - /* modulus */ - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&grp->P, ptrN, size)); - - /* Multiply */ - CAAM_PKHA_ECC_PointMul(CAAM_INSTANCE, &s_caamHandle, &A, ptrE, size_bin, ptrN, NULL, ptrParamA, ptrParamB, size, - kCAAM_PKHA_TimingEqualized, kCAAM_PKHA_IntegerArith, &result); - /* Convert result */ - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->X, ptrRX, size)); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->Y, ptrRY, size)); - /* if the integer multiplier is negative, the computation happens with abs() value - * and the result (x,y) is changed to (x, -y) - */ - R->Y.s = sign; - MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&R->Z, 1)); - -cleanup: - if (ptrAX) - { - mbedtls_free(ptrAX); - } - return (ret); -} - -#elif defined(MBEDTLS_FREESCALE_CAU3_PKHA) -int ecp_mul_comb(mbedtls_ecp_group * grp, mbedtls_ecp_point * R, const mbedtls_mpi * m, const mbedtls_ecp_point * P, - int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) -{ - int ret; - status_t status; - size_t size; - size_t size_bin; - int sign = m->s; - - cau3_pkha_ecc_point_t A; - cau3_pkha_ecc_point_t result; - - /* Allocate 7 elements with size of (CAU3_MAX_ECC / 8) plus ptrE with size of FREESCALE_PKHA_INT_MAX_BYTES */ - uint8_t * ptrAX = mbedtls_calloc((7 * (CAU3_MAX_ECC / 8)) + FREESCALE_PKHA_INT_MAX_BYTES, 1); - uint8_t * ptrAY = ptrAX + (CAU3_MAX_ECC / 8); - uint8_t * ptrRX = ptrAY + (CAU3_MAX_ECC / 8); - uint8_t * ptrRY = ptrRX + (CAU3_MAX_ECC / 8); - uint8_t * ptrN = ptrRY + (CAU3_MAX_ECC / 8); - uint8_t * ptrParamA = ptrN + (CAU3_MAX_ECC / 8); - uint8_t * ptrParamB = ptrParamA + (CAU3_MAX_ECC / 8); - uint8_t * ptrE = ptrParamB + (CAU3_MAX_ECC / 8); - if (NULL == ptrAX) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - A.X = ptrAX; - A.Y = ptrAY; - result.X = ptrRX; - result.Y = ptrRY; - size = mbedtls_mpi_size(&grp->P); - if (mbedtls_mpi_size(&P->X) > (CAU3_MAX_ECC / 8) || (mbedtls_mpi_get_bit(&grp->N, 0) != 1)) - { - CLEAN_RETURN(MBEDTLS_ERR_ECP_BAD_INPUT_DATA); - } - - /* Convert multi precision integers to arrays */ - MBEDTLS_MPI_CHK(cau3_get_from_mbedtls_mpi(A.X, &P->X, size)); - MBEDTLS_MPI_CHK(cau3_get_from_mbedtls_mpi(A.Y, &P->Y, size)); - MBEDTLS_MPI_CHK(cau3_get_from_mbedtls_mpi(ptrParamA, &grp->A, size)); - MBEDTLS_MPI_CHK(cau3_get_from_mbedtls_mpi(ptrParamB, &grp->B, size)); - - /* scalar multiplier integer of any size */ - size_bin = mbedtls_mpi_size(m); - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(m, ptrE, size_bin)); - cau3_reverse_array(ptrE, size_bin); - - /* modulus */ - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&grp->P, ptrN, size)); - cau3_reverse_array(ptrN, size); - - /* Multiply */ - status = CAU3_PKHA_ECC_PointMul(CAU3, &A, ptrE, size_bin, ptrN, NULL, ptrParamA, ptrParamB, size, kCAU3_PKHA_TimingEqualized, - kCAU3_PKHA_IntegerArith, &result); - - if (status != kStatus_Success) - { - CLEAN_RETURN(MBEDTLS_ERR_ECP_BAD_INPUT_DATA); - } - - /* Convert result */ - cau3_reverse_array(ptrRX, size); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->X, ptrRX, size)); - cau3_reverse_array(ptrRY, size); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->Y, ptrRY, size)); - /* if the integer multiplier is negative, the computation happens with abs() value - * and the result (x,y) is changed to (x, -y) - */ - R->Y.s = sign; - MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&R->Z, 1)); - -cleanup: - if (ptrAX) - { - mbedtls_free(ptrAX); - } - return (ret); -} - -#endif /* MBEDTLS_FREESCALE_LTC_PKHA */ -#endif /* MBEDTLS_ECP_MUL_COMB_ALT */ - -/* - * Curve types: internal for now, might be exposed later - */ -typedef enum -{ - ECP_TYPE_NONE = 0, - ECP_TYPE_SHORT_WEIERSTRASS, /* y^2 = x^3 + a x + b */ - ECP_TYPE_MONTGOMERY, /* y^2 = x^3 + a x^2 + x */ -} ecp_curve_type; -/* - * Get the type of a curve - */ -static inline ecp_curve_type ecp_get_type(const mbedtls_ecp_group * grp) -{ - if (grp->G.X.p == NULL) - return (ECP_TYPE_NONE); - - if (grp->G.Y.p == NULL) - return (ECP_TYPE_MONTGOMERY); - else - return (ECP_TYPE_SHORT_WEIERSTRASS); -} - -/* - * Addition: R = P + Q, result's coordinates normalized - */ -#if defined(MBEDTLS_ECP_ADD_ALT) -#if defined(MBEDTLS_FREESCALE_LTC_PKHA) -int ecp_add(const mbedtls_ecp_group * grp, mbedtls_ecp_point * R, const mbedtls_ecp_point * P, const mbedtls_ecp_point * Q) -{ - int ret; - size_t size; - ltc_pkha_ecc_point_t A; - ltc_pkha_ecc_point_t B; - ltc_pkha_ecc_point_t result; - - uint8_t * ptrAX = mbedtls_calloc(9, (LTC_MAX_ECC / 8)); - uint8_t * ptrAY = ptrAX + (LTC_MAX_ECC / 8); - uint8_t * ptrBX = ptrAY + (LTC_MAX_ECC / 8); - uint8_t * ptrBY = ptrBX + (LTC_MAX_ECC / 8); - uint8_t * ptrRX = ptrBY + (LTC_MAX_ECC / 8); - uint8_t * ptrRY = ptrRX + (LTC_MAX_ECC / 8); - uint8_t * ptrN = ptrRY + (LTC_MAX_ECC / 8); - uint8_t * ptrParamA = ptrN + (LTC_MAX_ECC / 8); - uint8_t * ptrParamB = ptrParamA + (LTC_MAX_ECC / 8); - if (NULL == ptrAX) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - if (ecp_get_type(grp) != ECP_TYPE_SHORT_WEIERSTRASS) - CLEAN_RETURN(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE); - - A.X = ptrAX; - A.Y = ptrAY; - B.X = ptrBX; - B.Y = ptrBY; - result.X = ptrRX; - result.Y = ptrRY; - size = mbedtls_mpi_size(&grp->P); - if (mbedtls_mpi_size(&P->X) > (LTC_MAX_ECC / 8) || (mbedtls_mpi_get_bit(&grp->P, 0) != 1)) - { - CLEAN_RETURN(MBEDTLS_ERR_ECP_BAD_INPUT_DATA); - } - - /* Convert multi precision integers to arrays */ - MBEDTLS_MPI_CHK(ltc_get_from_mbedtls_mpi(A.X, &P->X, size)); - MBEDTLS_MPI_CHK(ltc_get_from_mbedtls_mpi(A.Y, &P->Y, size)); - MBEDTLS_MPI_CHK(ltc_get_from_mbedtls_mpi(B.X, &Q->X, size)); - MBEDTLS_MPI_CHK(ltc_get_from_mbedtls_mpi(B.Y, &Q->Y, size)); - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&grp->P, ptrN, size)); - ltc_reverse_array(ptrN, size); - /* Multiply */ - LTC_PKHA_ECC_PointAdd(LTC_INSTANCE, &A, &B, ptrN, NULL, ptrParamA, ptrParamB, size, kLTC_PKHA_IntegerArith, &result); - /* Convert result */ - ltc_reverse_array(ptrRX, size); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->X, ptrRX, size)); - ltc_reverse_array(ptrRY, size); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->Y, ptrRY, size)); - R->X.s = P->X.s; - R->Y.s = P->Y.s; - MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&R->Z, 1)); - -cleanup: - if (ptrAX) - { - mbedtls_free(ptrAX); - } - return (ret); -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_PKHA) -int ecp_add(const mbedtls_ecp_group * grp, mbedtls_ecp_point * R, const mbedtls_ecp_point * P, const mbedtls_ecp_point * Q) -{ - int ret; - size_t size; - caam_pkha_ecc_point_t A; - caam_pkha_ecc_point_t B; - caam_pkha_ecc_point_t result; - - uint8_t * ptrAX = mbedtls_calloc(9, (CAAM_MAX_ECC / 8)); - uint8_t * ptrAY = ptrAX + (CAAM_MAX_ECC / 8); - uint8_t * ptrBX = ptrAY + (CAAM_MAX_ECC / 8); - uint8_t * ptrBY = ptrBX + (CAAM_MAX_ECC / 8); - uint8_t * ptrRX = ptrBY + (CAAM_MAX_ECC / 8); - uint8_t * ptrRY = ptrRX + (CAAM_MAX_ECC / 8); - uint8_t * ptrN = ptrRY + (CAAM_MAX_ECC / 8); - uint8_t * ptrParamA = ptrN + (CAAM_MAX_ECC / 8); - uint8_t * ptrParamB = ptrParamA + (CAAM_MAX_ECC / 8); - if (NULL == ptrAX) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - if (ecp_get_type(grp) != ECP_TYPE_SHORT_WEIERSTRASS) - CLEAN_RETURN(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE); - - A.X = ptrAX; - A.Y = ptrAY; - B.X = ptrBX; - B.Y = ptrBY; - result.X = ptrRX; - result.Y = ptrRY; - size = mbedtls_mpi_size(&grp->P); - if (mbedtls_mpi_size(&P->X) > (CAAM_MAX_ECC / 8) || (mbedtls_mpi_get_bit(&grp->P, 0) != 1)) - { - CLEAN_RETURN(MBEDTLS_ERR_ECP_BAD_INPUT_DATA); - } - - /* Convert multi precision integers to arrays */ - MBEDTLS_MPI_CHK(caam_get_from_mbedtls_mpi(A.X, &P->X, size)); - MBEDTLS_MPI_CHK(caam_get_from_mbedtls_mpi(A.Y, &P->Y, size)); - MBEDTLS_MPI_CHK(caam_get_from_mbedtls_mpi(B.X, &Q->X, size)); - MBEDTLS_MPI_CHK(caam_get_from_mbedtls_mpi(B.Y, &Q->Y, size)); - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&grp->P, ptrN, size)); - - /* Multiply */ - CAAM_PKHA_ECC_PointAdd(CAAM_INSTANCE, &s_caamHandle, &A, &B, ptrN, NULL, ptrParamA, ptrParamB, size, kCAAM_PKHA_IntegerArith, - &result); - /* Convert result */ - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->X, ptrRX, size)); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->Y, ptrRY, size)); - R->X.s = P->X.s; - R->Y.s = P->Y.s; - MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&R->Z, 1)); - -cleanup: - if (ptrAX) - { - mbedtls_free(ptrAX); - } - return (ret); -} - -#elif defined(MBEDTLS_FREESCALE_CAU3_PKHA) -int ecp_add(const mbedtls_ecp_group * grp, mbedtls_ecp_point * R, const mbedtls_ecp_point * P, const mbedtls_ecp_point * Q) -{ - int ret; - status_t status; - size_t size; - cau3_pkha_ecc_point_t A; - cau3_pkha_ecc_point_t B; - cau3_pkha_ecc_point_t result; - - uint8_t * ptrAX = mbedtls_calloc(9, (CAU3_MAX_ECC / 8)); - uint8_t * ptrAY = ptrAX + (CAU3_MAX_ECC / 8); - uint8_t * ptrBX = ptrAY + (CAU3_MAX_ECC / 8); - uint8_t * ptrBY = ptrBX + (CAU3_MAX_ECC / 8); - uint8_t * ptrRX = ptrBY + (CAU3_MAX_ECC / 8); - uint8_t * ptrRY = ptrRX + (CAU3_MAX_ECC / 8); - uint8_t * ptrN = ptrRY + (CAU3_MAX_ECC / 8); - uint8_t * ptrParamA = ptrN + (CAU3_MAX_ECC / 8); - uint8_t * ptrParamB = ptrParamA + (CAU3_MAX_ECC / 8); - if (NULL == ptrAX) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - if (ecp_get_type(grp) != ECP_TYPE_SHORT_WEIERSTRASS) - CLEAN_RETURN(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE); - - A.X = ptrAX; - A.Y = ptrAY; - B.X = ptrBX; - B.Y = ptrBY; - result.X = ptrRX; - result.Y = ptrRY; - size = mbedtls_mpi_size(&grp->P); - if (mbedtls_mpi_size(&P->X) > (CAU3_MAX_ECC / 8) || (mbedtls_mpi_get_bit(&grp->P, 0) != 1)) - { - CLEAN_RETURN(MBEDTLS_ERR_ECP_BAD_INPUT_DATA); - } - - /* Convert multi precision integers to arrays */ - MBEDTLS_MPI_CHK(cau3_get_from_mbedtls_mpi(A.X, &P->X, size)); - MBEDTLS_MPI_CHK(cau3_get_from_mbedtls_mpi(A.Y, &P->Y, size)); - MBEDTLS_MPI_CHK(cau3_get_from_mbedtls_mpi(B.X, &Q->X, size)); - MBEDTLS_MPI_CHK(cau3_get_from_mbedtls_mpi(B.Y, &Q->Y, size)); - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&grp->P, ptrN, size)); - cau3_reverse_array(ptrN, size); - /* Multiply */ - status = CAU3_PKHA_ECC_PointAdd(CAU3, &A, &B, ptrN, NULL, ptrParamA, ptrParamB, size, kCAU3_PKHA_IntegerArith, &result); - - if (status != kStatus_Success) - { - CLEAN_RETURN(MBEDTLS_ERR_ECP_BAD_INPUT_DATA); - } - - /* Convert result */ - cau3_reverse_array(ptrRX, size); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->X, ptrRX, size)); - cau3_reverse_array(ptrRY, size); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->Y, ptrRY, size)); - R->X.s = P->X.s; - R->Y.s = P->Y.s; - MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&R->Z, 1)); - -cleanup: - if (ptrAX) - { - mbedtls_free(ptrAX); - } - return (ret); -} - -#endif /* MBEDTLS_FREESCALE_LTC_PKHA */ - -#endif /* MBEDTLS_ECP_ADD_ALT */ - -#if defined(MBEDTLS_ECP_MUL_MXZ_ALT) -#if defined(MBEDTLS_FREESCALE_CAU3_PKHA) - -/* curve25519 params - in little endian for CAU3 */ -static const uint8_t s_curve25519_A24[] = { 0x42, 0xdb, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - -static const uint8_t s_curve25519_N[] = { 0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f }; - -static const uint8_t s_curve25519_R2modN[] = { 0xa4, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - -int ecp_mul_mxz(mbedtls_ecp_group * grp, mbedtls_ecp_point * R, const mbedtls_mpi * m, const mbedtls_ecp_point * P, - int (*f_rng)(void *, unsigned char *, size_t), void * p_rng) -{ - int ret; - status_t status; - size_t size; - size_t size_bin; - - cau3_pkha_ecc_point_t A; - cau3_pkha_ecc_point_t result; - - /* Allocate 2 elements with size of (CAU3_MAX_ECC / 8) plus ptrE with size of FREESCALE_PKHA_INT_MAX_BYTES */ - uint8_t * ptrAX = mbedtls_calloc((2 * (CAU3_MAX_ECC / 8)) + FREESCALE_PKHA_INT_MAX_BYTES, 1); - uint8_t * ptrRX = ptrAX + (CAU3_MAX_ECC / 8); - uint8_t * ptrE = ptrRX + (CAU3_MAX_ECC / 8); - if (NULL == ptrAX) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - A.X = ptrAX; - result.X = ptrRX; - size = mbedtls_mpi_size(&grp->P); - if (mbedtls_mpi_size(&P->X) > (CAAM_MAX_ECC / 8)) - { - CLEAN_RETURN(MBEDTLS_ERR_ECP_BAD_INPUT_DATA); - } - - /* Convert multi precision integers to arrays */ - MBEDTLS_MPI_CHK(cau3_get_from_mbedtls_mpi(A.X, &P->X, size)); - - /* scalar multiplier integer of any size */ - size_bin = mbedtls_mpi_size(m); - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(m, ptrE, size_bin)); - cau3_reverse_array(ptrE, size_bin); - - /* Multiply */ - status = CAU3_PKHA_ECM_PointMul(CAU3, ptrE, size_bin, A.X, s_curve25519_A24, s_curve25519_N, s_curve25519_R2modN, size, - kCAU3_PKHA_TimingEqualized, result.X); - - if (status != kStatus_Success) - { - CLEAN_RETURN(MBEDTLS_ERR_ECP_BAD_INPUT_DATA); - } - - /* Convert result */ - cau3_reverse_array(ptrRX, size); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&R->X, ptrRX, size)); - MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&R->Z, 1)); - -cleanup: - if (ptrAX) - { - mbedtls_free(ptrAX); - } - return (ret); -} - -#endif /* MBEDTLS_FREESCALE_CAU3_PKHA */ -#endif /* MBEDTLS_ECP_MUL_MXZ_ALT */ - -#endif /* MBEDTLS_ECP_C */ - -#endif /* MBEDTLS_FREESCALE_LTC_PKHA */ - -#if defined(MBEDTLS_RSA_PUBLIC_ALT) -#if defined(MBEDTLS_FREESCALE_CASPER_PKHA) - -#if defined(MBEDTLS_PLATFORM_C) -#include "mbedtls/platform.h" -#else -#include -#define mbedtls_calloc calloc -#define mbedtls_free free -#endif - -#include "mbedtls/bignum.h" -#include "mbedtls/rsa.h" - -static void reverse_array(uint8_t * src, size_t src_len) -{ - int i; - - for (i = 0; i < src_len / 2; i++) - { - uint8_t tmp; - - tmp = src[i]; - src[i] = src[src_len - 1 - i]; - src[src_len - 1 - i] = tmp; - } -} -/* - * Do an RSA public key operation - */ -static int mbedtls_mpi_exp_mod_shim(mbedtls_mpi * X, const mbedtls_mpi * A, const mbedtls_mpi * E, - const mbedtls_mpi * N /*, mbedtls_mpi *_RR */) -{ - int ret = MBEDTLS_ERR_MPI_ALLOC_FAILED; - size_t sizeA = mbedtls_mpi_size(A); - size_t sizeN = mbedtls_mpi_size(N); - uint8_t * ptrX = mbedtls_calloc(3, FREESCALE_PKHA_INT_MAX_BYTES); - uint8_t * ptrA = ptrX + FREESCALE_PKHA_INT_MAX_BYTES; - uint8_t * ptrN = ptrA + FREESCALE_PKHA_INT_MAX_BYTES; - - if (NULL == ptrX) - { - CLEAN_RETURN(MBEDTLS_ERR_MPI_ALLOC_FAILED); - } - - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(A, ptrA, sizeA)); - reverse_array(ptrA, sizeA); - - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(N, ptrN, sizeN)); - reverse_array(ptrN, sizeN); - - CASPER_ModExp(CASPER, ptrA, ptrN, sizeN / 4, E->p[0], ptrX); - - reverse_array(ptrX, sizeN); - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(X, ptrX, sizeN)); -cleanup: - if (ptrX != NULL) - { - mbedtls_free(ptrX); - } - - return ret; -} - -int mbedtls_rsa_public(mbedtls_rsa_context * ctx, const unsigned char * input, unsigned char * output) -{ - int ret; - size_t olen; - mbedtls_mpi T; - - mbedtls_mpi_init(&T); - -#if defined(MBEDTLS_THREADING_C) - if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) - return (ret); -#endif - - MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len)); - - if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) - { - ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; - goto cleanup; - } - - olen = ctx->len; - - MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod_shim(&T, &T, &ctx->E, &ctx->N /*, &ctx->RN */)); - - MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen)); - -cleanup: -#if defined(MBEDTLS_THREADING_C) - if (mbedtls_mutex_unlock(&ctx->mutex) != 0) - return (MBEDTLS_ERR_THREADING_MUTEX_ERROR); -#endif - - mbedtls_mpi_free(&T); - - if (ret != 0) - return (MBEDTLS_ERR_RSA_PUBLIC_FAILED + ret); - - return (0); -} - -#endif /* MBEDTLS_FREESCALE_CASPER_PKHA */ -#endif /* MBEDTLS_RSA_PUBLIC_ALT */ - -/******************************************************************************/ -/*************************** MD5 **********************************************/ -/******************************************************************************/ - -#if defined(MBEDTLS_MD5_C) - -#if defined(MBEDTLS_FREESCALE_MMCAU_MD5) - -#include "mbedtls/md5.h" - -int mbedtls_internal_md5_process(mbedtls_md5_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = MMCAU_MD5_HashN(data, 1, ctx->state); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_MD5_HW_ACCEL_FAILED; - } - return 0; -} - -#endif /* MBEDTLS_FREESCALE_MMCAU_MD5 */ - -#endif /* MBEDTLS_MD5_C */ - -/******************************************************************************/ -/*************************** SHA1 *********************************************/ -/******************************************************************************/ - -#if defined(MBEDTLS_SHA1_C) - -#if defined(MBEDTLS_FREESCALE_LTC_SHA1) -#include "mbedtls/sha1.h" - -void mbedtls_sha1_init(mbedtls_sha1_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_free(mbedtls_sha1_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_clone(mbedtls_sha1_context * dst, const mbedtls_sha1_context * src) -{ - memcpy(dst, src, sizeof(mbedtls_sha1_context)); -} - -/* - * SHA-1 context setup - */ -int mbedtls_sha1_starts_ret(mbedtls_sha1_context * ctx) -{ - status_t ret = kStatus_Fail; - ret = LTC_HASH_Init(LTC_INSTANCE, ctx, kLTC_Sha1, NULL, 0); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -int mbedtls_internal_sha1_process(mbedtls_sha1_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = LTC_HASH_Update(ctx, data, 64); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 process buffer - */ -int mbedtls_sha1_update_ret(mbedtls_sha1_context * ctx, const unsigned char * input, size_t ilen) -{ - status_t ret = kStatus_Fail; - ret = LTC_HASH_Update(ctx, input, ilen); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 final digest - */ -int mbedtls_sha1_finish_ret(mbedtls_sha1_context * ctx, unsigned char output[20]) -{ - status_t ret = kStatus_Fail; - ret = LTC_HASH_Finish(ctx, output, 0); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -#elif defined(MBEDTLS_FREESCALE_MMCAU_SHA1) - -#include "mbedtls/sha1.h" - -int mbedtls_internal_sha1_process(mbedtls_sha1_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = MMCAU_SHA1_HashN(data, 1, ctx->state); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -#elif defined(MBEDTLS_FREESCALE_LPC_SHA1) -#include "mbedtls/sha1.h" - -void mbedtls_sha1_init(mbedtls_sha1_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_free(mbedtls_sha1_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_clone(mbedtls_sha1_context * dst, const mbedtls_sha1_context * src) -{ - memcpy(dst, src, sizeof(mbedtls_sha1_context)); -} - -/* - * SHA-1 context setup - */ -int mbedtls_sha1_starts_ret(mbedtls_sha1_context * ctx) -{ - status_t ret = kStatus_Fail; - ret = SHA_Init(SHA_INSTANCE, ctx, kSHA_Sha1); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -int mbedtls_internal_sha1_process(mbedtls_sha1_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = SHA_Update(SHA_INSTANCE, ctx, data, 64); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 process buffer - */ -int mbedtls_sha1_update_ret(mbedtls_sha1_context * ctx, const unsigned char * input, size_t ilen) -{ - status_t ret = kStatus_Fail; - ret = SHA_Update(SHA_INSTANCE, ctx, input, ilen); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 final digest - */ -int mbedtls_sha1_finish_ret(mbedtls_sha1_context * ctx, unsigned char output[20]) -{ - size_t outputSize = 20u; - status_t ret = kStatus_Fail; - ret = SHA_Finish(SHA_INSTANCE, ctx, output, &outputSize); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} -#elif defined(MBEDTLS_FREESCALE_CAAM_SHA1) -#include "mbedtls/sha1.h" - -void mbedtls_sha1_init(mbedtls_sha1_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_free(mbedtls_sha1_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_clone(mbedtls_sha1_context * dst, const mbedtls_sha1_context * src) -{ - memcpy(dst, src, sizeof(mbedtls_sha1_context)); -} - -/* - * SHA-1 context setup - */ -int mbedtls_sha1_starts_ret(mbedtls_sha1_context * ctx) -{ - status_t ret = kStatus_Fail; - ret = CAAM_HASH_Init(CAAM_INSTANCE, &s_caamHandle, ctx, kCAAM_Sha1, NULL, 0); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -int mbedtls_internal_sha1_process(mbedtls_sha1_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = CAAM_HASH_Update(ctx, data, 64); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 process buffer - */ -int mbedtls_sha1_update_ret(mbedtls_sha1_context * ctx, const unsigned char * input, size_t ilen) -{ - status_t ret = kStatus_Fail; - ret = CAAM_HASH_Update(ctx, input, ilen); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 final digest - */ -int mbedtls_sha1_finish_ret(mbedtls_sha1_context * ctx, unsigned char output[20]) -{ - status_t ret = kStatus_Fail; - ret = CAAM_HASH_Finish(ctx, output, 0); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -#elif defined(MBEDTLS_FREESCALE_CAU3_SHA1) -#include "mbedtls/sha1.h" - -void mbedtls_sha1_init(mbedtls_sha1_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_free(mbedtls_sha1_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_clone(mbedtls_sha1_context * dst, const mbedtls_sha1_context * src) -{ - memcpy(dst, src, sizeof(mbedtls_sha1_context)); -} - -/* - * SHA-1 context setup - */ -int mbedtls_sha1_starts_ret(mbedtls_sha1_context * ctx) -{ - status_t ret = kStatus_Fail; - ret = CAU3_HASH_Init(CAU3, ctx, kCAU3_Sha1); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -int mbedtls_internal_sha1_process(mbedtls_sha1_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = CAU3_HASH_Update(CAU3, ctx, data, 64); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 process buffer - */ -int mbedtls_sha1_update_ret(mbedtls_sha1_context * ctx, const unsigned char * input, size_t ilen) -{ - status_t ret = kStatus_Fail; - ret = CAU3_HASH_Update(CAU3, ctx, input, ilen); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 final digest - */ -int mbedtls_sha1_finish_ret(mbedtls_sha1_context * ctx, unsigned char output[20]) -{ - status_t ret = kStatus_Fail; - ret = CAU3_HASH_Finish(CAU3, ctx, output, 0); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -#elif defined(MBEDTLS_FREESCALE_DCP_SHA1) -#include "mbedtls/sha1.h" - -void mbedtls_sha1_init(mbedtls_sha1_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_free(mbedtls_sha1_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_clone(mbedtls_sha1_context * dst, const mbedtls_sha1_context * src) -{ - memcpy(dst, src, sizeof(mbedtls_sha1_context)); -} - -/* - * SHA-1 context setup - */ -int mbedtls_sha1_starts_ret(mbedtls_sha1_context * ctx) -{ - status_t ret = kStatus_Fail; - ret = DCP_HASH_Init(DCP, &s_dcpHandle, ctx, kDCP_Sha1); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -int mbedtls_internal_sha1_process(mbedtls_sha1_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = DCP_HASH_Update(DCP, ctx, data, 64); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 process buffer - */ -int mbedtls_sha1_update_ret(mbedtls_sha1_context * ctx, const unsigned char * input, size_t ilen) -{ - status_t ret = kStatus_Fail; - ret = DCP_HASH_Update(DCP, ctx, input, ilen); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 final digest - */ -int mbedtls_sha1_finish_ret(mbedtls_sha1_context * ctx, unsigned char output[20]) -{ - status_t ret = kStatus_Fail; - ret = DCP_HASH_Finish(DCP, ctx, output, NULL); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -#elif defined(MBEDTLS_FREESCALE_HASHCRYPT_SHA1) -#include "mbedtls/sha1.h" - -void mbedtls_sha1_init(mbedtls_sha1_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_free(mbedtls_sha1_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha1_context)); -} - -void mbedtls_sha1_clone(mbedtls_sha1_context * dst, const mbedtls_sha1_context * src) -{ - memcpy(dst, src, sizeof(mbedtls_sha1_context)); -} - -/* - * SHA-1 context setup - */ -int mbedtls_sha1_starts_ret(mbedtls_sha1_context * ctx) -{ - status_t ret = kStatus_Fail; - ret = HASHCRYPT_SHA_Init(HASHCRYPT, ctx, kHASHCRYPT_Sha1); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -int mbedtls_internal_sha1_process(mbedtls_sha1_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = HASHCRYPT_SHA_Update(HASHCRYPT, ctx, data, 64); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 process buffer - */ -int mbedtls_sha1_update_ret(mbedtls_sha1_context * ctx, const unsigned char * input, size_t ilen) -{ - status_t ret = kStatus_Fail; - ret = HASHCRYPT_SHA_Update(HASHCRYPT, ctx, input, ilen); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-1 final digest - */ -int mbedtls_sha1_finish_ret(mbedtls_sha1_context * ctx, unsigned char output[20]) -{ - status_t ret = kStatus_Fail; - size_t outputSize = 20; - ret = HASHCRYPT_SHA_Finish(HASHCRYPT, ctx, output, &outputSize); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED; - } - return 0; -} -#endif /* MBEDTLS_FREESCALE_LPC_SHA1 */ -#if !defined(MBEDTLS_DEPRECATED_REMOVED) && defined(MBEDTLS_SHA1_ALT) -#include "mbedtls/sha1.h" - -void mbedtls_sha1_starts(mbedtls_sha1_context * ctx) -{ - mbedtls_sha1_starts_ret(ctx); -} - -void mbedtls_sha1_update(mbedtls_sha1_context * ctx, const unsigned char * input, size_t ilen) -{ - mbedtls_sha1_update_ret(ctx, input, ilen); -} - -void mbedtls_sha1_finish(mbedtls_sha1_context * ctx, unsigned char output[20]) -{ - mbedtls_sha1_finish_ret(ctx, output); -} - -void mbedtls_sha1_process(mbedtls_sha1_context * ctx, const unsigned char data[64]) -{ - mbedtls_internal_sha1_process(ctx, data); -} -#endif /* MBEDTLS_DEPRECATED_REMOVED */ -#endif /* MBEDTLS_SHA1_C */ - -/******************************************************************************/ -/*************************** SHA256********************************************/ -/******************************************************************************/ - -#if defined(MBEDTLS_SHA256_C) - -#if defined(MBEDTLS_FREESCALE_LTC_SHA256) -#include "mbedtls/sha256.h" - -void mbedtls_sha256_init(mbedtls_sha256_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_free(mbedtls_sha256_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_clone(mbedtls_sha256_context * dst, const mbedtls_sha256_context * src) -{ - memcpy(dst, src, sizeof(*dst)); -} - -/* - * SHA-256 context setup - */ -int mbedtls_sha256_starts_ret(mbedtls_sha256_context * ctx, int is224) -{ - status_t ret = kStatus_Fail; - if (is224) - { - ret = LTC_HASH_Init(LTC_INSTANCE, ctx, kLTC_Sha224, NULL, 0); - } - else - { - ret = LTC_HASH_Init(LTC_INSTANCE, ctx, kLTC_Sha256, NULL, 0); - } - - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -int mbedtls_internal_sha256_process(mbedtls_sha256_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = LTC_HASH_Update(ctx, data, 64); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-256 process buffer - */ -int mbedtls_sha256_update_ret(mbedtls_sha256_context * ctx, const unsigned char * input, size_t ilen) -{ - status_t ret = kStatus_Fail; - ret = LTC_HASH_Update(ctx, input, ilen); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-256 final digest - */ -int mbedtls_sha256_finish_ret(mbedtls_sha256_context * ctx, unsigned char output[32]) -{ - status_t ret = kStatus_Fail; - ret = LTC_HASH_Finish(ctx, output, 0); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -#elif defined(MBEDTLS_FREESCALE_MMCAU_SHA256) - -#include "mbedtls/sha256.h" - -int mbedtls_internal_sha256_process(mbedtls_sha256_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = MMCAU_SHA256_HashN(data, 1, ctx->state); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -#elif defined(MBEDTLS_FREESCALE_CAU3_SHA256) - -#include "mbedtls/sha256.h" - -void mbedtls_sha256_init(mbedtls_sha256_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_free(mbedtls_sha256_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_clone(mbedtls_sha256_context * dst, const mbedtls_sha256_context * src) -{ - memcpy(dst, src, sizeof(*dst)); -} - -/* - * SHA-256 context setup - */ -int mbedtls_sha256_starts_ret(mbedtls_sha256_context * ctx, int is224) -{ - status_t ret = kStatus_Fail; - if (!is224) /* SHA-224 not supported at the moment */ - { - ret = CAU3_HASH_Init(CAU3, ctx, kCAU3_Sha256); - } - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -int mbedtls_internal_sha256_process(mbedtls_sha256_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = CAU3_HASH_Update(CAU3, ctx, data, 64); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-256 process buffer - */ -int mbedtls_sha256_update_ret(mbedtls_sha256_context * ctx, const unsigned char * input, size_t ilen) -{ - status_t ret = kStatus_Fail; - ret = CAU3_HASH_Update(CAU3, ctx, input, ilen); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-256 final digest - */ -int mbedtls_sha256_finish_ret(mbedtls_sha256_context * ctx, unsigned char output[32]) -{ - status_t ret = kStatus_Fail; - ret = CAU3_HASH_Finish(CAU3, ctx, output, 0); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -#elif defined(MBEDTLS_FREESCALE_LPC_SHA256) -#include "mbedtls/sha256.h" - -void mbedtls_sha256_init(mbedtls_sha256_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_free(mbedtls_sha256_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_clone(mbedtls_sha256_context * dst, const mbedtls_sha256_context * src) -{ - memcpy(dst, src, sizeof(*dst)); -} - -/* - * SHA-256 context setup - */ -int mbedtls_sha256_starts_ret(mbedtls_sha256_context * ctx, int is224) -{ - int status = MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - if (!is224) /* SHA-224 not supported */ - { - SHA256_Init(ctx); - status = 0; - } - return status; -} - -int mbedtls_internal_sha256_process(mbedtls_sha256_context * ctx, const unsigned char data[64]) -{ - SHA256_HashUpdate(ctx, data, 64); - return 0; -} - -/* - * SHA-256 process buffer - */ -int mbedtls_sha256_update_ret(mbedtls_sha256_context * ctx, const unsigned char * input, size_t ilen) -{ - SHA256_HashUpdate(ctx, input, ilen); - - return 0; -} - -/* - * SHA-256 final digest - */ -int mbedtls_sha256_finish_ret(mbedtls_sha256_context * ctx, unsigned char output[32]) -{ - SHA256_HashFinish(ctx, output); - return 0; -} - -#elif defined(MBEDTLS_FREESCALE_CAAM_SHA256) -#include "mbedtls/sha256.h" - -void mbedtls_sha256_init(mbedtls_sha256_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_free(mbedtls_sha256_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_clone(mbedtls_sha256_context * dst, const mbedtls_sha256_context * src) -{ - memcpy(dst, src, sizeof(*dst)); -} - -/* - * SHA-256 context setup - */ -int mbedtls_sha256_starts_ret(mbedtls_sha256_context * ctx, int is224) -{ - status_t ret = kStatus_Fail; - if (is224) - { - ret = CAAM_HASH_Init(CAAM_INSTANCE, &s_caamHandle, ctx, kCAAM_Sha224, NULL, 0); - } - else - { - ret = CAAM_HASH_Init(CAAM_INSTANCE, &s_caamHandle, ctx, kCAAM_Sha256, NULL, 0); - } - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -int mbedtls_internal_sha256_process(mbedtls_sha256_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = CAAM_HASH_Update(ctx, data, 64); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-256 process buffer - */ -int mbedtls_sha256_update_ret(mbedtls_sha256_context * ctx, const unsigned char * input, size_t ilen) -{ - status_t ret = kStatus_Fail; - ret = CAAM_HASH_Update(ctx, input, ilen); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-256 final digest - */ -int mbedtls_sha256_finish_ret(mbedtls_sha256_context * ctx, unsigned char output[32]) -{ - status_t ret = kStatus_Fail; - ret = CAAM_HASH_Finish(ctx, output, 0); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -#elif defined(MBEDTLS_FREESCALE_DCP_SHA256) -#include "mbedtls/sha256.h" - -void mbedtls_sha256_init(mbedtls_sha256_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_free(mbedtls_sha256_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_clone(mbedtls_sha256_context * dst, const mbedtls_sha256_context * src) -{ - memcpy(dst, src, sizeof(*dst)); -} - -/* - * SHA-256 context setup - */ -int mbedtls_sha256_starts_ret(mbedtls_sha256_context * ctx, int is224) -{ - status_t ret = kStatus_Fail; - if (!is224) - { - ret = DCP_HASH_Init(DCP, &s_dcpHandle, ctx, kDCP_Sha256); - } - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -int mbedtls_internal_sha256_process(mbedtls_sha256_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = DCP_HASH_Update(DCP, ctx, data, 64); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-256 process buffer - */ -int mbedtls_sha256_update_ret(mbedtls_sha256_context * ctx, const unsigned char * input, size_t ilen) -{ - status_t ret = kStatus_Fail; - ret = DCP_HASH_Update(DCP, ctx, input, ilen); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-256 final digest - */ -int mbedtls_sha256_finish_ret(mbedtls_sha256_context * ctx, unsigned char output[32]) -{ - status_t ret = kStatus_Fail; - ret = DCP_HASH_Finish(DCP, ctx, output, NULL); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -#elif defined(MBEDTLS_FREESCALE_HASHCRYPT_SHA256) -#include "mbedtls/sha256.h" - -void mbedtls_sha256_init(mbedtls_sha256_context * ctx) -{ - memset(ctx, 0, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_free(mbedtls_sha256_context * ctx) -{ - if (ctx == NULL) - return; - - mbedtls_zeroize(ctx, sizeof(mbedtls_sha256_context)); -} - -void mbedtls_sha256_clone(mbedtls_sha256_context * dst, const mbedtls_sha256_context * src) -{ - memcpy(dst, src, sizeof(*dst)); -} - -/* - * SHA-256 context setup - */ -int mbedtls_sha256_starts_ret(mbedtls_sha256_context * ctx, int is224) -{ - status_t ret = kStatus_Fail; - if (!is224) /* SHA-224 not supported */ - { - ret = HASHCRYPT_SHA_Init(HASHCRYPT, ctx, kHASHCRYPT_Sha256); - } - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -int mbedtls_internal_sha256_process(mbedtls_sha256_context * ctx, const unsigned char data[64]) -{ - status_t ret = kStatus_Fail; - ret = HASHCRYPT_SHA_Update(HASHCRYPT, ctx, data, 64); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-256 process buffer - */ -int mbedtls_sha256_update_ret(mbedtls_sha256_context * ctx, const unsigned char * input, size_t ilen) -{ - status_t ret = kStatus_Fail; - ret = HASHCRYPT_SHA_Update(HASHCRYPT, ctx, input, ilen); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} - -/* - * SHA-256 final digest - */ -int mbedtls_sha256_finish_ret(mbedtls_sha256_context * ctx, unsigned char output[32]) -{ - status_t ret = kStatus_Fail; - size_t outputSize = 32; - ret = HASHCRYPT_SHA_Finish(HASHCRYPT, ctx, output, &outputSize); - if (ret != kStatus_Success) - { - return MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED; - } - return 0; -} -#endif /* MBEDTLS_FREESCALE_LTC_SHA256 */ -#if !defined(MBEDTLS_DEPRECATED_REMOVED) && defined(MBEDTLS_SHA256_ALT) -#include "mbedtls/sha256.h" - -void mbedtls_sha256_starts(mbedtls_sha256_context * ctx, int is224) -{ - mbedtls_sha256_starts_ret(ctx, is224); -} - -void mbedtls_sha256_update(mbedtls_sha256_context * ctx, const unsigned char * input, size_t ilen) -{ - mbedtls_sha256_update_ret(ctx, input, ilen); -} - -void mbedtls_sha256_finish(mbedtls_sha256_context * ctx, unsigned char output[32]) -{ - mbedtls_sha256_finish_ret(ctx, output); -} - -void mbedtls_sha256_process(mbedtls_sha256_context * ctx, const unsigned char data[64]) -{ - mbedtls_internal_sha256_process(ctx, data); -} -#endif /* MBEDTLS_DEPRECATED_REMOVED */ -#endif /* MBEDTLS_SHA256_C */ - -/* Entropy poll callback for a hardware source */ -#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT) - -#if defined(FSL_FEATURE_SOC_TRNG_COUNT) && (FSL_FEATURE_SOC_TRNG_COUNT > 0) -#if defined CPU_JN518X -#include "fsl_rng.h" -#else -#include "fsl_trng.h" -#endif -#elif defined(FSL_FEATURE_SOC_RNG_COUNT) && (FSL_FEATURE_SOC_RNG_COUNT > 0) -#include "fsl_rnga.h" -#elif defined(FSL_FEATURE_SOC_LPC_RNG_COUNT) && (FSL_FEATURE_SOC_LPC_RNG_COUNT > 0) -#include "fsl_rng.h" -#elif defined(FSL_FEATURE_SOC_LPC_RNG1_COUNT) && (FSL_FEATURE_SOC_LPC_RNG1_COUNT > 0) -#include "fsl_rng.h" -#endif - -int mbedtls_hardware_poll(void * data, unsigned char * output, size_t len, size_t * olen) -{ - status_t result = kStatus_Success; - -#if defined(FSL_FEATURE_SOC_TRNG_COUNT) && (FSL_FEATURE_SOC_TRNG_COUNT > 0) -#if defined CPU_JN518X -#ifndef TRNG0 -#define TRNG0 RNG -#endif -#else -#ifndef TRNG0 -#define TRNG0 TRNG -#endif -#endif - result = TRNG_GetRandomData(TRNG0, output, len); -#elif defined(FSL_FEATURE_SOC_RNG_COUNT) && (FSL_FEATURE_SOC_RNG_COUNT > 0) - result = RNGA_GetRandomData(RNG, (void *) output, len); -#elif defined(FSL_FEATURE_SOC_CAAM_COUNT) && (FSL_FEATURE_SOC_CAAM_COUNT > 0) && defined(CRYPTO_USE_DRIVER_CAAM) - result = CAAM_RNG_GetRandomData(CAAM_INSTANCE, &s_caamHandle, kCAAM_RngStateHandle0, output, len, kCAAM_RngDataAny, NULL); -#elif defined(FSL_FEATURE_SOC_LPC_RNG_COUNT) && (FSL_FEATURE_SOC_LPC_RNG_COUNT > 0) - uint32_t rn; - size_t length; - int i; - - length = len; - - while (length > 0) - { - rn = RNG_GetRandomData(); - - if (length >= sizeof(uint32_t)) - { - memcpy(output, &rn, sizeof(uint32_t)); - length -= sizeof(uint32_t); - output += sizeof(uint32_t); - } - else - { - memcpy(output, &rn, length); - output += length; - len = 0U; - } - - /* Discard next 32 random words for better entropy */ - for (i = 0; i < 32; i++) - { - RNG_GetRandomData(); - } - } - - result = kStatus_Success; -#elif defined(FSL_FEATURE_SOC_LPC_RNG1_COUNT) && (FSL_FEATURE_SOC_LPC_RNG1_COUNT > 0) - status_t status = kStatus_Fail; - - while (status != kStatus_Success) - { - status = RNG_GetRandomData(RNG, output, len); - - if (status == kStatus_Fail) - { - RNG_Init(RNG); - } - } - - result = status; -#endif - if (result == kStatus_Success) - { - *olen = len; - return 0; - } - else - { - return result; - } -} - -#endif - -/******************************************************************************/ -/*************************** FreeRTOS ********************************************/ -/******************************************************************************/ -#if USE_RTOS && defined(FSL_RTOS_FREE_RTOS) && defined(MBEDTLS_FREESCALE_FREERTOS_CALLOC_ALT) -#include "FreeRTOS.h" -#include "task.h" -#include - -/*---------HEAP_3 calloc --------------------------------------------------*/ - -void * pvPortCalloc(size_t num, size_t size) -{ - void * pvReturn; - - vTaskSuspendAll(); - { - pvReturn = calloc(num, size); - traceMALLOC(pvReturn, xWantedSize); - } - (void) xTaskResumeAll(); - -#if (configUSE_MALLOC_FAILED_HOOK == 1) - { - if (pvReturn == NULL) - { - extern void vApplicationMallocFailedHook(void); - vApplicationMallocFailedHook(); - } - } -#endif - - return pvReturn; -} -#endif /* USE_RTOS && defined(FSL_RTOS_FREE_RTOS) && defined(MBEDTLS_FREESCALE_FREERTOS_CALLOC_ALT) */ diff --git a/third_party/nxp/k32w0_sdk/k32w0_sdk.gni b/third_party/nxp/k32w0_sdk/k32w0_sdk.gni index 41e9761044106f..e8858022e20516 100644 --- a/third_party/nxp/k32w0_sdk/k32w0_sdk.gni +++ b/third_party/nxp/k32w0_sdk/k32w0_sdk.gni @@ -204,7 +204,28 @@ template("k32w0_sdk") { "${k32w0_sdk_root}/components/serial_manager", "${k32w0_sdk_root}/components/uart", "${k32w0_sdk_root}/devices/${device}", - "${k32w0_sdk_root}/devices/${device}/drivers", + "${k32w0_sdk_root}/devices/K32W061/drivers", + "${k32w0_sdk_root}/drivers/common", + "${k32w0_sdk_root}/drivers/lpc_gpio", + "${k32w0_sdk_root}/drivers/aes", + "${k32w0_sdk_root}/drivers/jn_iocon", + "${k32w0_sdk_root}/drivers/lpc_adc", + "${k32w0_sdk_root}/drivers/aes", + "${k32w0_sdk_root}/drivers/jn_flash", + "${k32w0_sdk_root}/drivers/sha", + "${k32w0_sdk_root}/drivers/flexcomm", + "${k32w0_sdk_root}/drivers/lpc_dma", + "${k32w0_sdk_root}/drivers/pint", + "${k32w0_sdk_root}/drivers/inputmux", + "${k32w0_sdk_root}/drivers/spifi", + "${k32w0_sdk_root}/drivers/jn_rtc", + "${k32w0_sdk_root}/drivers/fmeas", + "${k32w0_sdk_root}/drivers/jn_rng", + "${k32w0_sdk_root}/drivers/ctimer", + "${k32w0_sdk_root}/drivers/wwdt", + "${k32w0_sdk_root}/drivers/gint", + "${k32w0_sdk_root}/utilities/debug_console/str", + "${k32w0_sdk_root}/utilities/debug_console", "${k32w0_sdk_root}/devices/${device}/utilities", "${k32w0_sdk_root}/devices/${device}/utilities/debug_console", "${k32w0_sdk_root}/devices/${device}/utilities/str", @@ -257,7 +278,6 @@ template("k32w0_sdk") { ] defines = [ - "gPWR_CpuClk_48MHz=1", "gMainThreadPriority_c=5", "CPU_JN518X", "CPU_JN518X_REV=2", @@ -335,9 +355,15 @@ template("k32w0_sdk") { } if (use_fro_32k == 1) { - defines += [ "gClkUseFro32K=1" ] + defines += [ + "gClkUseFro32K=1", + "gPWR_CpuClk_48MHz=0", + ] } else { - defines += [ "gClkUseFro32K=0" ] + defines += [ + "gClkUseFro32K=0", + "gPWR_CpuClk_48MHz=1", + ] } if (chip_with_pdm_encryption == 1) { @@ -399,6 +425,7 @@ template("k32w0_sdk") { if (chip_with_low_power == 1) { defines += [ + "chip_with_low_power=1", "cPWR_UsePowerDownMode=1", "cPWR_FullPowerDownMode=1", "DBG_PostStepTickAssess=0", @@ -456,7 +483,7 @@ template("k32w0_sdk") { } if (chip_with_factory_data == 1) { - defines += [ "CONFIG_CHIP_K32W0_REAL_FACTORY_DATA=1" ] + defines += [ "CONFIG_CHIP_LOAD_REAL_FACTORY_DATA=1" ] } if (defined(invoker.defines)) { @@ -510,31 +537,29 @@ template("k32w0_sdk") { "${k32w0_sdk_root}/components/serial_manager/serial_manager.c", "${k32w0_sdk_root}/components/serial_manager/serial_port_uart.c", "${k32w0_sdk_root}/components/uart/usart_adapter.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_adc.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_aes.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_clock.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_common.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_ctimer.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_flash.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_flexcomm.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_fmeas.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_gpio.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_i2c.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_i2c_freertos.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_inputmux.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_pint.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_power.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_reset.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_rng.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_rtc.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_sha.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_spifi.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_usart.c", - "${k32w0_sdk_root}/devices/${device}/drivers/fsl_wtimer.c", "${k32w0_sdk_root}/devices/${device}/mcuxpresso/startup_${device_lowercase}.c", "${k32w0_sdk_root}/devices/${device}/system_${device}.c", - "${k32w0_sdk_root}/devices/${device}/utilities/debug_console/fsl_debug_console.c", - "${k32w0_sdk_root}/devices/${device}/utilities/str/fsl_str.c", + "${k32w0_sdk_root}/devices/K32W061/drivers/fsl_clock.c", + "${k32w0_sdk_root}/devices/K32W061/drivers/fsl_power.c", + "${k32w0_sdk_root}/devices/K32W061/drivers/fsl_reset.c", + "${k32w0_sdk_root}/devices/K32W061/drivers/fsl_wtimer.c", + "${k32w0_sdk_root}/drivers/aes/fsl_aes.c", + "${k32w0_sdk_root}/drivers/common/fsl_common.c", + "${k32w0_sdk_root}/drivers/ctimer/fsl_ctimer.c", + "${k32w0_sdk_root}/drivers/flexcomm/fsl_flexcomm.c", + "${k32w0_sdk_root}/drivers/flexcomm/fsl_i2c.c", + "${k32w0_sdk_root}/drivers/flexcomm/fsl_i2c_freertos.c", + "${k32w0_sdk_root}/drivers/flexcomm/fsl_usart.c", + "${k32w0_sdk_root}/drivers/fmeas/fsl_fmeas.c", + "${k32w0_sdk_root}/drivers/inputmux/fsl_inputmux.c", + "${k32w0_sdk_root}/drivers/jn_flash/fsl_flash.c", + "${k32w0_sdk_root}/drivers/jn_rng/fsl_rng.c", + "${k32w0_sdk_root}/drivers/jn_rtc/fsl_rtc.c", + "${k32w0_sdk_root}/drivers/lpc_adc/fsl_adc.c", + "${k32w0_sdk_root}/drivers/lpc_gpio/fsl_gpio.c", + "${k32w0_sdk_root}/drivers/pint/fsl_pint.c", + "${k32w0_sdk_root}/drivers/sha/fsl_sha.c", + "${k32w0_sdk_root}/drivers/spifi/fsl_spifi.c", "${k32w0_sdk_root}/middleware/wireless/ble_controller/config/controller_config.c", "${k32w0_sdk_root}/middleware/wireless/bluetooth/application/common/ble_conn_manager.c", "${k32w0_sdk_root}/middleware/wireless/bluetooth/application/common/ble_host_tasks.c", @@ -574,6 +599,8 @@ template("k32w0_sdk") { "${k32w0_sdk_root}/rtos/amazon-freertos/lib/FreeRTOS/queue.c", "${k32w0_sdk_root}/rtos/amazon-freertos/lib/FreeRTOS/tasks.c", "${k32w0_sdk_root}/rtos/amazon-freertos/lib/FreeRTOS/timers.c", + "${k32w0_sdk_root}/utilities/debug_console/fsl_debug_console.c", + "${k32w0_sdk_root}/utilities/debug_console/str/fsl_str.c", ] if (chip_with_DK6) { diff --git a/third_party/nxp/k32w0_sdk/repo/.gitignore b/third_party/nxp/k32w0_sdk/repo/.gitignore new file mode 100644 index 00000000000000..16b30e08a957c7 --- /dev/null +++ b/third_party/nxp/k32w0_sdk/repo/.gitignore @@ -0,0 +1,2 @@ +core +.west diff --git a/third_party/nxp/k32w0_sdk/repo/manifest/west.yml b/third_party/nxp/k32w0_sdk/repo/manifest/west.yml new file mode 100644 index 00000000000000..3a00791908f057 --- /dev/null +++ b/third_party/nxp/k32w0_sdk/repo/manifest/west.yml @@ -0,0 +1,43 @@ +# The west manifest file (west.yml) for MCUXpresso SDK delivery. +# +# See the west documentation for more information: +# +# https://docs.zephyrproject.org/latest/guides/west/index.html +manifest: + remotes: + - name: nxpmicro + url-base: https://github.com/NXPmicro + defaults: + remote: nxpmicro + projects: + - name: mcux-sdk + revision: b1ce670e8433142a3c78dca7f4597326eb5f5342 + path: core + - name: amazon-freertos + url: https://github.com/NXP/amazon-freertos.git + path: core/rtos/amazon-freertos + revision: fb74168634e716fb5f0a61714e5c0d1ac6246ba + - name: mbedtls + url: https://github.com/nxp-mcuxpresso/mbedtls.git + path: core/middleware/mbedtls + revision: 15458495823165de372f62c3dad621a8da6c86e3 + - name: framework + url: https://github.com/NXP/mcux-sdk-middleware-connectivity-framework.git + revision: a45ed24bc5f8d54312c4d9243c4423d226084412 + path: core/middleware/wireless/framework + - name: ble_controller + url: https://github.com/NXP/mcux-sdk-middleware-bluetooth-controller.git + revision: 0e4effc707a0d5569160b9335bc2e57c17255f01 + path: core/middleware/wireless/ble_controller + - name: bluetooth + url: https://github.com/NXP/mcux-sdk-middleware-bluetooth-host.git + revision: e5a1b7b9e3b44b49c6c0318edfc3acac74b342d8 + path: core/middleware/wireless/bluetooth + - name: ieee-802.15.4 + url: https://github.com/NXP/mcux-sdk-middleware-ieee_802.15.4.git + revision: 7cca871d58e53c78a703a39b269c4366b03f26e4 + path: core/middleware/wireless/ieee-802.15.4 + - name: examples + url: https://github.com/nxp-mcuxpresso/mcux-sdk-examples.git + revision: 39eed09d6a8485dcf365a24cd6ef957e7cc6fbf8 + path: core/boards diff --git a/third_party/openthread/ot-nxp b/third_party/openthread/ot-nxp index 015fd8d1dd3fa0..d533504a90f231 160000 --- a/third_party/openthread/ot-nxp +++ b/third_party/openthread/ot-nxp @@ -1 +1 @@ -Subproject commit 015fd8d1dd3fa032e78236f2b15e6ff4131c5108 +Subproject commit d533504a90f2312ba3cfe94f716f3ee9b59d4209