timers.c 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /* Copyright (c) 2016, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file timers.c
  5. * \brief Wrapper around William Ahern's fast hierarchical timer wheel
  6. * implementation, to tie it in with a libevent backend.
  7. *
  8. * Only use these functions from the main thread.
  9. *
  10. * The main advantage of tor_timer_t over using libevent's timers is that
  11. * they're way more efficient if we need to have thousands or millions of
  12. * them. For more information, see
  13. * http://www.25thandclement.com/~william/projects/timeout.c.html
  14. *
  15. * Periodic timers are available in the backend, but I've turned them off.
  16. * We can turn them back on if needed.
  17. */
  18. /* Notes:
  19. *
  20. * The use of tor_gettimeofday_cached_monotonic() is kind of ugly. It would
  21. * be neat to fix it.
  22. *
  23. * Having a way to free all timers on shutdown would free people from the
  24. * need to track them. Not sure if that's clever though.
  25. *
  26. * In an ideal world, Libevent would just switch to use this backend, and we
  27. * could throw this file away. But even if Libevent does switch, we'll be
  28. * stuck with legacy libevents for some time.
  29. */
  30. #include "orconfig.h"
  31. #include "compat.h"
  32. #include "compat_libevent.h"
  33. #include "timers.h"
  34. #include "torlog.h"
  35. #include "util.h"
  36. #include <event2/event.h>
  37. struct timeout_cb {
  38. timer_cb_fn_t cb;
  39. void *arg;
  40. };
  41. /*
  42. * These definitions are for timeouts.c and timeouts.h.
  43. */
  44. #ifdef __GNUC__
  45. /* We're not exposing any of the functions outside this file. */
  46. #define TIMEOUT_PUBLIC __attribute__((__unused__)) static
  47. #else
  48. /* We're not exposing any of the functions outside this file. */
  49. #define TIMEOUT_PUBLIC static
  50. #endif
  51. /* We're not using periodic events. */
  52. #define TIMEOUT_DISABLE_INTERVALS
  53. /* We always know the global_timeouts object, so we don't need each timeout
  54. * to keep a pointer to it. */
  55. #define TIMEOUT_DISABLE_RELATIVE_ACCESS
  56. /* We're providing our own struct timeout_cb. */
  57. #define TIMEOUT_CB_OVERRIDE
  58. /* We're going to support timers that are pretty far out in advance. Making
  59. * this big can be inefficient, but having a significant number of timers
  60. * above TIMEOUT_MAX can also be super-inefficent. Choosing 5 here sets
  61. * timeout_max to 2^30 ticks, or 29 hours with our value for USEC_PER_TICK */
  62. #define WHEEL_NUM 5
  63. #include "src/ext/timeouts/timeout.c"
  64. static struct timeouts *global_timeouts = NULL;
  65. static struct event *global_timer_event = NULL;
  66. /** We need to choose this value carefully. Because we're using timer wheels,
  67. * it actually costs us to have extra resolution we don't use. So for now,
  68. * I'm going to define our resolution as .1 msec, and hope that's good enough.
  69. *
  70. * Note that two of the most popular libevent backends (epoll without timerfd,
  71. * and windows select), simply can't support sub-millisecond resolution,
  72. * do this is optimistic for a lot of users.
  73. */
  74. #define USEC_PER_TICK 100
  75. /** One million microseconds in a second */
  76. #define USEC_PER_SEC 1000000
  77. /** Check at least once every N seconds. */
  78. #define MIN_CHECK_SECONDS 3600
  79. /** Check at least once every N ticks. */
  80. #define MIN_CHECK_TICKS \
  81. (((timeout_t)MIN_CHECK_SECONDS) * (1000000 / USEC_PER_TICK))
  82. /**
  83. * Convert the timeval in <b>tv</b> to a timeout_t, and return it.
  84. *
  85. * The output resolution is set by USEC_PER_TICK, and the time corresponding
  86. * to 0 is the same as the time corresponding to 0 from
  87. * tor_gettimeofday_cached_monotonic().
  88. */
  89. static timeout_t
  90. tv_to_timeout(const struct timeval *tv)
  91. {
  92. uint64_t usec = tv->tv_usec;
  93. usec += ((uint64_t)USEC_PER_SEC) * tv->tv_sec;
  94. return usec / USEC_PER_TICK;
  95. }
  96. /**
  97. * Convert the timeout in <b>t</b> to a timeval in <b>tv_out</b>
  98. */
  99. static void
  100. timeout_to_tv(timeout_t t, struct timeval *tv_out)
  101. {
  102. t *= USEC_PER_TICK;
  103. tv_out->tv_usec = (int)(t % USEC_PER_SEC);
  104. tv_out->tv_sec = (time_t)(t / USEC_PER_SEC);
  105. }
  106. /**
  107. * Update the timer <b>tv</b> to the current time in <b>tv</b>.
  108. */
  109. static void
  110. timer_advance_to_cur_time(const struct timeval *tv)
  111. {
  112. timeout_t cur_tick = tv_to_timeout(tv);
  113. if (BUG(cur_tick < timeouts_get_curtime(global_timeouts))) {
  114. cur_tick = timeouts_get_curtime(global_timeouts); // LCOV_EXCL_LINE
  115. }
  116. timeouts_update(global_timeouts, cur_tick);
  117. }
  118. /**
  119. * Adjust the time at which the libevent timer should fire based on
  120. * the next-expiring time in <b>global_timeouts</b>
  121. */
  122. static void
  123. libevent_timer_reschedule(void)
  124. {
  125. struct timeval now;
  126. tor_gettimeofday_cached_monotonic(&now);
  127. timer_advance_to_cur_time(&now);
  128. timeout_t delay = timeouts_timeout(global_timeouts);
  129. struct timeval d;
  130. if (delay > MIN_CHECK_TICKS)
  131. delay = MIN_CHECK_TICKS;
  132. timeout_to_tv(delay, &d);
  133. event_add(global_timer_event, &d);
  134. }
  135. /**
  136. * Invoked when the libevent timer has expired: see which tor_timer_t events
  137. * have fired, activate their callbacks, and reschedule the libevent timer.
  138. */
  139. static void
  140. libevent_timer_callback(evutil_socket_t fd, short what, void *arg)
  141. {
  142. (void)fd;
  143. (void)what;
  144. (void)arg;
  145. struct timeval now;
  146. tor_gettimeofday_cache_clear();
  147. tor_gettimeofday_cached_monotonic(&now);
  148. timer_advance_to_cur_time(&now);
  149. tor_timer_t *t;
  150. while ((t = timeouts_get(global_timeouts))) {
  151. t->callback.cb(t, t->callback.arg, &now);
  152. }
  153. tor_gettimeofday_cache_clear();
  154. libevent_timer_reschedule();
  155. }
  156. /**
  157. * Initialize the timers subsystem. Requires that libevent has already been
  158. * initialized.
  159. */
  160. void
  161. timers_initialize(void)
  162. {
  163. if (BUG(global_timeouts))
  164. return; // LCOV_EXCL_LINE
  165. timeout_error_t err;
  166. global_timeouts = timeouts_open(0, &err);
  167. if (!global_timeouts) {
  168. // LCOV_EXCL_START -- this can only fail on malloc failure.
  169. log_err(LD_BUG, "Unable to open timer backend: %s", strerror(err));
  170. tor_assert(0);
  171. // LCOV_EXCL_STOP
  172. }
  173. struct event *timer_event;
  174. timer_event = tor_event_new(tor_libevent_get_base(),
  175. -1, 0, libevent_timer_callback, NULL);
  176. tor_assert(timer_event);
  177. global_timer_event = timer_event;
  178. libevent_timer_reschedule();
  179. }
  180. /**
  181. * Release all storage held in the timers subsystem. Does not fire timers.
  182. */
  183. void
  184. timers_shutdown(void)
  185. {
  186. if (global_timer_event) {
  187. tor_event_free(global_timer_event);
  188. global_timer_event = NULL;
  189. }
  190. if (global_timeouts) {
  191. timeouts_close(global_timeouts);
  192. global_timeouts = NULL;
  193. }
  194. }
  195. /**
  196. * Allocate and return a new timer, with given callback and argument.
  197. */
  198. tor_timer_t *
  199. timer_new(timer_cb_fn_t cb, void *arg)
  200. {
  201. tor_timer_t *t = tor_malloc(sizeof(tor_timer_t));
  202. timeout_init(t, 0);
  203. timer_set_cb(t, cb, arg);
  204. return t;
  205. }
  206. /**
  207. * Release all storage held by <b>t</b>, and unschedule it if was already
  208. * scheduled.
  209. */
  210. void
  211. timer_free(tor_timer_t *t)
  212. {
  213. if (! t)
  214. return;
  215. timeouts_del(global_timeouts, t);
  216. tor_free(t);
  217. }
  218. /**
  219. * Change the callback and argument associated with a timer <b>t</b>.
  220. */
  221. void
  222. timer_set_cb(tor_timer_t *t, timer_cb_fn_t cb, void *arg)
  223. {
  224. t->callback.cb = cb;
  225. t->callback.arg = arg;
  226. }
  227. /**
  228. * Schedule the timer t to fire at the current time plus a delay of <b>tv</b>.
  229. * All times are relative to tor_gettimeofday_cached_monotonic.
  230. */
  231. void
  232. timer_schedule(tor_timer_t *t, const struct timeval *tv)
  233. {
  234. const timeout_t when = tv_to_timeout(tv);
  235. struct timeval now;
  236. tor_gettimeofday_cached_monotonic(&now);
  237. timer_advance_to_cur_time(&now);
  238. /* Take the old timeout value. */
  239. timeout_t to = timeouts_timeout(global_timeouts);
  240. timeouts_add(global_timeouts, t, when);
  241. /* Should we update the libevent timer? */
  242. if (to <= when) {
  243. return; /* we're already going to fire before this timer would trigger. */
  244. }
  245. libevent_timer_reschedule();
  246. }
  247. /**
  248. * Cancel the timer <b>t</b> if it is currently scheduled. (It's okay to call
  249. * this on an unscheduled timer.
  250. */
  251. void
  252. timer_disable(tor_timer_t *t)
  253. {
  254. timeouts_del(global_timeouts, t);
  255. /* We don't reschedule the libevent timer here, since it's okay if it fires
  256. * early. */
  257. }