]> git.pond.sub.org Git - empserver/blob - src/lib/lwp/lwp.c
de10fbc4f344cf657f4d64c4038908ed673a9873
[empserver] / src / lib / lwp / lwp.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1994-2006, 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-2006
33  */
34
35 #include <config.h>
36
37 #include <stdio.h>
38 #include <string.h>
39 #include "lwp.h"
40 #include "lwpint.h"
41 #include "prototypes.h"
42
43 struct lwpQueue LwpSchedQ[LWP_MAX_PRIO], LwpDeadQ;
44
45 struct lwpProc *LwpCurrent = NULL;
46 void **LwpContextPtr;
47 int LwpMaxpri = 0;              /* maximum priority so far */
48 int LwpStackGrowsDown;
49
50 static void lwpDestroy(struct lwpProc *proc);
51 static void lwpStackCheckInit(struct lwpProc *newp);
52 static void lwpStackCheck(struct lwpProc *newp);
53 static void lwpStackCheckUsed(struct lwpProc *newp);
54
55 /* check stack direction */
56 static int
57 growsdown(void *x)
58 {
59     int y;
60     y = (x > (void *)&y);
61     return y;
62 }
63
64 /*
65  * lwpReschedule -- schedule another process.  we also check for dead
66  * processes here and free them.
67  */
68 void
69 lwpReschedule(void)
70 {
71     static struct lwpProc *nextp;
72     static int i;
73
74     if (LwpCurrent && (LwpCurrent->flags & LWP_STACKCHECK)) {
75         lwpStackCheck(LwpCurrent);
76     }
77
78     lwpSigWakeup();
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, int flags, char *name, char *desc, int argc, char **argv, void *ud)
135 {
136     struct lwpProc *newp;
137
138     if (!(newp = malloc(sizeof(struct lwpProc))))
139         return NULL;
140     newp->flags = flags;
141     newp->name = strdup(name);
142     newp->desc = strdup(desc);
143     newp->entry = entry;
144     newp->argc = argc;
145     newp->argv = argv;
146     newp->ud = ud;
147     newp->dead = 0;
148     if (LWP_MAX_PRIO <= priority)
149         priority = LWP_MAX_PRIO - 1;
150     if (LwpMaxpri < (newp->pri = priority))
151         LwpMaxpri = priority;
152     if (lwpNewContext(newp, stacksz) < 0) {
153         free(newp->name);
154         free(newp->desc);
155         free(newp);
156         return NULL;
157     }
158     lwpStatus(newp, "creating process structure %p (sbtm %p)",
159               newp, newp->sbtm);
160     if (flags & LWP_STACKCHECK)
161         lwpStackCheckInit(newp);
162     lwpReady(newp);
163     lwpReady(LwpCurrent);
164     lwpReschedule();
165     return newp;
166 }
167
168 void
169 lwpDestroy(struct lwpProc *proc)
170 {
171     if (proc->flags & LWP_STACKCHECK) {
172         lwpStackCheckUsed(proc);
173         lwpStackCheck(proc);
174     }
175     lwpStatus(proc, "destroying sbtm: %p", proc->sbtm);
176     free(proc->sbtm);
177     free(proc->name);
178     free(proc->desc);
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  * set name & desc
218  */
219 void
220 lwpSetDesc(struct lwpProc *p, char *name, char *desc)
221 {
222     if (!p)
223         p = LwpCurrent;
224     free(p->name);
225     free(p->desc);
226     p->name = strdup(name);
227     p->desc = strdup(desc);
228 }
229
230 /*
231  * lwpYield -- yield the processor to another thread.
232  */
233 void
234 lwpYield(void)
235 {
236     lwpStatus(LwpCurrent, "yielding control");
237     lwpReady(LwpCurrent);
238     lwpReschedule();
239 }
240
241 /*
242  * cause the current process to be scheduled for deletion.
243  */
244 void
245 lwpExit(void)
246 {
247     lwpStatus(LwpCurrent, "marking self as dead");
248     LwpCurrent->dead = 1;
249     lwpYield();
250 }
251
252 /*
253  * mark another process as dead, so it will never be rescheduled.
254  * remove any lingering FD action
255  */
256 void
257 lwpTerminate(struct lwpProc *p)
258 {
259     lwpStatus(p, "terminating process");
260     p->dead = 1;
261     if (p->fd >= 0)
262         lwpWakeupFd(p);
263 }
264
265 /*
266  * set the thread's priority, returning the old.
267  * if the new priority is lower than the old, we reschedule.
268  */
269 int
270 lwpSetPriority(int new)
271 {
272     int old = LwpCurrent->pri;
273
274     if (LWP_MAX_PRIO <= new)
275         new = LWP_MAX_PRIO - 1;
276     if (LwpMaxpri < new)
277         LwpMaxpri = new;
278     LwpCurrent->pri = new;
279     lwpStatus(LwpCurrent, "resetting priority (%d -> %d)", old, new);
280     if (new < old)
281         lwpYield();
282     return old;
283 }
284
285 /*
286  * initialise the coroutine structures
287  */
288 struct lwpProc *
289 lwpInitSystem(int pri, void **ctxptr, int flags, sigset_t *waitset)
290 {
291     struct lwpQueue *q;
292     int i, *stack, marker;
293     struct lwpProc *sel;
294
295     LwpContextPtr = ctxptr;
296     if (pri < 1)
297         pri = 1;
298     LwpStackGrowsDown = growsdown(&marker);
299     if (!(LwpCurrent = calloc(1, sizeof(struct lwpProc))))
300         return NULL;
301     if (!(stack = malloc(64)))
302         return NULL;
303     if (LWP_MAX_PRIO <= pri)
304         pri = LWP_MAX_PRIO - 1;
305     if (LwpMaxpri < pri)
306         LwpMaxpri = pri;
307     LwpCurrent->next = 0;
308     LwpCurrent->sbtm = stack;   /* dummy stack for "main" */
309     LwpCurrent->pri = pri;
310     LwpCurrent->dead = 0;
311     LwpCurrent->flags = flags & ~LWP_STACKCHECK;
312     LwpCurrent->name = "Main";
313     for (i = LWP_MAX_PRIO, q = LwpSchedQ; i--; q++)
314         q->head = q->tail = 0;
315     LwpDeadQ.head = LwpDeadQ.tail = 0;
316     lwpInitSigWait(waitset);
317     /* must be lower in priority than us for this to work right */
318     sel = lwpCreate(0, lwpSelect, 16384, flags, "EventHandler",
319                     "Select (main loop) Event Handler", 0, 0, 0);
320     lwpInitSelect(sel);
321     return LwpCurrent;
322 }
323
324 /* lwpStackCheckInit
325  *
326  * Initialize the entire stack (including both redzones) with the stack
327  * check mark.  Thus, we can get some indication of how much stack was
328  * used.
329  */
330 static void
331 lwpStackCheckInit(struct lwpProc *newp)
332 {
333     int *p;
334     int *lim = (int *)((char *)newp->sbtm + newp->size);
335
336     for (p = newp->sbtm; p < lim; p++)
337         *p = LWP_CHECKMARK;
338 }
339
340 /* lwpStackCheck
341  *
342  * Check if the thread has overflowed/underflowed its stack.
343  * Should that happen, abort the process, as we cannot recover.
344  */
345 static void
346 lwpStackCheck(struct lwpProc *newp)
347 {
348     int *btm = (int *)(newp->ustack - LWP_REDZONE);
349     int *top = (int *)(newp->ustack + newp->usize + LWP_REDZONE);
350     int n = LWP_REDZONE / sizeof(int);
351     int i, lo_clean, hi_clean, overflow, underflow;
352
353     for (i = 0; i < n && btm[i] == LWP_CHECKMARK; i++) ;
354     lo_clean = i;
355
356     for (i = 1; i <= n && top[-i] == LWP_CHECKMARK; i++) ;
357     hi_clean = i - 1;
358
359     if (LwpStackGrowsDown) {
360         overflow = n - lo_clean;
361         underflow = n - hi_clean;
362     } else {
363         overflow = n - hi_clean;
364         underflow = n - lo_clean;
365     }
366     if (overflow)
367         logerror("Thread %s stack overflow %d bytes",
368                  newp->name, overflow * (int)sizeof(int));
369     if (underflow)
370         logerror("Thread %s stack underflow %d bytes",
371                  newp->name, underflow * (int)sizeof(int));
372     if (overflow || underflow)
373         abort();
374 }
375
376 /* lwpStackCheckUsed
377  *
378  * Figure out how much stack was used by this thread.
379  */
380 static void
381 lwpStackCheckUsed(struct lwpProc *newp)
382 {
383     int *base = (int *)newp->ustack;
384     int *lim = (int *)(newp->ustack + newp->usize);
385     int total = (lim + 1 - base) * sizeof(int);
386     int used, *p;
387
388     if (LwpStackGrowsDown) {
389         for (p = base; p < lim && *p == LWP_CHECKMARK; ++p) ;
390         used = (lim - p) * sizeof(int);
391     } else {
392         for (p = lim - 1; p >= base && *p == LWP_CHECKMARK; --p) ;
393         used = (p - base + 1) * sizeof(int);
394     }
395     lwpStatus(newp, "Thread stack %d used, %d left, %d total",
396               used, total - used, total);
397 }