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. workqueue_reply_t (*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. workqueue_reply_t (*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(workqueue_reply_t (*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. workqueue_reply_t 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. workqueue_reply_t (*update_fn)(void*,void*) =
  165. thread->in_pool->update_fn;
  166. thread->generation = thread->in_pool->generation;
  167. tor_mutex_release(&pool->lock);
  168. workqueue_reply_t r = update_fn(thread->state, arg);
  169. if (r != WQ_RPL_REPLY) {
  170. return;
  171. }
  172. tor_mutex_acquire(&pool->lock);
  173. continue;
  174. }
  175. work = TOR_TAILQ_FIRST(&pool->work);
  176. TOR_TAILQ_REMOVE(&pool->work, work, next_work);
  177. work->pending = 0;
  178. tor_mutex_release(&pool->lock);
  179. /* We run the work function without holding the thread lock. This
  180. * is the main thread's first opportunity to give us more work. */
  181. result = work->fn(thread->state, work->arg);
  182. /* Queue the reply for the main thread. */
  183. queue_reply(thread->reply_queue, work);
  184. /* We may need to exit the thread. */
  185. if (result != WQ_RPL_REPLY) {
  186. return;
  187. }
  188. tor_mutex_acquire(&pool->lock);
  189. }
  190. /* At this point the lock is held, and there is no work in this thread's
  191. * queue. */
  192. /* TODO: support an idle-function */
  193. /* Okay. Now, wait till somebody has work for us. */
  194. if (tor_cond_wait(&pool->condition, &pool->lock, NULL) < 0) {
  195. log_warn(LD_GENERAL, "Fail tor_cond_wait.");
  196. }
  197. }
  198. }
  199. /** Put a reply on the reply queue. The reply must not currently be on
  200. * any thread's work queue. */
  201. static void
  202. queue_reply(replyqueue_t *queue, workqueue_entry_t *work)
  203. {
  204. int was_empty;
  205. tor_mutex_acquire(&queue->lock);
  206. was_empty = TOR_TAILQ_EMPTY(&queue->answers);
  207. TOR_TAILQ_INSERT_TAIL(&queue->answers, work, next_work);
  208. tor_mutex_release(&queue->lock);
  209. if (was_empty) {
  210. if (queue->alert.alert_fn(queue->alert.write_fd) < 0) {
  211. /* XXXX complain! */
  212. }
  213. }
  214. }
  215. /** Allocate and start a new worker thread to use state object <b>state</b>,
  216. * and send responses to <b>replyqueue</b>. */
  217. static workerthread_t *
  218. workerthread_new(void *state, threadpool_t *pool, replyqueue_t *replyqueue)
  219. {
  220. workerthread_t *thr = tor_malloc_zero(sizeof(workerthread_t));
  221. thr->state = state;
  222. thr->reply_queue = replyqueue;
  223. thr->in_pool = pool;
  224. if (spawn_func(worker_thread_main, thr) < 0) {
  225. log_err(LD_GENERAL, "Can't launch worker thread.");
  226. tor_free(thr);
  227. return NULL;
  228. }
  229. return thr;
  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. workqueue_reply_t (*fn)(void *, void *),
  251. void (*reply_fn)(void *),
  252. void *arg)
  253. {
  254. workqueue_entry_t *ent = workqueue_entry_new(fn, reply_fn, arg);
  255. ent->on_pool = pool;
  256. ent->pending = 1;
  257. tor_mutex_acquire(&pool->lock);
  258. TOR_TAILQ_INSERT_TAIL(&pool->work, ent, next_work);
  259. tor_cond_signal_one(&pool->condition);
  260. tor_mutex_release(&pool->lock);
  261. return ent;
  262. }
  263. /**
  264. * Queue a copy of a work item for every thread in a pool. This can be used,
  265. * for example, to tell the threads to update some parameter in their states.
  266. *
  267. * Arguments are as for <b>threadpool_queue_work</b>, except that the
  268. * <b>arg</b> value is passed to <b>dup_fn</b> once per each thread to
  269. * make a copy of it.
  270. *
  271. * UPDATE FUNCTIONS MUST BE IDEMPOTENT. We do not guarantee that every update
  272. * will be run. If a new update is scheduled before the old update finishes
  273. * running, then the new will replace the old in any threads that haven't run
  274. * it yet.
  275. *
  276. * Return 0 on success, -1 on failure.
  277. */
  278. int
  279. threadpool_queue_update(threadpool_t *pool,
  280. void *(*dup_fn)(void *),
  281. workqueue_reply_t (*fn)(void *, void *),
  282. void (*free_fn)(void *),
  283. void *arg)
  284. {
  285. int i, n_threads;
  286. void (*old_args_free_fn)(void *arg);
  287. void **old_args;
  288. void **new_args;
  289. tor_mutex_acquire(&pool->lock);
  290. n_threads = pool->n_threads;
  291. old_args = pool->update_args;
  292. old_args_free_fn = pool->free_update_arg_fn;
  293. new_args = tor_calloc(n_threads, sizeof(void*));
  294. for (i = 0; i < n_threads; ++i) {
  295. if (dup_fn)
  296. new_args[i] = dup_fn(arg);
  297. else
  298. new_args[i] = arg;
  299. }
  300. pool->update_args = new_args;
  301. pool->free_update_arg_fn = free_fn;
  302. pool->update_fn = fn;
  303. ++pool->generation;
  304. tor_cond_signal_all(&pool->condition);
  305. tor_mutex_release(&pool->lock);
  306. if (old_args) {
  307. for (i = 0; i < n_threads; ++i) {
  308. if (old_args[i] && old_args_free_fn)
  309. old_args_free_fn(old_args[i]);
  310. }
  311. tor_free(old_args);
  312. }
  313. return 0;
  314. }
  315. /** Don't have more than this many threads per pool. */
  316. #define MAX_THREADS 1024
  317. /** Launch threads until we have <b>n</b>. */
  318. static int
  319. threadpool_start_threads(threadpool_t *pool, int n)
  320. {
  321. if (n < 0)
  322. return -1;
  323. if (n > MAX_THREADS)
  324. n = MAX_THREADS;
  325. tor_mutex_acquire(&pool->lock);
  326. if (pool->n_threads < n)
  327. pool->threads = tor_reallocarray(pool->threads,
  328. sizeof(workerthread_t*), n);
  329. while (pool->n_threads < n) {
  330. void *state = pool->new_thread_state_fn(pool->new_thread_state_arg);
  331. workerthread_t *thr = workerthread_new(state, pool, pool->reply_queue);
  332. if (!thr) {
  333. pool->free_thread_state_fn(state);
  334. tor_mutex_release(&pool->lock);
  335. return -1;
  336. }
  337. thr->index = pool->n_threads;
  338. pool->threads[pool->n_threads++] = thr;
  339. }
  340. tor_mutex_release(&pool->lock);
  341. return 0;
  342. }
  343. /**
  344. * Construct a new thread pool with <b>n</b> worker threads, configured to
  345. * send their output to <b>replyqueue</b>. The threads' states will be
  346. * constructed with the <b>new_thread_state_fn</b> call, receiving <b>arg</b>
  347. * as its argument. When the threads close, they will call
  348. * <b>free_thread_state_fn</b> on their states.
  349. */
  350. threadpool_t *
  351. threadpool_new(int n_threads,
  352. replyqueue_t *replyqueue,
  353. void *(*new_thread_state_fn)(void*),
  354. void (*free_thread_state_fn)(void*),
  355. void *arg)
  356. {
  357. threadpool_t *pool;
  358. pool = tor_malloc_zero(sizeof(threadpool_t));
  359. tor_mutex_init_nonrecursive(&pool->lock);
  360. tor_cond_init(&pool->condition);
  361. TOR_TAILQ_INIT(&pool->work);
  362. pool->new_thread_state_fn = new_thread_state_fn;
  363. pool->new_thread_state_arg = arg;
  364. pool->free_thread_state_fn = free_thread_state_fn;
  365. pool->reply_queue = replyqueue;
  366. if (threadpool_start_threads(pool, n_threads) < 0) {
  367. tor_cond_uninit(&pool->condition);
  368. tor_mutex_uninit(&pool->lock);
  369. tor_free(pool);
  370. return NULL;
  371. }
  372. return pool;
  373. }
  374. /** Return the reply queue associated with a given thread pool. */
  375. replyqueue_t *
  376. threadpool_get_replyqueue(threadpool_t *tp)
  377. {
  378. return tp->reply_queue;
  379. }
  380. /** Allocate a new reply queue. Reply queues are used to pass results from
  381. * worker threads to the main thread. Since the main thread is running an
  382. * IO-centric event loop, it needs to get woken up with means other than a
  383. * condition variable. */
  384. replyqueue_t *
  385. replyqueue_new(uint32_t alertsocks_flags)
  386. {
  387. replyqueue_t *rq;
  388. rq = tor_malloc_zero(sizeof(replyqueue_t));
  389. if (alert_sockets_create(&rq->alert, alertsocks_flags) < 0) {
  390. tor_free(rq);
  391. return NULL;
  392. }
  393. tor_mutex_init(&rq->lock);
  394. TOR_TAILQ_INIT(&rq->answers);
  395. return rq;
  396. }
  397. /**
  398. * Return the "read socket" for a given reply queue. The main thread should
  399. * listen for read events on this socket, and call replyqueue_process() every
  400. * time it triggers.
  401. */
  402. tor_socket_t
  403. replyqueue_get_socket(replyqueue_t *rq)
  404. {
  405. return rq->alert.read_fd;
  406. }
  407. /**
  408. * Process all pending replies on a reply queue. The main thread should call
  409. * this function every time the socket returned by replyqueue_get_socket() is
  410. * readable.
  411. */
  412. void
  413. replyqueue_process(replyqueue_t *queue)
  414. {
  415. if (queue->alert.drain_fn(queue->alert.read_fd) < 0) {
  416. static ratelim_t warn_limit = RATELIM_INIT(7200);
  417. log_fn_ratelim(&warn_limit, LOG_WARN, LD_GENERAL,
  418. "Failure from drain_fd: %s",
  419. tor_socket_strerror(tor_socket_errno(queue->alert.read_fd)));
  420. }
  421. tor_mutex_acquire(&queue->lock);
  422. while (!TOR_TAILQ_EMPTY(&queue->answers)) {
  423. /* lock must be held at this point.*/
  424. workqueue_entry_t *work = TOR_TAILQ_FIRST(&queue->answers);
  425. TOR_TAILQ_REMOVE(&queue->answers, work, next_work);
  426. tor_mutex_release(&queue->lock);
  427. work->on_pool = NULL;
  428. work->reply_fn(work->arg);
  429. workqueue_entry_free(work);
  430. tor_mutex_acquire(&queue->lock);
  431. }
  432. tor_mutex_release(&queue->lock);
  433. }