workqueue.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. #include "orconfig.h"
  10. #include "compat.h"
  11. #include "compat_threads.h"
  12. #include "util.h"
  13. #include "workqueue.h"
  14. #include "tor_queue.h"
  15. #include "torlog.h"
  16. struct threadpool_s {
  17. /** An array of pointers to workerthread_t: one for each running worker
  18. * thread. */
  19. struct workerthread_s **threads;
  20. /** Condition variable that we wait on when we have no work, and which
  21. * gets signaled when our queue becomes nonempty. */
  22. tor_cond_t condition;
  23. /** Queue of pending work that we have to do. */
  24. TOR_TAILQ_HEAD(, workqueue_entry_s) work;
  25. /** The current 'update generation' of the threadpool. Any thread that is
  26. * at an earlier generation needs to run the update function. */
  27. unsigned generation;
  28. /** Function that should be run for updates on each thread. */
  29. workqueue_reply_t (*update_fn)(void *, void *);
  30. /** Function to free update arguments if they can't be run. */
  31. void (*free_update_arg_fn)(void *);
  32. /** Array of n_threads update arguments. */
  33. void **update_args;
  34. /** Number of elements in threads. */
  35. int n_threads;
  36. /** Mutex to protect all the above fields. */
  37. tor_mutex_t lock;
  38. /** A reply queue to use when constructing new threads. */
  39. replyqueue_t *reply_queue;
  40. /** Functions used to allocate and free thread state. */
  41. void *(*new_thread_state_fn)(void*);
  42. void (*free_thread_state_fn)(void*);
  43. void *new_thread_state_arg;
  44. };
  45. struct workqueue_entry_s {
  46. /** The next workqueue_entry_t that's pending on the same thread or
  47. * reply queue. */
  48. TOR_TAILQ_ENTRY(workqueue_entry_s) next_work;
  49. /** The threadpool to which this workqueue_entry_t was assigned. This field
  50. * is set when the workqueue_entry_t is created, and won't be cleared until
  51. * after it's handled in the main thread. */
  52. struct threadpool_s *on_pool;
  53. /** True iff this entry is waiting for a worker to start processing it. */
  54. uint8_t pending;
  55. /** Function to run in the worker thread. */
  56. workqueue_reply_t (*fn)(void *state, void *arg);
  57. /** Function to run while processing the reply queue. */
  58. void (*reply_fn)(void *arg);
  59. /** Argument for the above functions. */
  60. void *arg;
  61. };
  62. struct replyqueue_s {
  63. /** Mutex to protect the answers field */
  64. tor_mutex_t lock;
  65. /** Doubly-linked list of answers that the reply queue needs to handle. */
  66. TOR_TAILQ_HEAD(, workqueue_entry_s) answers;
  67. /** Mechanism to wake up the main thread when it is receiving answers. */
  68. alert_sockets_t alert;
  69. };
  70. /** A worker thread represents a single thread in a thread pool. To avoid
  71. * contention, each gets its own queue. This breaks the guarantee that that
  72. * queued work will get executed strictly in order. */
  73. typedef struct workerthread_s {
  74. /** Which thread it this? In range 0..in_pool->n_threads-1 */
  75. int index;
  76. /** The pool this thread is a part of. */
  77. struct threadpool_s *in_pool;
  78. /** User-supplied state field that we pass to the worker functions of each
  79. * work item. */
  80. void *state;
  81. /** Reply queue to which we pass our results. */
  82. replyqueue_t *reply_queue;
  83. /** The current update generation of this thread */
  84. unsigned generation;
  85. } workerthread_t;
  86. static void queue_reply(replyqueue_t *queue, workqueue_entry_t *work);
  87. /** Allocate and return a new workqueue_entry_t, set up to run the function
  88. * <b>fn</b> in the worker thread, and <b>reply_fn</b> in the main
  89. * thread. See threadpool_queue_work() for full documentation. */
  90. static workqueue_entry_t *
  91. workqueue_entry_new(workqueue_reply_t (*fn)(void*, void*),
  92. void (*reply_fn)(void*),
  93. void *arg)
  94. {
  95. workqueue_entry_t *ent = tor_malloc_zero(sizeof(workqueue_entry_t));
  96. ent->fn = fn;
  97. ent->reply_fn = reply_fn;
  98. ent->arg = arg;
  99. return ent;
  100. }
  101. /**
  102. * Release all storage held in <b>ent</b>. Call only when <b>ent</b> is not on
  103. * any queue.
  104. */
  105. static void
  106. workqueue_entry_free(workqueue_entry_t *ent)
  107. {
  108. if (!ent)
  109. return;
  110. memset(ent, 0xf0, sizeof(*ent));
  111. tor_free(ent);
  112. }
  113. /**
  114. * Cancel a workqueue_entry_t that has been returned from
  115. * threadpool_queue_work.
  116. *
  117. * You must not call this function on any work whose reply function has been
  118. * executed in the main thread; that will cause undefined behavior (probably,
  119. * a crash).
  120. *
  121. * If the work is cancelled, this function return the argument passed to the
  122. * work function. It is the caller's responsibility to free this storage.
  123. *
  124. * This function will have no effect if the worker thread has already executed
  125. * or begun to execute the work item. In that case, it will return NULL.
  126. */
  127. void *
  128. workqueue_entry_cancel(workqueue_entry_t *ent)
  129. {
  130. int cancelled = 0;
  131. void *result = NULL;
  132. tor_mutex_acquire(&ent->on_pool->lock);
  133. if (ent->pending) {
  134. TOR_TAILQ_REMOVE(&ent->on_pool->work, ent, next_work);
  135. cancelled = 1;
  136. result = ent->arg;
  137. }
  138. tor_mutex_release(&ent->on_pool->lock);
  139. if (cancelled) {
  140. workqueue_entry_free(ent);
  141. }
  142. return result;
  143. }
  144. /**DOCDOC
  145. must hold lock */
  146. static int
  147. worker_thread_has_work(workerthread_t *thread)
  148. {
  149. return !TOR_TAILQ_EMPTY(&thread->in_pool->work) ||
  150. thread->generation != thread->in_pool->generation;
  151. }
  152. /**
  153. * Main function for the worker thread.
  154. */
  155. static void
  156. worker_thread_main(void *thread_)
  157. {
  158. workerthread_t *thread = thread_;
  159. threadpool_t *pool = thread->in_pool;
  160. workqueue_entry_t *work;
  161. workqueue_reply_t result;
  162. tor_mutex_acquire(&pool->lock);
  163. while (1) {
  164. /* lock must be held at this point. */
  165. while (worker_thread_has_work(thread)) {
  166. /* lock must be held at this point. */
  167. if (thread->in_pool->generation != thread->generation) {
  168. void *arg = thread->in_pool->update_args[thread->index];
  169. thread->in_pool->update_args[thread->index] = NULL;
  170. workqueue_reply_t (*update_fn)(void*,void*) =
  171. thread->in_pool->update_fn;
  172. thread->generation = thread->in_pool->generation;
  173. tor_mutex_release(&pool->lock);
  174. workqueue_reply_t r = update_fn(thread->state, arg);
  175. if (r != WQ_RPL_REPLY) {
  176. return;
  177. }
  178. tor_mutex_acquire(&pool->lock);
  179. continue;
  180. }
  181. work = TOR_TAILQ_FIRST(&pool->work);
  182. TOR_TAILQ_REMOVE(&pool->work, work, next_work);
  183. work->pending = 0;
  184. tor_mutex_release(&pool->lock);
  185. /* We run the work function without holding the thread lock. This
  186. * is the main thread's first opportunity to give us more work. */
  187. result = work->fn(thread->state, work->arg);
  188. /* Queue the reply for the main thread. */
  189. queue_reply(thread->reply_queue, work);
  190. /* We may need to exit the thread. */
  191. if (result != WQ_RPL_REPLY) {
  192. return;
  193. }
  194. tor_mutex_acquire(&pool->lock);
  195. }
  196. /* At this point the lock is held, and there is no work in this thread's
  197. * queue. */
  198. /* TODO: support an idle-function */
  199. /* Okay. Now, wait till somebody has work for us. */
  200. if (tor_cond_wait(&pool->condition, &pool->lock, NULL) < 0) {
  201. log_warn(LD_GENERAL, "Fail tor_cond_wait.");
  202. }
  203. }
  204. }
  205. /** Put a reply on the reply queue. The reply must not currently be on
  206. * any thread's work queue. */
  207. static void
  208. queue_reply(replyqueue_t *queue, workqueue_entry_t *work)
  209. {
  210. int was_empty;
  211. tor_mutex_acquire(&queue->lock);
  212. was_empty = TOR_TAILQ_EMPTY(&queue->answers);
  213. TOR_TAILQ_INSERT_TAIL(&queue->answers, work, next_work);
  214. tor_mutex_release(&queue->lock);
  215. if (was_empty) {
  216. if (queue->alert.alert_fn(queue->alert.write_fd) < 0) {
  217. /* XXXX complain! */
  218. }
  219. }
  220. }
  221. /** Allocate and start a new worker thread to use state object <b>state</b>,
  222. * and send responses to <b>replyqueue</b>. */
  223. static workerthread_t *
  224. workerthread_new(void *state, threadpool_t *pool, replyqueue_t *replyqueue)
  225. {
  226. workerthread_t *thr = tor_malloc_zero(sizeof(workerthread_t));
  227. thr->state = state;
  228. thr->reply_queue = replyqueue;
  229. thr->in_pool = pool;
  230. if (spawn_func(worker_thread_main, thr) < 0) {
  231. //LCOV_EXCL_START
  232. tor_assert_nonfatal_unreached();
  233. log_err(LD_GENERAL, "Can't launch worker thread.");
  234. tor_free(thr);
  235. return NULL;
  236. //LCOV_EXCL_STOP
  237. }
  238. return thr;
  239. }
  240. /**
  241. * Queue an item of work for a thread in a thread pool. The function
  242. * <b>fn</b> will be run in a worker thread, and will receive as arguments the
  243. * thread's state object, and the provided object <b>arg</b>. It must return
  244. * one of WQ_RPL_REPLY, WQ_RPL_ERROR, or WQ_RPL_SHUTDOWN.
  245. *
  246. * Regardless of its return value, the function <b>reply_fn</b> will later be
  247. * run in the main thread when it invokes replyqueue_process(), and will
  248. * receive as its argument the same <b>arg</b> object. It's the reply
  249. * function's responsibility to free the work object.
  250. *
  251. * On success, return a workqueue_entry_t object that can be passed to
  252. * workqueue_entry_cancel(). On failure, return NULL.
  253. *
  254. * Note that because each thread has its own work queue, work items may not
  255. * be executed strictly in order.
  256. */
  257. workqueue_entry_t *
  258. threadpool_queue_work(threadpool_t *pool,
  259. workqueue_reply_t (*fn)(void *, void *),
  260. void (*reply_fn)(void *),
  261. void *arg)
  262. {
  263. workqueue_entry_t *ent = workqueue_entry_new(fn, reply_fn, arg);
  264. ent->on_pool = pool;
  265. ent->pending = 1;
  266. tor_mutex_acquire(&pool->lock);
  267. TOR_TAILQ_INSERT_TAIL(&pool->work, ent, next_work);
  268. tor_cond_signal_one(&pool->condition);
  269. tor_mutex_release(&pool->lock);
  270. return ent;
  271. }
  272. /**
  273. * Queue a copy of a work item for every thread in a pool. This can be used,
  274. * for example, to tell the threads to update some parameter in their states.
  275. *
  276. * Arguments are as for <b>threadpool_queue_work</b>, except that the
  277. * <b>arg</b> value is passed to <b>dup_fn</b> once per each thread to
  278. * make a copy of it.
  279. *
  280. * UPDATE FUNCTIONS MUST BE IDEMPOTENT. We do not guarantee that every update
  281. * will be run. If a new update is scheduled before the old update finishes
  282. * running, then the new will replace the old in any threads that haven't run
  283. * it yet.
  284. *
  285. * Return 0 on success, -1 on failure.
  286. */
  287. int
  288. threadpool_queue_update(threadpool_t *pool,
  289. void *(*dup_fn)(void *),
  290. workqueue_reply_t (*fn)(void *, void *),
  291. void (*free_fn)(void *),
  292. void *arg)
  293. {
  294. int i, n_threads;
  295. void (*old_args_free_fn)(void *arg);
  296. void **old_args;
  297. void **new_args;
  298. tor_mutex_acquire(&pool->lock);
  299. n_threads = pool->n_threads;
  300. old_args = pool->update_args;
  301. old_args_free_fn = pool->free_update_arg_fn;
  302. new_args = tor_calloc(n_threads, sizeof(void*));
  303. for (i = 0; i < n_threads; ++i) {
  304. if (dup_fn)
  305. new_args[i] = dup_fn(arg);
  306. else
  307. new_args[i] = arg;
  308. }
  309. pool->update_args = new_args;
  310. pool->free_update_arg_fn = free_fn;
  311. pool->update_fn = fn;
  312. ++pool->generation;
  313. tor_cond_signal_all(&pool->condition);
  314. tor_mutex_release(&pool->lock);
  315. if (old_args) {
  316. for (i = 0; i < n_threads; ++i) {
  317. if (old_args[i] && old_args_free_fn)
  318. old_args_free_fn(old_args[i]);
  319. }
  320. tor_free(old_args);
  321. }
  322. return 0;
  323. }
  324. /** Don't have more than this many threads per pool. */
  325. #define MAX_THREADS 1024
  326. /** Launch threads until we have <b>n</b>. */
  327. static int
  328. threadpool_start_threads(threadpool_t *pool, int n)
  329. {
  330. if (BUG(n < 0))
  331. return -1; // LCOV_EXCL_LINE
  332. if (n > MAX_THREADS)
  333. n = MAX_THREADS;
  334. tor_mutex_acquire(&pool->lock);
  335. if (pool->n_threads < n)
  336. pool->threads = tor_reallocarray(pool->threads,
  337. sizeof(workerthread_t*), n);
  338. while (pool->n_threads < n) {
  339. void *state = pool->new_thread_state_fn(pool->new_thread_state_arg);
  340. workerthread_t *thr = workerthread_new(state, pool, pool->reply_queue);
  341. if (!thr) {
  342. //LCOV_EXCL_START
  343. tor_assert_nonfatal_unreached();
  344. pool->free_thread_state_fn(state);
  345. tor_mutex_release(&pool->lock);
  346. return -1;
  347. //LCOV_EXCL_STOP
  348. }
  349. thr->index = pool->n_threads;
  350. pool->threads[pool->n_threads++] = thr;
  351. }
  352. tor_mutex_release(&pool->lock);
  353. return 0;
  354. }
  355. /**
  356. * Construct a new thread pool with <b>n</b> worker threads, configured to
  357. * send their output to <b>replyqueue</b>. The threads' states will be
  358. * constructed with the <b>new_thread_state_fn</b> call, receiving <b>arg</b>
  359. * as its argument. When the threads close, they will call
  360. * <b>free_thread_state_fn</b> on their states.
  361. */
  362. threadpool_t *
  363. threadpool_new(int n_threads,
  364. replyqueue_t *replyqueue,
  365. void *(*new_thread_state_fn)(void*),
  366. void (*free_thread_state_fn)(void*),
  367. void *arg)
  368. {
  369. threadpool_t *pool;
  370. pool = tor_malloc_zero(sizeof(threadpool_t));
  371. tor_mutex_init_nonrecursive(&pool->lock);
  372. tor_cond_init(&pool->condition);
  373. TOR_TAILQ_INIT(&pool->work);
  374. pool->new_thread_state_fn = new_thread_state_fn;
  375. pool->new_thread_state_arg = arg;
  376. pool->free_thread_state_fn = free_thread_state_fn;
  377. pool->reply_queue = replyqueue;
  378. if (threadpool_start_threads(pool, n_threads) < 0) {
  379. //LCOV_EXCL_START
  380. tor_assert_nonfatal_unreached();
  381. tor_cond_uninit(&pool->condition);
  382. tor_mutex_uninit(&pool->lock);
  383. tor_free(pool);
  384. return NULL;
  385. //LCOV_EXCL_STOP
  386. }
  387. return pool;
  388. }
  389. /** Return the reply queue associated with a given thread pool. */
  390. replyqueue_t *
  391. threadpool_get_replyqueue(threadpool_t *tp)
  392. {
  393. return tp->reply_queue;
  394. }
  395. /** Allocate a new reply queue. Reply queues are used to pass results from
  396. * worker threads to the main thread. Since the main thread is running an
  397. * IO-centric event loop, it needs to get woken up with means other than a
  398. * condition variable. */
  399. replyqueue_t *
  400. replyqueue_new(uint32_t alertsocks_flags)
  401. {
  402. replyqueue_t *rq;
  403. rq = tor_malloc_zero(sizeof(replyqueue_t));
  404. if (alert_sockets_create(&rq->alert, alertsocks_flags) < 0) {
  405. //LCOV_EXCL_START
  406. tor_free(rq);
  407. return NULL;
  408. //LCOV_EXCL_STOP
  409. }
  410. tor_mutex_init(&rq->lock);
  411. TOR_TAILQ_INIT(&rq->answers);
  412. return rq;
  413. }
  414. /**
  415. * Return the "read socket" for a given reply queue. The main thread should
  416. * listen for read events on this socket, and call replyqueue_process() every
  417. * time it triggers.
  418. */
  419. tor_socket_t
  420. replyqueue_get_socket(replyqueue_t *rq)
  421. {
  422. return rq->alert.read_fd;
  423. }
  424. /**
  425. * Process all pending replies on a reply queue. The main thread should call
  426. * this function every time the socket returned by replyqueue_get_socket() is
  427. * readable.
  428. */
  429. void
  430. replyqueue_process(replyqueue_t *queue)
  431. {
  432. if (queue->alert.drain_fn(queue->alert.read_fd) < 0) {
  433. //LCOV_EXCL_START
  434. static ratelim_t warn_limit = RATELIM_INIT(7200);
  435. log_fn_ratelim(&warn_limit, LOG_WARN, LD_GENERAL,
  436. "Failure from drain_fd: %s",
  437. tor_socket_strerror(tor_socket_errno(queue->alert.read_fd)));
  438. //LCOV_EXCL_STOP
  439. }
  440. tor_mutex_acquire(&queue->lock);
  441. while (!TOR_TAILQ_EMPTY(&queue->answers)) {
  442. /* lock must be held at this point.*/
  443. workqueue_entry_t *work = TOR_TAILQ_FIRST(&queue->answers);
  444. TOR_TAILQ_REMOVE(&queue->answers, work, next_work);
  445. tor_mutex_release(&queue->lock);
  446. work->on_pool = NULL;
  447. work->reply_fn(work->arg);
  448. workqueue_entry_free(work);
  449. tor_mutex_acquire(&queue->lock);
  450. }
  451. tor_mutex_release(&queue->lock);
  452. }