workqueue.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. log_err(LD_GENERAL, "Can't launch worker thread.");
  232. tor_free(thr);
  233. return NULL;
  234. }
  235. return thr;
  236. }
  237. /**
  238. * Queue an item of work for a thread in a thread pool. The function
  239. * <b>fn</b> will be run in a worker thread, and will receive as arguments the
  240. * thread's state object, and the provided object <b>arg</b>. It must return
  241. * one of WQ_RPL_REPLY, WQ_RPL_ERROR, or WQ_RPL_SHUTDOWN.
  242. *
  243. * Regardless of its return value, the function <b>reply_fn</b> will later be
  244. * run in the main thread when it invokes replyqueue_process(), and will
  245. * receive as its argument the same <b>arg</b> object. It's the reply
  246. * function's responsibility to free the work object.
  247. *
  248. * On success, return a workqueue_entry_t object that can be passed to
  249. * workqueue_entry_cancel(). On failure, return NULL.
  250. *
  251. * Note that because each thread has its own work queue, work items may not
  252. * be executed strictly in order.
  253. */
  254. workqueue_entry_t *
  255. threadpool_queue_work(threadpool_t *pool,
  256. workqueue_reply_t (*fn)(void *, void *),
  257. void (*reply_fn)(void *),
  258. void *arg)
  259. {
  260. workqueue_entry_t *ent = workqueue_entry_new(fn, reply_fn, arg);
  261. ent->on_pool = pool;
  262. ent->pending = 1;
  263. tor_mutex_acquire(&pool->lock);
  264. TOR_TAILQ_INSERT_TAIL(&pool->work, ent, next_work);
  265. tor_cond_signal_one(&pool->condition);
  266. tor_mutex_release(&pool->lock);
  267. return ent;
  268. }
  269. /**
  270. * Queue a copy of a work item for every thread in a pool. This can be used,
  271. * for example, to tell the threads to update some parameter in their states.
  272. *
  273. * Arguments are as for <b>threadpool_queue_work</b>, except that the
  274. * <b>arg</b> value is passed to <b>dup_fn</b> once per each thread to
  275. * make a copy of it.
  276. *
  277. * UPDATE FUNCTIONS MUST BE IDEMPOTENT. We do not guarantee that every update
  278. * will be run. If a new update is scheduled before the old update finishes
  279. * running, then the new will replace the old in any threads that haven't run
  280. * it yet.
  281. *
  282. * Return 0 on success, -1 on failure.
  283. */
  284. int
  285. threadpool_queue_update(threadpool_t *pool,
  286. void *(*dup_fn)(void *),
  287. workqueue_reply_t (*fn)(void *, void *),
  288. void (*free_fn)(void *),
  289. void *arg)
  290. {
  291. int i, n_threads;
  292. void (*old_args_free_fn)(void *arg);
  293. void **old_args;
  294. void **new_args;
  295. tor_mutex_acquire(&pool->lock);
  296. n_threads = pool->n_threads;
  297. old_args = pool->update_args;
  298. old_args_free_fn = pool->free_update_arg_fn;
  299. new_args = tor_calloc(n_threads, sizeof(void*));
  300. for (i = 0; i < n_threads; ++i) {
  301. if (dup_fn)
  302. new_args[i] = dup_fn(arg);
  303. else
  304. new_args[i] = arg;
  305. }
  306. pool->update_args = new_args;
  307. pool->free_update_arg_fn = free_fn;
  308. pool->update_fn = fn;
  309. ++pool->generation;
  310. tor_cond_signal_all(&pool->condition);
  311. tor_mutex_release(&pool->lock);
  312. if (old_args) {
  313. for (i = 0; i < n_threads; ++i) {
  314. if (old_args[i] && old_args_free_fn)
  315. old_args_free_fn(old_args[i]);
  316. }
  317. tor_free(old_args);
  318. }
  319. return 0;
  320. }
  321. /** Don't have more than this many threads per pool. */
  322. #define MAX_THREADS 1024
  323. /** Launch threads until we have <b>n</b>. */
  324. static int
  325. threadpool_start_threads(threadpool_t *pool, int n)
  326. {
  327. if (n < 0)
  328. return -1;
  329. if (n > MAX_THREADS)
  330. n = MAX_THREADS;
  331. tor_mutex_acquire(&pool->lock);
  332. if (pool->n_threads < n)
  333. pool->threads = tor_reallocarray(pool->threads,
  334. sizeof(workerthread_t*), n);
  335. while (pool->n_threads < n) {
  336. void *state = pool->new_thread_state_fn(pool->new_thread_state_arg);
  337. workerthread_t *thr = workerthread_new(state, pool, pool->reply_queue);
  338. if (!thr) {
  339. pool->free_thread_state_fn(state);
  340. tor_mutex_release(&pool->lock);
  341. return -1;
  342. }
  343. thr->index = pool->n_threads;
  344. pool->threads[pool->n_threads++] = thr;
  345. }
  346. tor_mutex_release(&pool->lock);
  347. return 0;
  348. }
  349. /**
  350. * Construct a new thread pool with <b>n</b> worker threads, configured to
  351. * send their output to <b>replyqueue</b>. The threads' states will be
  352. * constructed with the <b>new_thread_state_fn</b> call, receiving <b>arg</b>
  353. * as its argument. When the threads close, they will call
  354. * <b>free_thread_state_fn</b> on their states.
  355. */
  356. threadpool_t *
  357. threadpool_new(int n_threads,
  358. replyqueue_t *replyqueue,
  359. void *(*new_thread_state_fn)(void*),
  360. void (*free_thread_state_fn)(void*),
  361. void *arg)
  362. {
  363. threadpool_t *pool;
  364. pool = tor_malloc_zero(sizeof(threadpool_t));
  365. tor_mutex_init_nonrecursive(&pool->lock);
  366. tor_cond_init(&pool->condition);
  367. TOR_TAILQ_INIT(&pool->work);
  368. pool->new_thread_state_fn = new_thread_state_fn;
  369. pool->new_thread_state_arg = arg;
  370. pool->free_thread_state_fn = free_thread_state_fn;
  371. pool->reply_queue = replyqueue;
  372. if (threadpool_start_threads(pool, n_threads) < 0) {
  373. tor_cond_uninit(&pool->condition);
  374. tor_mutex_uninit(&pool->lock);
  375. tor_free(pool);
  376. return NULL;
  377. }
  378. return pool;
  379. }
  380. /** Return the reply queue associated with a given thread pool. */
  381. replyqueue_t *
  382. threadpool_get_replyqueue(threadpool_t *tp)
  383. {
  384. return tp->reply_queue;
  385. }
  386. /** Allocate a new reply queue. Reply queues are used to pass results from
  387. * worker threads to the main thread. Since the main thread is running an
  388. * IO-centric event loop, it needs to get woken up with means other than a
  389. * condition variable. */
  390. replyqueue_t *
  391. replyqueue_new(uint32_t alertsocks_flags)
  392. {
  393. replyqueue_t *rq;
  394. rq = tor_malloc_zero(sizeof(replyqueue_t));
  395. if (alert_sockets_create(&rq->alert, alertsocks_flags) < 0) {
  396. tor_free(rq);
  397. return NULL;
  398. }
  399. tor_mutex_init(&rq->lock);
  400. TOR_TAILQ_INIT(&rq->answers);
  401. return rq;
  402. }
  403. /**
  404. * Return the "read socket" for a given reply queue. The main thread should
  405. * listen for read events on this socket, and call replyqueue_process() every
  406. * time it triggers.
  407. */
  408. tor_socket_t
  409. replyqueue_get_socket(replyqueue_t *rq)
  410. {
  411. return rq->alert.read_fd;
  412. }
  413. /**
  414. * Process all pending replies on a reply queue. The main thread should call
  415. * this function every time the socket returned by replyqueue_get_socket() is
  416. * readable.
  417. */
  418. void
  419. replyqueue_process(replyqueue_t *queue)
  420. {
  421. if (queue->alert.drain_fn(queue->alert.read_fd) < 0) {
  422. static ratelim_t warn_limit = RATELIM_INIT(7200);
  423. log_fn_ratelim(&warn_limit, LOG_WARN, LD_GENERAL,
  424. "Failure from drain_fd: %s",
  425. tor_socket_strerror(tor_socket_errno(queue->alert.read_fd)));
  426. }
  427. tor_mutex_acquire(&queue->lock);
  428. while (!TOR_TAILQ_EMPTY(&queue->answers)) {
  429. /* lock must be held at this point.*/
  430. workqueue_entry_t *work = TOR_TAILQ_FIRST(&queue->answers);
  431. TOR_TAILQ_REMOVE(&queue->answers, work, next_work);
  432. tor_mutex_release(&queue->lock);
  433. work->on_pool = NULL;
  434. work->reply_fn(work->arg);
  435. workqueue_entry_free(work);
  436. tor_mutex_acquire(&queue->lock);
  437. }
  438. tor_mutex_release(&queue->lock);
  439. }