From 77f9faf46cefdaf5dfd1dcf7feed118bde8e5bf9 Mon Sep 17 00:00:00 2001 From: Ron Eldor Date: Thu, 14 Feb 2019 14:25:55 +0200 Subject: [PATCH] Use a mutex in platform setup \ teardown functions Use a singleton Mutex in platforms_alt functions, to be shared with the trng function, to save RAM. Rename `platform_alt.c` to `platform_alt.cpp` as the mutex is in a `singletonPtr` template class. --- features/mbedtls/platform/src/mbed_trng.cpp | 8 +++++--- .../src/{platform_alt.c => platform_alt.cpp} | 13 +++++++++---- 2 files changed, 14 insertions(+), 7 deletions(-) rename features/mbedtls/platform/src/{platform_alt.c => platform_alt.cpp} (83%) diff --git a/features/mbedtls/platform/src/mbed_trng.cpp b/features/mbedtls/platform/src/mbed_trng.cpp index 53c1c21097..79fed2a7d0 100644 --- a/features/mbedtls/platform/src/mbed_trng.cpp +++ b/features/mbedtls/platform/src/mbed_trng.cpp @@ -17,17 +17,19 @@ #if DEVICE_TRNG #include "hal/trng_api.h" +#include "platform/SingletonPtr.h" #include "platform/PlatformMutex.h" +SingletonPtr mbedtls_mutex; + extern "C" int mbedtls_hardware_poll( void *data, unsigned char *output, size_t len, size_t *olen ) { - static PlatformMutex trng_mutex; trng_t trng_obj; - trng_mutex.lock(); + mbedtls_mutex->lock(); trng_init(&trng_obj); int ret = trng_get_bytes(&trng_obj, output, len, olen); trng_free(&trng_obj); - trng_mutex.unlock(); + mbedtls_mutex->unlock(); return ret; } diff --git a/features/mbedtls/platform/src/platform_alt.c b/features/mbedtls/platform/src/platform_alt.cpp similarity index 83% rename from features/mbedtls/platform/src/platform_alt.c rename to features/mbedtls/platform/src/platform_alt.cpp index c0254de9dc..c6f0abce66 100644 --- a/features/mbedtls/platform/src/platform_alt.c +++ b/features/mbedtls/platform/src/platform_alt.cpp @@ -20,33 +20,38 @@ #include "mbedtls/platform.h" #if defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT) -#include "mbed_critical.h" +#include "platform/SingletonPtr.h" +#include "platform/PlatformMutex.h" mbedtls_platform_context plat_ctx = { { 0 } }; +extern SingletonPtr mbedtls_mutex; int mbedtls_platform_setup( mbedtls_platform_context *unused_ctx ) { int ret = 0; - - core_util_atomic_incr_u32( ( volatile uint32_t * )&plat_ctx.reference_count, 1 ); + mbedtls_mutex->lock(); + ++plat_ctx.reference_count; if( plat_ctx.reference_count == 1 ) { /* call platform specific code to setup crypto driver */ ret = crypto_platform_setup( &plat_ctx.platform_impl_ctx ); } + mbedtls_mutex->unlock(); return ( ret ); } void mbedtls_platform_teardown( mbedtls_platform_context *unused_ctx ) { - core_util_atomic_decr_u32( ( volatile uint32_t * )&plat_ctx.reference_count, 1 ); + mbedtls_mutex->lock(); + --plat_ctx.reference_count; if( plat_ctx.reference_count < 1 ) { /* call platform specific code to terminate crypto driver */ crypto_platform_terminate( &plat_ctx.platform_impl_ctx ); plat_ctx.reference_count = 0; } + mbedtls_mutex->unlock(); } #endif /* MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT*/