]> git.pond.sub.org Git - empserver/blob - src/lib/lwp/lwp.c
Streamline copyright notices. Clearly document Stephen Crane's in
[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 the "LEGAL", "LICENSE", "CREDITS" and "README" files for all the
24  *  related information and legal notices. It is expected that any future
25  *  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 <signal.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include "lwp.h"
42 #include "lwpint.h"
43 #include "prototypes.h"
44
45 struct lwpQueue LwpSchedQ[LWP_MAX_PRIO], LwpDeadQ;
46
47 struct lwpProc *LwpCurrent = NULL;
48 char **LwpContextPtr;
49 int LwpMaxpri = 0;              /* maximum priority so far */
50 int LwpStackGrowsDown;
51
52 static sigset_t oldmask;
53
54 static void lwpStackCheckInit(struct lwpProc *newp);
55 static void lwpStackCheck(struct lwpProc *newp);
56 static void lwpStackCheckUsed(struct lwpProc *newp);
57
58 /* check stack direction */
59 static int
60 growsdown(void *x)
61 {
62     int y;
63     y = (x > (void *)&y);
64     return y;
65 }
66
67 /*
68  * lwpReschedule -- schedule another process.  we also check for dead
69  * processes here and free them.
70  */
71 void
72 lwpReschedule(void)
73 {
74     static int lcount = LCOUNT;
75     static struct lwpProc *nextp;
76     static int i;
77     static sigset_t tmask;
78
79     if (LwpCurrent && (LwpCurrent->flags & LWP_STACKCHECK)) {
80         lwpStackCheck(LwpCurrent);
81     }
82     if (!--lcount) {
83         int p = lwpSetPriority(LWP_MAX_PRIO - 1);
84         lcount = LCOUNT;
85         sigprocmask(SIG_SETMASK, &oldmask, &tmask);
86         sigprocmask(SIG_SETMASK, &tmask, &oldmask);
87         LwpCurrent->pri = p;
88     }
89
90     /* destroy dead threads */
91     lwpStatus(LwpCurrent, "Cleaning dead queue");
92     while (NULL != (nextp = lwpGetFirst(&LwpDeadQ))) {
93         if (nextp == LwpCurrent) {
94             lwpStatus(nextp, "OOOPS, we are running already dead thread");
95             exit(1);
96         }
97         lwpDestroy(nextp);
98         lwpStatus(LwpCurrent, "Destroying done");
99     }
100
101     for (i = LwpMaxpri + 1; i--;) {
102         while (NULL != (nextp = lwpGetFirst(&LwpSchedQ[i]))) {
103             if (!nextp->dead)
104                 break;
105             /* clean up after dead bodies */
106             lwpStatus(nextp, "got a dead body");
107             if (nextp == LwpCurrent) {
108                 lwpStatus(nextp, "we are in it -- will bury later");
109                 lwpAddTail(&LwpDeadQ, nextp);
110             } else {
111                 lwpDestroy(nextp);
112             }
113             nextp = 0;
114         }
115         if (nextp)
116             break;
117     }
118     if (LwpCurrent == 0 && nextp == 0) {
119         fprintf(stderr, "No processes to run!\n");
120         exit(1);
121     }
122     if (LwpCurrent != nextp) {
123         struct lwpProc *oldp = LwpCurrent;
124         if (oldp)
125             lwpStatus(oldp, "switch out");
126         LwpCurrent = nextp;
127         *LwpContextPtr = nextp->ud;
128         lwpSwitchContext(oldp, nextp);
129         lwpStatus(nextp, "switch in %d", nextp->pri);
130     }
131 }
132
133 /*
134  * lwpEntryPoint -- process entry point.
135  */
136 void
137 lwpEntryPoint(void)
138 {
139     sigset_t set;
140
141     sigemptyset(&set);
142     sigaddset(&set, SIGALRM);
143     sigprocmask(SIG_SETMASK, &set, &oldmask);
144     *LwpContextPtr = LwpCurrent->ud;
145
146     lwpStatus(LwpCurrent, "starting at entry point");
147     (*LwpCurrent->entry)(LwpCurrent->ud);
148     lwpExit();
149 }
150
151 /*
152  * lwpCreate -- create a process.
153  */
154 struct lwpProc *
155 lwpCreate(int priority, void (*entry)(void *), int stacksz, int flags, char *name, char *desc, int argc, char **argv, void *ud)
156 {
157     struct lwpProc *newp;
158
159     if (!(newp = malloc(sizeof(struct lwpProc))))
160         return NULL;
161     newp->flags = flags;
162     newp->name = strdup(name);
163     newp->desc = strdup(desc);
164     newp->entry = entry;
165     newp->argc = argc;
166     newp->argv = argv;
167     newp->ud = ud;
168     newp->dead = 0;
169     if (LWP_MAX_PRIO <= priority)
170         priority = LWP_MAX_PRIO - 1;
171     if (LwpMaxpri < (newp->pri = priority))
172         LwpMaxpri = priority;
173     if (lwpNewContext(newp, stacksz) < 0) {
174         free(newp->name);
175         free(newp->desc);
176         free(newp);
177         return NULL;
178     }
179     lwpStatus(newp, "creating process structure %p (sbtm %p)",
180               newp, newp->sbtm);
181     if (flags & LWP_STACKCHECK)
182         lwpStackCheckInit(newp);
183     lwpReady(newp);
184     lwpReady(LwpCurrent);
185     lwpReschedule();
186     return newp;
187 }
188
189 void
190 lwpDestroy(struct lwpProc *proc)
191 {
192     if (proc->flags & LWP_STACKCHECK) {
193         lwpStackCheckUsed(proc);
194         lwpStackCheck(proc);
195     }
196     lwpStatus(proc, "destroying sbtm: %p", proc->sbtm);
197     free(proc->sbtm);
198     free(proc->name);
199     free(proc->desc);
200     free(proc);
201 }
202
203 /*
204  * lwpReady -- put process on ready queue.  if null, assume current.
205  */
206 void
207 lwpReady(struct lwpProc *p)
208 {
209     if (!p)
210         p = LwpCurrent;
211     lwpStatus(p, "added to run queue");
212     lwpAddTail(&LwpSchedQ[p->pri], p);
213 }
214
215 /*
216  * return user's data
217  */
218 void *
219 lwpGetUD(struct lwpProc *p)
220 {
221     if (!p)
222         p = LwpCurrent;
223     return p->ud;
224 }
225
226 /*
227  * set user's data
228  */
229 void
230 lwpSetUD(struct lwpProc *p, char *ud)
231 {
232     if (!p)
233         p = LwpCurrent;
234     p->ud = ud;
235 }
236
237 /*
238  * set name & desc
239  */
240 void
241 lwpSetDesc(struct lwpProc *p, char *name, char *desc)
242 {
243     if (!p)
244         p = LwpCurrent;
245     free(p->name);
246     free(p->desc);
247     p->name = strdup(name);
248     p->desc = strdup(desc);
249 }
250
251 /*
252  * lwpYield -- yield the processor to another thread.
253  */
254 void
255 lwpYield(void)
256 {
257     lwpStatus(LwpCurrent, "yielding control");
258     lwpReady(LwpCurrent);
259     lwpReschedule();
260 }
261
262 /*
263  * cause the current process to be scheduled for deletion.
264  */
265 void
266 lwpExit(void)
267 {
268     lwpStatus(LwpCurrent, "marking self as dead");
269     LwpCurrent->dead = 1;
270     lwpYield();
271 }
272
273 /*
274  * mark another process as dead, so it will never be rescheduled.
275  * remove any lingering FD action
276  */
277 void
278 lwpTerminate(struct lwpProc *p)
279 {
280     lwpStatus(p, "terminating process");
281     p->dead = 1;
282     if (p->fd >= 0)
283         lwpWakeupFd(p);
284 }
285
286 /*
287  * set the thread's priority, returning the old.
288  * if the new priority is lower than the old, we reschedule.
289  */
290 int
291 lwpSetPriority(int new)
292 {
293     int old = LwpCurrent->pri;
294
295     if (LWP_MAX_PRIO <= new)
296         new = LWP_MAX_PRIO - 1;
297     if (LwpMaxpri < new)
298         LwpMaxpri = new;
299     LwpCurrent->pri = new;
300     lwpStatus(LwpCurrent, "resetting priority (%d -> %d)", old, new);
301     if (new < old)
302         lwpYield();
303     return old;
304 }
305
306 /*
307  * initialise the coroutine structures
308  */
309 struct lwpProc *
310 lwpInitSystem(int pri, char **ctxptr, int flags)
311 {
312     struct lwpQueue *q;
313     int i, *stack, marker;
314     struct lwpProc *sel;
315
316     LwpContextPtr = ctxptr;
317     if (pri < 1)
318         pri = 1;
319     /* *LwpContextPtr = 0; */
320     LwpStackGrowsDown = growsdown(&marker);
321     if (!(LwpCurrent = calloc(1, sizeof(struct lwpProc))))
322         return NULL;
323     if (!(stack = malloc(64)))
324         return NULL;
325     if (LWP_MAX_PRIO <= pri)
326         pri = LWP_MAX_PRIO - 1;
327     if (LwpMaxpri < pri)
328         LwpMaxpri = pri;
329     LwpCurrent->next = 0;
330     LwpCurrent->sbtm = stack;   /* dummy stack for "main" */
331     LwpCurrent->pri = pri;
332     LwpCurrent->dead = 0;
333     LwpCurrent->flags = flags & ~LWP_STACKCHECK;
334     LwpCurrent->name = "Main";
335     for (i = LWP_MAX_PRIO, q = LwpSchedQ; i--; q++)
336         q->head = q->tail = 0;
337     LwpDeadQ.head = LwpDeadQ.tail = 0;
338     /* must be lower in priority than us for this to work right */
339     sel = lwpCreate(0, lwpSelect, 16384, flags, "EventHandler",
340                     "Select (main loop) Event Handler", 0, 0, 0);
341     lwpInitSelect(sel);
342     return LwpCurrent;
343 }
344
345 /* lwpStackCheckInit
346  *
347  * Initialize the entire stack (including both redzones) with the stack
348  * check mark.  Thus, we can get some indication of how much stack was
349  * used.
350  */
351 static void
352 lwpStackCheckInit(struct lwpProc *newp)
353 {
354     int *p;
355     int *lim = (int *)((char *)newp->sbtm + newp->size);
356
357     for (p = newp->sbtm; p < lim; p++)
358         *p = LWP_CHECKMARK;
359 }
360
361 /* lwpStackCheck
362  *
363  * Check if the thread has overflowed/underflowed its stack.
364  * Should that happen, abort the process, as we cannot recover.
365  */
366 static void
367 lwpStackCheck(struct lwpProc *newp)
368 {
369     int *btm = (int *)(newp->ustack - LWP_REDZONE);
370     int *top = (int *)(newp->ustack + newp->usize + LWP_REDZONE);
371     int n = LWP_REDZONE / sizeof(int);
372     int i, lo_clean, hi_clean, overflow, underflow;
373
374     for (i = 0; i < n && btm[i] == LWP_CHECKMARK; i++) ;
375     lo_clean = i;
376
377     for (i = 1; i <= n && top[-i] == LWP_CHECKMARK; i++) ;
378     hi_clean = i - 1;
379
380     if (LwpStackGrowsDown) {
381         overflow = n - lo_clean;
382         underflow = n - hi_clean;
383     } else {
384         overflow = n - hi_clean;
385         underflow = n - lo_clean;
386     }
387     if (overflow)
388         logerror("Thread %s stack overflow %d bytes",
389                  newp->name, overflow * (int)sizeof(int));
390     if (underflow)
391         logerror("Thread %s stack underflow %d bytes",
392                  newp->name, underflow * (int)sizeof(int));
393     if (overflow || underflow)
394         abort();
395 }
396
397 /* lwpStackCheckUsed
398  *
399  * Figure out how much stack was used by this thread.
400  */
401 static void
402 lwpStackCheckUsed(struct lwpProc *newp)
403 {
404     int *base = (int *)newp->ustack;
405     int *lim = (int *)(newp->ustack + newp->usize);
406     int total = (lim + 1 - base) * sizeof(int);
407     int used, *p;
408
409     if (LwpStackGrowsDown) {
410         for (p = base; p < lim && *p == LWP_CHECKMARK; ++p) ;
411         used = (lim - p) * sizeof(int);
412     } else {
413         for (p = lim - 1; p >= base && *p == LWP_CHECKMARK; --p) ;
414         used = (p - base + 1) * sizeof(int);
415     }
416     lwpStatus(newp, "Thread stack %d used, %d left, %d total",
417               used, total - used, total);
418 }