compat_time.c 22 KB

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