compat_time.c 24 KB

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