]> git.pond.sub.org Git - empserver/blob - src/lib/lwp/lwp.c
9a8c2497b1eaed8e99dc36ceafccd965246fc9d1
[empserver] / src / lib / lwp / lwp.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1994-2016, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *  Copyright (C) 1991-3 Stephen Crane
6  *
7  *  Empire 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 3 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, see <http://www.gnu.org/licenses/>.
19  *
20  *  ---
21  *
22  *  See files README, COPYING and CREDITS in the root of the source
23  *  tree for related information and legal notices.  It is expected
24  *  that future projects/authors will amend these files as needed.
25  *
26  *  ---
27  *
28  *  lwp.c: lightweight process creation, destruction and manipulation
29  *
30  *  Known contributors to this file:
31  *     Markus Armbruster, 2004-2013
32  */
33
34 #include <config.h>
35
36 #include <string.h>
37 #include "lwp.h"
38 #include "lwpint.h"
39 #include "prototypes.h"
40
41 static struct lwpQueue LwpSchedQ[LWP_MAX_PRIO], LwpDeadQ;
42
43 struct lwpProc *LwpCurrent = NULL;
44 static void **LwpContextPtr;
45 static int LwpMaxpri = 0;       /* maximum priority so far */
46 static int LwpStackGrowsDown;
47
48 static void lwpDestroy(struct lwpProc *proc);
49 static void lwpStackCheckInit(struct lwpProc *newp);
50 static void lwpStackCheck(struct lwpProc *newp);
51 static void lwpStackCheckUsed(struct lwpProc *newp);
52
53 /* check stack direction */
54 static int
55 growsdown(void *x)
56 {
57     int y;
58     y = (x > (void *)&y);
59     return y;
60 }
61
62 /*
63  * lwpReschedule -- schedule another process.  we also check for dead
64  * processes here and free them.
65  */
66 void
67 lwpReschedule(void)
68 {
69     static struct lwpProc *nextp;
70     static int i;
71
72     if (LwpCurrent && (LwpCurrent->flags & LWP_STACKCHECK)) {
73         lwpStackCheck(LwpCurrent);
74     }
75
76     lwpSigWakeup();
77     lwpWakeupSleep();
78
79     /* destroy dead threads */
80     lwpStatus(LwpCurrent, "Cleaning dead queue");
81     while (NULL != (nextp = lwpGetFirst(&LwpDeadQ))) {
82         if (CANT_HAPPEN(nextp == LwpCurrent))
83             abort();
84         lwpDestroy(nextp);
85         lwpStatus(LwpCurrent, "Destroying done");
86     }
87
88     for (i = LwpMaxpri + 1; i--;) {
89         while (NULL != (nextp = lwpGetFirst(&LwpSchedQ[i]))) {
90             if (!nextp->dead)
91                 break;
92             /* clean up after dead bodies */
93             lwpStatus(nextp, "got a dead body");
94             if (nextp == LwpCurrent) {
95                 lwpStatus(nextp, "we are in it -- will bury later");
96                 lwpAddTail(&LwpDeadQ, nextp);
97             } else {
98                 lwpDestroy(nextp);
99             }
100             nextp = NULL;
101         }
102         if (nextp)
103             break;
104     }
105     if (CANT_HAPPEN(!nextp))
106         abort();
107     if (LwpCurrent != nextp) {
108         struct lwpProc *oldp = LwpCurrent;
109         if (oldp)
110             lwpStatus(oldp, "switch out");
111         LwpCurrent = nextp;
112         *LwpContextPtr = nextp->ud;
113         lwpSwitchContext(oldp, nextp);
114         lwpStatus(nextp, "switch in");
115     }
116 }
117
118 /*
119  * lwpEntryPoint -- process entry point.
120  */
121 void
122 lwpEntryPoint(void)
123 {
124     lwpStatus(LwpCurrent, "starting at entry point");
125     (*LwpCurrent->entry)(LwpCurrent->ud);
126     lwpExit();
127 }
128
129 static int
130 lwpNewStack(struct lwpProc *newp, int stacksz)
131 {
132     char *s;
133     int size, redsize;
134
135     /* Make size a multiple of sizeof(long) to keep things aligned */
136     stacksz = (stacksz + sizeof(long) - 1) & -sizeof(long);
137     /* Add a red zone on each side of the stack for LWP_STACKCHECK */
138     redsize = newp->flags & LWP_STACKCHECK ? LWP_REDZONE : 0;
139     size = stacksz + 2 * redsize;
140
141     s = malloc(size);
142     if (!s)
143         return -1;
144
145     newp->sbtm = s;
146     newp->size = size;
147     newp->ustack = s + redsize;
148     newp->usize = stacksz;
149
150     if (newp->flags & LWP_STACKCHECK)
151         lwpStackCheckInit(newp);
152     return 0;
153 }
154
155 /*
156  * lwpCreate -- create a process.
157  */
158 struct lwpProc *
159 lwpCreate(int priority, void (*entry)(void *), int stacksz,
160           int flags, char *name, int argc, char **argv, void *ud)
161 {
162     struct lwpProc *newp;
163
164     if (!(newp = malloc(sizeof(struct lwpProc))))
165         return NULL;
166     newp->flags = flags;
167     newp->name = strdup(name);
168     newp->entry = entry;
169     newp->argc = argc;
170     newp->argv = argv;
171     newp->ud = ud;
172     newp->dead = 0;
173     newp->runtime = (time_t)-1;
174     newp->fd = -1;
175     newp->sbtm = NULL;
176     if (LWP_MAX_PRIO <= priority)
177         priority = LWP_MAX_PRIO - 1;
178     if (LwpMaxpri < (newp->pri = priority))
179         LwpMaxpri = priority;
180     if (lwpNewStack(newp, stacksz) < 0 || lwpNewContext(newp) < 0) {
181         free(newp->sbtm);
182         free(newp->name);
183         free(newp);
184         return NULL;
185     }
186     lwpStatus(newp, "creating process structure %p (sbtm %p)",
187               newp, newp->sbtm);
188     lwpReady(newp);
189     lwpReady(LwpCurrent);
190     lwpReschedule();
191     return newp;
192 }
193
194 static void
195 lwpDestroy(struct lwpProc *proc)
196 {
197     if (proc->flags & LWP_STACKCHECK) {
198         lwpStackCheckUsed(proc);
199         lwpStackCheck(proc);
200     }
201     lwpStatus(proc, "destroying sbtm: %p", proc->sbtm);
202     free(proc->sbtm);
203     free(proc->name);
204     free(proc);
205 }
206
207 /*
208  * lwpReady -- put process on ready queue.  if null, assume current.
209  */
210 void
211 lwpReady(struct lwpProc *p)
212 {
213     if (!p)
214         p = LwpCurrent;
215     lwpStatus(p, "added to run queue");
216     lwpAddTail(&LwpSchedQ[p->pri], p);
217 }
218
219 /*
220  * return user's data
221  */
222 void *
223 lwpGetUD(struct lwpProc *p)
224 {
225     if (!p)
226         p = LwpCurrent;
227     return p->ud;
228 }
229
230 /*
231  * set user's data
232  */
233 void
234 lwpSetUD(struct lwpProc *p, char *ud)
235 {
236     if (!p)
237         p = LwpCurrent;
238     p->ud = ud;
239 }
240
241 /*
242  * lwpYield -- yield the processor to another thread.
243  */
244 void
245 lwpYield(void)
246 {
247     lwpStatus(LwpCurrent, "yielding control");
248     lwpReady(LwpCurrent);
249     lwpReschedule();
250 }
251
252 /*
253  * cause the current process to be scheduled for deletion.
254  */
255 void
256 lwpExit(void)
257 {
258     lwpStatus(LwpCurrent, "marking self as dead");
259     LwpCurrent->dead = 1;
260     lwpYield();
261 }
262
263 /*
264  * mark another process as dead, so it will never be rescheduled.
265  * remove any lingering FD action
266  */
267 void
268 lwpTerminate(struct lwpProc *p)
269 {
270     lwpStatus(p, "terminating process");
271     p->dead = 1;
272     lwpWakeup(p);
273 }
274
275 /*
276  * set the thread's priority, returning the old.
277  * if the new priority is lower than the old, we reschedule.
278  */
279 int
280 lwpSetPriority(int new)
281 {
282     int old = LwpCurrent->pri;
283
284     if (LWP_MAX_PRIO <= new)
285         new = LWP_MAX_PRIO - 1;
286     if (LwpMaxpri < new)
287         LwpMaxpri = new;
288     LwpCurrent->pri = new;
289     lwpStatus(LwpCurrent, "resetting priority (%d -> %d)", old, new);
290     if (new < old)
291         lwpYield();
292     return old;
293 }
294
295 /*
296  * initialise the coroutine structures
297  */
298 struct lwpProc *
299 lwpInitSystem(int pri, void **ctxptr, int flags, sigset_t *waitset)
300 {
301     struct lwpQueue *q;
302     int i, *stack, marker;
303     struct lwpProc *sel;
304
305     LwpContextPtr = ctxptr;
306     if (pri < 1)
307         pri = 1;
308     LwpStackGrowsDown = growsdown(&marker);
309     if (!(LwpCurrent = calloc(1, sizeof(struct lwpProc))))
310         return NULL;
311     if (!(stack = malloc(64)))
312         return NULL;
313     if (LWP_MAX_PRIO <= pri)
314         pri = LWP_MAX_PRIO - 1;
315     if (LwpMaxpri < pri)
316         LwpMaxpri = pri;
317     LwpCurrent->next = NULL;
318     LwpCurrent->sbtm = stack;   /* dummy stack for "main" */
319     LwpCurrent->pri = pri;
320     LwpCurrent->dead = 0;
321     LwpCurrent->flags = flags & ~LWP_STACKCHECK;
322     LwpCurrent->name = "Main";
323     for (i = LWP_MAX_PRIO, q = LwpSchedQ; i--; q++)
324         q->head = q->tail = NULL;
325     LwpDeadQ.head = LwpDeadQ.tail = NULL;
326     lwpInitSigWait(waitset);
327     /* must be lower in priority than us for this to work right */
328     sel = lwpCreate(0, lwpSelect, 65536, flags, "EventHandler", 0,
329                     NULL, NULL);
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 }