play: Convert com_quit() to lopsub.
[paraslash.git] / sched.c
1 /*
2 * Copyright (C) 2006 Andre Noll <maan@tuebingen.mpg.de>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file sched.c Paraslash's scheduling functions. */
8
9 #include <regex.h>
10
11 #include "para.h"
12 #include "ipc.h"
13 #include "fd.h"
14 #include "list.h"
15 #include "sched.h"
16 #include "string.h"
17 #include "time.h"
18 #include "error.h"
19
20 /**
21 * The possible states of a task.
22 *
23 * In addition to the states listed here, a task may also enter zombie state.
24 * This happens when its ->post_select function returns negative, the ->status
25 * field is then set to this return value. Such tasks are not scheduled any
26 * more (i.e. ->pre_select() and ->post_select() are no longer called), but
27 * they stay on the scheduler task list until \ref task_reap() or
28 * \ref sched_shutdown() is called.
29 */
30 enum task_status {
31 /** Task has been reaped and may be removed from the task list. */
32 TS_DEAD,
33 /** Task is active. */
34 TS_RUNNING,
35 };
36
37 struct task {
38 /** A copy of the task name supplied when the task was registered. */
39 char *name;
40 /** Copied during task_register(). */
41 struct task_info info;
42 /* TS_RUNNING, TS_DEAD, or zombie (negative value). */
43 int status;
44 /** Position of the task in the task list of the scheduler. */
45 struct list_head node;
46 /** If less than zero, the task was notified by another task. */
47 int notification;
48 };
49
50 static struct timeval now_struct;
51 const struct timeval *now = &now_struct;
52
53 static void sched_preselect(struct sched *s)
54 {
55 struct task *t, *tmp;
56
57 list_for_each_entry_safe(t, tmp, &s->task_list, node) {
58 if (t->status < 0)
59 continue;
60 if (t->notification != 0)
61 sched_min_delay(s);
62 if (t->info.pre_select)
63 t->info.pre_select(s, t->info.context);
64 }
65 }
66
67 static void unlink_and_free_task(struct task *t)
68 {
69 PARA_INFO_LOG("freeing task %s (%s)\n", t->name, t->status < 0?
70 para_strerror(-t->status) :
71 (t->status == TS_DEAD? "[dead]" : "[running]"));
72
73 list_del(&t->node);
74 free(t->name);
75 free(t);
76 }
77
78 //#define SCHED_DEBUG 1
79 static inline void call_post_select(struct sched *s, struct task *t)
80 {
81 int ret;
82
83 #ifndef SCHED_DEBUG
84 ret = t->info.post_select(s, t->info.context);
85 #else
86 struct timeval t1, t2, diff;
87 unsigned long pst;
88
89 clock_get_realtime(&t1);
90 ret = t->info.post_select(s, t->info.context);
91 clock_get_realtime(&t2);
92 tv_diff(&t1, &t2, &diff);
93 pst = tv2ms(&diff);
94 if (pst > 50)
95 PARA_WARNING_LOG("%s: post_select time: %lums\n",
96 t->name, pst);
97 #endif
98 t->status = ret < 0? ret : TS_RUNNING;
99 }
100
101 static unsigned sched_post_select(struct sched *s)
102 {
103 struct task *t, *tmp;
104 unsigned num_running_tasks = 0;
105
106 list_for_each_entry_safe(t, tmp, &s->task_list, node) {
107 if (t->status == TS_DEAD) /* task has been reaped */
108 unlink_and_free_task(t);
109 else if (t->status == TS_RUNNING) {
110 call_post_select(s, t); /* sets t->status */
111 t->notification = 0;
112 if (t->status == TS_RUNNING)
113 num_running_tasks++;
114 }
115 }
116 return num_running_tasks;
117 }
118
119 /**
120 * The core function of all paraslash programs.
121 *
122 * \param s Pointer to the scheduler struct.
123 *
124 * This function updates the global \a now pointer, calls all registered
125 * pre_select hooks which may set the timeout and add any file descriptors to
126 * the fd sets of \a s. Next, it calls para_select() and makes the result available
127 * to the registered tasks by calling their post_select hook.
128 *
129 * \return Zero if no more tasks are left in the task list, negative if the
130 * select function returned an error.
131 *
132 * \sa \ref now.
133 */
134 int schedule(struct sched *s)
135 {
136 int ret;
137 unsigned num_running_tasks;
138
139 if (!s->select_function)
140 s->select_function = para_select;
141 again:
142 FD_ZERO(&s->rfds);
143 FD_ZERO(&s->wfds);
144 s->select_timeout = s->default_timeout;
145 s->max_fileno = -1;
146 clock_get_realtime(&now_struct);
147 sched_preselect(s);
148 ret = s->select_function(s->max_fileno + 1, &s->rfds, &s->wfds,
149 &s->select_timeout);
150 if (ret < 0)
151 return ret;
152 if (ret == 0) {
153 /*
154 * APUE: Be careful not to check the descriptor sets on return
155 * unless the return value is greater than zero. The return
156 * state of the descriptor sets is implementation dependent if
157 * either a signal is caught or the timer expires.
158 */
159 FD_ZERO(&s->rfds);
160 FD_ZERO(&s->wfds);
161 }
162 clock_get_realtime(&now_struct);
163 num_running_tasks = sched_post_select(s);
164 if (num_running_tasks == 0)
165 return 0;
166 goto again;
167 }
168
169 /**
170 * Obtain the error status of a task and deallocate its resources.
171 *
172 * \param tptr Identifies the task to reap.
173 *
174 * This function is similar to wait(2) in that it returns information about a
175 * terminated task and allows to release the resources associated with the
176 * task. Until this function is called, the terminated task remains in a zombie
177 * state.
178 *
179 * \return If \a tptr is \p NULL, or \a *tptr is \p NULL, the function does
180 * nothing and returns zero. Otherwise, it is checked whether the task
181 * identified by \a tptr is still running. If it is, the function returns zero
182 * and again, no action is taken. Otherwise the (negative) error code of the
183 * terminated task is returned and \a *tptr is set to \p NULL. The task will
184 * then be removed removed from the scheduler task list.
185 *
186 * \sa \ref sched_shutdown(), wait(2).
187 */
188 int task_reap(struct task **tptr)
189 {
190 struct task *t;
191 int ret;
192
193 if (!tptr)
194 return 0;
195 t = *tptr;
196 if (!t)
197 return 0;
198 if (t->status >= 0)
199 return 0;
200 ret = t->status;
201 /*
202 * With list_for_each_entry_safe() it is only safe to remove the
203 * _current_ list item. Since we are being called from the loop in
204 * schedule() via some task's ->post_select() function, freeing the
205 * given task here would result in use-after-free bugs in schedule().
206 * So we only set the task status to TS_DEAD which tells schedule() to
207 * free the task in the next iteration of its loop.
208 */
209 t->status = TS_DEAD;
210
211 *tptr = NULL;
212 return ret;
213 }
214
215 /**
216 * Deallocate all resources of all tasks of a scheduler instance.
217 *
218 * \param s The scheduler instance.
219 *
220 * This should only be called after \ref schedule() has returned.
221 */
222 void sched_shutdown(struct sched *s)
223 {
224 struct task *t, *tmp;
225
226 list_for_each_entry_safe(t, tmp, &s->task_list, node) {
227 if (t->status == TS_RUNNING)
228 /* The task list should contain only terminated tasks. */
229 PARA_WARNING_LOG("shutting down running task %s\n",
230 t->name);
231 unlink_and_free_task(t);
232 }
233 }
234
235 /**
236 * Add a task to the scheduler task list.
237 *
238 * \param info Task information supplied by the caller.
239 * \param s The scheduler instance.
240 *
241 * \return A pointer to a newly allocated task structure. It will be
242 * freed by sched_shutdown().
243 */
244 struct task *task_register(struct task_info *info, struct sched *s)
245 {
246 struct task *t = para_malloc(sizeof(*t));
247
248 assert(info->post_select);
249
250 if (!s->task_list.next)
251 INIT_LIST_HEAD(&s->task_list);
252
253 t->info = *info;
254 t->name = para_strdup(info->name);
255 t->notification = 0;
256 t->status = TS_RUNNING;
257 list_add_tail(&t->node, &s->task_list);
258 return t;
259 }
260
261 /**
262 * Get the list of all registered tasks.
263 *
264 * \param s The scheduler instance to get the task list from.
265 *
266 * \return The task list.
267 *
268 * Each entry of the list contains an identifier which is simply a hex number.
269 * The result is dynamically allocated and must be freed by the caller.
270 */
271 char *get_task_list(struct sched *s)
272 {
273 struct task *t, *tmp;
274 char *msg = NULL;
275
276 list_for_each_entry_safe(t, tmp, &s->task_list, node) {
277 char *tmp_msg;
278 tmp_msg = make_message("%s%p\t%s\t%s\n", msg? msg : "", t,
279 t->status == TS_DEAD? "dead" :
280 (t->status == TS_RUNNING? "running" : "zombie"),
281 t->name);
282 free(msg);
283 msg = tmp_msg;
284 }
285 return msg;
286 }
287
288 /**
289 * Set the notification value of a task.
290 *
291 * \param t The task to notify.
292 * \param err A positive error code.
293 *
294 * Tasks which honor notifications are supposed to call \ref
295 * task_get_notification() in their post_select function and act on the
296 * returned notification value.
297 *
298 * If the scheduler detects during its pre_select loop that at least one task
299 * has been notified, the loop terminates, and the post_select methods of all
300 * taks are immediately called again.
301 *
302 * The notification for a task is reset after the call to its post_select
303 * method.
304 *
305 * \sa \ref task_get_notification().
306 */
307 void task_notify(struct task *t, int err)
308 {
309 assert(err > 0);
310 if (t->notification == -err) /* ignore subsequent notifications */
311 return;
312 PARA_INFO_LOG("notifying task %s: %s\n", t->name, para_strerror(err));
313 t->notification = -err;
314 }
315
316 /**
317 * Return the notification value of a task.
318 *
319 * \param t The task to get the notification value from.
320 *
321 * \return The notification value. If this is negative, the task has been
322 * notified by another task. Tasks are supposed to check for notifications by
323 * calling this function from their post_select method.
324 *
325 * \sa \ref task_notify().
326 */
327 int task_get_notification(const struct task *t)
328 {
329 return t->notification;
330 }
331
332 /**
333 * Return the status value of a task.
334 *
335 * \param t The task to get the status value from.
336 *
337 * \return Zero if task does not exist, one if task is running, negative error
338 * code if task has terminated.
339 */
340 int task_status(const struct task *t)
341 {
342 if (!t)
343 return 0;
344 if (t->status == TS_DEAD) /* pretend dead tasks don't exist */
345 return 0;
346 if (t->status == TS_RUNNING)
347 return 1;
348 return t->status;
349 }
350
351 /**
352 * Set the notification value of all tasks of a scheduler instance.
353 *
354 * \param s The scheduler instance whose tasks should be notified.
355 * \param err A positive error code.
356 *
357 * This simply iterates over all existing tasks of \a s and sets each
358 * task's notification value to \p -err.
359 */
360 void task_notify_all(struct sched *s, int err)
361 {
362 struct task *t;
363
364 list_for_each_entry(t, &s->task_list, node)
365 task_notify(t, err);
366 }
367
368 /**
369 * Set the select timeout to the minimal possible value.
370 *
371 * \param s Pointer to the scheduler struct.
372 *
373 * This causes the next select() call to return immediately.
374 */
375 void sched_min_delay(struct sched *s)
376 {
377 s->select_timeout.tv_sec = s->select_timeout.tv_usec = 0;
378 }
379
380 /**
381 * Impose an upper bound for the timeout of the next select() call.
382 *
383 * \param to Maximal allowed timeout.
384 * \param s Pointer to the scheduler struct.
385 *
386 * If the current scheduler timeout is already smaller than \a to, this
387 * function does nothing. Otherwise the timeout for the next select() call is
388 * set to the given value.
389 *
390 * \sa sched_request_timeout_ms().
391 */
392 void sched_request_timeout(struct timeval *to, struct sched *s)
393 {
394 if (tv_diff(&s->select_timeout, to, NULL) > 0)
395 s->select_timeout = *to;
396 }
397
398 /**
399 * Force the next select() call to return before the given amount of milliseconds.
400 *
401 * \param ms The maximal allowed timeout in milliseconds.
402 * \param s Pointer to the scheduler struct.
403 *
404 * Like sched_request_timeout() this imposes an upper bound on the timeout
405 * value for the next select() call.
406 */
407 void sched_request_timeout_ms(long unsigned ms, struct sched *s)
408 {
409 struct timeval tv;
410 ms2tv(ms, &tv);
411 sched_request_timeout(&tv, s);
412 }
413
414 /**
415 * Force the next select() call to return before the given future time.
416 *
417 * \param barrier Absolute time before select() should return.
418 * \param s Pointer to the scheduler struct.
419 *
420 * \return If \a barrier is in the past, this function does nothing and returns
421 * zero. Otherwise it returns one.
422 *
423 * \sa sched_request_barrier_or_min_delay().
424 */
425 int sched_request_barrier(struct timeval *barrier, struct sched *s)
426 {
427 struct timeval diff;
428
429 if (tv_diff(now, barrier, &diff) > 0)
430 return 0;
431 sched_request_timeout(&diff, s);
432 return 1;
433 }
434
435 /**
436 * Force the next select() call to return before the given time.
437 *
438 * \param barrier Absolute time before select() should return.
439 * \param s Pointer to the scheduler struct.
440 *
441 * \return If \a barrier is in the past, this function requests a minimal
442 * timeout and returns zero. Otherwise it returns one.
443 *
444 * \sa sched_min_delay(), sched_request_barrier().
445 */
446 int sched_request_barrier_or_min_delay(struct timeval *barrier, struct sched *s)
447 {
448 struct timeval diff;
449
450 if (tv_diff(now, barrier, &diff) > 0) {
451 sched_min_delay(s);
452 return 0;
453 }
454 sched_request_timeout(&diff, s);
455 return 1;
456 }