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 <eb32tree.h>
21 
22 #include <proto/proxy.h>
23 #include <proto/stream.h>
24 #include <proto/task.h>
25 
26 struct pool_head *pool2_task;
27 
28 unsigned int nb_tasks = 0;
29 unsigned int tasks_run_queue = 0;
30 unsigned int tasks_run_queue_cur = 0;    /* copy of the run queue size */
31 unsigned int nb_tasks_cur = 0;     /* copy of the tasks count */
32 unsigned int niced_tasks = 0;      /* number of niced tasks in the run queue */
33 struct eb32_node *last_timer = NULL;  /* optimization: last queued timer */
34 struct eb32_node *rq_next    = NULL;  /* optimization: next task except if delete/insert */
35 
36 static struct eb_root timers;      /* sorted timers tree */
37 static struct eb_root rqueue;      /* tree constituting the run queue */
38 static unsigned int rqueue_ticks;  /* insertion count */
39 
40 /* Puts the task <t> in run queue at a position depending on t->nice. <t> is
41  * returned. The nice value assigns boosts in 32th of the run queue size. A
42  * nice value of -1024 sets the task to -tasks_run_queue*32, while a nice value
43  * of 1024 sets the task to tasks_run_queue*32. The state flags are cleared, so
44  * the caller will have to set its flags after this call.
45  * The task must not already be in the run queue. If unsure, use the safer
46  * task_wakeup() function.
47  */
__task_wakeup(struct task * t)48 struct task *__task_wakeup(struct task *t)
49 {
50 	tasks_run_queue++;
51 	t->rq.key = ++rqueue_ticks;
52 
53 	if (likely(t->nice)) {
54 		int offset;
55 
56 		niced_tasks++;
57 		if (likely(t->nice > 0))
58 			offset = (unsigned)((tasks_run_queue * (unsigned int)t->nice) / 32U);
59 		else
60 			offset = -(unsigned)((tasks_run_queue * (unsigned int)-t->nice) / 32U);
61 		t->rq.key += offset;
62 	}
63 
64 	/* clear state flags at the same time */
65 	t->state &= ~TASK_WOKEN_ANY;
66 
67 	eb32_insert(&rqueue, &t->rq);
68 	rq_next = NULL;
69 	return t;
70 }
71 
72 /*
73  * __task_queue()
74  *
75  * Inserts a task into the wait queue at the position given by its expiration
76  * date. It does not matter if the task was already in the wait queue or not,
77  * as it will be unlinked. The task must not have an infinite expiration timer.
78  * Last, tasks must not be queued further than the end of the tree, which is
79  * between <now_ms> and <now_ms> + 2^31 ms (now+24days in 32bit).
80  *
81  * This function should not be used directly, it is meant to be called by the
82  * inline version of task_queue() which performs a few cheap preliminary tests
83  * before deciding to call __task_queue().
84  */
__task_queue(struct task * task)85 void __task_queue(struct task *task)
86 {
87 	if (likely(task_in_wq(task)))
88 		__task_unlink_wq(task);
89 
90 	/* the task is not in the queue now */
91 	task->wq.key = task->expire;
92 #ifdef DEBUG_CHECK_INVALID_EXPIRATION_DATES
93 	if (tick_is_lt(task->wq.key, now_ms))
94 		/* we're queuing too far away or in the past (most likely) */
95 		return;
96 #endif
97 
98 	if (likely(last_timer &&
99 		   last_timer->node.bit < 0 &&
100 		   last_timer->key == task->wq.key &&
101 		   last_timer->node.node_p)) {
102 		/* Most often, last queued timer has the same expiration date, so
103 		 * if it's not queued at the root, let's queue a dup directly there.
104 		 * Note that we can only use dups at the dup tree's root (most
105 		 * negative bit).
106 		 */
107 		eb_insert_dup(&last_timer->node, &task->wq.node);
108 		if (task->wq.node.bit < last_timer->node.bit)
109 			last_timer = &task->wq;
110 		return;
111 	}
112 	eb32_insert(&timers, &task->wq);
113 
114 	/* Make sure we don't assign the last_timer to a node-less entry */
115 	if (task->wq.node.node_p && (!last_timer || (task->wq.node.bit < last_timer->node.bit)))
116 		last_timer = &task->wq;
117 	return;
118 }
119 
120 /*
121  * Extract all expired timers from the timer queue, and wakes up all
122  * associated tasks. Returns the date of next event (or eternity).
123  */
wake_expired_tasks()124 int wake_expired_tasks()
125 {
126 	struct task *task;
127 	struct eb32_node *eb;
128 
129 	eb = eb32_lookup_ge(&timers, now_ms - TIMER_LOOK_BACK);
130 	while (1) {
131 		if (unlikely(!eb)) {
132 			/* we might have reached the end of the tree, typically because
133 			* <now_ms> is in the first half and we're first scanning the last
134 			* half. Let's loop back to the beginning of the tree now.
135 			*/
136 			eb = eb32_first(&timers);
137 			if (likely(!eb))
138 				break;
139 		}
140 
141 		if (likely(tick_is_lt(now_ms, eb->key))) {
142 			/* timer not expired yet, revisit it later */
143 			return eb->key;
144 		}
145 
146 		/* timer looks expired, detach it from the queue */
147 		task = eb32_entry(eb, struct task, wq);
148 		eb = eb32_next(eb);
149 		__task_unlink_wq(task);
150 
151 		/* It is possible that this task was left at an earlier place in the
152 		 * tree because a recent call to task_queue() has not moved it. This
153 		 * happens when the new expiration date is later than the old one.
154 		 * Since it is very unlikely that we reach a timeout anyway, it's a
155 		 * lot cheaper to proceed like this because we almost never update
156 		 * the tree. We may also find disabled expiration dates there. Since
157 		 * we have detached the task from the tree, we simply call task_queue
158 		 * to take care of this. Note that we might occasionally requeue it at
159 		 * the same place, before <eb>, so we have to check if this happens,
160 		 * and adjust <eb>, otherwise we may skip it which is not what we want.
161 		 * We may also not requeue the task (and not point eb at it) if its
162 		 * expiration time is not set.
163 		 */
164 		if (!tick_is_expired(task->expire, now_ms)) {
165 			if (!tick_isset(task->expire))
166 				continue;
167 			__task_queue(task);
168 			if (!eb || eb->key > task->wq.key)
169 				eb = &task->wq;
170 			continue;
171 		}
172 		task_wakeup(task, TASK_WOKEN_TIMER);
173 	}
174 
175 	/* No task is expired */
176 	return TICK_ETERNITY;
177 }
178 
179 /* The run queue is chronologically sorted in a tree. An insertion counter is
180  * used to assign a position to each task. This counter may be combined with
181  * other variables (eg: nice value) to set the final position in the tree. The
182  * counter may wrap without a problem, of course. We then limit the number of
183  * tasks processed at once to 1/4 of the number of tasks in the queue, and to
184  * 200 max in any case, so that general latency remains low and so that task
185  * positions have a chance to be considered.
186  *
187  * The function adjusts <next> if a new event is closer.
188  */
process_runnable_tasks()189 void process_runnable_tasks()
190 {
191 	struct task *t;
192 	unsigned int max_processed;
193 
194 	tasks_run_queue_cur = tasks_run_queue; /* keep a copy for reporting */
195 	nb_tasks_cur = nb_tasks;
196 	max_processed = tasks_run_queue;
197 
198 	if (!tasks_run_queue)
199 		return;
200 
201 	if (max_processed > 200)
202 		max_processed = 200;
203 
204 	if (likely(niced_tasks))
205 		max_processed = (max_processed + 3) / 4;
206 
207 	while (max_processed--) {
208 		/* Note: this loop is one of the fastest code path in
209 		 * the whole program. It should not be re-arranged
210 		 * without a good reason.
211 		 */
212 		if (unlikely(!rq_next)) {
213 			rq_next = eb32_lookup_ge(&rqueue, rqueue_ticks - TIMER_LOOK_BACK);
214 			if (!rq_next) {
215 				/* we might have reached the end of the tree, typically because
216 				 * <rqueue_ticks> is in the first half and we're first scanning
217 				 * the last half. Let's loop back to the beginning of the tree now.
218 				 */
219 				rq_next = eb32_first(&rqueue);
220 				if (!rq_next)
221 					break;
222 			}
223 		}
224 
225 		/* detach the task from the queue after updating the pointer to
226 		 * the next entry.
227 		 */
228 		t = eb32_entry(rq_next, struct task, rq);
229 		rq_next = eb32_next(rq_next);
230 		__task_unlink_rq(t);
231 
232 		t->state |= TASK_RUNNING;
233 		/* This is an optimisation to help the processor's branch
234 		 * predictor take this most common call.
235 		 */
236 		t->calls++;
237 		if (likely(t->process == process_stream))
238 			t = process_stream(t);
239 		else
240 			t = t->process(t);
241 
242 		if (likely(t != NULL)) {
243 			t->state &= ~TASK_RUNNING;
244 			if (t->expire)
245 				task_queue(t);
246 		}
247 	}
248 }
249 
250 /* perform minimal intializations, report 0 in case of error, 1 if OK. */
init_task()251 int init_task()
252 {
253 	memset(&timers, 0, sizeof(timers));
254 	memset(&rqueue, 0, sizeof(rqueue));
255 	pool2_task = create_pool("task", sizeof(struct task), MEM_F_SHARED);
256 	return pool2_task != NULL;
257 }
258 
259 /*
260  * Local variables:
261  *  c-indent-level: 8
262  *  c-basic-offset: 8
263  * End:
264  */
265