]> 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-2009, 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-2008
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 static struct lwpQueue LwpSchedQ[LWP_MAX_PRIO], LwpDeadQ;
43
44 struct lwpProc *LwpCurrent = NULL;
45 static void **LwpContextPtr;
46 static int LwpMaxpri = 0;       /* maximum priority so far */
47 static 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 static int
131 lwpNewStack(struct lwpProc *newp, int stacksz)
132 {
133     char *s;
134     int size, redsize;
135
136     /* Make size a multiple of sizeof(long) to keep things aligned */
137     stacksz = (stacksz + sizeof(long) - 1) & -sizeof(long);
138     /* Add a red zone on each side of the stack for LWP_STACKCHECK */
139     redsize = newp->flags & LWP_STACKCHECK ? LWP_REDZONE : 0;
140     size = stacksz + 2 * redsize;
141
142     s = malloc(size);
143     if (!s)
144         return -1;
145
146     newp->sbtm = s;
147     newp->size = size;
148     newp->ustack = s + redsize;
149     newp->usize = stacksz;
150
151     if (newp->flags & LWP_STACKCHECK)
152         lwpStackCheckInit(newp);
153     return 0;
154 }
155
156 /*
157  * lwpCreate -- create a process.
158  */
159 struct lwpProc *
160 lwpCreate(int priority, void (*entry)(void *), int stacksz,
161           int flags, char *name, int argc, char **argv, void *ud)
162 {
163     struct lwpProc *newp;
164
165     if (!(newp = malloc(sizeof(struct lwpProc))))
166         return NULL;
167     newp->flags = flags;
168     newp->name = strdup(name);
169     newp->entry = entry;
170     newp->argc = argc;
171     newp->argv = argv;
172     newp->ud = ud;
173     newp->dead = 0;
174     newp->runtime = (time_t)-1;
175     newp->fd = -1;
176     newp->sbtm = NULL;
177     if (LWP_MAX_PRIO <= priority)
178         priority = LWP_MAX_PRIO - 1;
179     if (LwpMaxpri < (newp->pri = priority))
180         LwpMaxpri = priority;
181     if (lwpNewStack(newp, stacksz) < 0 || lwpNewContext(newp) < 0) {
182         free(newp->sbtm);
183         free(newp->name);
184         free(newp);
185         return NULL;
186     }
187     lwpStatus(newp, "creating process structure %p (sbtm %p)",
188               newp, newp->sbtm);
189     lwpReady(newp);
190     lwpReady(LwpCurrent);
191     lwpReschedule();
192     return newp;
193 }
194
195 static void
196 lwpDestroy(struct lwpProc *proc)
197 {
198     if (proc->flags & LWP_STACKCHECK) {
199         lwpStackCheckUsed(proc);
200         lwpStackCheck(proc);
201     }
202     lwpStatus(proc, "destroying sbtm: %p", proc->sbtm);
203     free(proc->sbtm);
204     free(proc->name);
205     free(proc);
206 }
207
208 /*
209  * lwpReady -- put process on ready queue.  if null, assume current.
210  */
211 void
212 lwpReady(struct lwpProc *p)
213 {
214     if (!p)
215         p = LwpCurrent;
216     lwpStatus(p, "added to run queue");
217     lwpAddTail(&LwpSchedQ[p->pri], p);
218 }
219
220 /*
221  * return user's data
222  */
223 void *
224 lwpGetUD(struct lwpProc *p)
225 {
226     if (!p)
227         p = LwpCurrent;
228     return p->ud;
229 }
230
231 /*
232  * set user's data
233  */
234 void
235 lwpSetUD(struct lwpProc *p, char *ud)
236 {
237     if (!p)
238         p = LwpCurrent;
239     p->ud = ud;
240 }
241
242 /*
243  * lwpYield -- yield the processor to another thread.
244  */
245 void
246 lwpYield(void)
247 {
248     lwpStatus(LwpCurrent, "yielding control");
249     lwpReady(LwpCurrent);
250     lwpReschedule();
251 }
252
253 /*
254  * cause the current process to be scheduled for deletion.
255  */
256 void
257 lwpExit(void)
258 {
259     lwpStatus(LwpCurrent, "marking self as dead");
260     LwpCurrent->dead = 1;
261     lwpYield();
262 }
263
264 /*
265  * mark another process as dead, so it will never be rescheduled.
266  * remove any lingering FD action
267  */
268 void
269 lwpTerminate(struct lwpProc *p)
270 {
271     lwpStatus(p, "terminating process");
272     p->dead = 1;
273     lwpWakeup(p);
274 }
275
276 /*
277  * set the thread's priority, returning the old.
278  * if the new priority is lower than the old, we reschedule.
279  */
280 int
281 lwpSetPriority(int new)
282 {
283     int old = LwpCurrent->pri;
284
285     if (LWP_MAX_PRIO <= new)
286         new = LWP_MAX_PRIO - 1;
287     if (LwpMaxpri < new)
288         LwpMaxpri = new;
289     LwpCurrent->pri = new;
290     lwpStatus(LwpCurrent, "resetting priority (%d -> %d)", old, new);
291     if (new < old)
292         lwpYield();
293     return old;
294 }
295
296 /*
297  * initialise the coroutine structures
298  */
299 struct lwpProc *
300 lwpInitSystem(int pri, void **ctxptr, int flags, sigset_t *waitset)
301 {
302     struct lwpQueue *q;
303     int i, *stack, marker;
304     struct lwpProc *sel;
305
306     LwpContextPtr = ctxptr;
307     if (pri < 1)
308         pri = 1;
309     LwpStackGrowsDown = growsdown(&marker);
310     if (!(LwpCurrent = calloc(1, sizeof(struct lwpProc))))
311         return NULL;
312     if (!(stack = malloc(64)))
313         return NULL;
314     if (LWP_MAX_PRIO <= pri)
315         pri = LWP_MAX_PRIO - 1;
316     if (LwpMaxpri < pri)
317         LwpMaxpri = pri;
318     LwpCurrent->next = 0;
319     LwpCurrent->sbtm = stack;   /* dummy stack for "main" */
320     LwpCurrent->pri = pri;
321     LwpCurrent->dead = 0;
322     LwpCurrent->flags = flags & ~LWP_STACKCHECK;
323     LwpCurrent->name = "Main";
324     for (i = LWP_MAX_PRIO, q = LwpSchedQ; i--; q++)
325         q->head = q->tail = 0;
326     LwpDeadQ.head = LwpDeadQ.tail = 0;
327     lwpInitSigWait(waitset);
328     /* must be lower in priority than us for this to work right */
329     sel = lwpCreate(0, lwpSelect, 16384, flags, "EventHandler", 0, 0, 0);
330     lwpInitSelect(sel);
331     return LwpCurrent;
332 }
333
334 /* lwpStackCheckInit
335  *
336  * Initialize the entire stack (including both redzones) with the stack
337  * check mark.  Thus, we can get some indication of how much stack was
338  * used.
339  */
340 static void
341 lwpStackCheckInit(struct lwpProc *newp)
342 {
343     int *p;
344     int *lim = (int *)((char *)newp->sbtm + newp->size);
345
346     for (p = newp->sbtm; p < lim; p++)
347         *p = LWP_CHECKMARK;
348 }
349
350 /* lwpStackCheck
351  *
352  * Check if the thread has overflowed/underflowed its stack.
353  * Should that happen, abort the process, as we cannot recover.
354  */
355 static void
356 lwpStackCheck(struct lwpProc *newp)
357 {
358     int *btm = (int *)(newp->ustack - LWP_REDZONE);
359     int *top = (int *)(newp->ustack + newp->usize + LWP_REDZONE);
360     int n = LWP_REDZONE / sizeof(int);
361     int i, lo_clean, hi_clean, overflow, underflow;
362
363     for (i = 0; i < n && btm[i] == LWP_CHECKMARK; i++) ;
364     lo_clean = i;
365
366     for (i = 1; i <= n && top[-i] == LWP_CHECKMARK; i++) ;
367     hi_clean = i - 1;
368
369     if (LwpStackGrowsDown) {
370         overflow = n - lo_clean;
371         underflow = n - hi_clean;
372     } else {
373         overflow = n - hi_clean;
374         underflow = n - lo_clean;
375     }
376     if (overflow)
377         logerror("Thread %s stack overflow %d bytes",
378                  newp->name, overflow * (int)sizeof(int));
379     if (underflow)
380         logerror("Thread %s stack underflow %d bytes",
381                  newp->name, underflow * (int)sizeof(int));
382     if (overflow || underflow)
383         abort();
384 }
385
386 /* lwpStackCheckUsed
387  *
388  * Figure out how much stack was used by this thread.
389  */
390 static void
391 lwpStackCheckUsed(struct lwpProc *newp)
392 {
393     int *base = (int *)newp->ustack;
394     int *lim = (int *)(newp->ustack + newp->usize);
395     int total = (lim + 1 - base) * sizeof(int);
396     int used, *p;
397
398     if (LwpStackGrowsDown) {
399         for (p = base; p < lim && *p == LWP_CHECKMARK; ++p) ;
400         used = (lim - p) * sizeof(int);
401     } else {
402         for (p = lim - 1; p >= base && *p == LWP_CHECKMARK; --p) ;
403         used = (p - base + 1) * sizeof(int);
404     }
405     lwpStatus(newp, "Thread stack %d used, %d left, %d total",
406               used, total - used, total);
407 }
408
409 /* lwpName
410  *
411  * Return the name of the thread.
412  */
413 char *
414 lwpName(struct lwpProc *proc)
415 {
416     return proc->name;
417 }
418
419 /* lwpSetName
420  *
421  * Set the name of the thread.
422  */
423 void
424 lwpSetName(struct lwpProc *proc, char *name)
425 {
426     if (proc->name != NULL)
427         free(proc->name);
428
429     proc->name = strdup(name);
430 }
431