From f96f98e60e062535baaaa20ffc4735bbb43a27b4 Mon Sep 17 00:00:00 2001 From: Lingkai Dong Date: Fri, 11 Jun 2021 12:10:39 +0100 Subject: [PATCH] mbedtls: Use LowPowerTimer/Timer for timing Previously we used `gettimeofday()` for Mbed TLS timing, but its implementation provided by Mbed OS is only precise to seconds. The microsecond component of the output `struct timeval` is always set to zero. But Mbed TLS requires millisecond precision. To provide required timing precision, switch to use `LowPowerTicker` or (microsecond) `Ticker`. `LowPowerTicker` is preferred as it saves power and Mbed TLS does not require microsecond precision. --- .../mbedtls/platform/inc/timing_alt.h | 4 +-- .../mbedtls/platform/src/timing_mbed.cpp | 26 +++++++++++-------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/connectivity/mbedtls/platform/inc/timing_alt.h b/connectivity/mbedtls/platform/inc/timing_alt.h index de61d52814..533eab3d5b 100644 --- a/connectivity/mbedtls/platform/inc/timing_alt.h +++ b/connectivity/mbedtls/platform/inc/timing_alt.h @@ -24,11 +24,9 @@ #include "mbedtls/timing.h" #if defined(MBEDTLS_TIMING_ALT) -#include - struct mbedtls_timing_hr_time { - struct timeval start; + unsigned long start; }; typedef struct mbedtls_timing_delay_context diff --git a/connectivity/mbedtls/platform/src/timing_mbed.cpp b/connectivity/mbedtls/platform/src/timing_mbed.cpp index e26d2d5d77..4ee25fb1f2 100644 --- a/connectivity/mbedtls/platform/src/timing_mbed.cpp +++ b/connectivity/mbedtls/platform/src/timing_mbed.cpp @@ -25,6 +25,8 @@ #endif #include "mbedtls/timing.h" #include "drivers/Timeout.h" +#include "drivers/Timer.h" +#include "drivers/LowPowerTimer.h" #include extern "C" { @@ -46,22 +48,24 @@ extern "C" void mbedtls_set_alarm(int seconds) #if !defined(HAVE_HARDCLOCK) #define HAVE_HARDCLOCK -#include "platform/mbed_rtc_time.h" -static int hardclock_init = 0; -static struct timeval tv_init; +static int timer_init = 0; extern "C" unsigned long mbedtls_timing_hardclock(void) { - struct timeval tv_cur; +#if DEVICE_LPTICKER + static mbed::LowPowerTimer timer; +#elif DEVICE_USTICKER + static mbed::Timer timer; +#else +#error "MBEDTLS_TIMING_C requires either LPTICKER or USTICKER" +#endif - if (hardclock_init == 0) - { - gettimeofday(&tv_init, NULL); - hardclock_init = 1; + if (timer_init == 0) { + timer.reset(); + timer.start(); + timer_init = 1; } - gettimeofday(&tv_cur, NULL); - return((tv_cur.tv_sec - tv_init.tv_sec) * 1000000 - + (tv_cur.tv_usec - tv_init.tv_usec)); + return timer.elapsed_time().count(); } #endif /* !HAVE_HARDCLOCK */