timing.c 14 KB

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