workqueue.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. /* copyright (c) 2013-2015, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file workqueue.c
  5. *
  6. * \brief Implements worker threads, queues of work for them, and mechanisms
  7. * for them to send answers back to the main thread.
  8. *
  9. * The main structure here is a threadpool_t : it manages a set of worker
  10. * threads, a queue of pending work, and a reply queue. Every piece of work
  11. * is a workqueue_entry_t, containing data to process and a function to
  12. * process it with.
  13. *
  14. * The main thread informs the worker threads of pending work by using a
  15. * condition variable. The workers inform the main process of completed work
  16. * by using an alert_sockets_t object, as implemented in compat_threads.c.
  17. *
  18. * The main thread can also queue an "update" that will be handled by all the
  19. * workers. This is useful for updating state that all the workers share.
  20. *
  21. * In Tor today, there is currently only one thread pool, used in cpuworker.c.
  22. */
  23. #include "orconfig.h"
  24. #include "lib/evloop/compat_libevent.h"
  25. #include "lib/evloop/workqueue.h"
  26. #include "lib/crypt_ops/crypto_rand.h"
  27. #include "lib/intmath/weakrng.h"
  28. #include "lib/log/ratelim.h"
  29. #include "lib/log/log.h"
  30. #include "lib/log/util_bug.h"
  31. #include "lib/net/alertsock.h"
  32. #include "lib/net/socket.h"
  33. #include "lib/thread/threads.h"
  34. #include "tor_queue.h"
  35. #include <event2/event.h>
  36. #include <string.h>
  37. #define WORKQUEUE_PRIORITY_FIRST WQ_PRI_HIGH
  38. #define WORKQUEUE_PRIORITY_LAST WQ_PRI_LOW
  39. #define WORKQUEUE_N_PRIORITIES (((int) WORKQUEUE_PRIORITY_LAST)+1)
  40. TOR_TAILQ_HEAD(work_tailq_t, workqueue_entry_s);
  41. typedef struct work_tailq_t work_tailq_t;
  42. struct threadpool_s {
  43. /** An array of pointers to workerthread_t: one for each running worker
  44. * thread. */
  45. struct workerthread_s **threads;
  46. /** Condition variable that we wait on when we have no work, and which
  47. * gets signaled when our queue becomes nonempty. */
  48. tor_cond_t condition;
  49. /** Queues of pending work that we have to do. The queue with priority
  50. * <b>p</b> is work[p]. */
  51. work_tailq_t work[WORKQUEUE_N_PRIORITIES];
  52. /** Weak RNG, used to decide when to ignore priority. */
  53. tor_weak_rng_t weak_rng;
  54. /** The current 'update generation' of the threadpool. Any thread that is
  55. * at an earlier generation needs to run the update function. */
  56. unsigned generation;
  57. /** Function that should be run for updates on each thread. */
  58. workqueue_reply_t (*update_fn)(void *, void *);
  59. /** Function to free update arguments if they can't be run. */
  60. void (*free_update_arg_fn)(void *);
  61. /** Array of n_threads update arguments. */
  62. void **update_args;
  63. /** Event to notice when another thread has sent a reply. */
  64. struct event *reply_event;
  65. void (*reply_cb)(threadpool_t *);
  66. /** Number of elements in threads. */
  67. int n_threads;
  68. /** Mutex to protect all the above fields. */
  69. tor_mutex_t lock;
  70. /** A reply queue to use when constructing new threads. */
  71. replyqueue_t *reply_queue;
  72. /** Functions used to allocate and free thread state. */
  73. void *(*new_thread_state_fn)(void*);
  74. void (*free_thread_state_fn)(void*);
  75. void *new_thread_state_arg;
  76. };
  77. /** Used to put a workqueue_priority_t value into a bitfield. */
  78. #define workqueue_priority_bitfield_t ENUM_BF(workqueue_priority_t)
  79. /** Number of bits needed to hold all legal values of workqueue_priority_t */
  80. #define WORKQUEUE_PRIORITY_BITS 2
  81. struct workqueue_entry_s {
  82. /** The next workqueue_entry_t that's pending on the same thread or
  83. * reply queue. */
  84. TOR_TAILQ_ENTRY(workqueue_entry_s) next_work;
  85. /** The threadpool to which this workqueue_entry_t was assigned. This field
  86. * is set when the workqueue_entry_t is created, and won't be cleared until
  87. * after it's handled in the main thread. */
  88. struct threadpool_s *on_pool;
  89. /** True iff this entry is waiting for a worker to start processing it. */
  90. uint8_t pending;
  91. /** Priority of this entry. */
  92. workqueue_priority_bitfield_t priority : WORKQUEUE_PRIORITY_BITS;
  93. /** Function to run in the worker thread. */
  94. workqueue_reply_t (*fn)(void *state, void *arg);
  95. /** Function to run while processing the reply queue. */
  96. void (*reply_fn)(void *arg);
  97. /** Argument for the above functions. */
  98. void *arg;
  99. };
  100. struct replyqueue_s {
  101. /** Mutex to protect the answers field */
  102. tor_mutex_t lock;
  103. /** Doubly-linked list of answers that the reply queue needs to handle. */
  104. TOR_TAILQ_HEAD(, workqueue_entry_s) answers;
  105. /** Mechanism to wake up the main thread when it is receiving answers. */
  106. alert_sockets_t alert;
  107. };
  108. /** A worker thread represents a single thread in a thread pool. */
  109. typedef struct workerthread_s {
  110. /** Which thread it this? In range 0..in_pool->n_threads-1 */
  111. int index;
  112. /** The pool this thread is a part of. */
  113. struct threadpool_s *in_pool;
  114. /** User-supplied state field that we pass to the worker functions of each
  115. * work item. */
  116. void *state;
  117. /** Reply queue to which we pass our results. */
  118. replyqueue_t *reply_queue;
  119. /** The current update generation of this thread */
  120. unsigned generation;
  121. /** One over the probability of taking work from a lower-priority queue. */
  122. int32_t lower_priority_chance;
  123. } workerthread_t;
  124. static void queue_reply(replyqueue_t *queue, workqueue_entry_t *work);
  125. /** Allocate and return a new workqueue_entry_t, set up to run the function
  126. * <b>fn</b> in the worker thread, and <b>reply_fn</b> in the main
  127. * thread. See threadpool_queue_work() for full documentation. */
  128. static workqueue_entry_t *
  129. workqueue_entry_new(workqueue_reply_t (*fn)(void*, void*),
  130. void (*reply_fn)(void*),
  131. void *arg)
  132. {
  133. workqueue_entry_t *ent = tor_malloc_zero(sizeof(workqueue_entry_t));
  134. ent->fn = fn;
  135. ent->reply_fn = reply_fn;
  136. ent->arg = arg;
  137. ent->priority = WQ_PRI_HIGH;
  138. return ent;
  139. }
  140. #define workqueue_entry_free(ent) \
  141. FREE_AND_NULL(workqueue_entry_t, workqueue_entry_free_, (ent))
  142. /**
  143. * Release all storage held in <b>ent</b>. Call only when <b>ent</b> is not on
  144. * any queue.
  145. */
  146. static void
  147. workqueue_entry_free_(workqueue_entry_t *ent)
  148. {
  149. if (!ent)
  150. return;
  151. memset(ent, 0xf0, sizeof(*ent));
  152. tor_free(ent);
  153. }
  154. /**
  155. * Cancel a workqueue_entry_t that has been returned from
  156. * threadpool_queue_work.
  157. *
  158. * You must not call this function on any work whose reply function has been
  159. * executed in the main thread; that will cause undefined behavior (probably,
  160. * a crash).
  161. *
  162. * If the work is cancelled, this function return the argument passed to the
  163. * work function. It is the caller's responsibility to free this storage.
  164. *
  165. * This function will have no effect if the worker thread has already executed
  166. * or begun to execute the work item. In that case, it will return NULL.
  167. */
  168. void *
  169. workqueue_entry_cancel(workqueue_entry_t *ent)
  170. {
  171. int cancelled = 0;
  172. void *result = NULL;
  173. tor_mutex_acquire(&ent->on_pool->lock);
  174. workqueue_priority_t prio = ent->priority;
  175. if (ent->pending) {
  176. TOR_TAILQ_REMOVE(&ent->on_pool->work[prio], ent, next_work);
  177. cancelled = 1;
  178. result = ent->arg;
  179. }
  180. tor_mutex_release(&ent->on_pool->lock);
  181. if (cancelled) {
  182. workqueue_entry_free(ent);
  183. }
  184. return result;
  185. }
  186. /**DOCDOC
  187. must hold lock */
  188. static int
  189. worker_thread_has_work(workerthread_t *thread)
  190. {
  191. unsigned i;
  192. for (i = WORKQUEUE_PRIORITY_FIRST; i <= WORKQUEUE_PRIORITY_LAST; ++i) {
  193. if (!TOR_TAILQ_EMPTY(&thread->in_pool->work[i]))
  194. return 1;
  195. }
  196. return thread->generation != thread->in_pool->generation;
  197. }
  198. /** Extract the next workqueue_entry_t from the the thread's pool, removing
  199. * it from the relevant queues and marking it as non-pending.
  200. *
  201. * The caller must hold the lock. */
  202. static workqueue_entry_t *
  203. worker_thread_extract_next_work(workerthread_t *thread)
  204. {
  205. threadpool_t *pool = thread->in_pool;
  206. work_tailq_t *queue = NULL, *this_queue;
  207. unsigned i;
  208. for (i = WORKQUEUE_PRIORITY_FIRST; i <= WORKQUEUE_PRIORITY_LAST; ++i) {
  209. this_queue = &pool->work[i];
  210. if (!TOR_TAILQ_EMPTY(this_queue)) {
  211. queue = this_queue;
  212. if (! tor_weak_random_one_in_n(&pool->weak_rng,
  213. thread->lower_priority_chance)) {
  214. /* Usually we'll just break now, so that we can get out of the loop
  215. * and use the queue where we found work. But with a small
  216. * probability, we'll keep looking for lower priority work, so that
  217. * we don't ignore our low-priority queues entirely. */
  218. break;
  219. }
  220. }
  221. }
  222. if (queue == NULL)
  223. return NULL;
  224. workqueue_entry_t *work = TOR_TAILQ_FIRST(queue);
  225. TOR_TAILQ_REMOVE(queue, work, next_work);
  226. work->pending = 0;
  227. return work;
  228. }
  229. /**
  230. * Main function for the worker thread.
  231. */
  232. static void
  233. worker_thread_main(void *thread_)
  234. {
  235. workerthread_t *thread = thread_;
  236. threadpool_t *pool = thread->in_pool;
  237. workqueue_entry_t *work;
  238. workqueue_reply_t result;
  239. tor_mutex_acquire(&pool->lock);
  240. while (1) {
  241. /* lock must be held at this point. */
  242. while (worker_thread_has_work(thread)) {
  243. /* lock must be held at this point. */
  244. if (thread->in_pool->generation != thread->generation) {
  245. void *arg = thread->in_pool->update_args[thread->index];
  246. thread->in_pool->update_args[thread->index] = NULL;
  247. workqueue_reply_t (*update_fn)(void*,void*) =
  248. thread->in_pool->update_fn;
  249. thread->generation = thread->in_pool->generation;
  250. tor_mutex_release(&pool->lock);
  251. workqueue_reply_t r = update_fn(thread->state, arg);
  252. if (r != WQ_RPL_REPLY) {
  253. return;
  254. }
  255. tor_mutex_acquire(&pool->lock);
  256. continue;
  257. }
  258. work = worker_thread_extract_next_work(thread);
  259. if (BUG(work == NULL))
  260. break;
  261. tor_mutex_release(&pool->lock);
  262. /* We run the work function without holding the thread lock. This
  263. * is the main thread's first opportunity to give us more work. */
  264. result = work->fn(thread->state, work->arg);
  265. /* Queue the reply for the main thread. */
  266. queue_reply(thread->reply_queue, work);
  267. /* We may need to exit the thread. */
  268. if (result != WQ_RPL_REPLY) {
  269. return;
  270. }
  271. tor_mutex_acquire(&pool->lock);
  272. }
  273. /* At this point the lock is held, and there is no work in this thread's
  274. * queue. */
  275. /* TODO: support an idle-function */
  276. /* Okay. Now, wait till somebody has work for us. */
  277. if (tor_cond_wait(&pool->condition, &pool->lock, NULL) < 0) {
  278. log_warn(LD_GENERAL, "Fail tor_cond_wait.");
  279. }
  280. }
  281. }
  282. /** Put a reply on the reply queue. The reply must not currently be on
  283. * any thread's work queue. */
  284. static void
  285. queue_reply(replyqueue_t *queue, workqueue_entry_t *work)
  286. {
  287. int was_empty;
  288. tor_mutex_acquire(&queue->lock);
  289. was_empty = TOR_TAILQ_EMPTY(&queue->answers);
  290. TOR_TAILQ_INSERT_TAIL(&queue->answers, work, next_work);
  291. tor_mutex_release(&queue->lock);
  292. if (was_empty) {
  293. if (queue->alert.alert_fn(queue->alert.write_fd) < 0) {
  294. /* XXXX complain! */
  295. }
  296. }
  297. }
  298. /** Allocate and start a new worker thread to use state object <b>state</b>,
  299. * and send responses to <b>replyqueue</b>. */
  300. static workerthread_t *
  301. workerthread_new(int32_t lower_priority_chance,
  302. void *state, threadpool_t *pool, replyqueue_t *replyqueue)
  303. {
  304. workerthread_t *thr = tor_malloc_zero(sizeof(workerthread_t));
  305. thr->state = state;
  306. thr->reply_queue = replyqueue;
  307. thr->in_pool = pool;
  308. thr->lower_priority_chance = lower_priority_chance;
  309. if (spawn_func(worker_thread_main, thr) < 0) {
  310. //LCOV_EXCL_START
  311. tor_assert_nonfatal_unreached();
  312. log_err(LD_GENERAL, "Can't launch worker thread.");
  313. tor_free(thr);
  314. return NULL;
  315. //LCOV_EXCL_STOP
  316. }
  317. return thr;
  318. }
  319. /**
  320. * Queue an item of work for a thread in a thread pool. The function
  321. * <b>fn</b> will be run in a worker thread, and will receive as arguments the
  322. * thread's state object, and the provided object <b>arg</b>. It must return
  323. * one of WQ_RPL_REPLY, WQ_RPL_ERROR, or WQ_RPL_SHUTDOWN.
  324. *
  325. * Regardless of its return value, the function <b>reply_fn</b> will later be
  326. * run in the main thread when it invokes replyqueue_process(), and will
  327. * receive as its argument the same <b>arg</b> object. It's the reply
  328. * function's responsibility to free the work object.
  329. *
  330. * On success, return a workqueue_entry_t object that can be passed to
  331. * workqueue_entry_cancel(). On failure, return NULL. (Failure is not
  332. * currently possible, but callers should check anyway.)
  333. *
  334. * Items are executed in a loose priority order -- each thread will usually
  335. * take from the queued work with the highest prioirity, but will occasionally
  336. * visit lower-priority queues to keep them from starving completely.
  337. *
  338. * Note that because of priorities and thread behavior, work items may not
  339. * be executed strictly in order.
  340. */
  341. workqueue_entry_t *
  342. threadpool_queue_work_priority(threadpool_t *pool,
  343. workqueue_priority_t prio,
  344. workqueue_reply_t (*fn)(void *, void *),
  345. void (*reply_fn)(void *),
  346. void *arg)
  347. {
  348. tor_assert(((int)prio) >= WORKQUEUE_PRIORITY_FIRST &&
  349. ((int)prio) <= WORKQUEUE_PRIORITY_LAST);
  350. workqueue_entry_t *ent = workqueue_entry_new(fn, reply_fn, arg);
  351. ent->on_pool = pool;
  352. ent->pending = 1;
  353. ent->priority = prio;
  354. tor_mutex_acquire(&pool->lock);
  355. TOR_TAILQ_INSERT_TAIL(&pool->work[prio], ent, next_work);
  356. tor_cond_signal_one(&pool->condition);
  357. tor_mutex_release(&pool->lock);
  358. return ent;
  359. }
  360. /** As threadpool_queue_work_priority(), but assumes WQ_PRI_HIGH */
  361. workqueue_entry_t *
  362. threadpool_queue_work(threadpool_t *pool,
  363. workqueue_reply_t (*fn)(void *, void *),
  364. void (*reply_fn)(void *),
  365. void *arg)
  366. {
  367. return threadpool_queue_work_priority(pool, WQ_PRI_HIGH, fn, reply_fn, arg);
  368. }
  369. /**
  370. * Queue a copy of a work item for every thread in a pool. This can be used,
  371. * for example, to tell the threads to update some parameter in their states.
  372. *
  373. * Arguments are as for <b>threadpool_queue_work</b>, except that the
  374. * <b>arg</b> value is passed to <b>dup_fn</b> once per each thread to
  375. * make a copy of it.
  376. *
  377. * UPDATE FUNCTIONS MUST BE IDEMPOTENT. We do not guarantee that every update
  378. * will be run. If a new update is scheduled before the old update finishes
  379. * running, then the new will replace the old in any threads that haven't run
  380. * it yet.
  381. *
  382. * Return 0 on success, -1 on failure.
  383. */
  384. int
  385. threadpool_queue_update(threadpool_t *pool,
  386. void *(*dup_fn)(void *),
  387. workqueue_reply_t (*fn)(void *, void *),
  388. void (*free_fn)(void *),
  389. void *arg)
  390. {
  391. int i, n_threads;
  392. void (*old_args_free_fn)(void *arg);
  393. void **old_args;
  394. void **new_args;
  395. tor_mutex_acquire(&pool->lock);
  396. n_threads = pool->n_threads;
  397. old_args = pool->update_args;
  398. old_args_free_fn = pool->free_update_arg_fn;
  399. new_args = tor_calloc(n_threads, sizeof(void*));
  400. for (i = 0; i < n_threads; ++i) {
  401. if (dup_fn)
  402. new_args[i] = dup_fn(arg);
  403. else
  404. new_args[i] = arg;
  405. }
  406. pool->update_args = new_args;
  407. pool->free_update_arg_fn = free_fn;
  408. pool->update_fn = fn;
  409. ++pool->generation;
  410. tor_cond_signal_all(&pool->condition);
  411. tor_mutex_release(&pool->lock);
  412. if (old_args) {
  413. for (i = 0; i < n_threads; ++i) {
  414. if (old_args[i] && old_args_free_fn)
  415. old_args_free_fn(old_args[i]);
  416. }
  417. tor_free(old_args);
  418. }
  419. return 0;
  420. }
  421. /** Don't have more than this many threads per pool. */
  422. #define MAX_THREADS 1024
  423. /** For half of our threads, choose lower priority queues with probability
  424. * 1/N for each of these values. Both are chosen somewhat arbitrarily. If
  425. * CHANCE_PERMISSIVE is too low, then we have a risk of low-priority tasks
  426. * stalling forever. If it's too high, we have a risk of low-priority tasks
  427. * grabbing half of the threads. */
  428. #define CHANCE_PERMISSIVE 37
  429. #define CHANCE_STRICT INT32_MAX
  430. /** Launch threads until we have <b>n</b>. */
  431. static int
  432. threadpool_start_threads(threadpool_t *pool, int n)
  433. {
  434. if (BUG(n < 0))
  435. return -1; // LCOV_EXCL_LINE
  436. if (n > MAX_THREADS)
  437. n = MAX_THREADS;
  438. tor_mutex_acquire(&pool->lock);
  439. if (pool->n_threads < n)
  440. pool->threads = tor_reallocarray(pool->threads,
  441. sizeof(workerthread_t*), n);
  442. while (pool->n_threads < n) {
  443. /* For half of our threads, we'll choose lower priorities permissively;
  444. * for the other half, we'll stick more strictly to higher priorities.
  445. * This keeps slow low-priority tasks from taking over completely. */
  446. int32_t chance = (pool->n_threads & 1) ? CHANCE_STRICT : CHANCE_PERMISSIVE;
  447. void *state = pool->new_thread_state_fn(pool->new_thread_state_arg);
  448. workerthread_t *thr = workerthread_new(chance,
  449. state, pool, pool->reply_queue);
  450. if (!thr) {
  451. //LCOV_EXCL_START
  452. tor_assert_nonfatal_unreached();
  453. pool->free_thread_state_fn(state);
  454. tor_mutex_release(&pool->lock);
  455. return -1;
  456. //LCOV_EXCL_STOP
  457. }
  458. thr->index = pool->n_threads;
  459. pool->threads[pool->n_threads++] = thr;
  460. }
  461. tor_mutex_release(&pool->lock);
  462. return 0;
  463. }
  464. /**
  465. * Construct a new thread pool with <b>n</b> worker threads, configured to
  466. * send their output to <b>replyqueue</b>. The threads' states will be
  467. * constructed with the <b>new_thread_state_fn</b> call, receiving <b>arg</b>
  468. * as its argument. When the threads close, they will call
  469. * <b>free_thread_state_fn</b> on their states.
  470. */
  471. threadpool_t *
  472. threadpool_new(int n_threads,
  473. replyqueue_t *replyqueue,
  474. void *(*new_thread_state_fn)(void*),
  475. void (*free_thread_state_fn)(void*),
  476. void *arg)
  477. {
  478. threadpool_t *pool;
  479. pool = tor_malloc_zero(sizeof(threadpool_t));
  480. tor_mutex_init_nonrecursive(&pool->lock);
  481. tor_cond_init(&pool->condition);
  482. unsigned i;
  483. for (i = WORKQUEUE_PRIORITY_FIRST; i <= WORKQUEUE_PRIORITY_LAST; ++i) {
  484. TOR_TAILQ_INIT(&pool->work[i]);
  485. }
  486. {
  487. unsigned seed;
  488. crypto_rand((void*)&seed, sizeof(seed));
  489. tor_init_weak_random(&pool->weak_rng, seed);
  490. }
  491. pool->new_thread_state_fn = new_thread_state_fn;
  492. pool->new_thread_state_arg = arg;
  493. pool->free_thread_state_fn = free_thread_state_fn;
  494. pool->reply_queue = replyqueue;
  495. if (threadpool_start_threads(pool, n_threads) < 0) {
  496. //LCOV_EXCL_START
  497. tor_assert_nonfatal_unreached();
  498. tor_cond_uninit(&pool->condition);
  499. tor_mutex_uninit(&pool->lock);
  500. tor_free(pool);
  501. return NULL;
  502. //LCOV_EXCL_STOP
  503. }
  504. return pool;
  505. }
  506. /** Return the reply queue associated with a given thread pool. */
  507. replyqueue_t *
  508. threadpool_get_replyqueue(threadpool_t *tp)
  509. {
  510. return tp->reply_queue;
  511. }
  512. /** Allocate a new reply queue. Reply queues are used to pass results from
  513. * worker threads to the main thread. Since the main thread is running an
  514. * IO-centric event loop, it needs to get woken up with means other than a
  515. * condition variable. */
  516. replyqueue_t *
  517. replyqueue_new(uint32_t alertsocks_flags)
  518. {
  519. replyqueue_t *rq;
  520. rq = tor_malloc_zero(sizeof(replyqueue_t));
  521. if (alert_sockets_create(&rq->alert, alertsocks_flags) < 0) {
  522. //LCOV_EXCL_START
  523. tor_free(rq);
  524. return NULL;
  525. //LCOV_EXCL_STOP
  526. }
  527. tor_mutex_init(&rq->lock);
  528. TOR_TAILQ_INIT(&rq->answers);
  529. return rq;
  530. }
  531. /** Internal: Run from the libevent mainloop when there is work to handle in
  532. * the reply queue handler. */
  533. static void
  534. reply_event_cb(evutil_socket_t sock, short events, void *arg)
  535. {
  536. threadpool_t *tp = arg;
  537. (void) sock;
  538. (void) events;
  539. replyqueue_process(tp->reply_queue);
  540. if (tp->reply_cb)
  541. tp->reply_cb(tp);
  542. }
  543. /** Register the threadpool <b>tp</b>'s reply queue with the libevent
  544. * mainloop of <b>base</b>. If <b>tp</b> is provided, it is run after
  545. * each time there is work to process from the reply queue. Return 0 on
  546. * success, -1 on failure.
  547. */
  548. int
  549. threadpool_register_reply_event(threadpool_t *tp,
  550. void (*cb)(threadpool_t *tp))
  551. {
  552. struct event_base *base = tor_libevent_get_base();
  553. if (tp->reply_event) {
  554. tor_event_free(tp->reply_event);
  555. }
  556. tp->reply_event = tor_event_new(base,
  557. tp->reply_queue->alert.read_fd,
  558. EV_READ|EV_PERSIST,
  559. reply_event_cb,
  560. tp);
  561. tor_assert(tp->reply_event);
  562. tp->reply_cb = cb;
  563. return event_add(tp->reply_event, NULL);
  564. }
  565. /**
  566. * Process all pending replies on a reply queue. The main thread should call
  567. * this function every time the socket returned by replyqueue_get_socket() is
  568. * readable.
  569. */
  570. void
  571. replyqueue_process(replyqueue_t *queue)
  572. {
  573. int r = queue->alert.drain_fn(queue->alert.read_fd);
  574. if (r < 0) {
  575. //LCOV_EXCL_START
  576. static ratelim_t warn_limit = RATELIM_INIT(7200);
  577. log_fn_ratelim(&warn_limit, LOG_WARN, LD_GENERAL,
  578. "Failure from drain_fd: %s",
  579. tor_socket_strerror(-r));
  580. //LCOV_EXCL_STOP
  581. }
  582. tor_mutex_acquire(&queue->lock);
  583. while (!TOR_TAILQ_EMPTY(&queue->answers)) {
  584. /* lock must be held at this point.*/
  585. workqueue_entry_t *work = TOR_TAILQ_FIRST(&queue->answers);
  586. TOR_TAILQ_REMOVE(&queue->answers, work, next_work);
  587. tor_mutex_release(&queue->lock);
  588. work->on_pool = NULL;
  589. work->reply_fn(work->arg);
  590. workqueue_entry_free(work);
  591. tor_mutex_acquire(&queue->lock);
  592. }
  593. tor_mutex_release(&queue->lock);
  594. }