]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/ntthread.c
579672204865d586a2c7a68b77b055565ae61e01
[empserver] / src / lib / empthread / ntthread.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2009, 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  *  ntthread.c: Interface from Empire threads to Windows NT threads
29  *
30  *  Known contributors to this file:
31  *     Doug Hay, 1998
32  *     Steve McClure, 1998
33  *     Ron Koenderink, 2004-2009
34  */
35
36 /*
37  * EMPTHREADs for Windows NT.
38  *
39  * Actually, threads for any Win32 platform, like Win95, Win98, WinCE,
40  * and whatever other toy OSs are in our future from Microsoft.
41  *
42  * WIN32 has a full pre-emptive threading environment.  But Empire can
43  * not handle pre-emptive threading.  Thus, we will use the threads,
44  * but limit the preemption using a Mutex.
45  */
46
47 #include <config.h>
48
49 #include <errno.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <stdarg.h>
53 #include <sys/types.h>
54 #include <time.h>
55 #include <windows.h>
56 #include <process.h>
57 #include "misc.h"
58 #include "empthread.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
427     pThread = malloc(sizeof(*pThread));
428     if (!pThread) {
429         logerror("not enough memory to create thread %s", name);
430         return NULL;
431     }
432     memset(pThread, 0, sizeof(*pThread));
433
434     pThread->szName = strdup(name);
435     pThread->pvUserData = ud;
436     pThread->pfnEntry = entry;
437     pThread->bMainThread = FALSE;
438
439     /* Create thread event, auto reset. */
440     pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
441
442     if (size < loc_MIN_THREAD_STACK)
443         size = loc_MIN_THREAD_STACK;
444
445     pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
446     if (pThread->ulThreadID == 1L || pThread->ulThreadID == 0L) {
447         logerror("can not create thread: %s: %s", name, strerror(errno));
448         goto bad;
449     }
450
451     loc_debug("new thread id is %ld", pThread->ulThreadID);
452     empth_yield();
453     return pThread;
454
455 bad:
456     if (pThread) {
457         loc_FreeThreadInfo(pThread);
458     }
459     return NULL;
460 }
461
462
463 /************************
464  * empth_self
465  */
466 empth_t *
467 empth_self(void)
468 {
469     empth_t *pThread = TlsGetValue(dwTLSIndex);
470
471     return pThread;
472 }
473
474 /************************
475  * empth_name
476  */
477 char *
478 empth_name(empth_t *thread)
479 {
480     return thread->szName;
481 }
482
483 /************************
484  * empth_set_name
485  * Set the thread name
486  */
487 void
488 empth_set_name(empth_t *thread, char *name)
489 {
490     if (thread->szName != NULL)
491         free(thread->szName);
492     thread->szName = strdup(name);
493 }
494
495 /************************
496  * empth_exit
497  */
498 void
499 empth_exit(void)
500 {
501     empth_t *pThread = TlsGetValue(dwTLSIndex);
502
503     loc_debug("empth_exit");
504     loc_BlockThisThread();
505
506     TlsSetValue(dwTLSIndex, NULL);
507     loc_FreeThreadInfo(pThread);
508     _endthread();
509 }
510
511 /************************
512  * empth_yield
513  *
514  * Yield processing to another thread.
515  */
516 void
517 empth_yield(void)
518 {
519     loc_BlockThisThread();
520     Sleep(0);
521     loc_RunThisThread(NULL);
522 }
523
524 /************************
525  * empth_select
526  *
527  * Do a select on the given file.
528  * Wait for IO on it.
529  *
530  * This would be one of the main functions used within gen\io.c
531  */
532 int
533 empth_select(int fd, int flags, struct timeval *timeout)
534 {
535     SOCKET sock;
536     WSAEVENT hEventObject[2];
537     long events;
538     DWORD result, msec;
539     empth_t *pThread = TlsGetValue(dwTLSIndex);
540     int res;
541
542     loc_debug("%s select on %d",
543               flags == EMPTH_FD_READ ? "read" : "write", fd);
544     loc_BlockThisThread();
545
546     hEventObject[0] = WSACreateEvent();
547     hEventObject[1] = pThread->hThreadEvent;
548
549     sock = w32_fd2socket(fd);
550     CANT_HAPPEN(sock == (SOCKET)-1);
551
552     events = 0;
553     if (flags & EMPTH_FD_READ)
554         events |= FD_READ | FD_ACCEPT | FD_CLOSE;
555     if (flags & EMPTH_FD_WRITE)
556         events |= FD_WRITE | FD_CLOSE;
557     WSAEventSelect(sock, hEventObject[0], events);
558
559     if (timeout)
560         msec = timeout->tv_sec * 1000L + timeout->tv_usec / 1000L;
561     else
562         msec = WSA_INFINITE;
563     result = WSAWaitForMultipleEvents(2, hEventObject, FALSE, msec, FALSE);
564
565     switch (result) {
566     case WSA_WAIT_EVENT_0:
567         res = 1;
568         break;
569     case WSA_WAIT_EVENT_0 + 1:
570     case WSA_WAIT_TIMEOUT:
571         res = 0;
572         break;
573     case WSA_WAIT_FAILED:
574         w32_set_winsock_errno();
575         res = -1;
576         break;
577     default:
578         CANT_REACH();
579         errno = EINVAL;
580         res = -1;
581     }
582
583     WSAEventSelect(sock, hEventObject[0], 0);
584
585     WSACloseEvent(hEventObject[0]);
586
587     loc_RunThisThread(NULL);
588     return res;
589 }
590
591 /************************
592  * empth_wakeup
593  *
594  * Wake up the specified thread.
595  */
596 void
597 empth_wakeup(empth_t *pThread)
598 {
599     loc_debug("waking up thread %s", pThread->szName);
600
601     /* Let it run if it is blocked... */
602     SetEvent(pThread->hThreadEvent);
603 }
604
605 /************************
606  * empth_sleep
607  *
608  * Put the given thread to sleep...
609  */
610 int
611 empth_sleep(time_t until)
612 {
613     time_t now;
614     long lSec;
615     empth_t *pThread = TlsGetValue(dwTLSIndex);
616     DWORD result;
617
618     loc_BlockThisThread();
619
620     do {
621         now = time(NULL);
622         lSec = until >= now ? until - now : 0;
623         loc_debug("going to sleep %ld sec", lSec);
624         result = WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L);
625     } while (result != WAIT_TIMEOUT && result != WAIT_OBJECT_0);
626
627     loc_debug("sleep done. Waiting to run.");
628     loc_RunThisThread(NULL);
629
630     return result == WAIT_TIMEOUT ? 0 : -1;
631 }
632
633 /************************
634  * empth_request_shutdown
635  *
636  * This wakes up empth_wait_for_signal() so shutdown can proceed.
637  * This is done by signalling hShutdownEvent.
638  */
639 void
640 empth_request_shutdown(void)
641 {
642     SetEvent(hShutdownEvent);
643 }
644
645 int
646 empth_wait_for_signal(void)
647 {
648     loc_BlockThisThread();
649     loc_RunThisThread(hShutdownEvent);
650     return SIGTERM;
651 }
652
653 empth_rwlock_t *
654 empth_rwlock_create(char *name)
655 {
656     empth_rwlock_t *rwlock;
657
658     rwlock = malloc(sizeof(*rwlock));
659     if (!rwlock)
660         return NULL;
661
662     memset(rwlock, 0, sizeof(*rwlock));
663     rwlock->name = strdup(name);
664
665     if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
666         logerror("rwlock_create: failed to create reader event %s at %s:%d",
667                  name, __FILE__, __LINE__);
668         free(rwlock->name);
669         free(rwlock);
670         return NULL;
671     }
672
673     if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
674         logerror("rwlock_create: failed to create writer event %s at %s:%d",
675                  name, __FILE__, __LINE__);
676         free(rwlock->name);
677         CloseHandle(rwlock->can_read);
678         free(rwlock);
679         return NULL;
680     }
681     return rwlock;
682 }
683
684 void
685 empth_rwlock_destroy(empth_rwlock_t *rwlock)
686 {
687     if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
688         return;
689     if (rwlock->name != NULL)
690         free(rwlock->name);
691     CloseHandle(rwlock->can_read);
692     CloseHandle(rwlock->can_write);
693     free(rwlock);
694 }
695
696 void
697 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
698 {
699     /* block any new readers */
700     ResetEvent(rwlock->can_read);
701     rwlock->nwrite++;
702     loc_BlockThisThread();
703     loc_RunThisThread(rwlock->can_write);
704     CANT_HAPPEN(rwlock->nread != 0);
705 }
706
707 void
708 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
709 {
710     loc_BlockThisThread();
711     loc_RunThisThread(rwlock->can_read);
712     ResetEvent(rwlock->can_write);
713     rwlock->nread++;
714 }
715
716 void
717 empth_rwlock_unlock(empth_rwlock_t *rwlock)
718 {
719     if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
720         return;
721     if (rwlock->nread) {        /* holding read lock */
722         rwlock->nread--;
723         if (rwlock->nread == 0)
724             SetEvent(rwlock->can_write);
725     } else {
726         rwlock->nwrite--;
727         SetEvent(rwlock->can_write);
728     }
729     if (rwlock->nwrite == 0)
730         SetEvent(rwlock->can_read);
731 }