1 /*
2  * Portable interface to the CPU cycle counter
3  *
4  * SPDX-FileCopyrightText: The Mbed TLS Contributors
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  *
8  * SPDX-FileContributor: 2016-2022 Espressif Systems (Shanghai) CO LTD
9  */
10 /*
11  * mbedtls_timing_get_timer()m mbedtls_timing_set_delay() and
12  * mbedtls_timing_set_delay only abstracted from mbedtls/library/timing.c
13  * as that does not build on ESP-IDF but these 2 functions are needed for
14  * DTLS (in particular mbedtls_ssl_set_timer_cb() must be called for DTLS
15  * which requires these 2 delay functions).
16  */
17 
18 #include <mbedtls/build_info.h>
19 
20 #if !defined(MBEDTLS_ESP_TIMING_C)
21 
22 #include <sys/time.h>
23 #include "mbedtls/timing.h"
24 
25 struct _hr_time
26 {
27     struct timeval start;
28 };
29 
mbedtls_timing_get_timer(struct mbedtls_timing_hr_time * val,int reset)30 unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )
31 {
32     struct _hr_time *t = (struct _hr_time *) val;
33 
34     if( reset )
35     {
36         gettimeofday( &t->start, NULL );
37         return( 0 );
38     }
39     else
40     {
41         unsigned long delta;
42         struct timeval now;
43         gettimeofday( &now, NULL );
44         delta = ( now.tv_sec  - t->start.tv_sec  ) * 1000ul
45               + ( now.tv_usec - t->start.tv_usec ) / 1000;
46         return( delta );
47     }
48 }
49 
50 /*
51  * Set delays to watch
52  */
mbedtls_timing_set_delay(void * data,uint32_t int_ms,uint32_t fin_ms)53 void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms )
54 {
55     mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;
56 
57     ctx->MBEDTLS_PRIVATE(int_ms) = int_ms;
58     ctx->MBEDTLS_PRIVATE(fin_ms) = fin_ms;
59 
60     if( fin_ms != 0 )
61         (void) mbedtls_timing_get_timer( &ctx->MBEDTLS_PRIVATE(timer), 1 );
62 }
63 
64 /*
65  * Get number of delays expired
66  */
mbedtls_timing_get_delay(void * data)67 int mbedtls_timing_get_delay( void *data )
68 {
69     mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;
70     unsigned long elapsed_ms;
71 
72     if( ctx->MBEDTLS_PRIVATE(fin_ms) == 0 )
73         return( -1 );
74 
75     elapsed_ms = mbedtls_timing_get_timer( &ctx->MBEDTLS_PRIVATE(timer), 0 );
76 
77     if( elapsed_ms >= ctx->MBEDTLS_PRIVATE(fin_ms) )
78         return( 2 );
79 
80     if( elapsed_ms >= ctx->MBEDTLS_PRIVATE(int_ms) )
81         return( 1 );
82 
83     return( 0 );
84 }
85 
86 /*
87  * Get the final delay.
88  */
mbedtls_timing_get_final_delay(const mbedtls_timing_delay_context * data)89 uint32_t mbedtls_timing_get_final_delay( const mbedtls_timing_delay_context *data )
90 {
91     return( data->MBEDTLS_PRIVATE(fin_ms) );
92 }
93 
94 #endif /* MBEDTLS_ESP_TIMING_C */
95