1 /*
2 * Task management functions.
3 *
4 * Copyright 2000-2009 Willy Tarreau <w@1wt.eu>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13 #include <string.h>
14
15 #include <common/config.h>
16 #include <common/memory.h>
17 #include <common/mini-clist.h>
18 #include <common/standard.h>
19 #include <common/time.h>
20 #include <eb32sctree.h>
21 #include <eb32tree.h>
22
23 #include <proto/fd.h>
24 #include <proto/freq_ctr.h>
25 #include <proto/proxy.h>
26 #include <proto/stream.h>
27 #include <proto/task.h>
28
29 DECLARE_POOL(pool_head_task, "task", sizeof(struct task));
30 DECLARE_POOL(pool_head_tasklet, "tasklet", sizeof(struct tasklet));
31
32 /* This is the memory pool containing all the signal structs. These
33 * struct are used to store each required signal between two tasks.
34 */
35 DECLARE_POOL(pool_head_notification, "notification", sizeof(struct notification));
36
37 unsigned int nb_tasks = 0;
38 volatile unsigned long global_tasks_mask = 0; /* Mask of threads with tasks in the global runqueue */
39 unsigned int tasks_run_queue = 0;
40 unsigned int tasks_run_queue_cur = 0; /* copy of the run queue size */
41 unsigned int nb_tasks_cur = 0; /* copy of the tasks count */
42 unsigned int niced_tasks = 0; /* number of niced tasks in the run queue */
43
44 THREAD_LOCAL struct task *curr_task = NULL; /* task currently running or NULL */
45
46 __decl_aligned_spinlock(rq_lock); /* spin lock related to run queue */
47 __decl_aligned_rwlock(wq_lock); /* RW lock related to the wait queue */
48
49 #ifdef USE_THREAD
50 struct eb_root timers; /* sorted timers tree, global */
51 struct eb_root rqueue; /* tree constituting the run queue */
52 int global_rqueue_size; /* Number of element sin the global runqueue */
53 #endif
54
55 static unsigned int rqueue_ticks; /* insertion count */
56
57 struct task_per_thread task_per_thread[MAX_THREADS];
58
59 /* Puts the task <t> in run queue at a position depending on t->nice. <t> is
60 * returned. The nice value assigns boosts in 32th of the run queue size. A
61 * nice value of -1024 sets the task to -tasks_run_queue*32, while a nice value
62 * of 1024 sets the task to tasks_run_queue*32. The state flags are cleared, so
63 * the caller will have to set its flags after this call.
64 * The task must not already be in the run queue. If unsure, use the safer
65 * task_wakeup() function.
66 */
__task_wakeup(struct task * t,struct eb_root * root)67 void __task_wakeup(struct task *t, struct eb_root *root)
68 {
69 #ifdef USE_THREAD
70 if (root == &rqueue) {
71 HA_SPIN_LOCK(TASK_RQ_LOCK, &rq_lock);
72 }
73 #endif
74 /* Make sure if the task isn't in the runqueue, nobody inserts it
75 * in the meanwhile.
76 */
77 _HA_ATOMIC_ADD(&tasks_run_queue, 1);
78 #ifdef USE_THREAD
79 if (root == &rqueue) {
80 global_tasks_mask |= t->thread_mask;
81 __ha_barrier_store();
82 }
83 #endif
84 t->rq.key = _HA_ATOMIC_ADD(&rqueue_ticks, 1);
85
86 if (likely(t->nice)) {
87 int offset;
88
89 _HA_ATOMIC_ADD(&niced_tasks, 1);
90 offset = t->nice * (int)global.tune.runqueue_depth;
91 t->rq.key += offset;
92 }
93
94 if (task_profiling_mask & tid_bit)
95 t->call_date = now_mono_time();
96
97 eb32sc_insert(root, &t->rq, t->thread_mask);
98 #ifdef USE_THREAD
99 if (root == &rqueue) {
100 global_rqueue_size++;
101 _HA_ATOMIC_OR(&t->state, TASK_GLOBAL);
102 HA_SPIN_UNLOCK(TASK_RQ_LOCK, &rq_lock);
103 } else
104 #endif
105 {
106 int nb = ((void *)root - (void *)&task_per_thread[0].rqueue) / sizeof(task_per_thread[0]);
107 task_per_thread[nb].rqueue_size++;
108 }
109 #ifdef USE_THREAD
110 /* If all threads that are supposed to handle this task are sleeping,
111 * wake one.
112 */
113 if ((((t->thread_mask & all_threads_mask) & sleeping_thread_mask) ==
114 (t->thread_mask & all_threads_mask))) {
115 unsigned long m = (t->thread_mask & all_threads_mask) &~ tid_bit;
116
117 m = (m & (m - 1)) ^ m; // keep lowest bit set
118 _HA_ATOMIC_AND(&sleeping_thread_mask, ~m);
119 wake_thread(my_ffsl(m) - 1);
120 }
121 #endif
122 return;
123 }
124
125 /*
126 * __task_queue()
127 *
128 * Inserts a task into wait queue <wq> at the position given by its expiration
129 * date. It does not matter if the task was already in the wait queue or not,
130 * as it will be unlinked. The task must not have an infinite expiration timer.
131 * Last, tasks must not be queued further than the end of the tree, which is
132 * between <now_ms> and <now_ms> + 2^31 ms (now+24days in 32bit).
133 *
134 * This function should not be used directly, it is meant to be called by the
135 * inline version of task_queue() which performs a few cheap preliminary tests
136 * before deciding to call __task_queue(). Moreover this function doesn't care
137 * at all about locking so the caller must be careful when deciding whether to
138 * lock or not around this call.
139 */
__task_queue(struct task * task,struct eb_root * wq)140 void __task_queue(struct task *task, struct eb_root *wq)
141 {
142 if (likely(task_in_wq(task)))
143 __task_unlink_wq(task);
144
145 /* the task is not in the queue now */
146 task->wq.key = task->expire;
147 #ifdef DEBUG_CHECK_INVALID_EXPIRATION_DATES
148 if (tick_is_lt(task->wq.key, now_ms))
149 /* we're queuing too far away or in the past (most likely) */
150 return;
151 #endif
152
153 eb32_insert(wq, &task->wq);
154 }
155
156 /*
157 * Extract all expired timers from the timer queue, and wakes up all
158 * associated tasks. Returns the date of next event (or eternity).
159 */
wake_expired_tasks()160 int wake_expired_tasks()
161 {
162 int max_processed = global.tune.runqueue_depth;
163 struct task *task;
164 struct eb32_node *eb;
165 int ret = TICK_ETERNITY;
166 __decl_hathreads(int key);
167
168 while (max_processed-- > 0) {
169 lookup_next_local:
170 eb = eb32_lookup_ge(&task_per_thread[tid].timers, now_ms - TIMER_LOOK_BACK);
171 if (!eb) {
172 /* we might have reached the end of the tree, typically because
173 * <now_ms> is in the first half and we're first scanning the last
174 * half. Let's loop back to the beginning of the tree now.
175 */
176 eb = eb32_first(&task_per_thread[tid].timers);
177 if (likely(!eb))
178 break;
179 }
180
181 if (tick_is_lt(now_ms, eb->key)) {
182 /* timer not expired yet, revisit it later */
183 ret = eb->key;
184 break;
185 }
186
187 /* timer looks expired, detach it from the queue */
188 task = eb32_entry(eb, struct task, wq);
189 __task_unlink_wq(task);
190
191 /* It is possible that this task was left at an earlier place in the
192 * tree because a recent call to task_queue() has not moved it. This
193 * happens when the new expiration date is later than the old one.
194 * Since it is very unlikely that we reach a timeout anyway, it's a
195 * lot cheaper to proceed like this because we almost never update
196 * the tree. We may also find disabled expiration dates there. Since
197 * we have detached the task from the tree, we simply call task_queue
198 * to take care of this. Note that we might occasionally requeue it at
199 * the same place, before <eb>, so we have to check if this happens,
200 * and adjust <eb>, otherwise we may skip it which is not what we want.
201 * We may also not requeue the task (and not point eb at it) if its
202 * expiration time is not set.
203 */
204 if (!tick_is_expired(task->expire, now_ms)) {
205 if (tick_isset(task->expire))
206 __task_queue(task, &task_per_thread[tid].timers);
207 goto lookup_next_local;
208 }
209 task_wakeup(task, TASK_WOKEN_TIMER);
210 }
211
212 #ifdef USE_THREAD
213 if (eb_is_empty(&timers))
214 goto leave;
215
216 HA_RWLOCK_RDLOCK(TASK_WQ_LOCK, &wq_lock);
217 eb = eb32_lookup_ge(&timers, now_ms - TIMER_LOOK_BACK);
218 if (!eb) {
219 eb = eb32_first(&timers);
220 if (likely(!eb)) {
221 HA_RWLOCK_RDUNLOCK(TASK_WQ_LOCK, &wq_lock);
222 goto leave;
223 }
224 }
225 key = eb->key;
226 HA_RWLOCK_RDUNLOCK(TASK_WQ_LOCK, &wq_lock);
227
228 if (tick_is_lt(now_ms, key)) {
229 /* timer not expired yet, revisit it later */
230 ret = tick_first(ret, key);
231 goto leave;
232 }
233
234 /* There's really something of interest here, let's visit the queue */
235
236 while (1) {
237 HA_RWLOCK_WRLOCK(TASK_WQ_LOCK, &wq_lock);
238 lookup_next:
239 if (max_processed-- <= 0)
240 break;
241 eb = eb32_lookup_ge(&timers, now_ms - TIMER_LOOK_BACK);
242 if (!eb) {
243 /* we might have reached the end of the tree, typically because
244 * <now_ms> is in the first half and we're first scanning the last
245 * half. Let's loop back to the beginning of the tree now.
246 */
247 eb = eb32_first(&timers);
248 if (likely(!eb))
249 break;
250 }
251
252 if (tick_is_lt(now_ms, eb->key)) {
253 /* timer not expired yet, revisit it later */
254 ret = tick_first(ret, eb->key);
255 break;
256 }
257
258 /* timer looks expired, detach it from the queue */
259 task = eb32_entry(eb, struct task, wq);
260 __task_unlink_wq(task);
261
262 /* It is possible that this task was left at an earlier place in the
263 * tree because a recent call to task_queue() has not moved it. This
264 * happens when the new expiration date is later than the old one.
265 * Since it is very unlikely that we reach a timeout anyway, it's a
266 * lot cheaper to proceed like this because we almost never update
267 * the tree. We may also find disabled expiration dates there. Since
268 * we have detached the task from the tree, we simply call task_queue
269 * to take care of this. Note that we might occasionally requeue it at
270 * the same place, before <eb>, so we have to check if this happens,
271 * and adjust <eb>, otherwise we may skip it which is not what we want.
272 * We may also not requeue the task (and not point eb at it) if its
273 * expiration time is not set.
274 */
275 if (!tick_is_expired(task->expire, now_ms)) {
276 if (tick_isset(task->expire))
277 __task_queue(task, &timers);
278 goto lookup_next;
279 }
280 task_wakeup(task, TASK_WOKEN_TIMER);
281 HA_RWLOCK_WRUNLOCK(TASK_WQ_LOCK, &wq_lock);
282 }
283
284 HA_RWLOCK_WRUNLOCK(TASK_WQ_LOCK, &wq_lock);
285 #endif
286 leave:
287 return ret;
288 }
289
290 /* The run queue is chronologically sorted in a tree. An insertion counter is
291 * used to assign a position to each task. This counter may be combined with
292 * other variables (eg: nice value) to set the final position in the tree. The
293 * counter may wrap without a problem, of course. We then limit the number of
294 * tasks processed to 200 in any case, so that general latency remains low and
295 * so that task positions have a chance to be considered. The function scans
296 * both the global and local run queues and picks the most urgent task between
297 * the two. We need to grab the global runqueue lock to touch it so it's taken
298 * on the very first access to the global run queue and is released as soon as
299 * it reaches the end.
300 *
301 * The function adjusts <next> if a new event is closer.
302 */
process_runnable_tasks()303 void process_runnable_tasks()
304 {
305 struct eb32sc_node *lrq = NULL; // next local run queue entry
306 struct eb32sc_node *grq = NULL; // next global run queue entry
307 struct task *t;
308 int max_processed;
309
310 ti->flags &= ~TI_FL_STUCK; // this thread is still running
311
312 if (!thread_has_tasks()) {
313 activity[tid].empty_rq++;
314 return;
315 }
316
317 tasks_run_queue_cur = tasks_run_queue; /* keep a copy for reporting */
318 nb_tasks_cur = nb_tasks;
319 max_processed = global.tune.runqueue_depth;
320
321 if (likely(niced_tasks))
322 max_processed = (max_processed + 3) / 4;
323
324 /* Note: the grq lock is always held when grq is not null */
325
326 while (task_per_thread[tid].task_list_size < max_processed) {
327 if ((global_tasks_mask & tid_bit) && !grq) {
328 #ifdef USE_THREAD
329 HA_SPIN_LOCK(TASK_RQ_LOCK, &rq_lock);
330 grq = eb32sc_lookup_ge(&rqueue, rqueue_ticks - TIMER_LOOK_BACK, tid_bit);
331 if (unlikely(!grq)) {
332 grq = eb32sc_first(&rqueue, tid_bit);
333 if (!grq) {
334 global_tasks_mask &= ~tid_bit;
335 HA_SPIN_UNLOCK(TASK_RQ_LOCK, &rq_lock);
336 }
337 }
338 #endif
339 }
340
341 /* If a global task is available for this thread, it's in grq
342 * now and the global RQ is locked.
343 */
344
345 if (!lrq) {
346 lrq = eb32sc_lookup_ge(&task_per_thread[tid].rqueue, rqueue_ticks - TIMER_LOOK_BACK, tid_bit);
347 if (unlikely(!lrq))
348 lrq = eb32sc_first(&task_per_thread[tid].rqueue, tid_bit);
349 }
350
351 if (!lrq && !grq)
352 break;
353
354 if (likely(!grq || (lrq && (int)(lrq->key - grq->key) <= 0))) {
355 t = eb32sc_entry(lrq, struct task, rq);
356 lrq = eb32sc_next(lrq, tid_bit);
357 __task_unlink_rq(t);
358 }
359 #ifdef USE_THREAD
360 else {
361 t = eb32sc_entry(grq, struct task, rq);
362 grq = eb32sc_next(grq, tid_bit);
363 __task_unlink_rq(t);
364 if (unlikely(!grq)) {
365 grq = eb32sc_first(&rqueue, tid_bit);
366 if (!grq) {
367 global_tasks_mask &= ~tid_bit;
368 HA_SPIN_UNLOCK(TASK_RQ_LOCK, &rq_lock);
369 }
370 }
371 }
372 #endif
373
374 /* And add it to the local task list */
375 tasklet_insert_into_tasklet_list((struct tasklet *)t);
376 task_per_thread[tid].task_list_size++;
377 activity[tid].tasksw++;
378 }
379
380 /* release the rqueue lock */
381 if (grq) {
382 HA_SPIN_UNLOCK(TASK_RQ_LOCK, &rq_lock);
383 grq = NULL;
384 }
385
386 while (max_processed > 0 && !LIST_ISEMPTY(&task_per_thread[tid].task_list)) {
387 struct task *t;
388 unsigned short state;
389 void *ctx;
390 struct task *(*process)(struct task *t, void *ctx, unsigned short state);
391
392 t = (struct task *)LIST_ELEM(task_per_thread[tid].task_list.n, struct tasklet *, list);
393 state = (t->state & TASK_SHARED_WQ) | TASK_RUNNING;
394 state = _HA_ATOMIC_XCHG(&t->state, state);
395 __ha_barrier_atomic_store();
396 __tasklet_remove_from_tasklet_list((struct tasklet *)t);
397 if (!TASK_IS_TASKLET(t))
398 task_per_thread[tid].task_list_size--;
399
400 ti->flags &= ~TI_FL_STUCK; // this thread is still running
401 activity[tid].ctxsw++;
402 ctx = t->context;
403 process = t->process;
404 t->calls++;
405
406 if (unlikely(!TASK_IS_TASKLET(t) && t->call_date)) {
407 uint64_t now_ns = now_mono_time();
408
409 t->lat_time += now_ns - t->call_date;
410 t->call_date = now_ns;
411 }
412
413 curr_task = (struct task *)t;
414 __ha_barrier_store();
415 if (likely(process == process_stream))
416 t = process_stream(t, ctx, state);
417 else if (process != NULL)
418 t = process(TASK_IS_TASKLET(t) ? NULL : t, ctx, state);
419 else {
420 __task_free(t);
421 curr_task = NULL;
422 __ha_barrier_store();
423 /* We don't want max_processed to be decremented if
424 * we're just freeing a destroyed task, we should only
425 * do so if we really ran a task.
426 */
427 continue;
428 }
429 curr_task = NULL;
430 __ha_barrier_store();
431 /* If there is a pending state we have to wake up the task
432 * immediately, else we defer it into wait queue
433 */
434 if (t != NULL) {
435 if (unlikely(!TASK_IS_TASKLET(t) && t->call_date)) {
436 t->cpu_time += now_mono_time() - t->call_date;
437 t->call_date = 0;
438 }
439
440 state = _HA_ATOMIC_AND(&t->state, ~TASK_RUNNING);
441 if (state & TASK_WOKEN_ANY)
442 task_wakeup(t, 0);
443 else
444 task_queue(t);
445 }
446
447 max_processed--;
448 }
449
450 if (!LIST_ISEMPTY(&task_per_thread[tid].task_list))
451 activity[tid].long_rq++;
452 }
453
454 /* create a work list array for <nbthread> threads, using tasks made of
455 * function <fct>. The context passed to the function will be the pointer to
456 * the thread's work list, which will contain a copy of argument <arg>. The
457 * wake up reason will be TASK_WOKEN_OTHER. The pointer to the work_list array
458 * is returned on success, otherwise NULL on failure.
459 */
work_list_create(int nbthread,struct task * (* fct)(struct task *,void *,unsigned short),void * arg)460 struct work_list *work_list_create(int nbthread,
461 struct task *(*fct)(struct task *, void *, unsigned short),
462 void *arg)
463 {
464 struct work_list *wl;
465 int i;
466
467 wl = calloc(nbthread, sizeof(*wl));
468 if (!wl)
469 goto fail;
470
471 for (i = 0; i < nbthread; i++) {
472 LIST_INIT(&wl[i].head);
473 wl[i].task = task_new(1UL << i);
474 if (!wl[i].task)
475 goto fail;
476 wl[i].task->process = fct;
477 wl[i].task->context = &wl[i];
478 wl[i].arg = arg;
479 }
480 return wl;
481
482 fail:
483 work_list_destroy(wl, nbthread);
484 return NULL;
485 }
486
487 /* destroy work list <work> */
work_list_destroy(struct work_list * work,int nbthread)488 void work_list_destroy(struct work_list *work, int nbthread)
489 {
490 int t;
491
492 if (!work)
493 return;
494 for (t = 0; t < nbthread; t++)
495 task_destroy(work[t].task);
496 free(work);
497 }
498
499 /*
500 * Delete every tasks before running the master polling loop
501 */
mworker_cleantasks()502 void mworker_cleantasks()
503 {
504 struct task *t;
505 int i;
506 struct eb32_node *tmp_wq = NULL;
507 struct eb32sc_node *tmp_rq = NULL;
508
509 #ifdef USE_THREAD
510 /* cleanup the global run queue */
511 tmp_rq = eb32sc_first(&rqueue, MAX_THREADS_MASK);
512 while (tmp_rq) {
513 t = eb32sc_entry(tmp_rq, struct task, rq);
514 tmp_rq = eb32sc_next(tmp_rq, MAX_THREADS_MASK);
515 task_destroy(t);
516 }
517 /* cleanup the timers queue */
518 tmp_wq = eb32_first(&timers);
519 while (tmp_wq) {
520 t = eb32_entry(tmp_wq, struct task, wq);
521 tmp_wq = eb32_next(tmp_wq);
522 task_destroy(t);
523 }
524 #endif
525 /* clean the per thread run queue */
526 for (i = 0; i < global.nbthread; i++) {
527 tmp_rq = eb32sc_first(&task_per_thread[i].rqueue, MAX_THREADS_MASK);
528 while (tmp_rq) {
529 t = eb32sc_entry(tmp_rq, struct task, rq);
530 tmp_rq = eb32sc_next(tmp_rq, MAX_THREADS_MASK);
531 task_destroy(t);
532 }
533 /* cleanup the per thread timers queue */
534 tmp_wq = eb32_first(&task_per_thread[i].timers);
535 while (tmp_wq) {
536 t = eb32_entry(tmp_wq, struct task, wq);
537 tmp_wq = eb32_next(tmp_wq);
538 task_destroy(t);
539 }
540 }
541 }
542
543 /* perform minimal intializations */
init_task()544 static void init_task()
545 {
546 int i;
547
548 #ifdef USE_THREAD
549 memset(&timers, 0, sizeof(timers));
550 memset(&rqueue, 0, sizeof(rqueue));
551 #endif
552 memset(&task_per_thread, 0, sizeof(task_per_thread));
553 for (i = 0; i < MAX_THREADS; i++) {
554 LIST_INIT(&task_per_thread[i].task_list);
555 }
556 }
557
558 INITCALL0(STG_PREPARE, init_task);
559
560 /*
561 * Local variables:
562 * c-indent-level: 8
563 * c-basic-offset: 8
564 * End:
565 */
566