]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/pthread.c
Update copyright notice
[empserver] / src / lib / empthread / pthread.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2020, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire 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 3 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, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  pthread.c: Interface from Empire threads to POSIX threads
28  *
29  *  Known contributors to this file:
30  *     Sasha Mikheev
31  *     Steve McClure, 1998
32  *     Markus Armbruster, 2005-2012
33  *     Ron Koenderink, 2007-2009
34  */
35
36 /* Required for PTHREAD_STACK_MIN on some systems, e.g. Solaris: */
37 #define _XOPEN_SOURCE 500
38
39 #include <config.h>
40
41 #include <errno.h>
42 #include <limits.h>
43 #include <pthread.h>
44 #include <signal.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sys/select.h>
50 #include <unistd.h>
51 #include "misc.h"
52 #include "empthread.h"
53 #include "file.h"
54 #include "prototypes.h"
55
56 struct empth_t {
57     char *name;                 /* thread name */
58     void *ud;                   /* user data */
59     int wakeup;
60     void (*ep)(void *);         /* entry point */
61     pthread_t id;               /* thread ID */
62 };
63
64 struct empth_rwlock_t {
65     /* Can't use pthread_rwlock_t, because it needn't prefer writers */
66     char *name;
67     int nread;                  /* #active readers */
68     int nwrite;                 /* total #writers (active and waiting) */
69     pthread_cond_t can_read;
70     pthread_cond_t can_write;
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, ...)
91     ATTRIBUTE((format (printf, 1, 2)));
92 static void empth_alarm(int sig);
93
94 static void *
95 empth_start(void *arg)
96 {
97     empth_t *ctx = arg;
98
99     ctx->id = pthread_self();
100     pthread_setspecific(ctx_key, ctx);
101     pthread_mutex_lock(&mtx_ctxsw);
102     *udata = ctx->ud;
103     ctx->ep(ctx->ud);
104     empth_exit();
105     return NULL;
106 }
107
108 static void
109 empth_status(char *format, ...)
110 {
111     va_list ap;
112     static struct timeval startTime;
113     struct timeval tv;
114     char buf[1024];
115     int sec, msec;
116     empth_t *a;
117
118     va_start(ap, format);
119     if (empth_flags & EMPTH_PRINT) {
120         if (startTime.tv_sec == 0)
121             gettimeofday(&startTime, 0);
122         gettimeofday(&tv, 0);
123         sec = tv.tv_sec - startTime.tv_sec;
124         msec = (tv.tv_usec - startTime.tv_usec) / 1000;
125         if (msec < 0) {
126             sec++;
127             msec += 1000;
128         }
129         vsprintf(buf, format, ap);
130         a = empth_self();
131         printf("%d:%02d.%03d %17s: %s\n", sec / 60, sec % 60, msec / 10,
132                a->name, buf);
133
134     }
135     va_end(ap);
136 }
137
138
139 int
140 empth_init(void **ctx_ptr, int flags)
141 {
142     empth_t *ctx;
143     sigset_t set;
144     struct sigaction act;
145
146     empth_flags = flags;
147     udata = ctx_ptr;
148
149     empth_init_signals();
150     sigemptyset(&set);
151     sigaddset(&set, SIGHUP);
152     sigaddset(&set, SIGINT);
153     sigaddset(&set, SIGTERM);
154     pthread_sigmask(SIG_BLOCK, &set, NULL);
155     act.sa_flags = 0;
156     sigemptyset(&act.sa_mask);
157     act.sa_handler = empth_alarm;
158     sigaction(SIGALRM, &act, NULL);
159
160     pthread_key_create(&ctx_key, NULL);
161     pthread_mutex_init(&mtx_ctxsw, NULL);
162
163     ctx = malloc(sizeof(empth_t));
164     if (!ctx) {
165         logerror("pthread init failed: not enough memory");
166         exit(1);
167     }
168     ctx->name = "Main";
169     ctx->ep = 0;
170     ctx->ud = 0;
171     ctx->id = pthread_self();
172     ctx->wakeup = 0;
173     pthread_setspecific(ctx_key, ctx);
174     pthread_mutex_lock(&mtx_ctxsw);
175     return 0;
176 }
177
178
179 empth_t *
180 empth_create(void (*entry)(void *), int size, int flags,
181              char *name, void *ud)
182 {
183     pthread_t t;
184     pthread_attr_t attr;
185     empth_t *ctx;
186     int eno;
187
188     empth_status("creating new thread %s", name);
189     ef_make_stale();
190
191     ctx = malloc(sizeof(empth_t));
192     if (!ctx) {
193         logerror("not enough memory to create thread %s", name);
194         return NULL;
195     }
196     ctx->name = strdup(name);
197     ctx->ud = ud;
198     ctx->wakeup = 0;
199     ctx->ep = entry;
200
201     eno = pthread_attr_init(&attr);
202     if (eno) {
203         logerror("can not create thread attribute %s: %s",
204                  name, strerror(eno));
205         goto bad;
206     }
207     if (size < PTHREAD_STACK_MIN)
208         size = PTHREAD_STACK_MIN;
209     pthread_attr_setstacksize(&attr, size);
210     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
211
212     eno = pthread_create(&t, &attr, empth_start, ctx);
213     if (eno) {
214         logerror("can not create thread: %s: %s", name, strerror(eno));
215         goto bad;
216     }
217     empth_status("new thread ID is %ld", (long)t);
218     empth_yield();
219     return ctx;
220
221   bad:
222     pthread_attr_destroy(&attr);
223     free(ctx);
224     return NULL;
225 }
226
227
228 static void
229 empth_restorectx(void)
230 {
231     empth_t *ctx_ptr;
232
233     ctx_ptr = pthread_getspecific(ctx_key);
234     *udata = ctx_ptr->ud;
235     ctx_ptr->wakeup = 0;
236     empth_status("context restored");
237 }
238
239 empth_t *
240 empth_self(void)
241 {
242     return udata ? pthread_getspecific(ctx_key) : NULL;
243 }
244
245 char *
246 empth_name(empth_t *thread)
247 {
248     return thread->name;
249 }
250
251 void
252 empth_set_name(empth_t *thread, char *name)
253 {
254     if (thread->name)
255         free(thread->name);
256     thread->name = strdup(name);
257 }
258
259 void
260 empth_exit(void)
261 {
262     empth_t *ctx = pthread_getspecific(ctx_key);
263
264     empth_status("empth_exit");
265     ef_make_stale();
266     pthread_mutex_unlock(&mtx_ctxsw);
267     free(ctx->name);
268     free(ctx);
269     pthread_exit(0);
270 }
271
272 void
273 empth_yield(void)
274 {
275     ef_make_stale();
276     pthread_mutex_unlock(&mtx_ctxsw);
277     pthread_mutex_lock(&mtx_ctxsw);
278     empth_restorectx();
279 }
280
281 int
282 empth_select(int fd, int flags, struct timeval *timeout)
283 {
284     fd_set readmask;
285     fd_set writemask;
286     struct timeval tv;
287     int n;
288     empth_t *ctx;
289     int res = 0;
290
291     if (CANT_HAPPEN(fd < 0 || fd >= FD_SETSIZE)) {
292         errno = EBADF;
293         return -1;
294     }
295
296     ef_make_stale();
297     pthread_mutex_unlock(&mtx_ctxsw);
298     empth_status("select on %d for %d", fd, flags);
299
300 again:
301     FD_ZERO(&readmask);
302     FD_ZERO(&writemask);
303     if (flags & EMPTH_FD_READ)
304         FD_SET(fd, &readmask);
305     if (flags & EMPTH_FD_WRITE)
306         FD_SET(fd, &writemask);
307
308     if (timeout)
309         tv = *timeout;
310     n = select(fd + 1, &readmask, &writemask, NULL, timeout ? &tv : NULL);
311     if (n < 0) {
312         ctx = pthread_getspecific(ctx_key);
313         if (ctx->wakeup) {
314             empth_status("select woken up");
315             res = 0;
316         } else if (errno == EINTR) {
317             empth_status("select broken by signal");
318             goto again;
319         } else {
320             empth_status("select failed (%s)", strerror(errno));
321             res = -1;
322         }
323     } else if (n == 0) {
324         empth_status("select timed out");
325         res = 0;
326     } else if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
327         empth_status("input ready");
328         res = 1;
329     } else if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
330         empth_status("output ready");
331         res = 1;
332     }
333
334     pthread_mutex_lock(&mtx_ctxsw);
335     empth_restorectx();
336     return res;
337 }
338
339 static void
340 empth_alarm(int sig)
341 {
342     /*
343      * Nothing to do --- we handle this signal just to let
344      * empth_wakeup() interrupt system calls.
345      */
346 }
347
348 void
349 empth_wakeup(empth_t *a)
350 {
351     empth_status("waking up thread %s", a->name);
352     a->wakeup = 1;
353     pthread_kill(a->id, SIGALRM);
354 }
355
356 int
357 empth_sleep(time_t until)
358 {
359     empth_t *ctx = pthread_getspecific(ctx_key);
360     time_t now;
361     struct timeval tv;
362     int res;
363
364     ef_make_stale();
365     pthread_mutex_unlock(&mtx_ctxsw);
366     do {
367         now = time(NULL);
368         tv.tv_sec = until >= now ? until - now : 0;
369         tv.tv_usec = 0;
370         empth_status("going to sleep %ld sec", (long)tv.tv_sec);
371         res = select(0, NULL, NULL, NULL, &tv);
372     } while (res < 0 && !ctx->wakeup);
373     empth_status("sleep done. Waiting for lock");
374     pthread_mutex_lock(&mtx_ctxsw);
375     empth_restorectx();
376     return res;
377 }
378
379 int
380 empth_wait_for_signal(void)
381 {
382     sigset_t set;
383     int sig, err;
384
385     ef_make_stale();
386     sigemptyset(&set);
387     sigaddset(&set, SIGHUP);
388     sigaddset(&set, SIGINT);
389     sigaddset(&set, SIGTERM);
390     pthread_mutex_unlock(&mtx_ctxsw);
391     for (;;) {
392         empth_status("waiting for signals");
393         err = sigwait(&set, &sig);
394         if (CANT_HAPPEN(err)) {
395             sleep(60);
396             continue;
397         }
398         empth_status("got awaited signal %d", sig);
399         pthread_mutex_lock(&mtx_ctxsw);
400         empth_restorectx();
401         return sig;
402     }
403 }
404
405 empth_rwlock_t *
406 empth_rwlock_create(char *name)
407 {
408     empth_rwlock_t *rwlock;
409
410     rwlock = malloc(sizeof(*rwlock));
411     if (!rwlock)
412         return NULL;
413
414     if (pthread_cond_init(&rwlock->can_read, NULL) != 0
415         || pthread_cond_init(&rwlock->can_write, NULL) != 0) {
416         free(rwlock);
417         return NULL;
418     }
419
420     rwlock->name = strdup(name);
421     rwlock->nread = rwlock->nwrite = 0;
422     return rwlock;
423 }
424
425 void
426 empth_rwlock_destroy(empth_rwlock_t *rwlock)
427 {
428     pthread_cond_destroy(&rwlock->can_read);
429     pthread_cond_destroy(&rwlock->can_write);
430     free(rwlock->name);
431     free(rwlock);
432 }
433
434 void
435 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
436 {
437     empth_status("wrlock %s %d %d",
438                  rwlock->name, rwlock->nread, rwlock->nwrite);
439     ef_make_stale();
440     rwlock->nwrite++;
441     while (rwlock->nread != 0 || rwlock->nwrite != 1) {
442         empth_status("waiting for wrlock %s", rwlock->name);
443         pthread_cond_wait(&rwlock->can_write, &mtx_ctxsw);
444         empth_status("got wrlock %s %d %d",
445                      rwlock->name, rwlock->nread, rwlock->nwrite);
446         empth_restorectx();
447     }
448 }
449
450 void
451 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
452 {
453     empth_status("rdlock %s %d %d",
454                  rwlock->name, rwlock->nread, rwlock->nwrite);
455     ef_make_stale();
456     while (rwlock->nwrite) {
457         empth_status("waiting for rdlock %s", rwlock->name);
458         pthread_cond_wait(&rwlock->can_read, &mtx_ctxsw);
459         empth_status("got rdlock %s %d %d",
460                      rwlock->name, rwlock->nread, rwlock->nwrite);
461         empth_restorectx();
462     }
463     rwlock->nread++;
464 }
465
466 void
467 empth_rwlock_unlock(empth_rwlock_t *rwlock)
468 {
469     if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
470         return;
471     if (rwlock->nread) {        /* holding read lock */
472         if (!--rwlock->nread)
473             pthread_cond_signal(&rwlock->can_write);
474     } else {
475         rwlock->nwrite--;
476         pthread_cond_signal(&rwlock->can_write);
477     }
478     if (rwlock->nwrite == 0)
479         pthread_cond_broadcast(&rwlock->can_read);
480 }