1 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to
5  * deal in the Software without restriction, including without limitation the
6  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7  * sell copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19  * IN THE SOFTWARE.
20  */
21 
22 #include "uv-common.h"
23 
24 #if !defined(_WIN32)
25 # include "unix/internal.h"
26 #endif
27 
28 #include <stdlib.h>
29 
30 #define MAX_THREADPOOL_SIZE 1024
31 
32 static uv_once_t once = UV_ONCE_INIT;
33 static uv_cond_t cond;
34 static uv_mutex_t mutex;
35 static unsigned int idle_threads;
36 static unsigned int slow_io_work_running;
37 static unsigned int nthreads;
38 static uv_thread_t* threads;
39 static uv_thread_t default_threads[4];
40 static QUEUE exit_message;
41 static QUEUE wq;
42 static QUEUE run_slow_work_message;
43 static QUEUE slow_io_pending_wq;
44 
slow_work_thread_threshold(void)45 static unsigned int slow_work_thread_threshold(void) {
46   return (nthreads + 1) / 2;
47 }
48 
uv__cancelled(struct uv__work * w)49 static void uv__cancelled(struct uv__work* w) {
50   abort();
51 }
52 
53 
54 /* To avoid deadlock with uv_cancel() it's crucial that the worker
55  * never holds the global mutex and the loop-local mutex at the same time.
56  */
worker(void * arg)57 static void worker(void* arg) {
58   struct uv__work* w;
59   QUEUE* q;
60   int is_slow_work;
61 
62   uv_sem_post((uv_sem_t*) arg);
63   arg = NULL;
64 
65   uv_mutex_lock(&mutex);
66   for (;;) {
67     /* `mutex` should always be locked at this point. */
68 
69     /* Keep waiting while either no work is present or only slow I/O
70        and we're at the threshold for that. */
71     while (QUEUE_EMPTY(&wq) ||
72            (QUEUE_HEAD(&wq) == &run_slow_work_message &&
73             QUEUE_NEXT(&run_slow_work_message) == &wq &&
74             slow_io_work_running >= slow_work_thread_threshold())) {
75       idle_threads += 1;
76       uv_cond_wait(&cond, &mutex);
77       idle_threads -= 1;
78     }
79 
80     q = QUEUE_HEAD(&wq);
81     if (q == &exit_message) {
82       uv_cond_signal(&cond);
83       uv_mutex_unlock(&mutex);
84       break;
85     }
86 
87     QUEUE_REMOVE(q);
88     QUEUE_INIT(q);  /* Signal uv_cancel() that the work req is executing. */
89 
90     is_slow_work = 0;
91     if (q == &run_slow_work_message) {
92       /* If we're at the slow I/O threshold, re-schedule until after all
93          other work in the queue is done. */
94       if (slow_io_work_running >= slow_work_thread_threshold()) {
95         QUEUE_INSERT_TAIL(&wq, q);
96         continue;
97       }
98 
99       /* If we encountered a request to run slow I/O work but there is none
100          to run, that means it's cancelled => Start over. */
101       if (QUEUE_EMPTY(&slow_io_pending_wq))
102         continue;
103 
104       is_slow_work = 1;
105       slow_io_work_running++;
106 
107       q = QUEUE_HEAD(&slow_io_pending_wq);
108       QUEUE_REMOVE(q);
109       QUEUE_INIT(q);
110 
111       /* If there is more slow I/O work, schedule it to be run as well. */
112       if (!QUEUE_EMPTY(&slow_io_pending_wq)) {
113         QUEUE_INSERT_TAIL(&wq, &run_slow_work_message);
114         if (idle_threads > 0)
115           uv_cond_signal(&cond);
116       }
117     }
118 
119     uv_mutex_unlock(&mutex);
120 
121     w = QUEUE_DATA(q, struct uv__work, wq);
122     w->work(w);
123 
124     uv_mutex_lock(&w->loop->wq_mutex);
125     w->work = NULL;  /* Signal uv_cancel() that the work req is done
126                         executing. */
127     QUEUE_INSERT_TAIL(&w->loop->wq, &w->wq);
128     uv_async_send(&w->loop->wq_async);
129     uv_mutex_unlock(&w->loop->wq_mutex);
130 
131     /* Lock `mutex` since that is expected at the start of the next
132      * iteration. */
133     uv_mutex_lock(&mutex);
134     if (is_slow_work) {
135       /* `slow_io_work_running` is protected by `mutex`. */
136       slow_io_work_running--;
137     }
138   }
139 }
140 
141 
post(QUEUE * q,enum uv__work_kind kind)142 static void post(QUEUE* q, enum uv__work_kind kind) {
143   uv_mutex_lock(&mutex);
144   if (kind == UV__WORK_SLOW_IO) {
145     /* Insert into a separate queue. */
146     QUEUE_INSERT_TAIL(&slow_io_pending_wq, q);
147     if (!QUEUE_EMPTY(&run_slow_work_message)) {
148       /* Running slow I/O tasks is already scheduled => Nothing to do here.
149          The worker that runs said other task will schedule this one as well. */
150       uv_mutex_unlock(&mutex);
151       return;
152     }
153     q = &run_slow_work_message;
154   }
155 
156   QUEUE_INSERT_TAIL(&wq, q);
157   if (idle_threads > 0)
158     uv_cond_signal(&cond);
159   uv_mutex_unlock(&mutex);
160 }
161 
162 
uv__threadpool_cleanup(void)163 void uv__threadpool_cleanup(void) {
164   unsigned int i;
165 
166   if (nthreads == 0)
167     return;
168 
169   post(&exit_message, UV__WORK_CPU);
170 
171   for (i = 0; i < nthreads; i++)
172     if (uv_thread_join(threads + i))
173       abort();
174 
175   if (threads != default_threads)
176     uv__free(threads);
177 
178   uv_mutex_destroy(&mutex);
179   uv_cond_destroy(&cond);
180 
181   threads = NULL;
182   nthreads = 0;
183 }
184 
185 
init_threads(void)186 static void init_threads(void) {
187   unsigned int i;
188   const char* val;
189   uv_sem_t sem;
190 
191   nthreads = ARRAY_SIZE(default_threads);
192   val = getenv("UV_THREADPOOL_SIZE");
193   if (val != NULL)
194     nthreads = atoi(val);
195   if (nthreads == 0)
196     nthreads = 1;
197   if (nthreads > MAX_THREADPOOL_SIZE)
198     nthreads = MAX_THREADPOOL_SIZE;
199 
200   threads = default_threads;
201   if (nthreads > ARRAY_SIZE(default_threads)) {
202     threads = uv__malloc(nthreads * sizeof(threads[0]));
203     if (threads == NULL) {
204       nthreads = ARRAY_SIZE(default_threads);
205       threads = default_threads;
206     }
207   }
208 
209   if (uv_cond_init(&cond))
210     abort();
211 
212   if (uv_mutex_init(&mutex))
213     abort();
214 
215   QUEUE_INIT(&wq);
216   QUEUE_INIT(&slow_io_pending_wq);
217   QUEUE_INIT(&run_slow_work_message);
218 
219   if (uv_sem_init(&sem, 0))
220     abort();
221 
222   for (i = 0; i < nthreads; i++)
223     if (uv_thread_create(threads + i, worker, &sem))
224       abort();
225 
226   for (i = 0; i < nthreads; i++)
227     uv_sem_wait(&sem);
228 
229   uv_sem_destroy(&sem);
230 }
231 
232 
233 #ifndef _WIN32
reset_once(void)234 static void reset_once(void) {
235   uv_once_t child_once = UV_ONCE_INIT;
236   memcpy(&once, &child_once, sizeof(child_once));
237 }
238 #endif
239 
240 
init_once(void)241 static void init_once(void) {
242 #ifndef _WIN32
243   /* Re-initialize the threadpool after fork.
244    * Note that this discards the global mutex and condition as well
245    * as the work queue.
246    */
247   if (pthread_atfork(NULL, NULL, &reset_once))
248     abort();
249 #endif
250   init_threads();
251 }
252 
253 
uv__work_submit(uv_loop_t * loop,struct uv__work * w,enum uv__work_kind kind,void (* work)(struct uv__work * w),void (* done)(struct uv__work * w,int status))254 void uv__work_submit(uv_loop_t* loop,
255                      struct uv__work* w,
256                      enum uv__work_kind kind,
257                      void (*work)(struct uv__work* w),
258                      void (*done)(struct uv__work* w, int status)) {
259   uv_once(&once, init_once);
260   w->loop = loop;
261   w->work = work;
262   w->done = done;
263   post(&w->wq, kind);
264 }
265 
266 
uv__work_cancel(uv_loop_t * loop,uv_req_t * req,struct uv__work * w)267 static int uv__work_cancel(uv_loop_t* loop, uv_req_t* req, struct uv__work* w) {
268   int cancelled;
269 
270   uv_mutex_lock(&mutex);
271   uv_mutex_lock(&w->loop->wq_mutex);
272 
273   cancelled = !QUEUE_EMPTY(&w->wq) && w->work != NULL;
274   if (cancelled)
275     QUEUE_REMOVE(&w->wq);
276 
277   uv_mutex_unlock(&w->loop->wq_mutex);
278   uv_mutex_unlock(&mutex);
279 
280   if (!cancelled)
281     return UV_EBUSY;
282 
283   w->work = uv__cancelled;
284   uv_mutex_lock(&loop->wq_mutex);
285   QUEUE_INSERT_TAIL(&loop->wq, &w->wq);
286   uv_async_send(&loop->wq_async);
287   uv_mutex_unlock(&loop->wq_mutex);
288 
289   return 0;
290 }
291 
292 
uv__work_done(uv_async_t * handle)293 void uv__work_done(uv_async_t* handle) {
294   struct uv__work* w;
295   uv_loop_t* loop;
296   QUEUE* q;
297   QUEUE wq;
298   int err;
299 
300   loop = container_of(handle, uv_loop_t, wq_async);
301   uv_mutex_lock(&loop->wq_mutex);
302   QUEUE_MOVE(&loop->wq, &wq);
303   uv_mutex_unlock(&loop->wq_mutex);
304 
305   while (!QUEUE_EMPTY(&wq)) {
306     q = QUEUE_HEAD(&wq);
307     QUEUE_REMOVE(q);
308 
309     w = container_of(q, struct uv__work, wq);
310     err = (w->work == uv__cancelled) ? UV_ECANCELED : 0;
311     w->done(w, err);
312   }
313 }
314 
315 
uv__queue_work(struct uv__work * w)316 static void uv__queue_work(struct uv__work* w) {
317   uv_work_t* req = container_of(w, uv_work_t, work_req);
318 
319   req->work_cb(req);
320 }
321 
322 
uv__queue_done(struct uv__work * w,int err)323 static void uv__queue_done(struct uv__work* w, int err) {
324   uv_work_t* req;
325 
326   req = container_of(w, uv_work_t, work_req);
327   uv__req_unregister(req->loop, req);
328 
329   if (req->after_work_cb == NULL)
330     return;
331 
332   req->after_work_cb(req, err);
333 }
334 
335 
uv_queue_work(uv_loop_t * loop,uv_work_t * req,uv_work_cb work_cb,uv_after_work_cb after_work_cb)336 int uv_queue_work(uv_loop_t* loop,
337                   uv_work_t* req,
338                   uv_work_cb work_cb,
339                   uv_after_work_cb after_work_cb) {
340   if (work_cb == NULL)
341     return UV_EINVAL;
342 
343   uv__req_init(loop, req, UV_WORK);
344   req->loop = loop;
345   req->work_cb = work_cb;
346   req->after_work_cb = after_work_cb;
347   uv__work_submit(loop,
348                   &req->work_req,
349                   UV__WORK_CPU,
350                   uv__queue_work,
351                   uv__queue_done);
352   return 0;
353 }
354 
355 
uv_cancel(uv_req_t * req)356 int uv_cancel(uv_req_t* req) {
357   struct uv__work* wreq;
358   uv_loop_t* loop;
359 
360   switch (req->type) {
361   case UV_FS:
362     loop =  ((uv_fs_t*) req)->loop;
363     wreq = &((uv_fs_t*) req)->work_req;
364     break;
365   case UV_GETADDRINFO:
366     loop =  ((uv_getaddrinfo_t*) req)->loop;
367     wreq = &((uv_getaddrinfo_t*) req)->work_req;
368     break;
369   case UV_GETNAMEINFO:
370     loop = ((uv_getnameinfo_t*) req)->loop;
371     wreq = &((uv_getnameinfo_t*) req)->work_req;
372     break;
373   case UV_RANDOM:
374     loop = ((uv_random_t*) req)->loop;
375     wreq = &((uv_random_t*) req)->work_req;
376     break;
377   case UV_WORK:
378     loop =  ((uv_work_t*) req)->loop;
379     wreq = &((uv_work_t*) req)->work_req;
380     break;
381   default:
382     return UV_EINVAL;
383   }
384 
385   return uv__work_cancel(loop, req, wreq);
386 }
387