2 * Portable interface to the CPU cycle counter
4 * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5 * SPDX-License-Identifier: Apache-2.0
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may
8 * not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * This file is part of mbed TLS (https://tls.mbed.org)
22 #if !defined(MBEDTLS_CONFIG_FILE)
23 #include "mbedtls/config.h"
25 #include MBEDTLS_CONFIG_FILE
28 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_PLATFORM_C)
29 #include "mbedtls/platform.h"
32 #define mbedtls_printf printf
35 #if defined(MBEDTLS_TIMING_C)
37 #include "mbedtls/timing.h"
39 #if !defined(MBEDTLS_TIMING_ALT)
41 #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \
42 !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \
44 #error "This module only works on Unix and Windows, see MBEDTLS_TIMING_C in config.h"
51 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
65 #include <sys/types.h>
75 #endif /* _WIN32 && !EFIX64 && !EFI32 */
77 #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
78 ( defined(_MSC_VER) && defined(_M_IX86) ) || defined(__WATCOMC__)
80 #define HAVE_HARDCLOCK
82 unsigned long mbedtls_timing_hardclock( void )
89 #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
90 ( _MSC_VER && _M_IX86 ) || __WATCOMC__ */
92 /* some versions of mingw-64 have 32-bit longs even on x84_64 */
93 #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
94 defined(__GNUC__) && ( defined(__i386__) || ( \
95 ( defined(__amd64__) || defined( __x86_64__) ) && __SIZEOF_LONG__ == 4 ) )
97 #define HAVE_HARDCLOCK
99 unsigned long mbedtls_timing_hardclock( void )
101 unsigned long lo, hi;
102 asm volatile( "rdtsc" : "=a" (lo), "=d" (hi) );
105 #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
106 __GNUC__ && __i386__ */
108 #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
109 defined(__GNUC__) && ( defined(__amd64__) || defined(__x86_64__) )
111 #define HAVE_HARDCLOCK
113 unsigned long mbedtls_timing_hardclock( void )
115 unsigned long lo, hi;
116 asm volatile( "rdtsc" : "=a" (lo), "=d" (hi) );
117 return( lo | ( hi << 32 ) );
119 #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
120 __GNUC__ && ( __amd64__ || __x86_64__ ) */
122 #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
123 defined(__GNUC__) && ( defined(__powerpc__) || defined(__ppc__) )
125 #define HAVE_HARDCLOCK
127 unsigned long mbedtls_timing_hardclock( void )
129 unsigned long tbl, tbu0, tbu1;
133 asm volatile( "mftbu %0" : "=r" (tbu0) );
134 asm volatile( "mftb %0" : "=r" (tbl ) );
135 asm volatile( "mftbu %0" : "=r" (tbu1) );
137 while( tbu0 != tbu1 );
141 #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
142 __GNUC__ && ( __powerpc__ || __ppc__ ) */
144 #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
145 defined(__GNUC__) && defined(__sparc64__)
147 #if defined(__OpenBSD__)
148 #warning OpenBSD does not allow access to tick register using software version instead
150 #define HAVE_HARDCLOCK
152 unsigned long mbedtls_timing_hardclock( void )
155 asm volatile( "rdpr %%tick, %0;" : "=&r" (tick) );
158 #endif /* __OpenBSD__ */
159 #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
160 __GNUC__ && __sparc64__ */
162 #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
163 defined(__GNUC__) && defined(__sparc__) && !defined(__sparc64__)
165 #define HAVE_HARDCLOCK
167 unsigned long mbedtls_timing_hardclock( void )
170 asm volatile( ".byte 0x83, 0x41, 0x00, 0x00" );
171 asm volatile( "mov %%g1, %0" : "=r" (tick) );
174 #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
175 __GNUC__ && __sparc__ && !__sparc64__ */
177 #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
178 defined(__GNUC__) && defined(__alpha__)
180 #define HAVE_HARDCLOCK
182 unsigned long mbedtls_timing_hardclock( void )
185 asm volatile( "rpcc %0" : "=r" (cc) );
186 return( cc & 0xFFFFFFFF );
188 #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
189 __GNUC__ && __alpha__ */
191 #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
192 defined(__GNUC__) && defined(__ia64__)
194 #define HAVE_HARDCLOCK
196 unsigned long mbedtls_timing_hardclock( void )
199 asm volatile( "mov %0 = ar.itc" : "=r" (itc) );
202 #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
203 __GNUC__ && __ia64__ */
205 #if !defined(HAVE_HARDCLOCK) && defined(_MSC_VER) && \
206 !defined(EFIX64) && !defined(EFI32)
208 #define HAVE_HARDCLOCK
210 unsigned long mbedtls_timing_hardclock( void )
212 LARGE_INTEGER offset;
214 QueryPerformanceCounter( &offset );
216 return( (unsigned long)( offset.QuadPart ) );
218 #endif /* !HAVE_HARDCLOCK && _MSC_VER && !EFIX64 && !EFI32 */
220 #if !defined(HAVE_HARDCLOCK)
222 #define HAVE_HARDCLOCK
224 static int hardclock_init = 0;
225 static struct timeval tv_init;
227 unsigned long mbedtls_timing_hardclock( void )
229 struct timeval tv_cur;
231 if( hardclock_init == 0 )
233 gettimeofday( &tv_init, NULL );
237 gettimeofday( &tv_cur, NULL );
238 return( ( tv_cur.tv_sec - tv_init.tv_sec ) * 1000000
239 + ( tv_cur.tv_usec - tv_init.tv_usec ) );
241 #endif /* !HAVE_HARDCLOCK */
243 volatile int mbedtls_timing_alarmed = 0;
245 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
247 unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )
249 struct _hr_time *t = (struct _hr_time *) val;
253 QueryPerformanceCounter( &t->start );
259 LARGE_INTEGER now, hfreq;
260 QueryPerformanceCounter( &now );
261 QueryPerformanceFrequency( &hfreq );
262 delta = (unsigned long)( ( now.QuadPart - t->start.QuadPart ) * 1000ul
268 /* It's OK to use a global because alarm() is supposed to be global anyway */
269 static DWORD alarmMs;
271 static void TimerProc( void *TimerContext )
275 mbedtls_timing_alarmed = 1;
276 /* _endthread will be called implicitly on return
277 * That ensures execution of thread funcition's epilogue */
280 void mbedtls_set_alarm( int seconds )
284 /* No need to create a thread for this simple case.
285 * Also, this shorcut is more reliable at least on MinGW32 */
286 mbedtls_timing_alarmed = 1;
290 mbedtls_timing_alarmed = 0;
291 alarmMs = seconds * 1000;
292 (void) _beginthread( TimerProc, 0, NULL );
295 #else /* _WIN32 && !EFIX64 && !EFI32 */
297 unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )
299 struct _hr_time *t = (struct _hr_time *) val;
303 gettimeofday( &t->start, NULL );
310 gettimeofday( &now, NULL );
311 delta = ( now.tv_sec - t->start.tv_sec ) * 1000ul
312 + ( now.tv_usec - t->start.tv_usec ) / 1000;
317 static void sighandler( int signum )
319 mbedtls_timing_alarmed = 1;
320 signal( signum, sighandler );
323 void mbedtls_set_alarm( int seconds )
325 mbedtls_timing_alarmed = 0;
326 signal( SIGALRM, sighandler );
330 /* alarm(0) cancelled any previous pending alarm, but the
331 handler won't fire, so raise the flag straight away. */
332 mbedtls_timing_alarmed = 1;
336 #endif /* _WIN32 && !EFIX64 && !EFI32 */
339 * Set delays to watch
341 void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms )
343 mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;
345 ctx->int_ms = int_ms;
346 ctx->fin_ms = fin_ms;
349 (void) mbedtls_timing_get_timer( &ctx->timer, 1 );
353 * Get number of delays expired
355 int mbedtls_timing_get_delay( void *data )
357 mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;
358 unsigned long elapsed_ms;
360 if( ctx->fin_ms == 0 )
363 elapsed_ms = mbedtls_timing_get_timer( &ctx->timer, 0 );
365 if( elapsed_ms >= ctx->fin_ms )
368 if( elapsed_ms >= ctx->int_ms )
374 #endif /* !MBEDTLS_TIMING_ALT */
376 #if defined(MBEDTLS_SELF_TEST)
379 * Busy-waits for the given number of milliseconds.
380 * Used for testing mbedtls_timing_hardclock.
382 static void busy_msleep( unsigned long msec )
384 struct mbedtls_timing_hr_time hires;
385 unsigned long i = 0; /* for busy-waiting */
386 volatile unsigned long j; /* to prevent optimisation */
388 (void) mbedtls_timing_get_timer( &hires, 1 );
390 while( mbedtls_timing_get_timer( &hires, 0 ) < msec )
401 mbedtls_printf( "failed at line %d\n", __LINE__ ); \
402 mbedtls_printf( " cycles=%lu ratio=%lu millisecs=%lu secs=%lu hardfail=%d a=%lu b=%lu\n", \
403 cycles, ratio, millisecs, secs, hardfail, \
404 (unsigned long) a, (unsigned long) b ); \
405 mbedtls_printf( " elapsed(hires)=%lu elapsed(ctx)=%lu status(ctx)=%d\n", \
406 mbedtls_timing_get_timer( &hires, 0 ), \
407 mbedtls_timing_get_timer( &ctx.timer, 0 ), \
408 mbedtls_timing_get_delay( &ctx ) ); \
416 * Warning: this is work in progress, some tests may not be reliable enough
417 * yet! False positives may happen.
419 int mbedtls_timing_self_test( int verbose )
421 unsigned long cycles = 0, ratio = 0;
422 unsigned long millisecs = 0, secs = 0;
424 struct mbedtls_timing_hr_time hires;
425 uint32_t a = 0, b = 0;
426 mbedtls_timing_delay_context ctx;
429 mbedtls_printf( " TIMING tests note: will take some time!\n" );
432 mbedtls_printf( " TIMING test #1 (set_alarm / get_timer): " );
437 (void) mbedtls_timing_get_timer( &hires, 1 );
439 mbedtls_set_alarm( (int) secs );
440 while( !mbedtls_timing_alarmed )
443 millisecs = mbedtls_timing_get_timer( &hires, 0 );
445 /* For some reason on Windows it looks like alarm has an extra delay
446 * (maybe related to creating a new thread). Allow some room here. */
447 if( millisecs < 800 * secs || millisecs > 1200 * secs + 300 )
452 mbedtls_printf( "passed\n" );
455 mbedtls_printf( " TIMING test #2 (set/get_delay ): " );
460 mbedtls_timing_set_delay( &ctx, a, a + b ); /* T = 0 */
462 busy_msleep( a - a / 4 ); /* T = a - a/4 */
463 if( mbedtls_timing_get_delay( &ctx ) != 0 )
466 busy_msleep( a / 4 + b / 4 ); /* T = a + b/4 */
467 if( mbedtls_timing_get_delay( &ctx ) != 1 )
470 busy_msleep( b ); /* T = a + b + b/4 */
471 if( mbedtls_timing_get_delay( &ctx ) != 2 )
475 mbedtls_timing_set_delay( &ctx, 0, 0 );
477 if( mbedtls_timing_get_delay( &ctx ) != -1 )
481 mbedtls_printf( "passed\n" );
484 mbedtls_printf( " TIMING test #3 (hardclock / get_timer): " );
487 * Allow one failure for possible counter wrapping.
488 * On a 4Ghz 32-bit machine the cycle counter wraps about once per second;
489 * since the whole test is about 10ms, it shouldn't happen twice in a row.
496 mbedtls_printf( "failed (ignored)\n" );
501 /* Get a reference ratio cycles/ms */
503 cycles = mbedtls_timing_hardclock();
504 busy_msleep( millisecs );
505 cycles = mbedtls_timing_hardclock() - cycles;
506 ratio = cycles / millisecs;
508 /* Check that the ratio is mostly constant */
509 for( millisecs = 2; millisecs <= 4; millisecs++ )
511 cycles = mbedtls_timing_hardclock();
512 busy_msleep( millisecs );
513 cycles = mbedtls_timing_hardclock() - cycles;
515 /* Allow variation up to 20% */
516 if( cycles / millisecs < ratio - ratio / 5 ||
517 cycles / millisecs > ratio + ratio / 5 )
525 mbedtls_printf( "passed\n" );
530 mbedtls_printf( "\n" );
535 #endif /* MBEDTLS_SELF_TEST */
537 #endif /* MBEDTLS_TIMING_C */