compat_time.c 23 KB

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