compat_time.c 22 KB

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