timing.c 11.9 KB
Newer Older
1 2 3
/*
 *  Portable interface to the CPU cycle counter
 *
Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
4
 *  Copyright (C) 2006-2014, ARM Limited, All Rights Reserved
Paul Bakker's avatar
Paul Bakker committed
5
 *
Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
6
 *  This file is part of mbed TLS (https://polarssl.org)
Paul Bakker's avatar
Paul Bakker committed
7
 *
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

23
#if !defined(POLARSSL_CONFIG_FILE)
24
#include "polarssl/config.h"
25 26 27
#else
#include POLARSSL_CONFIG_FILE
#endif
28

29 30 31 32 33 34 35
#if defined(POLARSSL_SELF_TEST) && defined(POLARSSL_PLATFORM_C)
#include "polarssl/platform.h"
#else
#include <stdio.h>
#define polarssl_printf     printf
#endif

36
#if defined(POLARSSL_TIMING_C) && !defined(POLARSSL_TIMING_ALT)
37

38
#include "polarssl/timing.h"
39

40
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

#include <windows.h>
#include <winbase.h>

struct _hr_time
{
    LARGE_INTEGER start;
};

#else

#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <time.h>

struct _hr_time
{
    struct timeval start;
};

63
#endif /* _WIN32 && !EFIX64 && !EFI32 */
64

65
#if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(POLARSSL_HAVE_ASM) &&  \
66
    ( defined(_MSC_VER) && defined(_M_IX86) ) || defined(__WATCOMC__)
67

68 69
#define POLARSSL_HAVE_HARDCLOCK

70 71 72 73 74 75 76
unsigned long hardclock( void )
{
    unsigned long tsc;
    __asm   rdtsc
    __asm   mov  [tsc], eax
    return( tsc );
}
77 78
#endif /* !POLARSSL_HAVE_HARDCLOCK && POLARSSL_HAVE_ASM &&
          ( _MSC_VER && _M_IX86 ) || __WATCOMC__ */
79

80
/* some versions of mingw-64 have 32-bit longs even on x84_64 */
81
#if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(POLARSSL_HAVE_ASM) &&  \
82 83
    defined(__GNUC__) && ( defined(__i386__) || (                       \
    ( defined(__amd64__) || defined( __x86_64__) ) && __SIZEOF_LONG__ == 4 ) )
84 85

#define POLARSSL_HAVE_HARDCLOCK
86 87 88

unsigned long hardclock( void )
{
89
    unsigned long lo, hi;
90
    asm volatile( "rdtsc" : "=a" (lo), "=d" (hi) );
91
    return( lo );
92
}
93 94
#endif /* !POLARSSL_HAVE_HARDCLOCK && POLARSSL_HAVE_ASM &&
          __GNUC__ && __i386__ */
95

96
#if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(POLARSSL_HAVE_ASM) &&  \
97
    defined(__GNUC__) && ( defined(__amd64__) || defined(__x86_64__) )
98 99

#define POLARSSL_HAVE_HARDCLOCK
100 101 102 103

unsigned long hardclock( void )
{
    unsigned long lo, hi;
104
    asm volatile( "rdtsc" : "=a" (lo), "=d" (hi) );
105
    return( lo | ( hi << 32 ) );
106
}
107 108
#endif /* !POLARSSL_HAVE_HARDCLOCK && POLARSSL_HAVE_ASM &&
          __GNUC__ && ( __amd64__ || __x86_64__ ) */
109

110
#if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(POLARSSL_HAVE_ASM) &&  \
111
    defined(__GNUC__) && ( defined(__powerpc__) || defined(__ppc__) )
112 113

#define POLARSSL_HAVE_HARDCLOCK
114 115 116 117 118 119 120

unsigned long hardclock( void )
{
    unsigned long tbl, tbu0, tbu1;

    do
    {
121 122 123
        asm volatile( "mftbu %0" : "=r" (tbu0) );
        asm volatile( "mftb  %0" : "=r" (tbl ) );
        asm volatile( "mftbu %0" : "=r" (tbu1) );
124 125 126 127 128
    }
    while( tbu0 != tbu1 );

    return( tbl );
}
129 130
#endif /* !POLARSSL_HAVE_HARDCLOCK && POLARSSL_HAVE_ASM &&
          __GNUC__ && ( __powerpc__ || __ppc__ ) */
