compat_time.c 22 KB

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