timing.c 14 KB

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