131 132 133

#if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(POLARSSL_HAVE_ASM) &&  \
    defined(__GNUC__) && defined(__sparc64__)
134

135 136
#if defined(__OpenBSD__)
#warning OpenBSD does not allow access to tick register using software version instead
137
#else
138 139 140 141 142
#define POLARSSL_HAVE_HARDCLOCK

unsigned long hardclock( void )
{
    unsigned long tick;
143
    asm volatile( "rdpr %%tick, %0;" : "=&r" (tick) );
144 145
    return( tick );
}
146 147 148
#endif /* __OpenBSD__ */
#endif /* !POLARSSL_HAVE_HARDCLOCK && POLARSSL_HAVE_ASM &&
          __GNUC__ && __sparc64__ */
149 150 151 152 153

#if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(POLARSSL_HAVE_ASM) &&  \
    defined(__GNUC__) && defined(__sparc__) && !defined(__sparc64__)

#define POLARSSL_HAVE_HARDCLOCK
154 155 156 157

unsigned long hardclock( void )
{
    unsigned long tick;
158 159
    asm volatile( ".byte 0x83, 0x41, 0x00, 0x00" );
    asm volatile( "mov   %%g1, %0" : "=r" (tick) );
160 161
    return( tick );
}
162 163
#endif /* !POLARSSL_HAVE_HARDCLOCK && POLARSSL_HAVE_ASM &&
          __GNUC__ && __sparc__ && !__sparc64__ */
164

165 166 167 168
#if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(POLARSSL_HAVE_ASM) &&      \
    defined(__GNUC__) && defined(__alpha__)

#define POLARSSL_HAVE_HARDCLOCK
169 170 171 172

unsigned long hardclock( void )
{
    unsigned long cc;
173
    asm volatile( "rpcc %0" : "=r" (cc) );
174 175
    return( cc & 0xFFFFFFFF );
}
176 177
#endif /* !POLARSSL_HAVE_HARDCLOCK && POLARSSL_HAVE_ASM &&
          __GNUC__ && __alpha__ */
178

179 180 181 182
#if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(POLARSSL_HAVE_ASM) &&      \
    defined(__GNUC__) && defined(__ia64__)

#define POLARSSL_HAVE_HARDCLOCK
183 184 185 186

unsigned long hardclock( void )
{
    unsigned long itc;
187
    asm volatile( "mov %0 = ar.itc" : "=r" (itc) );
188 189
    return( itc );
}
190 191
#endif /* !POLARSSL_HAVE_HARDCLOCK && POLARSSL_HAVE_ASM &&
          __GNUC__ && __ia64__ */
192

193 194
#if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(_MSC_VER) && \
    !defined(EFIX64) && !defined(EFI32)
195 196

#define POLARSSL_HAVE_HARDCLOCK
197 198 199 200

unsigned long hardclock( void )
{
    LARGE_INTEGER offset;
201

Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
202
    QueryPerformanceCounter( &offset );
203

204
    return( (unsigned long)( offset.QuadPart ) );
205
}
206
#endif /* !POLARSSL_HAVE_HARDCLOCK && _MSC_VER && !EFIX64 && !EFI32 */
207

208 209 210
#if !defined(POLARSSL_HAVE_HARDCLOCK)

#define POLARSSL_HAVE_HARDCLOCK
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

static int hardclock_init = 0;
static struct timeval tv_init;

unsigned long hardclock( void )
{
    struct timeval tv_cur;

    if( hardclock_init == 0 )
    {
        gettimeofday( &tv_init, NULL );
        hardclock_init = 1;
    }

    gettimeofday( &tv_cur, NULL );
    return( ( tv_cur.tv_sec  - tv_init.tv_sec  ) * 1000000
          + ( tv_cur.tv_usec - tv_init.tv_usec ) );
}
229
#endif /* !POLARSSL_HAVE_HARDCLOCK */
230

