workqueue.c 14 KB

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