timers.c 7.7 KB

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