231
volatile int alarmed = 0;
232

233
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

unsigned long get_timer( struct hr_time *val, int reset )
{
    unsigned long delta;
    LARGE_INTEGER offset, hfreq;
    struct _hr_time *t = (struct _hr_time *) val;

    QueryPerformanceCounter(  &offset );
    QueryPerformanceFrequency( &hfreq );

    delta = (unsigned long)( ( 1000 *
        ( offset.QuadPart - t->start.QuadPart ) ) /
           hfreq.QuadPart );

    if( reset )
        QueryPerformanceCounter( &t->start );

    return( delta );
}

DWORD WINAPI TimerProc( LPVOID uElapse )
Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
255
{
256
    Sleep( (DWORD) uElapse );
Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
257
    alarmed = 1;
258 259 260 261
    return( TRUE );
}

void set_alarm( int seconds )
Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
262
{
263 264
    DWORD ThreadId;

Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
265
    alarmed = 0;
266 267 268 269 270 271 272 273 274
    CloseHandle( CreateThread( NULL, 0, TimerProc,
        (LPVOID) ( seconds * 1000 ), 0, &ThreadId ) );
}

void m_sleep( int milliseconds )
{
    Sleep( milliseconds );
}

275
#else /* _WIN32 && !EFIX64 && !EFI32 */
276 277 278 279 280 281 282 283 284 285 286 287 288

unsigned long get_timer( struct hr_time *val, int reset )
{
    unsigned long delta;
    struct timeval offset;
    struct _hr_time *t = (struct _hr_time *) val;

    gettimeofday( &offset, NULL );

    if( reset )
    {
        t->start.tv_sec  = offset.tv_sec;
        t->start.tv_usec = offset.tv_usec;
289
        return( 0 );
290 291
    }

292 293 294
    delta = ( offset.tv_sec  - t->start.tv_sec  ) * 1000
          + ( offset.tv_usec - t->start.tv_usec ) / 1000;

295 296 297
    return( delta );
}

Paul Bakker's avatar
Paul Bakker committed
298 299 300 301 302 303
#if defined(INTEGRITY)
void m_sleep( int milliseconds )
{
    usleep( milliseconds * 1000 );
}

304
#else /* INTEGRITY */
Paul Bakker's avatar
Paul Bakker committed
305

306
static void sighandler( int signum )
Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
307
{
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    alarmed = 1;
    signal( signum, sighandler );
}

void set_alarm( int seconds )
{
    alarmed = 0;
    signal( SIGALRM, sighandler );
    alarm( seconds );
}

void m_sleep( int milliseconds )
{
    struct timeval tv;

    tv.tv_sec  = milliseconds / 1000;
324
    tv.tv_usec = ( milliseconds % 1000 ) * 1000;
325 326 327

    select( 0, NULL, NULL, NULL, &tv );
}
Paul Bakker's avatar
Paul Bakker committed
328
#endif /* INTEGRITY */
329

330
#endif /* _WIN32 && !EFIX64 && !EFI32 */
331

332 333
#if defined(POLARSSL_SELF_TEST)

334
/* To test net_usleep against our functions */
335
#if defined(POLARSSL_NET_C) && defined(POLARSSL_HAVE_TIME)
336 337 338
#include "polarssl/net.h"
#endif

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
/*
 * Busy-waits for the given number of milliseconds.
 * Used for testing hardclock.
 */
static void busy_msleep( unsigned long msec )
{
    struct hr_time hires;
    unsigned long i = 0; /* for busy-waiting */
    volatile unsigned long j; /* to prevent optimisation */

    (void) get_timer( &hires, 1 );

    while( get_timer( &hires, 0 ) < msec )
        i++;

    j = i;
    (void) j;
}

358 359
/*
 * Checkup routine
360 361 362
 *
 * Warning: this is work in progress, some tests may not be reliable enough
 * yet! False positives may happen.
363 364 365 366 367 368 369 370
 */
