]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/pthread.c
8512a4683b6c6f49bc2741296fa73d29dae5b4dc
[empserver] / src / lib / empthread / pthread.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2006, 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 <config.h>
36
37 #include <stdio.h>
38 #if !defined(_WIN32)
39 #include <sys/time.h>
40 #include <unistd.h>
41 #endif
42 #include <sys/types.h>
43 #include <signal.h>
44 #include <errno.h>
45 #include <string.h>
46 #include <limits.h>
47
48 #include "misc.h"
49 #include "empthread.h"
50 #include "prototypes.h"
51
52 #include <stdarg.h>
53
54 #define EMPTH_KILLED  1
55
56 struct empth_t {
57     char *name;                 /* thread name */
58     char *desc;                 /* description */
59     void *ud;                   /* user data */
60     int state;                  /* my state */
61     void (*ep)(void *);         /* entry point */
62     pthread_t id;               /* thread id */
63 };
64
65 struct empth_sem_t {
66     pthread_mutex_t mtx_update; /* use it to update count */
67     int count;
68     char name[80];
69     pthread_mutex_t mtx_sem;
70     pthread_cond_t cnd_sem;
71 };
72
73 /* Thread-specific data key */
74 static pthread_key_t ctx_key;
75
76 /* Flags that were passed to empth_init() */
77 static int empth_flags;
78
79 /* Pointer to thread context variable */
80 static void **udata;
81
82 /*
83  * Non-preemption mutex.
84  * Empire code outside this file is only executed while holding this
85  * mutex.  This makes sure Empire code is never preempted by Empire
86  * code.
87  */
88 static pthread_mutex_t mtx_ctxsw;
89
90 static void empth_status(char *format, ...) ATTRIBUTE((format (printf, 1, 2)));
91 static void empth_alarm(int sig);
92
93 static void *
94 empth_start(void *arg)
95 {
96     empth_t *ctx = arg;
97     struct sigaction act;
98
99     /* actually it should inherit all this from main but... */
100     act.sa_flags = 0;
101     sigemptyset(&act.sa_mask);
102     act.sa_handler = shutdwn;
103     sigaction(SIGTERM, &act, NULL);
104     sigaction(SIGINT, &act, NULL);
105     act.sa_handler = panic;
106     sigaction(SIGBUS, &act, NULL);
107     sigaction(SIGSEGV, &act, NULL);
108     sigaction(SIGILL, &act, NULL);
109     sigaction(SIGFPE, &act, NULL);
110     act.sa_handler = SIG_IGN;
111     sigaction(SIGPIPE, &act, NULL);
112
113     act.sa_handler = empth_alarm;
114     sigaction(SIGALRM, &act, NULL);
115
116     ctx->id = pthread_self();
117     pthread_setspecific(ctx_key, ctx);
118     pthread_mutex_lock(&mtx_ctxsw);
119     *udata = ctx->ud;
120     ctx->ep(ctx->ud);
121     empth_exit();
122     return NULL;
123 }
124
125 static void
126 empth_status(char *format, ...)
127 {
128     va_list ap;
129     static struct timeval startTime;
130     struct timeval tv;
131     char buf[1024];
132     int sec, msec;
133     empth_t *a;
134
135     va_start(ap, format);
136     if (empth_flags & EMPTH_PRINT) {
137         if (startTime.tv_sec == 0)
138             gettimeofday(&startTime, 0);
139         gettimeofday(&tv, 0);
140         sec = tv.tv_sec - startTime.tv_sec;
141         msec = (tv.tv_usec - startTime.tv_usec) / 1000;
142         if (msec < 0) {
143             sec++;
144             msec += 1000;
145         }
146         vsprintf(buf, format, ap);
147         a = empth_self();
148         printf("%d:%02d.%03d %17s: %s\n", sec / 60, sec % 60, msec / 10,
149                a->name, buf);
150
151     }
152     va_end(ap);
153 }
154
155
156 int
157 empth_init(void **ctx_ptr, int flags)
158 {
159     empth_t *ctx;
160     struct sigaction act;
161
162
163     pthread_key_create(&ctx_key, NULL);
164     pthread_mutex_init(&mtx_ctxsw, NULL);
165
166     act.sa_flags = 0;
167     sigemptyset(&act.sa_mask);
168     act.sa_handler = empth_alarm;
169     sigaction(SIGALRM, &act, NULL);
170
171     udata = ctx_ptr;
172     ctx = malloc(sizeof(empth_t));
173     if (!ctx) {
174         logerror("pthread init failed: not enough memory");
175         exit(1);
176     }
177     ctx->name = "Main";
178     ctx->desc = "empire main";
179     ctx->ep = 0;
180     ctx->ud = 0;
181     ctx->id = pthread_self();
182     ctx->state = 0;
183     pthread_setspecific(ctx_key, ctx);
184     pthread_mutex_lock(&mtx_ctxsw);
185     empth_flags = flags;
186     logerror("pthreads initialized");
187     return 0;
188 }
189
190
191 /*
192  * prio can be used for setting scheeduling policy but...
193  * it seems to be optional in POSIX threads and Solaris
194  * for example just ignores it.
195  * More then that priority is not needed even in lwp threads.
196  */
197 empth_t *
198 empth_create(int prio, void (*entry)(void *), int size, int flags,
199              char *name, char *desc, void *ud)
200 {
201     pthread_t t;
202     pthread_attr_t attr;
203     empth_t *ctx;
204     int eno;
205
206     empth_status("creating new thread %s:%s", name, desc);
207
208     ctx = malloc(sizeof(empth_t));
209     if (!ctx) {
210         logerror("not enough memory to create thread: %s (%s)", name,
211                  desc);
212         return NULL;
213     }
214     ctx->name = strdup(name);
215     ctx->desc = strdup(desc);
216     ctx->ud = ud;
217     ctx->state = 0;
218     ctx->ep = entry;
219
220     eno = pthread_attr_init(&attr);
221     if (eno) {
222         logerror("can not create thread attribute %s (%s): %s", name, desc,
223                  strerror(eno));
224         goto bad;
225     }
226     if (size < PTHREAD_STACK_MIN)
227         size = PTHREAD_STACK_MIN;
228     pthread_attr_setstacksize(&attr, size);
229     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
230
231     eno = pthread_create(&t, &attr, empth_start, ctx);
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 %ld", (long)t);
238     return ctx;
239
240   bad:
241     pthread_attr_destroy(&attr);
242     free(ctx);
243     return NULL;
244 }
245
246
247 static void
248 empth_restorectx(void)
249 {
250     empth_t *ctx_ptr;
251
252     ctx_ptr = pthread_getspecific(ctx_key);
253     *udata = ctx_ptr->ud;
254     if (ctx_ptr->state == EMPTH_KILLED) {
255         empth_status("i am dead");
256         empth_exit();
257     }
258     empth_status("context restored");
259 }
260
261 empth_t *
262 empth_self(void)
263 {
264     return pthread_getspecific(ctx_key);
265 }
266
267 void
268 empth_exit(void)
269 {
270     empth_t *ctx_ptr;
271
272     pthread_mutex_unlock(&mtx_ctxsw);
273     empth_status("empth_exit");
274     ctx_ptr = pthread_getspecific(ctx_key);
275     /* We want to leave the main thread around forever, until it's time
276        for it to die for real (in a shutdown) */
277     if (!strcmp(ctx_ptr->name, "Main")) {
278         while (1) {
279             sleep(60);
280         }
281     }
282
283     free(ctx_ptr);
284     pthread_exit(0);
285 }
286
287 void
288 empth_yield(void)
289 {
290     pthread_mutex_unlock(&mtx_ctxsw);
291     pthread_mutex_lock(&mtx_ctxsw);
292     empth_restorectx();
293 }
294
295 void
296 empth_terminate(empth_t *a)
297 {
298     empth_status("killing thread %s", a->name);
299     a->state = EMPTH_KILLED;
300     pthread_kill(a->id, SIGALRM);
301 }
302
303 void
304 empth_select(int fd, int flags)
305 {
306
307     fd_set readmask;
308     fd_set writemask;
309     struct timeval tv;
310     int n;
311
312     pthread_mutex_unlock(&mtx_ctxsw);
313     empth_status("%s select on %d",
314                  flags == EMPTH_FD_READ ? "read" : "write", fd);
315     while (1) {
316         tv.tv_sec = 1000000;
317         tv.tv_usec = 0;
318
319         FD_ZERO(&readmask);
320         FD_ZERO(&writemask);
321
322         switch (flags) {
323         case EMPTH_FD_READ:
324             FD_SET(fd, &readmask);
325             break;
326         case EMPTH_FD_WRITE:
327             FD_SET(fd, &writemask);
328             break;
329         default:
330             logerror("bad flag %d passed to empth_select", flags);
331             empth_exit();
332         }
333
334         n = select(fd + 1, &readmask, &writemask, (fd_set *) 0, &tv);
335
336         if (n < 0) {
337             if (errno == EINTR) {
338                 /* go handle the signal */
339                 empth_status("select broken by signal");
340                 goto done;
341                 return;
342             }
343             /* strange but we dont get EINTR on select broken by signal */
344             empth_status("select failed (%s)", strerror(errno));
345             goto done;
346             return;
347         }
348
349         if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
350             empth_status("input ready");
351             break;
352         }
353         if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
354             empth_status("output ready");
355             break;
356         }
357     }
358
359   done:
360     pthread_mutex_lock(&mtx_ctxsw);
361     empth_restorectx();
362
363 }
364
365
366 static void
367 empth_alarm(int sig)
368 {
369     struct sigaction act;
370     empth_status("got alarm signal");
371 #ifdef SA_RESTART
372     act.sa_flags &= ~SA_RESTART;
373 #endif
374     sigemptyset(&act.sa_mask);
375     act.sa_handler = empth_alarm;
376     sigaction(SIGALRM, &act, NULL);
377 }
378
379 void
380 empth_wakeup(empth_t *a)
381 {
382     empth_status("waking up thread %s", a->name);
383     pthread_kill(a->id, SIGALRM);
384     empth_status("waiting for it to run");
385 }
386
387 void
388 empth_sleep(time_t until)
389 {
390     struct timeval tv;
391
392     empth_status("going to sleep %ld sec", until - time(0));
393     pthread_mutex_unlock(&mtx_ctxsw);
394     tv.tv_sec = until - time(NULL);
395     tv.tv_usec = 0;
396     do {
397         select(0, NULL, NULL, NULL, &tv);
398     } while ((tv.tv_sec = until - time(NULL)) > 0);
399     empth_status("sleep done. Waiting for lock");
400     pthread_mutex_lock(&mtx_ctxsw);
401     empth_restorectx();
402 }
403
404
405 empth_sem_t *
406 empth_sem_create(char *name, int cnt)
407 {
408     empth_sem_t *sm;
409
410     sm = malloc(sizeof(empth_sem_t));
411     if (!sm) {
412         logerror("out of memory at %s:%d", __FILE__, __LINE__);
413         return NULL;
414     }
415     strncpy(sm->name, name, sizeof(sm->name) - 1);
416     sm->count = cnt;
417     pthread_mutex_init(&sm->mtx_update, NULL);
418     pthread_mutex_init(&sm->mtx_sem, NULL);
419     pthread_cond_init(&sm->cnd_sem, NULL);
420     return sm;
421 }
422
423 void
424 empth_sem_signal(empth_sem_t *sm)
425 {
426     empth_status("signal on semaphore %s:%d", sm->name, sm->count);
427     pthread_mutex_lock(&sm->mtx_update);
428     if (sm->count++ < 0) {
429         pthread_mutex_unlock(&sm->mtx_update);
430         pthread_mutex_lock(&sm->mtx_sem);
431         pthread_cond_signal(&sm->cnd_sem);
432         pthread_mutex_unlock(&sm->mtx_sem);
433     } else
434         pthread_mutex_unlock(&sm->mtx_update);
435 }
436
437 void
438 empth_sem_wait(empth_sem_t *sm)
439 {
440     empth_status("wait on semaphore %s:%d", sm->name, sm->count);
441     pthread_mutex_lock(&sm->mtx_update);
442     if (--sm->count < 0) {
443         pthread_mutex_unlock(&sm->mtx_update);
444         empth_status("blocking");
445         pthread_mutex_unlock(&mtx_ctxsw);
446         pthread_mutex_lock(&sm->mtx_sem);
447         pthread_cond_wait(&sm->cnd_sem, &sm->mtx_sem);
448         empth_status("waking up");
449         pthread_mutex_unlock(&sm->mtx_sem);
450         pthread_mutex_lock(&mtx_ctxsw);
451         empth_restorectx();
452     } else
453         pthread_mutex_unlock(&sm->mtx_update);
454 }