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