int timing_self_test( int verbose )
{
    unsigned long cycles, ratio;
    unsigned long millisecs, secs;
    int hardfail;
    struct hr_time hires;

371
    if( verbose != 0 )
372
        polarssl_printf( "  TIMING tests note: will take some time!\n" );
373 374 375 376 377 378 379 380

    if( verbose != 0 )
        polarssl_printf( "  TIMING test #1 (m_sleep   / get_timer): " );

    for( secs = 1; secs <= 3; secs++ )
    {
        (void) get_timer( &hires, 1 );

381
        m_sleep( (int)( 500 * secs ) );
382 383 384

        millisecs = get_timer( &hires, 0 );

385
        if( millisecs < 450 * secs || millisecs > 550 * secs )
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
        {
            if( verbose != 0 )
                polarssl_printf( "failed\n" );

            return( 1 );
        }
    }

    if( verbose != 0 )
        polarssl_printf( "passed\n" );

    if( verbose != 0 )
        polarssl_printf( "  TIMING test #2 (set_alarm / get_timer): " );

    for( secs = 1; secs <= 3; secs++ )
    {
        (void) get_timer( &hires, 1 );

404
        set_alarm( (int) secs );
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
        while( !alarmed )
            ;

        millisecs = get_timer( &hires, 0 );

        if( millisecs < 900 * secs || millisecs > 1100 * secs )
        {
            if( verbose != 0 )
                polarssl_printf( "failed\n" );

            return( 1 );
        }
    }

    if( verbose != 0 )
        polarssl_printf( "passed\n" );

    if( verbose != 0 )
423
        polarssl_printf( "  TIMING test #3 (hardclock / get_timer): " );
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

    /*
     * Allow one failure for possible counter wrapping.
     * On a 4Ghz 32-bit machine the cycle counter wraps about once per second;
     * since the whole test is about 10ms, it shouldn't happen twice in a row.
     */
    hardfail = 0;

hard_test:
    if( hardfail > 1 )
    {
        if( verbose != 0 )
            polarssl_printf( "failed\n" );

        return( 1 );
    }

    /* Get a reference ratio cycles/ms */
442
    millisecs = 1;
443
    cycles = hardclock();
444
    busy_msleep( millisecs );
445
    cycles = hardclock() - cycles;
446
    ratio = cycles / millisecs;
447

448
    /* Check that the ratio is mostly constant */
449 450 451
    for( millisecs = 2; millisecs <= 4; millisecs++ )
    {
        cycles = hardclock();
452
        busy_msleep( millisecs );
453 454 455 456 457 458 459 460 461 462 463 464 465 466
        cycles = hardclock() - cycles;

        /* Allow variation up to 20% */
        if( cycles / millisecs < ratio - ratio / 5 ||
            cycles / millisecs > ratio + ratio / 5 )
        {
            hardfail++;
            goto hard_test;
        }
    }

    if( verbose != 0 )
        polarssl_printf( "passed\n" );

467
#if defined(POLARSSL_NET_C) && defined(POLARSSL_HAVE_TIME)
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    if( verbose != 0 )
        polarssl_printf( "  TIMING test #4 (net_usleep/ get_timer): " );

    for( secs = 1; secs <= 3; secs++ )
    {
        (void) get_timer( &hires, 1 );

        net_usleep( 500000 * secs );

        millisecs = get_timer( &hires, 0 );

        if( millisecs < 450 * secs || millisecs > 550 * secs )
        {
            if( verbose != 0 )
                polarssl_printf( "failed\n" );

            return( 1 );
        }
    }

    if( verbose != 0 )
        polarssl_printf( "passed\n" );
490
#endif /* POLARSSL_NET_C */
491

492 493 494
    if( verbose != 0 )
        polarssl_printf( "\n" );

495 496 497 498 499 500
    return( 0 );
}

#endif /* POLARSSL_SELF_TEST */

#endif /* POLARSSL_TIMING_C && !POLARSSL_TIMING_ALT */