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