timing.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /*
  2. * Portable interface to the CPU cycle counter
  3. *
  4. * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  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
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  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.
  18. *
  19. * This file is part of mbed TLS (https://tls.mbed.org)
  20. */
  21. #if !defined(MBEDTLS_CONFIG_FILE)
  22. #include "mbedtls/config.h"
  23. #else
  24. #include MBEDTLS_CONFIG_FILE
  25. #endif
  26. #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_PLATFORM_C)
  27. #include "mbedtls/platform.h"
  28. #else
  29. #include <stdio.h>
  30. #define mbedtls_printf printf
  31. #endif
  32. #if defined(MBEDTLS_TIMING_C)
  33. #include "mbedtls/timing.h"
  34. #if !defined(MBEDTLS_TIMING_ALT)
  35. #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \
  36. !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \
  37. !defined(__HAIKU__)
  38. #error "This module only works on Unix and Windows, see MBEDTLS_TIMING_C in config.h"
  39. #endif
  40. #ifndef asm
  41. #define asm __asm
  42. #endif
  43. #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
  44. #include <windows.h>
  45. #include <winbase.h>
  46. #include <process.h>
  47. struct _hr_time
  48. {
  49. LARGE_INTEGER start;
  50. };
  51. #else
  52. #include <unistd.h>
  53. #include <sys/types.h>
  54. #include <sys/time.h>
  55. #include <signal.h>
  56. #include <time.h>
  57. struct _hr_time
  58. {
  59. struct timeval start;
  60. };
  61. #endif /* _WIN32 && !EFIX64 && !EFI32 */
  62. #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
  63. ( defined(_MSC_VER) && defined(_M_IX86) ) || defined(__WATCOMC__)
  64. #define HAVE_HARDCLOCK
  65. unsigned long mbedtls_timing_hardclock( void )
  66. {
  67. unsigned long tsc;
  68. __asm rdtsc
  69. __asm mov [tsc], eax
  70. return( tsc );
  71. }
  72. #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
  73. ( _MSC_VER && _M_IX86 ) || __WATCOMC__ */
  74. /* some versions of mingw-64 have 32-bit longs even on x84_64 */
  75. #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
  76. defined(__GNUC__) && ( defined(__i386__) || ( \
  77. ( defined(__amd64__) || defined( __x86_64__) ) && __SIZEOF_LONG__ == 4 ) )
  78. #define HAVE_HARDCLOCK
  79. unsigned long mbedtls_timing_hardclock( void )
  80. {
  81. unsigned long lo, hi;
  82. asm volatile( "rdtsc" : "=a" (lo), "=d" (hi) );
  83. return( lo );
  84. }
  85. #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
  86. __GNUC__ && __i386__ */
  87. #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
  88. defined(__GNUC__) && ( defined(__amd64__) || defined(__x86_64__) )
  89. #define HAVE_HARDCLOCK
  90. unsigned long mbedtls_timing_hardclock( void )
  91. {
  92. unsigned long lo, hi;
  93. asm volatile( "rdtsc" : "=a" (lo), "=d" (hi) );
  94. return( lo | ( hi << 32 ) );
  95. }
  96. #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
  97. __GNUC__ && ( __amd64__ || __x86_64__ ) */
  98. #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
  99. defined(__GNUC__) && ( defined(__powerpc__) || defined(__ppc__) )
  100. #define HAVE_HARDCLOCK
  101. unsigned long mbedtls_timing_hardclock( void )
  102. {
  103. unsigned long tbl, tbu0, tbu1;
  104. do
  105. {
  106. asm volatile( "mftbu %0" : "=r" (tbu0) );
  107. asm volatile( "mftb %0" : "=r" (tbl ) );
  108. asm volatile( "mftbu %0" : "=r" (tbu1) );
  109. }
  110. while( tbu0 != tbu1 );
  111. return( tbl );
  112. }
  113. #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
  114. __GNUC__ && ( __powerpc__ || __ppc__ ) */
  115. #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
  116. defined(__GNUC__) && defined(__sparc64__)
  117. #if defined(__OpenBSD__)
  118. #warning OpenBSD does not allow access to tick register using software version instead
  119. #else
  120. #define HAVE_HARDCLOCK
  121. unsigned long mbedtls_timing_hardclock( void )
  122. {
  123. unsigned long tick;
  124. asm volatile( "rdpr %%tick, %0;" : "=&r" (tick) );
  125. return( tick );
  126. }
  127. #endif /* __OpenBSD__ */
  128. #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
  129. __GNUC__ && __sparc64__ */
  130. #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
  131. defined(__GNUC__) && defined(__sparc__) && !defined(__sparc64__)
  132. #define HAVE_HARDCLOCK
  133. unsigned long mbedtls_timing_hardclock( void )
  134. {
  135. unsigned long tick;
  136. asm volatile( ".byte 0x83, 0x41, 0x00, 0x00" );
  137. asm volatile( "mov %%g1, %0" : "=r" (tick) );
  138. return( tick );
  139. }
  140. #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
  141. __GNUC__ && __sparc__ && !__sparc64__ */
  142. #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
  143. defined(__GNUC__) && defined(__alpha__)
  144. #define HAVE_HARDCLOCK
  145. unsigned long mbedtls_timing_hardclock( void )
  146. {
  147. unsigned long cc;
  148. asm volatile( "rpcc %0" : "=r" (cc) );
  149. return( cc & 0xFFFFFFFF );
  150. }
  151. #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
  152. __GNUC__ && __alpha__ */
  153. #if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
  154. defined(__GNUC__) && defined(__ia64__)
  155. #define HAVE_HARDCLOCK
  156. unsigned long mbedtls_timing_hardclock( void )
  157. {
  158. unsigned long itc;
  159. asm volatile( "mov %0 = ar.itc" : "=r" (itc) );
  160. return( itc );
  161. }
  162. #endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
  163. __GNUC__ && __ia64__ */
  164. #if !defined(HAVE_HARDCLOCK) && defined(_MSC_VER) && \
  165. !defined(EFIX64) && !defined(EFI32)
  166. #define HAVE_HARDCLOCK
  167. unsigned long mbedtls_timing_hardclock( void )
  168. {
  169. LARGE_INTEGER offset;
  170. QueryPerformanceCounter( &offset );
  171. return( (unsigned long)( offset.QuadPart ) );
  172. }
  173. #endif /* !HAVE_HARDCLOCK && _MSC_VER && !EFIX64 && !EFI32 */
  174. #if !defined(HAVE_HARDCLOCK)
  175. #define HAVE_HARDCLOCK
  176. static int hardclock_init = 0;
  177. static struct timeval tv_init;
  178. unsigned long mbedtls_timing_hardclock( void )
  179. {
  180. struct timeval tv_cur;
  181. if( hardclock_init == 0 )
  182. {
  183. gettimeofday( &tv_init, NULL );
  184. hardclock_init = 1;
  185. }
  186. gettimeofday( &tv_cur, NULL );
  187. return( ( tv_cur.tv_sec - tv_init.tv_sec ) * 1000000
  188. + ( tv_cur.tv_usec - tv_init.tv_usec ) );
  189. }
  190. #endif /* !HAVE_HARDCLOCK */
  191. volatile int mbedtls_timing_alarmed = 0;
  192. #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
  193. unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )
  194. {
  195. struct _hr_time *t = (struct _hr_time *) val;
  196. if( reset )
  197. {
  198. QueryPerformanceCounter( &t->start );
  199. return( 0 );
  200. }
  201. else
  202. {
  203. unsigned long delta;
  204. LARGE_INTEGER now, hfreq;
  205. QueryPerformanceCounter( &now );
  206. QueryPerformanceFrequency( &hfreq );
  207. delta = (unsigned long)( ( now.QuadPart - t->start.QuadPart ) * 1000ul
  208. / hfreq.QuadPart );
  209. return( delta );
  210. }
  211. }
  212. /* It's OK to use a global because alarm() is supposed to be global anyway */
  213. static DWORD alarmMs;
  214. static void TimerProc( void *TimerContext )
  215. {
  216. (void) TimerContext;
  217. Sleep( alarmMs );
  218. mbedtls_timing_alarmed = 1;
  219. /* _endthread will be called implicitly on return
  220. * That ensures execution of thread funcition's epilogue */
  221. }
  222. void mbedtls_set_alarm( int seconds )
  223. {
  224. if( seconds == 0 )
  225. {
  226. /* No need to create a thread for this simple case.
  227. * Also, this shorcut is more reliable at least on MinGW32 */
  228. mbedtls_timing_alarmed = 1;
  229. return;
  230. }
  231. mbedtls_timing_alarmed = 0;
  232. alarmMs = seconds * 1000;
  233. (void) _beginthread( TimerProc, 0, NULL );
  234. }
  235. #else /* _WIN32 && !EFIX64 && !EFI32 */
  236. unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )
  237. {
  238. struct _hr_time *t = (struct _hr_time *) val;
  239. if( reset )
  240. {
  241. gettimeofday( &t->start, NULL );
  242. return( 0 );
  243. }
  244. else
  245. {
  246. unsigned long delta;
  247. struct timeval now;
  248. gettimeofday( &now, NULL );
  249. delta = ( now.tv_sec - t->start.tv_sec ) * 1000ul
  250. + ( now.tv_usec - t->start.tv_usec ) / 1000;
  251. return( delta );
  252. }
  253. }
  254. static void sighandler( int signum )
  255. {
  256. mbedtls_timing_alarmed = 1;
  257. signal( signum, sighandler );
  258. }
  259. void mbedtls_set_alarm( int seconds )
  260. {
  261. mbedtls_timing_alarmed = 0;
  262. signal( SIGALRM, sighandler );
  263. alarm( seconds );
  264. if( seconds == 0 )
  265. {
  266. /* alarm(0) cancelled any previous pending alarm, but the
  267. handler won't fire, so raise the flag straight away. */
  268. mbedtls_timing_alarmed = 1;
  269. }
  270. }
  271. #endif /* _WIN32 && !EFIX64 && !EFI32 */
  272. /*
  273. * Set delays to watch
  274. */
  275. void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms )
  276. {
  277. mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;
  278. ctx->int_ms = int_ms;
  279. ctx->fin_ms = fin_ms;
  280. if( fin_ms != 0 )
  281. (void) mbedtls_timing_get_timer( &ctx->timer, 1 );
  282. }
  283. /*
  284. * Get number of delays expired
  285. */
  286. int mbedtls_timing_get_delay( void *data )
  287. {
  288. mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;
  289. unsigned long elapsed_ms;
  290. if( ctx->fin_ms == 0 )
  291. return( -1 );
  292. elapsed_ms = mbedtls_timing_get_timer( &ctx->timer, 0 );
  293. if( elapsed_ms >= ctx->fin_ms )
  294. return( 2 );
  295. if( elapsed_ms >= ctx->int_ms )
  296. return( 1 );
  297. return( 0 );
  298. }
  299. #endif /* !MBEDTLS_TIMING_ALT */
  300. #if defined(MBEDTLS_SELF_TEST)
  301. /*
  302. * Busy-waits for the given number of milliseconds.
  303. * Used for testing mbedtls_timing_hardclock.
  304. */
  305. static void busy_msleep( unsigned long msec )
  306. {
  307. struct mbedtls_timing_hr_time hires;
  308. unsigned long i = 0; /* for busy-waiting */
  309. volatile unsigned long j; /* to prevent optimisation */
  310. (void) mbedtls_timing_get_timer( &hires, 1 );
  311. while( mbedtls_timing_get_timer( &hires, 0 ) < msec )
  312. i++;
  313. j = i;
  314. (void) j;
  315. }
  316. #define FAIL do \
  317. { \
  318. if( verbose != 0 ) \
  319. { \
  320. mbedtls_printf( "failed at line %d\n", __LINE__ ); \
  321. mbedtls_printf( " cycles=%lu ratio=%lu millisecs=%lu secs=%lu hardfail=%d a=%lu b=%lu\n", \
  322. cycles, ratio, millisecs, secs, hardfail, \
  323. (unsigned long) a, (unsigned long) b ); \
  324. mbedtls_printf( " elapsed(hires)=%lu elapsed(ctx)=%lu status(ctx)=%d\n", \
  325. mbedtls_timing_get_timer( &hires, 0 ), \
  326. mbedtls_timing_get_timer( &ctx.timer, 0 ), \
  327. mbedtls_timing_get_delay( &ctx ) ); \
  328. } \
  329. return( 1 ); \
  330. } while( 0 )
  331. /*
  332. * Checkup routine
  333. *
  334. * Warning: this is work in progress, some tests may not be reliable enough
  335. * yet! False positives may happen.
  336. */
  337. int mbedtls_timing_self_test( int verbose )
  338. {
  339. unsigned long cycles = 0, ratio = 0;
  340. unsigned long millisecs = 0, secs = 0;
  341. int hardfail = 0;
  342. struct mbedtls_timing_hr_time hires;
  343. uint32_t a = 0, b = 0;
  344. mbedtls_timing_delay_context ctx;
  345. if( verbose != 0 )
  346. mbedtls_printf( " TIMING tests note: will take some time!\n" );
  347. if( verbose != 0 )
  348. mbedtls_printf( " TIMING test #1 (set_alarm / get_timer): " );
  349. {
  350. secs = 1;
  351. (void) mbedtls_timing_get_timer( &hires, 1 );
  352. mbedtls_set_alarm( (int) secs );
  353. while( !mbedtls_timing_alarmed )
  354. ;
  355. millisecs = mbedtls_timing_get_timer( &hires, 0 );
  356. /* For some reason on Windows it looks like alarm has an extra delay
  357. * (maybe related to creating a new thread). Allow some room here. */
  358. if( millisecs < 800 * secs || millisecs > 1200 * secs + 300 )
  359. FAIL;
  360. }
  361. if( verbose != 0 )
  362. mbedtls_printf( "passed\n" );
  363. if( verbose != 0 )
  364. mbedtls_printf( " TIMING test #2 (set/get_delay ): " );
  365. {
  366. a = 800;
  367. b = 400;
  368. mbedtls_timing_set_delay( &ctx, a, a + b ); /* T = 0 */
  369. busy_msleep( a - a / 4 ); /* T = a - a/4 */
  370. if( mbedtls_timing_get_delay( &ctx ) != 0 )
  371. FAIL;
  372. busy_msleep( a / 4 + b / 4 ); /* T = a + b/4 */
  373. if( mbedtls_timing_get_delay( &ctx ) != 1 )
  374. FAIL;
  375. busy_msleep( b ); /* T = a + b + b/4 */
  376. if( mbedtls_timing_get_delay( &ctx ) != 2 )
  377. FAIL;
  378. }
  379. mbedtls_timing_set_delay( &ctx, 0, 0 );
  380. busy_msleep( 200 );
  381. if( mbedtls_timing_get_delay( &ctx ) != -1 )
  382. FAIL;
  383. if( verbose != 0 )
  384. mbedtls_printf( "passed\n" );
  385. if( verbose != 0 )
  386. mbedtls_printf( " TIMING test #3 (hardclock / get_timer): " );
  387. /*
  388. * Allow one failure for possible counter wrapping.
  389. * On a 4Ghz 32-bit machine the cycle counter wraps about once per second;
  390. * since the whole test is about 10ms, it shouldn't happen twice in a row.
  391. */
  392. hard_test:
  393. if( hardfail > 1 )
  394. {
  395. if( verbose != 0 )
  396. mbedtls_printf( "failed (ignored)\n" );
  397. goto hard_test_done;
  398. }
  399. /* Get a reference ratio cycles/ms */
  400. millisecs = 1;
  401. cycles = mbedtls_timing_hardclock();
  402. busy_msleep( millisecs );
  403. cycles = mbedtls_timing_hardclock() - cycles;
  404. ratio = cycles / millisecs;
  405. /* Check that the ratio is mostly constant */
  406. for( millisecs = 2; millisecs <= 4; millisecs++ )
  407. {
  408. cycles = mbedtls_timing_hardclock();
  409. busy_msleep( millisecs );
  410. cycles = mbedtls_timing_hardclock() - cycles;
  411. /* Allow variation up to 20% */
  412. if( cycles / millisecs < ratio - ratio / 5 ||
  413. cycles / millisecs > ratio + ratio / 5 )
  414. {
  415. hardfail++;
  416. goto hard_test;
  417. }
  418. }
  419. if( verbose != 0 )
  420. mbedtls_printf( "passed\n" );
  421. hard_test_done:
  422. if( verbose != 0 )
  423. mbedtls_printf( "\n" );
  424. return( 0 );
  425. }
  426. #endif /* MBEDTLS_SELF_TEST */
  427. #endif /* MBEDTLS_TIMING_C */