timing.c 11.7 KB
Newer Older
1 2 3
/*
 *  Portable interface to the CPU cycle counter
 *
4
 *  Copyright (C) 2006-2014, Brainspark B.V.
Paul Bakker's avatar
Paul Bakker committed
5 6
 *
 *  This file is part of PolarSSL (http://www.polarssl.org)
7
 *  Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
Paul Bakker's avatar
Paul Bakker committed
8
 *
9
 *  All rights reserved.
Paul Bakker's avatar
Paul Bakker committed
10
 *
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *  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.
 */

26
#if !defined(POLARSSL_CONFIG_FILE)
27
#include "polarssl/config.h"
28 29 30
#else
#include POLARSSL_CONFIG_FILE
#endif
31

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

39
#if defined(POLARSSL_TIMING_C) && !defined(POLARSSL_TIMING_ALT)
40

41
#include "polarssl/timing.h"
42

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

#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;
};

66
#endif /* _WIN32 && !EFIX64 && !EFI32 */
67

68
#if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(POLARSSL_HAVE_ASM) &&  \
69
    ( defined(_MSC_VER) && defined(_M_IX86) ) || defined(__WATCOMC__)
70

71 72
#define POLARSSL_HAVE_HARDCLOCK

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

83 84 85 86
#if !defined(POLARSSL_HAVE_HARDCLOCK) && defined(POLARSSL_HAVE_ASM) &&  \
    defined(__GNUC__) && defined(__i386__)

#define POLARSSL_HAVE_HARDCLOCK
87 88 89

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

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

#define POLARSSL_HAVE_HARDCLOCK
101 102 103 104

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

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

#define POLARSSL_HAVE_HARDCLOCK
115 116 117 118 119 120 121

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

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

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

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

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

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

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

#define POLARSSL_HAVE_HARDCLOCK
155 156 157 158

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

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

#define POLARSSL_HAVE_HARDCLOCK
170 171 172 173

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

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

#define POLARSSL_HAVE_HARDCLOCK
184 185 186 187

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

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

#define POLARSSL_HAVE_HARDCLOCK
198 199 200 201

unsigned long hardclock( void )
{
    LARGE_INTEGER offset;
202

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

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

209 210 211
#if !defined(POLARSSL_HAVE_HARDCLOCK)

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

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 ) );
}
230
#endif /* !POLARSSL_HAVE_HARDCLOCK */
231

232
volatile int alarmed = 0;
233

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

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
256
{
257
    Sleep( (DWORD) uElapse );
Manuel Pégourié-Gonnard's avatar
Manuel Pégourié-Gonnard committed
258
    alarmed = 1;
259 260 261 262
    return( TRUE );
}

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

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

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

276
#else /* _WIN32 && !EFIX64 && !EFI32 */
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297

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 );

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

    if( reset )
    {
        t->start.tv_sec  = offset.tv_sec;
        t->start.tv_usec = offset.tv_usec;
    }

    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 335 336 337 338
/* To test net_usleep against our functions */
#if defined(POLARSSL_NET_C)
#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( 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 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
        {
            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 );

        set_alarm( secs );
        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 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
#if defined(POLARSSL_NET_C)
    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 */