Skip to content

Commit f96f98e

Browse files
committed
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.
1 parent 2a73d44 commit f96f98e

File tree

2 files changed

+16
-14
lines changed

2 files changed

+16
-14
lines changed

connectivity/mbedtls/platform/inc/timing_alt.h

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,9 @@
2424
#include "mbedtls/timing.h"
2525
#if defined(MBEDTLS_TIMING_ALT)
2626

27-
#include <time.h>
28-
2927
struct mbedtls_timing_hr_time
3028
{
31-
struct timeval start;
29+
unsigned long start;
3230
};
3331

3432
typedef struct mbedtls_timing_delay_context

connectivity/mbedtls/platform/src/timing_mbed.cpp

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
#endif
2626
#include "mbedtls/timing.h"
2727
#include "drivers/Timeout.h"
28+
#include "drivers/Timer.h"
29+
#include "drivers/LowPowerTimer.h"
2830
#include <chrono>
2931

3032
extern "C" {
@@ -46,22 +48,24 @@ extern "C" void mbedtls_set_alarm(int seconds)
4648

4749
#if !defined(HAVE_HARDCLOCK)
4850
#define HAVE_HARDCLOCK
49-
#include "platform/mbed_rtc_time.h"
50-
static int hardclock_init = 0;
51-
static struct timeval tv_init;
51+
static int timer_init = 0;
5252

5353
extern "C" unsigned long mbedtls_timing_hardclock(void)
5454
{
55-
struct timeval tv_cur;
55+
#if DEVICE_LPTICKER
56+
static mbed::LowPowerTimer timer;
57+
#elif DEVICE_USTICKER
58+
static mbed::Timer timer;
59+
#else
60+
#error "MBEDTLS_TIMING_C requires either LPTICKER or USTICKER"
61+
#endif
5662

57-
if (hardclock_init == 0)
58-
{
59-
gettimeofday(&tv_init, NULL);
60-
hardclock_init = 1;
63+
if (timer_init == 0) {
64+
timer.reset();
65+
timer.start();
66+
timer_init = 1;
6167
}
6268

63-
gettimeofday(&tv_cur, NULL);
64-
return((tv_cur.tv_sec - tv_init.tv_sec) * 1000000
65-
+ (tv_cur.tv_usec - tv_init.tv_usec));
69+
return timer.elapsed_time().count();
6670
}
6771
#endif /* !HAVE_HARDCLOCK */

0 commit comments

Comments
 (0)