]> git.pond.sub.org Git - empserver/blob - src/lib/lwp/lwp.c
Update copyright notice
[empserver] / src / lib / lwp / lwp.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1994-2008, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                           Ken Stevens, Steve McClure
5  *  Copyright (C) 1991-3 Stephen Crane
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  *  ---
22  *
23  *  See files README, COPYING and CREDITS in the root of the source
24  *  tree for related information and legal notices.  It is expected
25  *  that future projects/authors will amend these files as needed.
26  *
27  *  ---
28  *
29  *  lwp.c: lightweight process creation, destruction and manipulation
30  * 
31  *  Known contributors to this file:
32  *     Markus Armbruster, 2004-2007
33  */
34
35 #include <config.h>
36
37 #include <string.h>
38 #include "lwp.h"
39 #include "lwpint.h"
40 #include "prototypes.h"
41
42 struct lwpQueue LwpSchedQ[LWP_MAX_PRIO], LwpDeadQ;
43
44 struct lwpProc *LwpCurrent = NULL;
45 void **LwpContextPtr;
46 int LwpMaxpri = 0;              /* maximum priority so far */
47 int LwpStackGrowsDown;
48
49 static void lwpDestroy(struct lwpProc *proc);
50 static void lwpStackCheckInit(struct lwpProc *newp);
51 static void lwpStackCheck(struct lwpProc *newp);
52 static void lwpStackCheckUsed(struct lwpProc *newp);
53
54 /* check stack direction */
55 static int
56 growsdown(void *x)
57 {
58     int y;
59     y = (x > (void *)&y);
60     return y;
61 }
62
63 /*
64  * lwpReschedule -- schedule another process.  we also check for dead
65  * processes here and free them.
66  */
67 void
68 lwpReschedule(void)
69 {
70     static struct lwpProc *nextp;
71     static int i;
72
73     if (LwpCurrent && (LwpCurrent->flags & LWP_STACKCHECK)) {
74         lwpStackCheck(LwpCurrent);
75     }
76
77     lwpSigWakeup();
78     lwpWakeupSleep();
79
80     /* destroy dead threads */
81     lwpStatus(LwpCurrent, "Cleaning dead queue");
82     while (NULL != (nextp = lwpGetFirst(&LwpDeadQ))) {
83         if (CANT_HAPPEN(nextp == LwpCurrent))
84             abort();
85         lwpDestroy(nextp);
86         lwpStatus(LwpCurrent, "Destroying done");
87     }
88
89     for (i = LwpMaxpri + 1; i--;) {
90         while (NULL != (nextp = lwpGetFirst(&LwpSchedQ[i]))) {
91             if (!nextp->dead)
92                 break;
93             /* clean up after dead bodies */
94             lwpStatus(nextp, "got a dead body");
95             if (nextp == LwpCurrent) {
96                 lwpStatus(nextp, "we are in it -- will bury later");
97                 lwpAddTail(&LwpDeadQ, nextp);
98             } else {
99                 lwpDestroy(nextp);
100             }
101             nextp = 0;
102         }
103         if (nextp)
104             break;
105     }
106     if (CANT_HAPPEN(LwpCurrent == 0 && nextp == 0))
107         abort();
108     if (LwpCurrent != nextp) {
109         struct lwpProc *oldp = LwpCurrent;
110         if (oldp)
111             lwpStatus(oldp, "switch out");
112         LwpCurrent = nextp;
113         *LwpContextPtr = nextp->ud;
114         lwpSwitchContext(oldp, nextp);
115         lwpStatus(nextp, "switch in %d", nextp->pri);
116     }
117 }
118
119 /*
120  * lwpEntryPoint -- process entry point.
121  */
122 void
123 lwpEntryPoint(void)
124 {
125     lwpStatus(LwpCurrent, "starting at entry point");
126     (*LwpCurrent->entry)(LwpCurrent->ud);
127     lwpExit();
128 }
129
130 /*
131  * lwpCreate -- create a process.
132  */
133 struct lwpProc *
134 lwpCreate(int priority, void (*entry)(void *), int stacksz,
135           int flags, char *name, int argc, char **argv, void *ud)
136 {
137     struct lwpProc *newp;
138
139     if (!(newp = malloc(sizeof(struct lwpProc))))
140         return NULL;
141     newp->flags = flags;
142     newp->name = strdup(name);
143     newp->entry = entry;
144     newp->argc = argc;
145     newp->argv = argv;
146     newp->ud = ud;
147     newp->dead = 0;
148     newp->runtime = (time_t)-1;
149     newp->fd = -1;
150     if (LWP_MAX_PRIO <= priority)
151         priority = LWP_MAX_PRIO - 1;
152     if (LwpMaxpri < (newp->pri = priority))
153         LwpMaxpri = priority;
154     if (lwpNewContext(newp, stacksz) < 0) {
155         free(newp->name);
156         free(newp);
157         return NULL;
158     }
159     lwpStatus(newp, "creating process structure %p (sbtm %p)",
160               newp, newp->sbtm);
161     if (flags & LWP_STACKCHECK)
162         lwpStackCheckInit(newp);
163     lwpReady(newp);
164     lwpReady(LwpCurrent);
165     lwpReschedule();
166     return newp;
167 }
168
169 static void
170 lwpDestroy(struct lwpProc *proc)
171 {
172     if (proc->flags & LWP_STACKCHECK) {
173         lwpStackCheckUsed(proc);
174         lwpStackCheck(proc);
175     }
176     lwpStatus(proc, "destroying sbtm: %p", proc->sbtm);
177     free(proc->sbtm);
178     free(proc->name);
179     free(proc);
180 }
181
182 /*
183  * lwpReady -- put process on ready queue.  if null, assume current.
184  */
185 void
186 lwpReady(struct lwpProc *p)
187 {
188     if (!p)
189         p = LwpCurrent;
190     lwpStatus(p, "added to run queue");
191     lwpAddTail(&LwpSchedQ[p->pri], p);
192 }
193
194 /*
195  * return user's data
196  */
197 void *
198 lwpGetUD(struct lwpProc *p)
199 {
200     if (!p)
201         p = LwpCurrent;
202     return p->ud;
203 }
204
205 /*
206  * set user's data
207  */
208 void
209 lwpSetUD(struct lwpProc *p, char *ud)
210 {
211     if (!p)
212         p = LwpCurrent;
213     p->ud = ud;
214 }
215
216 /*
217  * lwpYield -- yield the processor to another thread.
218  */
219 void
220 lwpYield(void)
221 {
222     lwpStatus(LwpCurrent, "yielding control");
223     lwpReady(LwpCurrent);
224     lwpReschedule();
225 }
226
227 /*
228  * cause the current process to be scheduled for deletion.
229  */
230 void
231 lwpExit(void)
232 {
233     lwpStatus(LwpCurrent, "marking self as dead");
234     LwpCurrent->dead = 1;
235     lwpYield();
236 }
237
238 /*
239  * mark another process as dead, so it will never be rescheduled.
240  * remove any lingering FD action
241  */
242 void
243 lwpTerminate(struct lwpProc *p)
244 {
245     lwpStatus(p, "terminating process");
246     p->dead = 1;
247     lwpWakeup(p);
248 }
249
250 /*
251  * set the thread's priority, returning the old.
252  * if the new priority is lower than the old, we reschedule.
253  */
254 int
255 lwpSetPriority(int new)
256 {
257     int old = LwpCurrent->pri;
258
259     if (LWP_MAX_PRIO <= new)
260         new = LWP_MAX_PRIO - 1;
261     if (LwpMaxpri < new)
262         LwpMaxpri = new;
263     LwpCurrent->pri = new;
264     lwpStatus(LwpCurrent, "resetting priority (%d -> %d)", old, new);
265     if (new < old)
266         lwpYield();
267     return old;
268 }
269
270 /*
271  * initialise the coroutine structures
272  */
273 struct lwpProc *
274 lwpInitSystem(int pri, void **ctxptr, int flags, sigset_t *waitset)
275 {
276     struct lwpQueue *q;
277     int i, *stack, marker;
278     struct lwpProc *sel;
279
280     LwpContextPtr = ctxptr;
281     if (pri < 1)
282         pri = 1;
283     LwpStackGrowsDown = growsdown(&marker);
284     if (!(LwpCurrent = calloc(1, sizeof(struct lwpProc))))
285         return NULL;
286     if (!(stack = malloc(64)))
287         return NULL;
288     if (LWP_MAX_PRIO <= pri)
289         pri = LWP_MAX_PRIO - 1;
290     if (LwpMaxpri < pri)
291         LwpMaxpri = pri;
292     LwpCurrent->next = 0;
293     LwpCurrent->sbtm = stack;   /* dummy stack for "main" */
294     LwpCurrent->pri = pri;
295     LwpCurrent->dead = 0;
296     LwpCurrent->flags = flags & ~LWP_STACKCHECK;
297     LwpCurrent->name = "Main";
298     for (i = LWP_MAX_PRIO, q = LwpSchedQ; i--; q++)
299         q->head = q->tail = 0;
300     LwpDeadQ.head = LwpDeadQ.tail = 0;
301     lwpInitSigWait(waitset);
302     /* must be lower in priority than us for this to work right */
303     sel = lwpCreate(0, lwpSelect, 16384, flags, "EventHandler", 0, 0, 0);
304     lwpInitSelect(sel);
305     return LwpCurrent;
306 }
307
308 /* lwpStackCheckInit
309  *
310  * Initialize the entire stack (including both redzones) with the stack
311  * check mark.  Thus, we can get some indication of how much stack was
312  * used.
313  */
314 static void
315 lwpStackCheckInit(struct lwpProc *newp)
316 {
317     int *p;
318     int *lim = (int *)((char *)newp->sbtm + newp->size);
319
320     for (p = newp->sbtm; p < lim; p++)
321         *p = LWP_CHECKMARK;
322 }
323
324 /* lwpStackCheck
325  *
326  * Check if the thread has overflowed/underflowed its stack.
327  * Should that happen, abort the process, as we cannot recover.
328  */
329 static void
330 lwpStackCheck(struct lwpProc *newp)
331 {
332     int *btm = (int *)(newp->ustack - LWP_REDZONE);
333     int *top = (int *)(newp->ustack + newp->usize + LWP_REDZONE);
334     int n = LWP_REDZONE / sizeof(int);
335     int i, lo_clean, hi_clean, overflow, underflow;
336
337     for (i = 0; i < n && btm[i] == LWP_CHECKMARK; i++) ;
338     lo_clean = i;
339
340     for (i = 1; i <= n && top[-i] == LWP_CHECKMARK; i++) ;
341     hi_clean = i - 1;
342
343     if (LwpStackGrowsDown) {
344         overflow = n - lo_clean;
345         underflow = n - hi_clean;
346     } else {
347         overflow = n - hi_clean;
348         underflow = n - lo_clean;
349     }
350     if (overflow)
351         logerror("Thread %s stack overflow %d bytes",
352                  newp->name, overflow * (int)sizeof(int));
353     if (underflow)
354         logerror("Thread %s stack underflow %d bytes",
355                  newp->name, underflow * (int)sizeof(int));
356     if (overflow || underflow)
357         abort();
358 }
359
360 /* lwpStackCheckUsed
361  *
362  * Figure out how much stack was used by this thread.
363  */
364 static void
365 lwpStackCheckUsed(struct lwpProc *newp)
366 {
367     int *base = (int *)newp->ustack;
368     int *lim = (int *)(newp->ustack + newp->usize);
369     int total = (lim + 1 - base) * sizeof(int);
370     int used, *p;
371
372     if (LwpStackGrowsDown) {
373         for (p = base; p < lim && *p == LWP_CHECKMARK; ++p) ;
374         used = (lim - p) * sizeof(int);
375     } else {
376         for (p = lim - 1; p >= base && *p == LWP_CHECKMARK; --p) ;
377         used = (p - base + 1) * sizeof(int);
378     }
379     lwpStatus(newp, "Thread stack %d used, %d left, %d total",
380               used, total - used, total);
381 }