timing.c 14 KB

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