]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/ntthread.c
License upgrade to GPL version 3 or later
[empserver] / src / lib / empthread / ntthread.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2011, 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  *  ntthread.c: Interface from Empire threads to Windows NT threads
28  *
29  *  Known contributors to this file:
30  *     Doug Hay, 1998
31  *     Steve McClure, 1998
32  *     Ron Koenderink, 2004-2009
33  */
34
35 /*
36  * EMPTHREADs for Windows NT.
37  *
38  * Actually, threads for any Win32 platform, like Win95, Win98, WinCE,
39  * and whatever other toy OSs are in our future from Microsoft.
40  *
41  * WIN32 has a full pre-emptive threading environment.  But Empire can
42  * not handle pre-emptive threading.  Thus, we will use the threads,
43  * but limit the preemption using a Mutex.
44  */
45
46 #include <config.h>
47
48 #include <errno.h>
49 #include <signal.h>
50 #include <stdio.h>
51 #include <stdarg.h>
52 #include <sys/types.h>
53 #include <time.h>
54 #include <windows.h>
55 #include <process.h>
56 #include "misc.h"
57 #include "empthread.h"
58 #include "file.h"
59 #include "prototypes.h"
60 #include "server.h"
61 #include "sys/socket.h"
62
63 #define loc_MIN_THREAD_STACK  16384
64
65 /************************
66  * loc_Thread
67  */
68 struct loc_Thread {
69
70     /* The thread name, passed in at create time. */
71     char *szName;
72
73     /* True if this is the main line, and not a real thread. */
74     BOOL bMainThread;
75
76     /* The user data passed in at create time. */
77     void *pvUserData;
78
79     /* The entry function for the thread. */
80     void (*pfnEntry) (void *);
81
82     /* The system thread ID. */
83     unsigned long ulThreadID;
84
85     /* An Mutex that the thread will wait/sleep on. */
86     HANDLE hThreadEvent;
87 };
88
89
90 /************************
91  * loc_RWLock
92  *
93  * Invariants
94  *      must hold at function call, return, sleep
95  *      and resume from sleep.
96  *
97  * any state:
98  *      nwrite >= 0
99  *      nread >= 0
100  *
101  * if unlocked:
102  *      can_read set
103  *      can_write set
104  *      nwrite == 0
105  *      nread == 0
106  *
107  * if read-locked without writers contending:
108  *      can_read set
109  *      can_write clear
110  *      nwrite == 0
111  *      nread > 0
112  *
113  * if read-locked with writers contending:
114  *      can_read clear
115  *      can_write clear
116  *      nwrite > 0    #writers blocked
117  *      nread > 0
118  *
119  * if write-locked:
120  *      can_read clear
121  *      can_write clear
122  *      nwrite > 0    #writers blocked + 1
123  *      nread == 0
124  *
125  * To ensure consistency, state normally changes only while the
126  * thread changing it holds hThreadMutex.
127  *
128  */
129 struct loc_RWLock {
130     char *name;         /* The lock name, passed in at create time. */
131     HANDLE can_read;    /* Manual event -- allows read locks */
132     HANDLE can_write;   /* Auto-reset event -- allows write locks */
133     int nread;          /* number of active readers */
134     int nwrite;         /* total number of writers (active and waiting) */
135 };
136
137 /* This is the thread exclusion/non-premption mutex. */
138 /* The running thread has this MUTEX, and all others are */
139 /* either blocked on it, or waiting for some OS response. */
140 static HANDLE hThreadMutex;
141
142 /* This is the thread startup event. */
143 /* We use this to lockstep when we are starting up threads. */
144 static HANDLE hThreadStartEvent;
145
146 /* This is an event used to wakeup the main thread */
147 /* to start the shutdown sequence. */
148 static HANDLE hShutdownEvent;
149
150 /* The Thread Local Storage index.  We store the pThread pointer */
151 /* for each thread at this index. */
152 static DWORD dwTLSIndex;
153
154 /* The current running thread. */
155 static empth_t *pCurThread;
156
157 /* Ticks at start */
158 static unsigned long ulTickAtStart;
159
160 /* Pointer out to global context.  "player". */
161 /* From empth_init parameter. */
162 static void **ppvUserData;
163
164 /* Global flags.  From empth_init parameter. */
165 static int global_flags;
166
167 static void loc_debug(const char *, ...) ATTRIBUTE((format(printf, 1, 2)));
168
169 /************************
170  * loc_debug
171  *
172  * Print out the current thread's status??
173  */
174 static void
175 loc_debug(const char *pszFmt, ...)
176 {
177     va_list vaList;
178     unsigned long ulCurTick;
179     unsigned long ulRunTick;
180     unsigned long ulMs, ulSec, ulMin, ulHr;
181     empth_t *pThread = TlsGetValue(dwTLSIndex);
182     char buf[1024];
183
184     if ((global_flags & EMPTH_PRINT) != 0) {
185
186         /* Ticks are in milliseconds */
187         ulCurTick = GetTickCount();
188
189         ulRunTick = ulCurTick - ulTickAtStart;
190         ulMs = ulRunTick % 1000L;
191         ulSec = (ulRunTick / 1000L) % 60L;
192         ulMin = (ulRunTick / (60L * 1000L)) % 60L;
193         ulHr = (ulRunTick / (60L * 60L * 1000L));
194
195         va_start(vaList, pszFmt);
196         vsprintf(buf, pszFmt, vaList);
197         va_end(vaList);
198
199         if (pThread) {
200             printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
201                    ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
202         } else {
203             printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
204                    ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
205         }
206
207     }
208 }
209
210 /************************
211  * loc_FreeThreadInfo
212  */
213 static void
214 loc_FreeThreadInfo(empth_t *pThread)
215 {
216     if (pThread) {
217         if (pThread->hThreadEvent)
218             CloseHandle(pThread->hThreadEvent);
219         if (pThread->szName != NULL)
220             free(pThread->szName);
221         free(pThread);
222     }
223 }
224
225 /************************
226  * loc_RunThisThread
227  *
228  * This thread wants to run.
229  * When this function returns, the globals are set to this thread
230  * info, and the thread owns the MUTEX.
231  */
232 static void
233 loc_RunThisThread(HANDLE hWaitObject)
234 {
235     HANDLE hWaitObjects[2];
236
237     empth_t *pThread = TlsGetValue(dwTLSIndex);
238
239     hWaitObjects[0] = hThreadMutex;
240     hWaitObjects[1] = hWaitObject;
241
242     WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
243                            TRUE, INFINITE);
244
245     if (!pCurThread) {
246         /* Set the globals to this thread. */
247         *ppvUserData = pThread->pvUserData;
248
249         pCurThread = pThread;
250     } else {
251         /* Hmm, a problem, eh? */
252         logerror("RunThisThread, someone already running.");
253     }
254 }
255
256 /************************
257  * loc_BlockThisThread
258  *
259  * This thread was running.  It no longer wants to.
260  */
261 static void
262 loc_BlockThisThread(void)
263 {
264     empth_t *pThread = TlsGetValue(dwTLSIndex);
265
266     if (pCurThread == pThread) {
267         /* Reset the globals back to original */
268
269         pCurThread = NULL;
270         *ppvUserData = NULL;
271
272         /* Release the MUTEX */
273         ReleaseMutex(hThreadMutex);
274     } else {
275         /* Hmm, this thread was not the running one. */
276         logerror("BlockThisThread, not running.");
277     }
278 }
279
280 /************************
281  * loc_Exit_Handler
282  *
283  * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
284  * System-Shutdown will initiate a shutdown.
285  * This is done by calling empth_request_shutdown()
286  */
287 static BOOL WINAPI
288 loc_Exit_Handler(DWORD fdwCtrlType)
289 {
290     switch (fdwCtrlType) {
291     case CTRL_C_EVENT:
292     case CTRL_CLOSE_EVENT:
293     case CTRL_BREAK_EVENT:
294     case CTRL_LOGOFF_EVENT:
295     case CTRL_SHUTDOWN_EVENT:
296         empth_request_shutdown();
297         return TRUE;
298     default:
299         return FALSE;
300     }
301 }
302
303 /************************
304  * empth_threadMain
305  *
306  * This is the main line of each thread.
307  * This is really a static local func....
308  * Note: As the POSIX compatibility layer is not thread safe
309  * this function can not open or create any files or sockets until
310  * loc_RunThisThread() is called
311  */
312 static void
313 empth_threadMain(void *pvData)
314 {
315     empth_t *pThread = pvData;
316
317     /* Out of here... */
318     if (!pvData)
319         return;
320
321     /* Store pThread on this thread. */
322     TlsSetValue(dwTLSIndex, pvData);
323
324     /* Get the ID of the thread. */
325     pThread->ulThreadID = GetCurrentThreadId();
326
327     /* Signal that the thread has started. */
328     SetEvent(hThreadStartEvent);
329
330     /* Switch to this thread context */
331     loc_RunThisThread(NULL);
332
333     /* Run the thread. */
334     if (pThread->pfnEntry)
335         pThread->pfnEntry(pThread->pvUserData);
336
337     /* Kill the thread. */
338     empth_exit();
339 }
340
341 /************************
342  * empth_init
343  *
344  * Initialize the thread environment.
345  *
346  * This is called from the program main line.
347  */
348 int
349 empth_init(void **ctx_ptr, int flags)
350 {
351     empth_t *pThread = NULL;
352
353     ulTickAtStart = GetTickCount();
354     ppvUserData = ctx_ptr;
355     global_flags = flags;
356     dwTLSIndex = TlsAlloc();
357
358     /* Create the thread mutex. */
359     /* Initally unowned. */
360     hThreadMutex = CreateMutex(NULL, FALSE, NULL);
361     if (!hThreadMutex) {
362         logerror("Failed to create mutex %lu", GetLastError());
363         return 0;
364     }
365
366     /* Create the thread start event. */
367     /* Automatic state reset. */
368     hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
369     if (!hThreadStartEvent) {
370         logerror("Failed to create start event %lu", GetLastError());
371         return 0;
372     }
373
374     /* Create the shutdown event for the main thread. */
375     /* Manual reset */
376     hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
377     if (!hShutdownEvent) {
378         logerror("Failed to create shutdown event %lu", GetLastError());
379         return 0;
380     }
381     SetConsoleCtrlHandler(loc_Exit_Handler, TRUE);
382
383     /* Create the global Thread context. */
384     pThread = malloc(sizeof(*pThread));
385     if (!pThread) {
386         logerror("not enough memory to create main thread.");
387         return 0;
388     }
389     memset(pThread, 0, sizeof(*pThread));
390
391     pThread->szName = strdup("Main");
392     pThread->ulThreadID = GetCurrentThreadId();
393     pThread->bMainThread = TRUE;
394
395     TlsSetValue(dwTLSIndex, pThread);
396
397     /* Make this the running thread. */
398     loc_RunThisThread(NULL);
399
400     logerror("NT pthreads initialized");
401     return 0;
402 }
403
404
405 /************************
406  * empth_create
407  *
408  * Create a new thread.
409  *
410  * entry - entry point function for thread.
411  * size  - stack size.
412  * flags - debug control.
413  *           LWP_STACKCHECK  - not needed
414  * name  - name of the thread, for debug.
415  * ud    - "user data".  The "ctx_ptr" gets this value
416  *         when the thread is active.
417  *         It is also passed to the entry function...
418  */
419 empth_t *
420 empth_create(void (*entry)(void *), int size, int flags,
421              char *name, void *ud)
422 {
423     empth_t *pThread = NULL;
424
425     loc_debug("creating new thread %s", name);
426     ef_make_stale();
427
428     pThread = malloc(sizeof(*pThread));
429     if (!pThread) {
430         logerror("not enough memory to create thread %s", name);
431         return NULL;
432     }
433     memset(pThread, 0, sizeof(*pThread));
434
435     pThread->szName = strdup(name);
436     pThread->pvUserData = ud;
437     pThread->pfnEntry = entry;
438     pThread->bMainThread = FALSE;
439
440     /* Create thread event, auto reset. */
441     pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
442
443     if (size < loc_MIN_THREAD_STACK)
444         size = loc_MIN_THREAD_STACK;
445
446     pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
447     if (pThread->ulThreadID == 1L || pThread->ulThreadID == 0L) {
448         logerror("can not create thread: %s: %s", name, strerror(errno));
449         goto bad;
450     }
451
452     loc_debug("new thread id is %ld", pThread->ulThreadID);
453     empth_yield();
454     return pThread;
455
456 bad:
457     if (pThread) {
458         loc_FreeThreadInfo(pThread);
459     }
460     return NULL;
461 }
462
463
464 /************************
465  * empth_self
466  */
467 empth_t *
468 empth_self(void)
469 {
470     empth_t *pThread = TlsGetValue(dwTLSIndex);
471
472     return pThread;
473 }
474
475 /************************
476  * empth_name
477  */
478 char *
479 empth_name(empth_t *thread)
480 {
481     return thread->szName;
482 }
483
484 /************************
485  * empth_set_name
486  * Set the thread name
487  */
488 void
489 empth_set_name(empth_t *thread, char *name)
490 {
491     if (thread->szName != NULL)
492         free(thread->szName);
493     thread->szName = strdup(name);
494 }
495
496 /************************
497  * empth_exit
498  */
499 void
500 empth_exit(void)
501 {
502     empth_t *pThread = TlsGetValue(dwTLSIndex);
503
504     loc_debug("empth_exit");
505     ef_make_stale();
506     loc_BlockThisThread();
507
508     TlsSetValue(dwTLSIndex, NULL);
509     loc_FreeThreadInfo(pThread);
510     _endthread();
511 }
512
513 /************************
514  * empth_yield
515  *
516  * Yield processing to another thread.
517  */
518 void
519 empth_yield(void)
520 {
521     ef_make_stale();
522     loc_BlockThisThread();
523     Sleep(0);
524     loc_RunThisThread(NULL);
525 }
526
527 /************************
528  * empth_select
529  *
530  * Do a select on the given file.
531  * Wait for IO on it.
532  *
533  * This would be one of the main functions used within gen\io.c
534  */
535 int
536 empth_select(int fd, int flags, struct timeval *timeout)
537 {
538     SOCKET sock;
539     WSAEVENT hEventObject[2];
540     long events;
541     DWORD result, msec;
542     empth_t *pThread = TlsGetValue(dwTLSIndex);
543     int res;
544
545     loc_debug("%s select on %d",
546               flags == EMPTH_FD_READ ? "read" : "write", fd);
547     ef_make_stale();
548     loc_BlockThisThread();
549
550     hEventObject[0] = WSACreateEvent();
551     hEventObject[1] = pThread->hThreadEvent;
552
553     sock = w32_fd2socket(fd);
554     CANT_HAPPEN(sock == (SOCKET)-1);
555
556     events = 0;
557     if (flags & EMPTH_FD_READ)
558         events |= FD_READ | FD_ACCEPT | FD_CLOSE;
559     if (flags & EMPTH_FD_WRITE)
560         events |= FD_WRITE | FD_CLOSE;
561     WSAEventSelect(sock, hEventObject[0], events);
562
563     if (timeout)
564         msec = timeout->tv_sec * 1000L + timeout->tv_usec / 1000L;
565     else
566         msec = WSA_INFINITE;
567     result = WSAWaitForMultipleEvents(2, hEventObject, FALSE, msec, FALSE);
568
569     switch (result) {
570     case WSA_WAIT_EVENT_0:
571         res = 1;
572         break;
573     case WSA_WAIT_EVENT_0 + 1:
574     case WSA_WAIT_TIMEOUT:
575         res = 0;
576         break;
577     case WSA_WAIT_FAILED:
578         w32_set_winsock_errno();
579         res = -1;
580         break;
581     default:
582         CANT_REACH();
583         errno = EINVAL;
584         res = -1;
585     }
586
587     WSAEventSelect(sock, hEventObject[0], 0);
588
589     WSACloseEvent(hEventObject[0]);
590
591     loc_RunThisThread(NULL);
592     return res;
593 }
594
595 /************************
596  * empth_wakeup
597  *
598  * Wake up the specified thread.
599  */
600 void
601 empth_wakeup(empth_t *pThread)
602 {
603     loc_debug("waking up thread %s", pThread->szName);
604
605     /* Let it run if it is blocked... */
606     SetEvent(pThread->hThreadEvent);
607 }
608
609 /************************
610  * empth_sleep
611  *
612  * Put the given thread to sleep...
613  */
614 int
615 empth_sleep(time_t until)
616 {
617     time_t now;
618     long lSec;
619     empth_t *pThread = TlsGetValue(dwTLSIndex);
620     DWORD result;
621
622     ef_make_stale();
623     loc_BlockThisThread();
624
625     do {
626         now = time(NULL);
627         lSec = until >= now ? until - now : 0;
628         loc_debug("going to sleep %ld sec", lSec);
629         result = WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L);
630     } while (result != WAIT_TIMEOUT && result != WAIT_OBJECT_0);
631
632     loc_debug("sleep done. Waiting to run.");
633     loc_RunThisThread(NULL);
634
635     return result == WAIT_TIMEOUT ? 0 : -1;
636 }
637
638 /************************
639  * empth_request_shutdown
640  *
641  * This wakes up empth_wait_for_signal() so shutdown can proceed.
642  * This is done by signalling hShutdownEvent.
643  */
644 void
645 empth_request_shutdown(void)
646 {
647     SetEvent(hShutdownEvent);
648 }
649
650 int
651 empth_wait_for_signal(void)
652 {
653     ef_make_stale();
654     loc_BlockThisThread();
655     loc_RunThisThread(hShutdownEvent);
656     return SIGTERM;
657 }
658
659 empth_rwlock_t *
660 empth_rwlock_create(char *name)
661 {
662     empth_rwlock_t *rwlock;
663
664     rwlock = malloc(sizeof(*rwlock));
665     if (!rwlock)
666         return NULL;
667
668     memset(rwlock, 0, sizeof(*rwlock));
669     rwlock->name = strdup(name);
670
671     if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
672         logerror("rwlock_create: failed to create reader event %s at %s:%d",
673                  name, __FILE__, __LINE__);
674         free(rwlock->name);
675         free(rwlock);
676         return NULL;
677     }
678
679     if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
680         logerror("rwlock_create: failed to create writer event %s at %s:%d",
681                  name, __FILE__, __LINE__);
682         free(rwlock->name);
683         CloseHandle(rwlock->can_read);
684         free(rwlock);
685         return NULL;
686     }
687     return rwlock;
688 }
689
690 void
691 empth_rwlock_destroy(empth_rwlock_t *rwlock)
692 {
693     if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
694         return;
695     if (rwlock->name != NULL)
696         free(rwlock->name);
697     CloseHandle(rwlock->can_read);
698     CloseHandle(rwlock->can_write);
699     free(rwlock);
700 }
701
702 void
703 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
704 {
705     ef_make_stale();
706     /* block any new readers */
707     ResetEvent(rwlock->can_read);
708     rwlock->nwrite++;
709     loc_BlockThisThread();
710     loc_RunThisThread(rwlock->can_write);
711     CANT_HAPPEN(rwlock->nread != 0);
712 }
713
714 void
715 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
716 {
717     ef_make_stale();
718     loc_BlockThisThread();
719     loc_RunThisThread(rwlock->can_read);
720     ResetEvent(rwlock->can_write);
721     rwlock->nread++;
722 }
723
724 void
725 empth_rwlock_unlock(empth_rwlock_t *rwlock)
726 {
727     if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
728         return;
729     if (rwlock->nread) {        /* holding read lock */
730         rwlock->nread--;
731         if (rwlock->nread == 0)
732             SetEvent(rwlock->can_write);
733     } else {
734         rwlock->nwrite--;
735         SetEvent(rwlock->can_write);
736     }
737     if (rwlock->nwrite == 0)
738         SetEvent(rwlock->can_read);
739 }