workqueue.c 13 KB

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