compat_time.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file compat_time.c
  7. * \brief Portable wrappers for finding out the current time, running
  8. * timers, etc.
  9. **/
  10. #define COMPAT_TIME_PRIVATE
  11. #include "lib/time/compat_time.h"
  12. #include "lib/err/torerr.h"
  13. #include "lib/log/log.h"
  14. #include "lib/log/util_bug.h"
  15. #include "lib/intmath/muldiv.h"
  16. #include "lib/intmath/bits.h"
  17. #include "lib/fs/winlib.h"
  18. #include "lib/wallclock/timeval.h"
  19. #ifdef _WIN32
  20. #include <winsock2.h>
  21. #include <windows.h>
  22. #endif
  23. #ifdef HAVE_SYS_TYPES_H
  24. #include <sys/types.h>
  25. #endif
  26. #ifdef HAVE_SYS_TIME_H
  27. #include <sys/time.h>
  28. #endif
  29. #ifdef HAVE_UNISTD_H
  30. #include <unistd.h>
  31. #endif
  32. #ifdef TOR_UNIT_TESTS
  33. #if !defined(HAVE_USLEEP) && defined(HAVE_SYS_SELECT_H)
  34. /* as fallback implementation for tor_sleep_msec */
  35. #include <sys/select.h>
  36. #endif
  37. #endif /* defined(TOR_UNIT_TESTS) */
  38. #ifdef __APPLE__
  39. #include <mach/mach_time.h>
  40. #endif
  41. #include <errno.h>
  42. #include <stdlib.h>
  43. #include <string.h>
  44. #ifdef _WIN32
  45. #undef HAVE_CLOCK_GETTIME
  46. #endif
  47. #ifdef TOR_UNIT_TESTS
  48. /** Delay for <b>msec</b> milliseconds. Only used in tests. */
  49. void
  50. tor_sleep_msec(int msec)
  51. {
  52. #ifdef _WIN32
  53. Sleep(msec);
  54. #elif defined(HAVE_USLEEP)
  55. sleep(msec / 1000);
  56. /* Some usleep()s hate sleeping more than 1 sec */
  57. usleep((msec % 1000) * 1000);
  58. #elif defined(HAVE_SYS_SELECT_H)
  59. struct timeval tv = { msec / 1000, (msec % 1000) * 1000};
  60. select(0, NULL, NULL, NULL, &tv);
  61. #else
  62. sleep(CEIL_DIV(msec, 1000));
  63. #endif /* defined(_WIN32) || ... */
  64. }
  65. #endif /* defined(TOR_UNIT_TESTS) */
  66. #define ONE_MILLION ((int64_t) (1000 * 1000))
  67. #define ONE_BILLION ((int64_t) (1000 * 1000 * 1000))
  68. /** True iff monotime_init has been called. */
  69. static int monotime_initialized = 0;
  70. static monotime_t initialized_at;
  71. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  72. static monotime_coarse_t initialized_at_coarse;
  73. #endif
  74. #ifdef TOR_UNIT_TESTS
  75. /** True if we are running unit tests and overriding the current monotonic
  76. * time. Note that mocked monotonic time might not be monotonic.
  77. */
  78. static int monotime_mocking_enabled = 0;
  79. static monotime_t initialized_at_saved;
  80. static int64_t mock_time_nsec = 0;
  81. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  82. static int64_t mock_time_nsec_coarse = 0;
  83. static monotime_coarse_t initialized_at_coarse_saved;
  84. #endif
  85. void
  86. monotime_enable_test_mocking(void)
  87. {
  88. if (BUG(monotime_initialized == 0)) {
  89. monotime_init();
  90. }
  91. tor_assert_nonfatal(monotime_mocking_enabled == 0);
  92. monotime_mocking_enabled = 1;
  93. memcpy(&initialized_at_saved,
  94. &initialized_at, sizeof(monotime_t));
  95. memset(&initialized_at, 0, sizeof(monotime_t));
  96. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  97. memcpy(&initialized_at_coarse_saved,
  98. &initialized_at_coarse, sizeof(monotime_coarse_t));
  99. memset(&initialized_at_coarse, 0, sizeof(monotime_coarse_t));
  100. #endif
  101. }
  102. void
  103. monotime_disable_test_mocking(void)
  104. {
  105. tor_assert_nonfatal(monotime_mocking_enabled == 1);
  106. monotime_mocking_enabled = 0;
  107. memcpy(&initialized_at,
  108. &initialized_at_saved, sizeof(monotime_t));
  109. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  110. memcpy(&initialized_at_coarse,
  111. &initialized_at_coarse_saved, sizeof(monotime_coarse_t));
  112. #endif
  113. }
  114. void
  115. monotime_set_mock_time_nsec(int64_t nsec)
  116. {
  117. tor_assert_nonfatal(monotime_mocking_enabled == 1);
  118. mock_time_nsec = nsec;
  119. }
  120. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  121. void
  122. monotime_coarse_set_mock_time_nsec(int64_t nsec)
  123. {
  124. tor_assert_nonfatal(monotime_mocking_enabled == 1);
  125. mock_time_nsec_coarse = nsec;
  126. }
  127. #endif /* defined(MONOTIME_COARSE_FN_IS_DIFFERENT) */
  128. #endif /* defined(TOR_UNIT_TESTS) */
  129. /* "ratchet" functions for monotonic time. */
  130. #if defined(_WIN32) || defined(TOR_UNIT_TESTS)
  131. /** Protected by lock: last value returned by monotime_get(). */
  132. static int64_t last_pctr = 0;
  133. /** Protected by lock: offset we must add to monotonic time values. */
  134. static int64_t pctr_offset = 0;
  135. /* If we are using GetTickCount(), how many times has it rolled over? */
  136. static uint32_t rollover_count = 0;
  137. /* If we are using GetTickCount(), what's the last value it returned? */
  138. static int64_t last_tick_count = 0;
  139. /** Helper for windows: Called with a sequence of times that are supposed
  140. * to be monotonic; increments them as appropriate so that they actually
  141. * _are_ monotonic.
  142. *
  143. * The returned time may be the same as the previous returned time.
  144. *
  145. * Caller must hold lock. */
  146. STATIC int64_t
  147. ratchet_performance_counter(int64_t count_raw)
  148. {
  149. /* must hold lock */
  150. const int64_t count_adjusted = count_raw + pctr_offset;
  151. if (PREDICT_UNLIKELY(count_adjusted < last_pctr)) {
  152. /* Monotonicity failed! Pretend no time elapsed. */
  153. pctr_offset = last_pctr - count_raw;
  154. return last_pctr;
  155. } else {
  156. last_pctr = count_adjusted;
  157. return count_adjusted;
  158. }
  159. }
  160. STATIC int64_t
  161. ratchet_coarse_performance_counter(const int64_t count_raw)
  162. {
  163. int64_t count = count_raw + (((int64_t)rollover_count) << 32);
  164. while (PREDICT_UNLIKELY(count < last_tick_count)) {
  165. ++rollover_count;
  166. count = count_raw + (((int64_t)rollover_count) << 32);
  167. }
  168. last_tick_count = count;
  169. return count;
  170. }
  171. #endif /* defined(_WIN32) || defined(TOR_UNIT_TESTS) */
  172. #if defined(MONOTIME_USING_GETTIMEOFDAY) || defined(TOR_UNIT_TESTS)
  173. static struct timeval last_timeofday = { 0, 0 };
  174. static struct timeval timeofday_offset = { 0, 0 };
  175. /** Helper for gettimeofday(): Called with a sequence of times that are
  176. * supposed to be monotonic; increments them as appropriate so that they
  177. * actually _are_ monotonic.
  178. *
  179. * The returned time may be the same as the previous returned time.
  180. *
  181. * Caller must hold lock. */
  182. STATIC void
  183. ratchet_timeval(const struct timeval *timeval_raw, struct timeval *out)
  184. {
  185. /* must hold lock */
  186. timeradd(timeval_raw, &timeofday_offset, out);
  187. if (PREDICT_UNLIKELY(timercmp(out, &last_timeofday, OP_LT))) {
  188. /* time ran backwards. Instead, declare that no time occurred. */
  189. timersub(&last_timeofday, timeval_raw, &timeofday_offset);
  190. memcpy(out, &last_timeofday, sizeof(struct timeval));
  191. } else {
  192. memcpy(&last_timeofday, out, sizeof(struct timeval));
  193. }
  194. }
  195. #endif /* defined(MONOTIME_USING_GETTIMEOFDAY) || defined(TOR_UNIT_TESTS) */
  196. #ifdef TOR_UNIT_TESTS
  197. /** For testing: reset all the ratchets */
  198. void
  199. monotime_reset_ratchets_for_testing(void)
  200. {
  201. last_pctr = pctr_offset = last_tick_count = 0;
  202. rollover_count = 0;
  203. memset(&last_timeofday, 0, sizeof(struct timeval));
  204. memset(&timeofday_offset, 0, sizeof(struct timeval));
  205. }
  206. #endif /* defined(TOR_UNIT_TESTS) */
  207. #ifdef __APPLE__
  208. /** Initialized on startup: tells is how to convert from ticks to
  209. * nanoseconds.
  210. */
  211. static struct mach_timebase_info mach_time_info;
  212. static struct mach_timebase_info mach_time_info_msec_cvt;
  213. static int32_t mach_time_msec_cvt_threshold;
  214. static int monotime_shift = 0;
  215. static void
  216. monotime_init_internal(void)
  217. {
  218. tor_assert(!monotime_initialized);
  219. int r = mach_timebase_info(&mach_time_info);
  220. tor_assert(r == 0);
  221. tor_assert(mach_time_info.denom != 0);
  222. {
  223. // approximate only.
  224. uint64_t ns_per_tick = mach_time_info.numer / mach_time_info.denom;
  225. uint64_t ms_per_tick = ns_per_tick * ONE_MILLION;
  226. // requires that tor_log2(0) == 0.
  227. monotime_shift = tor_log2(ms_per_tick);
  228. }
  229. {
  230. // For converting ticks to milliseconds in a 32-bit-friendly way, we
  231. // will first right-shift by 20, and then multiply by 2048/1953, since
  232. // (1<<20) * 1953/2048 is about 1e6. We precompute a new numerator and
  233. // denominator here to avoid multiple multiplies.
  234. mach_time_info_msec_cvt.numer = mach_time_info.numer * 2048;
  235. mach_time_info_msec_cvt.denom = mach_time_info.denom * 1953;
  236. // For any value above this amount, we should divide before multiplying,
  237. // to avoid overflow. For a value below this, we should multiply
  238. // before dividing, to improve accuracy.
  239. mach_time_msec_cvt_threshold = INT32_MAX / mach_time_info_msec_cvt.numer;
  240. }
  241. }
  242. /**
  243. * Set "out" to the most recent monotonic time value.
  244. *
  245. * The returned time may be the same as the previous returned time.
  246. */
  247. void
  248. monotime_get(monotime_t *out)
  249. {
  250. #ifdef TOR_UNIT_TESTS
  251. if (monotime_mocking_enabled) {
  252. out->abstime_ = (mock_time_nsec * mach_time_info.denom)
  253. / mach_time_info.numer;
  254. return;
  255. }
  256. #endif /* defined(TOR_UNIT_TESTS) */
  257. out->abstime_ = mach_absolute_time();
  258. }
  259. #if defined(HAVE_MACH_APPROXIMATE_TIME)
  260. void
  261. monotime_coarse_get(monotime_coarse_t *out)
  262. {
  263. #ifdef TOR_UNIT_TESTS
  264. if (monotime_mocking_enabled) {
  265. out->abstime_ = (mock_time_nsec_coarse * mach_time_info.denom)
  266. / mach_time_info.numer;
  267. return;
  268. }
  269. #endif /* defined(TOR_UNIT_TESTS) */
  270. out->abstime_ = mach_approximate_time();
  271. }
  272. #endif /* defined(HAVE_MACH_APPROXIMATE_TIME) */
  273. /**
  274. * Return the number of nanoseconds between <b>start</b> and <b>end</b>.
  275. *
  276. * The returned value may be equal to zero.
  277. */
  278. int64_t
  279. monotime_diff_nsec(const monotime_t *start,
  280. const monotime_t *end)
  281. {
  282. if (BUG(mach_time_info.denom == 0)) {
  283. monotime_init();
  284. }
  285. const int64_t diff_ticks = end->abstime_ - start->abstime_;
  286. const int64_t diff_nsec =
  287. (diff_ticks * mach_time_info.numer) / mach_time_info.denom;
  288. return diff_nsec;
  289. }
  290. int32_t
  291. monotime_coarse_diff_msec32_(const monotime_coarse_t *start,
  292. const monotime_coarse_t *end)
  293. {
  294. if (BUG(mach_time_info.denom == 0)) {
  295. monotime_init();
  296. }
  297. const int64_t diff_ticks = end->abstime_ - start->abstime_;
  298. /* We already require in di_ops.c that right-shift performs a sign-extend. */
  299. const int32_t diff_microticks = (int32_t)(diff_ticks >> 20);
  300. if (diff_microticks >= mach_time_msec_cvt_threshold) {
  301. return (diff_microticks / mach_time_info_msec_cvt.denom) *
  302. mach_time_info_msec_cvt.numer;
  303. } else {
  304. return (diff_microticks * mach_time_info_msec_cvt.numer) /
  305. mach_time_info_msec_cvt.denom;
  306. }
  307. }
  308. uint32_t
  309. monotime_coarse_to_stamp(const monotime_coarse_t *t)
  310. {
  311. return (uint32_t)(t->abstime_ >> monotime_shift);
  312. }
  313. int
  314. monotime_is_zero(const monotime_t *val)
  315. {
  316. return val->abstime_ == 0;
  317. }
  318. void
  319. monotime_add_msec(monotime_t *out, const monotime_t *val, uint32_t msec)
  320. {
  321. const uint64_t nsec = msec * ONE_MILLION;
  322. const uint64_t ticks = (nsec * mach_time_info.denom) / mach_time_info.numer;
  323. out->abstime_ = val->abstime_ + ticks;
  324. }
  325. /* end of "__APPLE__" */
  326. #elif defined(HAVE_CLOCK_GETTIME)
  327. #ifdef CLOCK_MONOTONIC_COARSE
  328. /**
  329. * Which clock should we use for coarse-grained monotonic time? By default
  330. * this is CLOCK_MONOTONIC_COARSE, but it might not work -- for example,
  331. * if we're compiled with newer Linux headers and then we try to run on
  332. * an old Linux kernel. In that case, we will fall back to CLOCK_MONOTONIC.
  333. */
  334. static int clock_monotonic_coarse = CLOCK_MONOTONIC_COARSE;
  335. #endif /* defined(CLOCK_MONOTONIC_COARSE) */
  336. static void
  337. monotime_init_internal(void)
  338. {
  339. #ifdef CLOCK_MONOTONIC_COARSE
  340. struct timespec ts;
  341. if (clock_gettime(CLOCK_MONOTONIC_COARSE, &ts) < 0) {
  342. log_info(LD_GENERAL, "CLOCK_MONOTONIC_COARSE isn't working (%s); "
  343. "falling back to CLOCK_MONOTONIC.", strerror(errno));
  344. clock_monotonic_coarse = CLOCK_MONOTONIC;
  345. }
  346. #endif /* defined(CLOCK_MONOTONIC_COARSE) */
  347. }
  348. void
  349. monotime_get(monotime_t *out)
  350. {
  351. #ifdef TOR_UNIT_TESTS
  352. if (monotime_mocking_enabled) {
  353. out->ts_.tv_sec = (time_t) (mock_time_nsec / ONE_BILLION);
  354. out->ts_.tv_nsec = (int) (mock_time_nsec % ONE_BILLION);
  355. return;
  356. }
  357. #endif /* defined(TOR_UNIT_TESTS) */
  358. int r = clock_gettime(CLOCK_MONOTONIC, &out->ts_);
  359. tor_assert(r == 0);
  360. }
  361. #ifdef CLOCK_MONOTONIC_COARSE
  362. void
  363. monotime_coarse_get(monotime_coarse_t *out)
  364. {
  365. #ifdef TOR_UNIT_TESTS
  366. if (monotime_mocking_enabled) {
  367. out->ts_.tv_sec = (time_t) (mock_time_nsec_coarse / ONE_BILLION);
  368. out->ts_.tv_nsec = (int) (mock_time_nsec_coarse % ONE_BILLION);
  369. return;
  370. }
  371. #endif /* defined(TOR_UNIT_TESTS) */
  372. int r = clock_gettime(clock_monotonic_coarse, &out->ts_);
  373. if (PREDICT_UNLIKELY(r < 0) &&
  374. errno == EINVAL &&
  375. clock_monotonic_coarse == CLOCK_MONOTONIC_COARSE) {
  376. /* We should have caught this at startup in monotime_init_internal!
  377. */
  378. log_warn(LD_BUG, "Falling back to non-coarse monotonic time %s initial "
  379. "system start?", monotime_initialized?"after":"without");
  380. clock_monotonic_coarse = CLOCK_MONOTONIC;
  381. r = clock_gettime(clock_monotonic_coarse, &out->ts_);
  382. }
  383. tor_assert(r == 0);
  384. }
  385. #endif /* defined(CLOCK_MONOTONIC_COARSE) */
  386. int64_t
  387. monotime_diff_nsec(const monotime_t *start,
  388. const monotime_t *end)
  389. {
  390. const int64_t diff_sec = end->ts_.tv_sec - start->ts_.tv_sec;
  391. const int64_t diff_nsec = diff_sec * ONE_BILLION +
  392. (end->ts_.tv_nsec - start->ts_.tv_nsec);
  393. return diff_nsec;
  394. }
  395. int32_t
  396. monotime_coarse_diff_msec32_(const monotime_coarse_t *start,
  397. const monotime_coarse_t *end)
  398. {
  399. const int32_t diff_sec = (int32_t)(end->ts_.tv_sec - start->ts_.tv_sec);
  400. const int32_t diff_nsec = (int32_t)(end->ts_.tv_nsec - start->ts_.tv_nsec);
  401. return diff_sec * 1000 + diff_nsec / ONE_MILLION;
  402. }
  403. /* This value is ONE_BILLION >> 20. */
  404. static const uint32_t STAMP_TICKS_PER_SECOND = 953;
  405. uint32_t
  406. monotime_coarse_to_stamp(const monotime_coarse_t *t)
  407. {
  408. uint32_t nsec = (uint32_t)t->ts_.tv_nsec;
  409. uint32_t sec = (uint32_t)t->ts_.tv_sec;
  410. return (sec * STAMP_TICKS_PER_SECOND) + (nsec >> 20);
  411. }
  412. int
  413. monotime_is_zero(const monotime_t *val)
  414. {
  415. return val->ts_.tv_sec == 0 && val->ts_.tv_nsec == 0;
  416. }
  417. void
  418. monotime_add_msec(monotime_t *out, const monotime_t *val, uint32_t msec)
  419. {
  420. const uint32_t sec = msec / 1000;
  421. const uint32_t msec_remainder = msec % 1000;
  422. out->ts_.tv_sec = val->ts_.tv_sec + sec;
  423. out->ts_.tv_nsec = val->ts_.tv_nsec + (msec_remainder * ONE_MILLION);
  424. if (out->ts_.tv_nsec > ONE_BILLION) {
  425. out->ts_.tv_nsec -= ONE_BILLION;
  426. out->ts_.tv_sec += 1;
  427. }
  428. }
  429. /* end of "HAVE_CLOCK_GETTIME" */
  430. #elif defined (_WIN32)
  431. /** Result of QueryPerformanceFrequency, in terms needed to
  432. * convert ticks to nanoseconds. */
  433. static int64_t nsec_per_tick_numer = 1;
  434. static int64_t nsec_per_tick_denom = 1;
  435. /** Lock to protect last_pctr and pctr_offset */
  436. static CRITICAL_SECTION monotime_lock;
  437. /** Lock to protect rollover_count and last_tick_count */
  438. static CRITICAL_SECTION monotime_coarse_lock;
  439. typedef ULONGLONG (WINAPI *GetTickCount64_fn_t)(void);
  440. static GetTickCount64_fn_t GetTickCount64_fn = NULL;
  441. static void
  442. monotime_init_internal(void)
  443. {
  444. tor_assert(!monotime_initialized);
  445. BOOL ok = InitializeCriticalSectionAndSpinCount(&monotime_lock, 200);
  446. tor_assert(ok);
  447. ok = InitializeCriticalSectionAndSpinCount(&monotime_coarse_lock, 200);
  448. tor_assert(ok);
  449. LARGE_INTEGER li;
  450. ok = QueryPerformanceFrequency(&li);
  451. tor_assert(ok);
  452. tor_assert(li.QuadPart);
  453. uint64_t n = ONE_BILLION;
  454. uint64_t d = li.QuadPart;
  455. /* We need to simplify this or we'll probably overflow the int64. */
  456. simplify_fraction64(&n, &d);
  457. tor_assert(n <= INT64_MAX);
  458. tor_assert(d <= INT64_MAX);
  459. nsec_per_tick_numer = (int64_t) n;
  460. nsec_per_tick_denom = (int64_t) d;
  461. last_pctr = 0;
  462. pctr_offset = 0;
  463. HANDLE h = load_windows_system_library(TEXT("kernel32.dll"));
  464. if (h) {
  465. GetTickCount64_fn = (GetTickCount64_fn_t) (void(*)(void))
  466. GetProcAddress(h, "GetTickCount64");
  467. }
  468. // We can't call FreeLibrary(h) here, because freeing the handle may
  469. // unload the library, and cause future calls to GetTickCount64_fn()
  470. // to fail. See 29642 for details.
  471. }
  472. void
  473. monotime_get(monotime_t *out)
  474. {
  475. if (BUG(monotime_initialized == 0)) {
  476. monotime_init();
  477. }
  478. #ifdef TOR_UNIT_TESTS
  479. if (monotime_mocking_enabled) {
  480. out->pcount_ = (mock_time_nsec * nsec_per_tick_denom)
  481. / nsec_per_tick_numer;
  482. return;
  483. }
  484. #endif /* defined(TOR_UNIT_TESTS) */
  485. /* Alas, QueryPerformanceCounter is not always monotonic: see bug list at
  486. https://www.python.org/dev/peps/pep-0418/#windows-queryperformancecounter
  487. */
  488. EnterCriticalSection(&monotime_lock);
  489. LARGE_INTEGER res;
  490. BOOL ok = QueryPerformanceCounter(&res);
  491. tor_assert(ok);
  492. const int64_t count_raw = res.QuadPart;
  493. out->pcount_ = ratchet_performance_counter(count_raw);
  494. LeaveCriticalSection(&monotime_lock);
  495. }
  496. void
  497. monotime_coarse_get(monotime_coarse_t *out)
  498. {
  499. #ifdef TOR_UNIT_TESTS
  500. if (monotime_mocking_enabled) {
  501. out->tick_count_ = mock_time_nsec_coarse / ONE_MILLION;
  502. return;
  503. }
  504. #endif /* defined(TOR_UNIT_TESTS) */
  505. if (GetTickCount64_fn) {
  506. out->tick_count_ = (int64_t)GetTickCount64_fn();
  507. } else {
  508. EnterCriticalSection(&monotime_coarse_lock);
  509. DWORD tick = GetTickCount();
  510. out->tick_count_ = ratchet_coarse_performance_counter(tick);
  511. LeaveCriticalSection(&monotime_coarse_lock);
  512. }
  513. }
  514. int64_t
  515. monotime_diff_nsec(const monotime_t *start,
  516. const monotime_t *end)
  517. {
  518. if (BUG(monotime_initialized == 0)) {
  519. monotime_init();
  520. }
  521. const int64_t diff_ticks = end->pcount_ - start->pcount_;
  522. return (diff_ticks * nsec_per_tick_numer) / nsec_per_tick_denom;
  523. }
  524. int64_t
  525. monotime_coarse_diff_msec(const monotime_coarse_t *start,
  526. const monotime_coarse_t *end)
  527. {
  528. const int64_t diff_ticks = end->tick_count_ - start->tick_count_;
  529. return diff_ticks;
  530. }
  531. int32_t
  532. monotime_coarse_diff_msec32_(const monotime_coarse_t *start,
  533. const monotime_coarse_t *end)
  534. {
  535. return (int32_t)monotime_coarse_diff_msec(start, end);
  536. }
  537. int64_t
  538. monotime_coarse_diff_usec(const monotime_coarse_t *start,
  539. const monotime_coarse_t *end)
  540. {
  541. return monotime_coarse_diff_msec(start, end) * 1000;
  542. }
  543. int64_t
  544. monotime_coarse_diff_nsec(const monotime_coarse_t *start,
  545. const monotime_coarse_t *end)
  546. {
  547. return monotime_coarse_diff_msec(start, end) * ONE_MILLION;
  548. }
  549. static const uint32_t STAMP_TICKS_PER_SECOND = 1000;
  550. uint32_t
  551. monotime_coarse_to_stamp(const monotime_coarse_t *t)
  552. {
  553. return (uint32_t) t->tick_count_;
  554. }
  555. int
  556. monotime_is_zero(const monotime_t *val)
  557. {
  558. return val->pcount_ == 0;
  559. }
  560. int
  561. monotime_coarse_is_zero(const monotime_coarse_t *val)
  562. {
  563. return val->tick_count_ == 0;
  564. }
  565. void
  566. monotime_add_msec(monotime_t *out, const monotime_t *val, uint32_t msec)
  567. {
  568. const uint64_t nsec = msec * ONE_MILLION;
  569. const uint64_t ticks = (nsec * nsec_per_tick_denom) / nsec_per_tick_numer;
  570. out->pcount_ = val->pcount_ + ticks;
  571. }
  572. void
  573. monotime_coarse_add_msec(monotime_coarse_t *out, const monotime_coarse_t *val,
  574. uint32_t msec)
  575. {
  576. out->tick_count_ = val->tick_count_ + msec;
  577. }
  578. /* end of "_WIN32" */
  579. #elif defined(MONOTIME_USING_GETTIMEOFDAY)
  580. static tor_mutex_t monotime_lock;
  581. /** Initialize the monotonic timer subsystem. */
  582. static void
  583. monotime_init_internal(void)
  584. {
  585. tor_assert(!monotime_initialized);
  586. tor_mutex_init(&monotime_lock);
  587. }
  588. void
  589. monotime_get(monotime_t *out)
  590. {
  591. if (BUG(monotime_initialized == 0)) {
  592. monotime_init();
  593. }
  594. tor_mutex_acquire(&monotime_lock);
  595. struct timeval timeval_raw;
  596. tor_gettimeofday(&timeval_raw);
  597. ratchet_timeval(&timeval_raw, &out->tv_);
  598. tor_mutex_release(&monotime_lock);
  599. }
  600. int64_t
  601. monotime_diff_nsec(const monotime_t *start,
  602. const monotime_t *end)
  603. {
  604. struct timeval diff;
  605. timersub(&end->tv_, &start->tv_, &diff);
  606. return (diff.tv_sec * ONE_BILLION + diff.tv_usec * 1000);
  607. }
  608. int32_t
  609. monotime_coarse_diff_msec32_(const monotime_coarse_t *start,
  610. const monotime_coarse_t *end)
  611. {
  612. struct timeval diff;
  613. timersub(&end->tv_, &start->tv_, &diff);
  614. return diff.tv_sec * 1000 + diff.tv_usec / 1000;
  615. }
  616. /* This value is ONE_MILLION >> 10. */
  617. static const uint32_t STAMP_TICKS_PER_SECOND = 976;
  618. uint32_t
  619. monotime_coarse_to_stamp(const monotime_coarse_t *t)
  620. {
  621. const uint32_t usec = (uint32_t)t->tv_.tv_usec;
  622. const uint32_t sec = (uint32_t)t->tv_.tv_sec;
  623. return (sec * STAMP_TICKS_PER_SECOND) | (nsec >> 10);
  624. }
  625. int
  626. monotime_is_zero(const monotime_t *val)
  627. {
  628. return val->tv_.tv_sec == 0 && val->tv_.tv_usec == 0;
  629. }
  630. void
  631. monotime_add_msec(monotime_t *out, const monotime_t *val, uint32_t msec)
  632. {
  633. const uint32_t sec = msec / 1000;
  634. const uint32_t msec_remainder = msec % 1000;
  635. out->tv_.tv_sec = val->tv_.tv_sec + sec;
  636. out->tv_.tv_usec = val->tv_.tv_nsec + (msec_remainder * 1000);
  637. if (out->tv_.tv_usec > ONE_MILLION) {
  638. out->tv_.tv_usec -= ONE_MILLION;
  639. out->tv_.tv_sec += 1;
  640. }
  641. }
  642. /* end of "MONOTIME_USING_GETTIMEOFDAY" */
  643. #else
  644. #error "No way to implement monotonic timers."
  645. #endif /* defined(__APPLE__) || ... */
  646. /**
  647. * Initialize the monotonic timer subsystem. Must be called before any
  648. * monotonic timer functions. This function is idempotent.
  649. */
  650. void
  651. monotime_init(void)
  652. {
  653. if (!monotime_initialized) {
  654. monotime_init_internal();
  655. monotime_initialized = 1;
  656. monotime_get(&initialized_at);
  657. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  658. monotime_coarse_get(&initialized_at_coarse);
  659. #endif
  660. }
  661. }
  662. void
  663. monotime_zero(monotime_t *out)
  664. {
  665. memset(out, 0, sizeof(*out));
  666. }
  667. #ifdef MONOTIME_COARSE_TYPE_IS_DIFFERENT
  668. void
  669. monotime_coarse_zero(monotime_coarse_t *out)
  670. {
  671. memset(out, 0, sizeof(*out));
  672. }
  673. #endif /* defined(MONOTIME_COARSE_TYPE_IS_DIFFERENT) */
  674. int64_t
  675. monotime_diff_usec(const monotime_t *start,
  676. const monotime_t *end)
  677. {
  678. const int64_t nsec = monotime_diff_nsec(start, end);
  679. return CEIL_DIV(nsec, 1000);
  680. }
  681. int64_t
  682. monotime_diff_msec(const monotime_t *start,
  683. const monotime_t *end)
  684. {
  685. const int64_t nsec = monotime_diff_nsec(start, end);
  686. return CEIL_DIV(nsec, ONE_MILLION);
  687. }
  688. uint64_t
  689. monotime_absolute_nsec(void)
  690. {
  691. monotime_t now;
  692. if (BUG(monotime_initialized == 0)) {
  693. monotime_init();
  694. }
  695. monotime_get(&now);
  696. return monotime_diff_nsec(&initialized_at, &now);
  697. }
  698. MOCK_IMPL(uint64_t,
  699. monotime_absolute_usec,(void))
  700. {
  701. return monotime_absolute_nsec() / 1000;
  702. }
  703. uint64_t
  704. monotime_absolute_msec(void)
  705. {
  706. return monotime_absolute_nsec() / ONE_MILLION;
  707. }
  708. #ifdef MONOTIME_COARSE_FN_IS_DIFFERENT
  709. uint64_t
  710. monotime_coarse_absolute_nsec(void)
  711. {
  712. if (BUG(monotime_initialized == 0)) {
  713. monotime_init();
  714. }
  715. monotime_coarse_t now;
  716. monotime_coarse_get(&now);
  717. return monotime_coarse_diff_nsec(&initialized_at_coarse, &now);
  718. }
  719. uint64_t
  720. monotime_coarse_absolute_usec(void)
  721. {
  722. return monotime_coarse_absolute_nsec() / 1000;
  723. }
  724. uint64_t
  725. monotime_coarse_absolute_msec(void)
  726. {
  727. return monotime_coarse_absolute_nsec() / ONE_MILLION;
  728. }
  729. #else /* !defined(MONOTIME_COARSE_FN_IS_DIFFERENT) */
  730. #define initialized_at_coarse initialized_at
  731. #endif /* defined(MONOTIME_COARSE_FN_IS_DIFFERENT) */
  732. /**
  733. * Return the current time "stamp" as described by monotime_coarse_to_stamp.
  734. */
  735. uint32_t
  736. monotime_coarse_get_stamp(void)
  737. {
  738. monotime_coarse_t now;
  739. monotime_coarse_get(&now);
  740. return monotime_coarse_to_stamp(&now);
  741. }
  742. #ifdef __APPLE__
  743. uint64_t
  744. monotime_coarse_stamp_units_to_approx_msec(uint64_t units)
  745. {
  746. /* Recover as much precision as we can. */
  747. uint64_t abstime_diff = (units << monotime_shift);
  748. return (abstime_diff * mach_time_info.numer) /
  749. (mach_time_info.denom * ONE_MILLION);
  750. }
  751. uint64_t
  752. monotime_msec_to_approx_coarse_stamp_units(uint64_t msec)
  753. {
  754. uint64_t abstime_val =
  755. (((uint64_t)msec) * ONE_MILLION * mach_time_info.denom) /
  756. mach_time_info.numer;
  757. return abstime_val >> monotime_shift;
  758. }
  759. #else /* !defined(__APPLE__) */
  760. uint64_t
  761. monotime_coarse_stamp_units_to_approx_msec(uint64_t units)
  762. {
  763. return (units * 1000) / STAMP_TICKS_PER_SECOND;
  764. }
  765. uint64_t
  766. monotime_msec_to_approx_coarse_stamp_units(uint64_t msec)
  767. {
  768. return (msec * STAMP_TICKS_PER_SECOND) / 1000;
  769. }
  770. #endif /* defined(__APPLE__) */