workqueue.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. /** True iff this thread is currently in its loop. (Not currently used.) */
  73. unsigned is_running;
  74. /** True iff this thread has crashed or is shut down for some reason. (Not
  75. * currently used.) */
  76. unsigned is_shut_down;
  77. /** True if we're waiting for more elements to get added to the queue. */
  78. unsigned waiting;
  79. /** User-supplied state field that we pass to the worker functions of each
  80. * work item. */
  81. void *state;
  82. /** Reply queue to which we pass our results. */
  83. replyqueue_t *reply_queue;
  84. /** The current update generation of this thread */
  85. unsigned generation;
  86. } workerthread_t;
  87. static void queue_reply(replyqueue_t *queue, workqueue_entry_t *work);
  88. /** Allocate and return a new workqueue_entry_t, set up to run the function
  89. * <b>fn</b> in the worker thread, and <b>reply_fn</b> in the main
  90. * thread. See threadpool_queue_work() for full documentation. */
  91. static workqueue_entry_t *
  92. workqueue_entry_new(int (*fn)(void*, void*),
  93. void (*reply_fn)(void*),
  94. void *arg)
  95. {
  96. workqueue_entry_t *ent = tor_malloc_zero(sizeof(workqueue_entry_t));
  97. ent->fn = fn;
  98. ent->reply_fn = reply_fn;
  99. ent->arg = arg;
  100. return ent;
  101. }
  102. /**
  103. * Release all storage held in <b>ent</b>. Call only when <b>ent</b> is not on
  104. * any queue.
  105. */
  106. static void
  107. workqueue_entry_free(workqueue_entry_t *ent)
  108. {
  109. if (!ent)
  110. return;
  111. memset(ent, 0xf0, sizeof(*ent));
  112. tor_free(ent);
  113. }
  114. /**
  115. * Cancel a workqueue_entry_t that has been returned from
  116. * threadpool_queue_work.
  117. *
  118. * You must not call this function on any work whose reply function has been
  119. * executed in the main thread; that will cause undefined behavior (probably,
  120. * a crash).
  121. *
  122. * If the work is cancelled, this function return the argument passed to the
  123. * work function. It is the caller's responsibility to free this storage.
  124. *
  125. * This function will have no effect if the worker thread has already executed
  126. * or begun to execute the work item. In that case, it will return NULL.
  127. */
  128. void *
  129. workqueue_entry_cancel(workqueue_entry_t *ent)
  130. {
  131. int cancelled = 0;
  132. void *result = NULL;
  133. tor_mutex_acquire(&ent->on_pool->lock);
  134. if (ent->pending) {
  135. TOR_TAILQ_REMOVE(&ent->on_pool->work, ent, next_work);
  136. cancelled = 1;
  137. result = ent->arg;
  138. }
  139. tor_mutex_release(&ent->on_pool->lock);
  140. if (cancelled) {
  141. tor_free(ent);
  142. }
  143. return result;
  144. }
  145. /**DOCDOC
  146. must hold lock */
  147. static int
  148. worker_thread_has_work(workerthread_t *thread)
  149. {
  150. return !TOR_TAILQ_EMPTY(&thread->in_pool->work) ||
  151. thread->generation != thread->in_pool->generation;
  152. }
  153. /**
  154. * Main function for the worker thread.
  155. */
  156. static void
  157. worker_thread_main(void *thread_)
  158. {
  159. workerthread_t *thread = thread_;
  160. threadpool_t *pool = thread->in_pool;
  161. workqueue_entry_t *work;
  162. int result;
  163. thread->is_running = 1;
  164. tor_mutex_acquire(&pool->lock);
  165. while (1) {
  166. /* lock must be held at this point. */
  167. while (worker_thread_has_work(thread)) {
  168. /* lock must be held at this point. */
  169. if (thread->in_pool->generation != thread->generation) {
  170. void *arg = thread->in_pool->update_args[thread->index];
  171. thread->in_pool->update_args[thread->index] = NULL;
  172. int (*update_fn)(void*,void*) = thread->in_pool->update_fn;
  173. thread->generation = thread->in_pool->generation;
  174. tor_mutex_release(&pool->lock);
  175. int r = update_fn(thread->state, arg);
  176. if (r < 0) {
  177. thread->is_running = 0;
  178. thread->is_shut_down = 1;
  179. return;
  180. }
  181. tor_mutex_acquire(&pool->lock);
  182. continue;
  183. }
  184. work = TOR_TAILQ_FIRST(&pool->work);
  185. TOR_TAILQ_REMOVE(&pool->work, work, next_work);
  186. work->pending = 0;
  187. tor_mutex_release(&pool->lock);
  188. /* We run the work function without holding the thread lock. This
  189. * is the main thread's first opportunity to give us more work. */
  190. result = work->fn(thread->state, work->arg);
  191. /* Queue the reply for the main thread. */
  192. queue_reply(thread->reply_queue, work);
  193. /* We may need to exit the thread. */
  194. if (result >= WQ_RPL_ERROR) {
  195. thread->is_running = 0;
  196. thread->is_shut_down = 1;
  197. return;
  198. }
  199. tor_mutex_acquire(&pool->lock);
  200. }
  201. /* At this point the lock is held, and there is no work in this thread's
  202. * queue. */
  203. /* TODO: support an idle-function */
  204. /* Okay. Now, wait till somebody has work for us. */
  205. /* XXXX we could just omit waiting and instead */
  206. thread->waiting = 1;
  207. if (tor_cond_wait(&pool->condition, &pool->lock, NULL) < 0) {
  208. /* XXXX ERROR */
  209. }
  210. thread->waiting = 0;
  211. }
  212. }
  213. /** Put a reply on the reply queue. The reply must not currently be on
  214. * any thread's work queue. */
  215. static void
  216. queue_reply(replyqueue_t *queue, workqueue_entry_t *work)
  217. {
  218. int was_empty;
  219. tor_mutex_acquire(&queue->lock);
  220. was_empty = TOR_TAILQ_EMPTY(&queue->answers);
  221. TOR_TAILQ_INSERT_TAIL(&queue->answers, work, next_work);
  222. tor_mutex_release(&queue->lock);
  223. if (was_empty) {
  224. if (queue->alert.alert_fn(queue->alert.write_fd) < 0) {
  225. /* XXXX complain! */
  226. }
  227. }
  228. }
  229. /** Allocate and start a new worker thread to use state object <b>state</b>,
  230. * and send responses to <b>replyqueue</b>. */
  231. static workerthread_t *
  232. workerthread_new(void *state, threadpool_t *pool, replyqueue_t *replyqueue)
  233. {
  234. workerthread_t *thr = tor_malloc_zero(sizeof(workerthread_t));
  235. thr->state = state;
  236. thr->reply_queue = replyqueue;
  237. thr->in_pool = pool;
  238. if (spawn_func(worker_thread_main, thr) < 0) {
  239. log_err(LD_GENERAL, "Can't launch worker thread.");
  240. return NULL;
  241. }
  242. return thr;
  243. }
  244. /**
  245. * Queue an item of work for a thread in a thread pool. The function
  246. * <b>fn</b> will be run in a worker thread, and will receive as arguments the
  247. * thread's state object, and the provided object <b>arg</b>. It must return
  248. * one of WQ_RPL_REPLY, WQ_RPL_ERROR, or WQ_RPL_SHUTDOWN.
  249. *
  250. * Regardless of its return value, the function <b>reply_fn</b> will later be
  251. * run in the main thread when it invokes replyqueue_process(), and will
  252. * receive as its argument the same <b>arg</b> object. It's the reply
  253. * function's responsibility to free the work object.
  254. *
  255. * On success, return a workqueue_entry_t object that can be passed to
  256. * workqueue_entry_cancel(). On failure, return NULL.
  257. *
  258. * Note that because each thread has its own work queue, work items may not
  259. * be executed strictly in order.
  260. */
  261. workqueue_entry_t *
  262. threadpool_queue_work(threadpool_t *pool,
  263. int (*fn)(void *, void *),
  264. void (*reply_fn)(void *),
  265. void *arg)
  266. {
  267. workqueue_entry_t *ent = workqueue_entry_new(fn, reply_fn, arg);
  268. ent->on_pool = pool;
  269. ent->pending = 1;
  270. tor_mutex_acquire(&pool->lock);
  271. TOR_TAILQ_INSERT_TAIL(&pool->work, ent, next_work);
  272. tor_mutex_release(&pool->lock);
  273. tor_cond_signal_one(&pool->condition);
  274. return ent;
  275. }
  276. /**
  277. * Queue a copy of a work item for every thread in a pool. This can be used,
  278. * for example, to tell the threads to update some parameter in their states.
  279. *
  280. * Arguments are as for <b>threadpool_queue_work</b>, except that the
  281. * <b>arg</b> value is passed to <b>dup_fn</b> once per each thread to
  282. * make a copy of it.
  283. *
  284. * UPDATE FUNCTIONS MUST BE IDEMPOTENT. We do not guarantee that every update
  285. * will be run. If a new update is scheduled before the old update finishes
  286. * running, then the new will replace the old in any threads that haven't run
  287. * it yet.
  288. *
  289. * Return 0 on success, -1 on failure.
  290. */
  291. int
  292. threadpool_queue_update(threadpool_t *pool,
  293. void *(*dup_fn)(void *),
  294. int (*fn)(void *, void *),
  295. void (*free_fn)(void *),
  296. void *arg)
  297. {
  298. int i, n_threads;
  299. void (*old_args_free_fn)(void *arg);
  300. void **old_args;
  301. void **new_args;
  302. tor_mutex_acquire(&pool->lock);
  303. n_threads = pool->n_threads;
  304. old_args = pool->update_args;
  305. old_args_free_fn = pool->free_update_arg_fn;
  306. new_args = tor_calloc(n_threads, sizeof(void*));
  307. for (i = 0; i < n_threads; ++i) {
  308. if (dup_fn)
  309. new_args[i] = dup_fn(arg);
  310. else
  311. new_args[i] = arg;
  312. }
  313. pool->update_args = new_args;
  314. pool->free_update_arg_fn = free_fn;
  315. pool->update_fn = fn;
  316. ++pool->generation;
  317. tor_mutex_release(&pool->lock);
  318. tor_cond_signal_all(&pool->condition);
  319. if (old_args) {
  320. for (i = 0; i < n_threads; ++i) {
  321. if (old_args[i] && old_args_free_fn)
  322. old_args_free_fn(old_args[i]);
  323. }
  324. tor_free(old_args);
  325. }
  326. return 0;
  327. }
  328. /** Launch threads until we have <b>n</b>. */
  329. static int
  330. threadpool_start_threads(threadpool_t *pool, int n)
  331. {
  332. tor_mutex_acquire(&pool->lock);
  333. if (pool->n_threads < n)
  334. pool->threads = tor_realloc(pool->threads, 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. thr->index = pool->n_threads;
  339. if (!thr) {
  340. tor_mutex_release(&pool->lock);
  341. return -1;
  342. }
  343. pool->threads[pool->n_threads++] = thr;
  344. }
  345. tor_mutex_release(&pool->lock);
  346. return 0;
  347. }
  348. /**
  349. * Construct a new thread pool with <b>n</b> worker threads, configured to
  350. * send their output to <b>replyqueue</b>. The threads' states will be
  351. * constructed with the <b>new_thread_state_fn</b> call, receiving <b>arg</b>
  352. * as its argument. When the threads close, they will call
  353. * <b>free_thread_state_fn</b> on their states.
  354. */
  355. threadpool_t *
  356. threadpool_new(int n_threads,
  357. replyqueue_t *replyqueue,
  358. void *(*new_thread_state_fn)(void*),
  359. void (*free_thread_state_fn)(void*),
  360. void *arg)
  361. {
  362. threadpool_t *pool;
  363. pool = tor_malloc_zero(sizeof(threadpool_t));
  364. tor_mutex_init_nonrecursive(&pool->lock);
  365. tor_cond_init(&pool->condition);
  366. TOR_TAILQ_INIT(&pool->work);
  367. pool->new_thread_state_fn = new_thread_state_fn;
  368. pool->new_thread_state_arg = arg;
  369. pool->free_thread_state_fn = free_thread_state_fn;
  370. pool->reply_queue = replyqueue;
  371. if (threadpool_start_threads(pool, n_threads) < 0) {
  372. tor_mutex_uninit(&pool->lock);
  373. tor_free(pool);
  374. return NULL;
  375. }
  376. return pool;
  377. }
  378. /** Return the reply queue associated with a given thread pool. */
  379. replyqueue_t *
  380. threadpool_get_replyqueue(threadpool_t *tp)
  381. {
  382. return tp->reply_queue;
  383. }
  384. /** Allocate a new reply queue. Reply queues are used to pass results from
  385. * worker threads to the main thread. Since the main thread is running an
  386. * IO-centric event loop, it needs to get woken up with means other than a
  387. * condition variable. */
  388. replyqueue_t *
  389. replyqueue_new(uint32_t alertsocks_flags)
  390. {
  391. replyqueue_t *rq;
  392. rq = tor_malloc_zero(sizeof(replyqueue_t));
  393. if (alert_sockets_create(&rq->alert, alertsocks_flags) < 0) {
  394. tor_free(rq);
  395. return NULL;
  396. }
  397. tor_mutex_init(&rq->lock);
  398. TOR_TAILQ_INIT(&rq->answers);
  399. return rq;
  400. }
  401. /**
  402. * Return the "read socket" for a given reply queue. The main thread should
  403. * listen for read events on this socket, and call replyqueue_process() every
  404. * time it triggers.
  405. */
  406. tor_socket_t
  407. replyqueue_get_socket(replyqueue_t *rq)
  408. {
  409. return rq->alert.read_fd;
  410. }
  411. /**
  412. * Process all pending replies on a reply queue. The main thread should call
  413. * this function every time the socket returned by replyqueue_get_socket() is
  414. * readable.
  415. */
  416. void
  417. replyqueue_process(replyqueue_t *queue)
  418. {
  419. if (queue->alert.drain_fn(queue->alert.read_fd) < 0) {
  420. /* XXXX complain! */
  421. }
  422. tor_mutex_acquire(&queue->lock);
  423. while (!TOR_TAILQ_EMPTY(&queue->answers)) {
  424. /* lock must be held at this point.*/
  425. workqueue_entry_t *work = TOR_TAILQ_FIRST(&queue->answers);
  426. TOR_TAILQ_REMOVE(&queue->answers, work, next_work);
  427. tor_mutex_release(&queue->lock);
  428. work->on_pool = NULL;
  429. work->reply_fn(work->arg);
  430. workqueue_entry_free(work);
  431. tor_mutex_acquire(&queue->lock);
  432. }
  433. tor_mutex_release(&queue->lock);
  434. }