]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/pthread.c
(emp_sig_t): Pre-ISO C compatibility cruft. Just use void.
[empserver] / src / lib / empthread / pthread.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2000, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                           Ken Stevens, Steve McClure
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  *  ---
21  *
22  *  See the "LEGAL", "LICENSE", "CREDITS" and "README" files for all the
23  *  related information and legal notices. It is expected that any future
24  *  projects/authors will amend these files as needed.
25  *
26  *  ---
27  *
28  *  pthread.c: Interface from Empire threads to POSIX threads
29  * 
30  *  Known contributors to this file:
31  *     Sasha Mikheev
32  *     Steve McClure, 1998
33  */
34
35 #include <stdio.h>
36 #if !defined(_WIN32)
37 #include <sys/time.h>
38 #include <unistd.h>
39 #endif
40 #include <sys/types.h>
41 #include <signal.h>
42 #include <errno.h>
43 #include <string.h>
44
45 #include "misc.h"
46 #include "empthread.h"
47 #include "prototypes.h"
48
49 #include <stdarg.h>
50
51 #ifdef _EMPTH_POSIX
52 static pthread_key_t ctx_key;
53 static int empth_flags;
54 static char **udata;            /* pointer to out global context */
55
56 static pthread_mutex_t mtx_ctxsw;       /* thread in critical section */
57
58
59 #if 0
60 static void empth_setctx _PROTO((void *));
61 #endif
62 static void empth_restorectx _PROTO(());
63
64 static void *
65 empth_start(void *ctx)
66 {
67     struct sigaction act;
68
69     /* actually it should inherit all this from main but... */
70 #ifdef SA_SIGINFO
71     act.sa_flags = SA_SIGINFO;
72 #endif
73     sigemptyset(&act.sa_mask);
74     act.sa_handler = shutdwn;
75     /* pthreads on Linux use SIGUSR1 (*shrug*) so only catch it if not on
76        a Linux box running POSIX threads -- STM */
77 #if !(defined(__linux__) && defined(_EMPTH_POSIX))
78     sigaction(SIGUSR1, &act, NULL);
79 #endif
80     sigaction(SIGTERM, &act, NULL);
81     sigaction(SIGINT, &act, NULL);
82     act.sa_handler = panic;
83     sigaction(SIGBUS, &act, NULL);
84     sigaction(SIGSEGV, &act, NULL);
85     sigaction(SIGILL, &act, NULL);
86     sigaction(SIGFPE, &act, NULL);
87     act.sa_handler = SIG_IGN;
88     sigaction(SIGPIPE, &act, NULL);
89
90     act.sa_handler = empth_alarm;
91     sigaction(SIGALRM, &act, NULL);
92
93     ((empth_t *)ctx)->id = pthread_self();
94     pthread_setspecific(ctx_key, ctx);
95     pthread_mutex_lock(&mtx_ctxsw);
96     *udata = ((empth_t *)ctx)->ud;
97     ((empth_t *)ctx)->ep(((empth_t *)ctx)->ud);
98     empth_exit();
99     return NULL;
100 }
101
102 static void
103 empth_status(char *format, ...)
104 {
105     va_list ap;
106     static struct timeval startTime;
107     struct timeval tv;
108     char buf[1024];
109     int sec, msec;
110     empth_t *a;
111
112     va_start(ap, format);
113     if (empth_flags & EMPTH_PRINT) {
114         if (startTime.tv_sec == 0)
115             gettimeofday(&startTime, 0);
116         gettimeofday(&tv, 0);
117         sec = tv.tv_sec - startTime.tv_sec;
118         msec = (tv.tv_usec - startTime.tv_usec) / 1000;
119         if (msec < 0) {
120             sec++;
121             msec += 1000;
122         }
123         vsprintf(buf, format, ap);
124         a = empth_self();
125         printf("%d:%02d.%03d %17s: %s\n", sec / 60, sec % 60, msec / 10,
126                a->name, buf);
127
128     }
129     va_end(ap);
130 }
131
132
133 int
134 empth_init(char **ctx_ptr, int flags)
135 {
136     empth_t *ctx;
137     struct sigaction act;
138
139
140     pthread_key_create(&ctx_key, 0);
141 #ifdef _DECTHREADS_
142     pthread_mutex_init(&mtx_ctxsw, pthread_mutexattr_default);
143 #else
144     pthread_mutex_init(&mtx_ctxsw, 0);
145 #endif
146
147     act.sa_flags = 0;
148     sigemptyset(&act.sa_mask);
149     act.sa_handler = empth_alarm;
150     sigaction(SIGALRM, &act, NULL);
151
152     udata = ctx_ptr;
153     ctx = (empth_t *)malloc(sizeof(empth_t));
154     if (!ctx) {
155         logerror("pthread init failed: not enough memory");
156         exit(1);
157     }
158     ctx->name = "Main";
159     ctx->desc = "empire main";
160     ctx->ep = 0;
161     ctx->ud = 0;
162     ctx->id = pthread_self();
163     ctx->state = 0;
164     pthread_setspecific(ctx_key, ctx);
165     pthread_mutex_lock(&mtx_ctxsw);
166     empth_flags = flags;
167     logerror("pthreads initialized");
168     return 0;
169 }
170
171
172 /*
173  * prio can be used for setting scheeduling policy but...
174  * it seems to be optional in POSIX threads and Solaris
175  * for example just ignores it.
176  * More then that priority is not needed even in lwp threads.
177  */
178 empth_t *
179 empth_create(int prio, void (*entry) (), int size, int flags,
180              char *name, char *desc, void *ud)
181 {
182     pthread_t t;
183     pthread_attr_t attr;
184     empth_t *ctx;
185     int eno;
186
187     empth_status("creating new thread %s:%s", name, desc);
188
189     ctx = (empth_t *)malloc(sizeof(empth_t));
190     if (!ctx) {
191         logerror("not enough memoty to create thread: %s (%s)", name,
192                  desc);
193         return NULL;
194     }
195     ctx->name = strdup(name);
196     ctx->desc = strdup(desc);
197     ctx->ud = ud;
198     ctx->state = 0;
199     ctx->ep = entry;
200
201 #ifdef _DECTHREADS_
202     eno = pthread_attr_init(&attr) ? errno : 0;
203 #else
204     eno = pthread_attr_init(&attr);
205 #endif
206     if (eno) {
207         logerror("can not create thread attribute %s (%s): %s", name, desc,
208                  strerror(eno));
209         goto bad;
210     }
211 #if defined(__linux__)
212     /* Linux doesn't let you adjust the stack */
213 #elif defined(_DECTHREADS_)
214     /* DEC does not have PTHREAD_STACK_MIN constant */
215     /* Do not go below default size                 */
216     if (size > pthread_attr_getstacksize(attr))
217         pthread_attr_setstacksize(&attr, size);
218 #else
219     if (size < PTHREAD_STACK_MIN)
220         size = PTHREAD_STACK_MIN + 1;
221
222     pthread_attr_setstacksize(&attr, size);
223 #endif
224
225     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
226
227 #ifdef _DECTHREADS_
228     eno = pthread_create(&t, attr, empth_start, (void *)ctx) ? errno : 0;
229 #else
230     eno = pthread_create(&t, &attr, empth_start, (void *)ctx);
231 #endif
232     if (eno) {
233         logerror("can not create thread: %s (%s): %s", name, desc,
234                  strerror(eno));
235         goto bad;
236     }
237     empth_status("new thread id is %d", t);
238     return ctx;
239     pthread_attr_destroy(&attr);
240   bad:
241     pthread_attr_destroy(&attr);
242     free(ctx);
243     return NULL;
244 }
245
246
247 #if 0
248 static void
249 empth_setctx(void *ct)
250 {
251     empth_t *ctx_ptr;
252
253 #ifdef _DECTHREADS_
254     pthread_getspecific(ctx_key, (pthread_addr_t *) & ctx_ptr);
255 #else
256     ctx_ptr = (empth_t *)pthread_getspecific(ctx_key);
257 #endif
258     ctx_ptr->ud = ct;
259     *udata = ((empth_t *)ctx_ptr)->ud;
260     pthread_setspecific(ctx_key, (void *)ctx_ptr);
261     empth_status("context saved");
262 }
263 #endif
264
265 static void
266 empth_restorectx(void)
267 {
268     empth_t *ctx_ptr;
269
270 #ifdef _DECTHREADS_
271     pthread_getspecific(ctx_key, (pthread_addr_t *) & ctx_ptr);
272 #else
273     ctx_ptr = (empth_t *)pthread_getspecific(ctx_key);
274 #endif
275     *udata = (char *)ctx_ptr->ud;
276     if (ctx_ptr->state == EMPTH_KILLED) {
277         empth_status("i am dead");
278         empth_exit();
279     }
280     empth_status("context restored");
281 }
282
283 empth_t *
284 empth_self(void)
285 {
286 #ifdef _DECTHREADS_
287     empth_t *ctx_ptr;
288
289     pthread_getspecific(ctx_key, (pthread_addr_t *) & ctx_ptr);
290     return ctx_ptr;
291 #else
292     return (empth_t *)pthread_getspecific(ctx_key);
293 #endif
294 }
295
296 void
297 empth_exit(void)
298 {
299     empth_t *ctx_ptr;
300
301     pthread_mutex_unlock(&mtx_ctxsw);
302     empth_status("empth_exit");
303 #ifdef _DECTHREADS_
304     pthread_getspecific(ctx_key, (pthread_addr_t *) & ctx_ptr);
305 #else
306     ctx_ptr = (empth_t *)pthread_getspecific(ctx_key);
307 #endif
308     /* We want to leave the main thread around forever, until it's time
309        for it to die for real (in a shutdown) */
310     if (!strcmp(ctx_ptr->name, "Main")) {
311         while (1) {
312 #ifdef _DECTHREADS_
313             pthread_yield();
314 #endif
315             sleep(60);
316         }
317     }
318
319     free(ctx_ptr);
320     pthread_exit(0);
321 }
322
323 void
324 empth_yield(void)
325 {
326     pthread_mutex_unlock(&mtx_ctxsw);
327     sleep(10);                  /* take a nap  pthread_yield(); */
328     pthread_mutex_lock(&mtx_ctxsw);
329     empth_restorectx();
330 }
331
332 void
333 empth_terminate(empth_t *a)
334 {
335     /* logerror("calling non supported function empth_terminate: %s:%d",
336        __FILE__, __LINE__); */
337     empth_status("killing thread %s", a->name);
338     a->state = EMPTH_KILLED;
339 #ifndef _DECTHREADS_
340     /* DEC and OSX do not have pthread_kill. Not sure that cancel is correct. */
341 #if (!defined __ppc__)
342     pthread_kill(a->id, SIGALRM);
343 #endif
344 #endif
345     return;
346 }
347
348 void
349 empth_select(int fd, int flags)
350 {
351
352     fd_set readmask;
353     fd_set writemask;
354     struct timeval tv;
355     int n;
356
357     pthread_mutex_unlock(&mtx_ctxsw);
358     empth_status("%s select on %d",
359                  flags == EMPTH_FD_READ ? "read" : "write", fd);
360     while (1) {
361         tv.tv_sec = 1000000;
362         tv.tv_usec = 0;
363
364         FD_ZERO(&readmask);
365         FD_ZERO(&writemask);
366
367         switch (flags) {
368         case EMPTH_FD_READ:
369             FD_SET(fd, &readmask);
370             break;
371         case EMPTH_FD_WRITE:
372             FD_SET(fd, &writemask);
373             break;
374         default:
375             logerror("bad flag %d passed to empth_select", flags);
376             empth_exit();
377         }
378
379         n = select(fd + 1, &readmask, &writemask, (fd_set *) 0, &tv);
380
381         if (n < 0) {
382             if (errno == EINTR) {
383                 /* go handle the signal */
384                 empth_status("select broken by signal");
385                 goto done;
386                 return;
387             }
388             /* strange but we dont get EINTR on select broken by signal */
389             empth_status("select failed (%s)", strerror(errno));
390             goto done;
391             return;
392         }
393
394         if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
395             empth_status("input ready");
396             break;
397         }
398         if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
399             empth_status("output ready");
400             break;
401         }
402     }
403
404   done:
405     pthread_mutex_lock(&mtx_ctxsw);
406     empth_restorectx();
407
408 }
409
410
411 void
412 empth_alarm(int sig)
413 {
414     struct sigaction act;
415     empth_status("got alarm signal");
416 #ifdef SA_RESTART
417     act.sa_flags &= ~SA_RESTART;
418 #endif
419     sigemptyset(&act.sa_mask);
420     act.sa_handler = empth_alarm;
421     sigaction(SIGALRM, &act, NULL);
422 }
423
424 void
425 empth_wakeup(empth_t *a)
426 {
427     empth_status("waking up thread %s", a->name);
428 #ifndef _DECTHREADS_
429 #if (!defined __ppc__)
430     pthread_kill(a->id, SIGALRM);
431 #endif
432 #endif
433     empth_status("waiting for it to run");
434     /* empth_yield(); */
435 }
436
437 void
438 empth_sleep(long until)
439 {
440     struct timeval tv;
441
442     empth_status("going to sleep %ld sec", until - time(0));
443     pthread_mutex_unlock(&mtx_ctxsw);
444     tv.tv_sec = until - time(NULL);
445     tv.tv_usec = 0;
446     do {
447         select(0, NULL, NULL, NULL, &tv);
448     } while ((tv.tv_sec = until - time(NULL)) > 0);
449     empth_status("sleep done. Waiting for lock");
450     pthread_mutex_lock(&mtx_ctxsw);
451     empth_restorectx();
452 }
453
454
455 empth_sem_t *
456 empth_sem_create(char *name, int cnt)
457 {
458     empth_sem_t *sm;
459
460     sm = (empth_sem_t *)malloc(sizeof(empth_sem_t));
461     if (!sm) {
462         logerror("out of memory at %s:%d", __FILE__, __LINE__);
463         return NULL;
464     }
465     strncpy(sm->name, name, sizeof(sm->name) - 1);
466     sm->count = cnt;
467 #ifdef _DECTHREADS_
468     pthread_mutex_init(&sm->mtx_update, pthread_mutexattr_default);
469     pthread_mutex_init(&sm->mtx_sem, pthread_mutexattr_default);
470     pthread_cond_init(&sm->cnd_sem, pthread_condattr_default);
471 #else
472     pthread_mutex_init(&sm->mtx_update, 0);
473     pthread_mutex_init(&sm->mtx_sem, 0);
474     pthread_cond_init(&sm->cnd_sem, 0);
475 #endif
476     return sm;
477 }
478
479 void
480 empth_sem_signal(empth_sem_t *sm)
481 {
482     empth_status("signal on semaphore %s:%d", sm->name, sm->count);
483     pthread_mutex_lock(&sm->mtx_update);
484     if (sm->count++ < 0) {
485         pthread_mutex_unlock(&sm->mtx_update);
486         pthread_mutex_lock(&sm->mtx_sem);
487         pthread_cond_signal(&sm->cnd_sem);
488         pthread_mutex_unlock(&sm->mtx_sem);
489     } else
490         pthread_mutex_unlock(&sm->mtx_update);
491 }
492
493 void
494 empth_sem_wait(empth_sem_t *sm)
495 {
496     empth_status("wait on semaphore %s:%d", sm->name, sm->count);
497     pthread_mutex_lock(&sm->mtx_update);
498     if (--sm->count < 0) {
499         pthread_mutex_unlock(&sm->mtx_update);
500         empth_status("blocking");
501         pthread_mutex_unlock(&mtx_ctxsw);
502         pthread_mutex_lock(&sm->mtx_sem);
503         pthread_cond_wait(&sm->cnd_sem, &sm->mtx_sem);
504         empth_status("waking up");
505         pthread_mutex_unlock(&sm->mtx_sem);
506         pthread_mutex_lock(&mtx_ctxsw);
507         empth_restorectx();
508     } else
509         pthread_mutex_unlock(&sm->mtx_update);
510 }
511
512 #endif