]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/ntthread.c
Update known contributors comments
[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 <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;
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;         /* The lock 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         if (pThread->szName != NULL)
228             free(pThread->szName);
229         memset(pThread, 0, sizeof(*pThread));
230         free(pThread);
231     }
232 }
233
234 /************************
235  * loc_RunThisThread
236  *
237  * This thread wants to run.
238  * When this function returns, the globals are set to this thread
239  * info, and the thread owns the MUTEX.
240  */
241 static void
242 loc_RunThisThread(HANDLE hWaitObject)
243 {
244     HANDLE hWaitObjects[2];
245
246     empth_t *pThread = TlsGetValue(dwTLSIndex);
247
248     if (pThread->bKilled) {
249         if (!pThread->bMainThread) {
250             TlsSetValue(dwTLSIndex, NULL);
251             loc_FreeThreadInfo(pThread);
252             _endthread();
253         }
254     }
255
256     hWaitObjects[0] = hThreadMutex;
257     hWaitObjects[1] = hWaitObject;
258
259     WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
260                            TRUE, INFINITE);
261
262     if (!pCurThread) {
263         /* Set the globals to this thread. */
264         *ppvUserData = pThread->pvUserData;
265
266         pCurThread = pThread;
267     } else {
268         /* Hmm, a problem, eh? */
269         logerror("RunThisThread, someone already running.");
270     }
271 }
272
273 /************************
274  * loc_BlockThisThread
275  *
276  * This thread was running.  It no longer wants to.
277  */
278 static void
279 loc_BlockThisThread(void)
280 {
281     empth_t *pThread = TlsGetValue(dwTLSIndex);
282
283     if (pCurThread == pThread) {
284         /* Reset the globals back to original */
285
286         pCurThread = NULL;
287         *ppvUserData = NULL;
288
289         /* Release the MUTEX */
290         ReleaseMutex(hThreadMutex);
291     } else {
292         /* Hmm, this thread was not the running one. */
293         logerror("BlockThisThread, not running.");
294     }
295 }
296
297 /************************
298  * loc_Exit_Handler
299  *
300  * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
301  * System-Shutdown will initiate a shutdown.
302  * This is done by calling empth_request_shutdown()
303  */
304 static BOOL WINAPI
305 loc_Exit_Handler(DWORD fdwCtrlType)
306 {
307     switch (fdwCtrlType) {
308         case CTRL_C_EVENT:
309         case CTRL_CLOSE_EVENT:
310         case CTRL_BREAK_EVENT:
311         case CTRL_LOGOFF_EVENT:
312         case CTRL_SHUTDOWN_EVENT:
313             empth_request_shutdown();
314             return TRUE;
315         default:
316             return FALSE;
317     }
318 }
319
320 /************************
321  * empth_threadMain
322  *
323  * This is the main line of each thread.
324  * This is really a static local func....
325  * Note: As the POSIX compatibility layer is not thread safe
326  * this function can not open or create any files or sockets until
327  * loc_RunThisThread() is called
328  */
329 static void
330 empth_threadMain(void *pvData)
331 {
332     empth_t *pThread = pvData;
333
334     /* Out of here... */
335     if (!pvData)
336         return;
337
338     /* Store pThread on this thread. */
339     TlsSetValue(dwTLSIndex, pvData);
340
341     /* Get the ID of the thread. */
342     pThread->ulThreadID = GetCurrentThreadId();
343
344     /* Signal that the thread has started. */
345     SetEvent(hThreadStartEvent);
346
347     /* Switch to this thread context */
348     loc_RunThisThread(NULL);
349
350     /* Run the thread. */
351     if (pThread->pfnEntry)
352         pThread->pfnEntry(pThread->pvUserData);
353
354     /* Kill the thread. */
355     empth_exit();
356 }
357
358 /************************
359  * empth_init
360  *
361  * Initialize the thread environment.
362  *
363  * This is called from the program main line.
364  */
365 int
366 empth_init(void **ctx_ptr, int flags)
367 {
368     empth_t *pThread = NULL;
369
370     ulTickAtStart = GetTickCount();
371     ppvUserData = ctx_ptr;
372     global_flags = flags;
373     dwTLSIndex = TlsAlloc();
374
375     /* Create the thread mutex. */
376     /* Initally unowned. */
377     hThreadMutex = CreateMutex(NULL, FALSE, NULL);
378     if (!hThreadMutex) {
379         logerror("Failed to create mutex %lu", GetLastError());
380         return 0;
381     }
382
383     /* Create the thread start event. */
384     /* Automatic state reset. */
385     hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
386     if (!hThreadStartEvent) {
387         logerror("Failed to create start event %lu", GetLastError());
388         return 0;
389     }
390
391     /* Create the shutdown event for the main thread. */
392     /* Manual reset */
393     hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
394     if (!hShutdownEvent) {
395         logerror("Failed to create shutdown event %lu", GetLastError());
396         return 0;
397     }
398     SetConsoleCtrlHandler(loc_Exit_Handler, TRUE);
399
400     /* Create the global Thread context. */
401     pThread = malloc(sizeof(*pThread));
402     if (!pThread) {
403         logerror("not enough memory to create main thread.");
404         return 0;
405     }
406     memset(pThread, 0, sizeof(*pThread));
407
408     pThread->szName = strdup("Main");
409     pThread->ulThreadID = GetCurrentThreadId();
410     pThread->bMainThread = TRUE;
411
412     TlsSetValue(dwTLSIndex, pThread);
413
414     /* Make this the running thread. */
415     loc_RunThisThread(NULL);
416
417     logerror("NT pthreads initialized");
418     return 0;
419 }
420
421
422 /************************
423  * empth_create
424  *
425  * Create a new thread.
426  *
427  * entry - entry point function for thread.
428  * size  - stack size.
429  * flags - debug control.
430  *           LWP_STACKCHECK  - not needed
431  * name  - name of the thread, for debug.
432  * ud    - "user data".  The "ctx_ptr" gets this value
433  *         when the thread is active.
434  *         It is also passed to the entry function...
435  */
436 empth_t *
437 empth_create(void (*entry)(void *), int size, int flags,
438              char *name, void *ud)
439 {
440     empth_t *pThread = NULL;
441
442     loc_debug("creating new thread %s", name);
443
444     pThread = malloc(sizeof(*pThread));
445     if (!pThread) {
446         logerror("not enough memory to create thread %s", name);
447         return NULL;
448     }
449     memset(pThread, 0, sizeof(*pThread));
450
451     pThread->szName = strdup(name);
452     pThread->pvUserData = ud;
453     pThread->pfnEntry = entry;
454     pThread->bMainThread = FALSE;
455
456     /* Create thread event, auto reset. */
457     pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
458
459     if (size < loc_MIN_THREAD_STACK)
460         size = loc_MIN_THREAD_STACK;
461
462     pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
463     if (pThread->ulThreadID == 1L || pThread->ulThreadID == 0L) {
464         logerror("can not create thread: %s: %s", name, strerror(errno));
465         goto bad;
466     }
467
468     loc_debug("new thread id is %ld", pThread->ulThreadID);
469     empth_yield();
470     return pThread;
471
472   bad:
473     if (pThread) {
474         loc_FreeThreadInfo(pThread);
475     }
476     return NULL;
477 }
478
479
480 /************************
481  * empth_self
482  */
483 empth_t *
484 empth_self(void)
485 {
486     empth_t *pThread = TlsGetValue(dwTLSIndex);
487
488     return pThread;
489 }
490
491 /************************
492  * empth_name
493  */
494 char *
495 empth_name(empth_t *thread)
496 {
497     return thread->szName;
498 }
499
500 /************************
501  * empth_set_name
502  * Set the thread name
503  */
504 void
505 empth_set_name(empth_t *thread, char *name)
506 {
507     if (thread->szName != NULL)
508         free(thread->szName);
509     thread->szName = strdup(name);
510 }
511
512 /************************
513  * empth_exit
514  */
515 void
516 empth_exit(void)
517 {
518     empth_t *pThread = TlsGetValue(dwTLSIndex);
519
520     loc_debug("empth_exit");
521     loc_BlockThisThread();
522
523     TlsSetValue(dwTLSIndex, NULL);
524     loc_FreeThreadInfo(pThread);
525     _endthread();
526 }
527
528 /************************
529  * empth_yield
530  *
531  * Yield processing to another thread.
532  */
533 void
534 empth_yield(void)
535 {
536     loc_BlockThisThread();
537     Sleep(0);
538     loc_RunThisThread(NULL);
539 }
540
541 /************************
542  * empth_terminate
543  *
544  * Kill off the thread.
545  */
546 void
547 empth_terminate(empth_t *pThread)
548 {
549     loc_debug("killing thread %s", pThread->szName);
550     pThread->bKilled = TRUE;
551
552     SetEvent(pThread->hThreadEvent);
553 }
554
555 /************************
556  * empth_select
557  *
558  * Do a select on the given file.
559  * Wait for IO on it.
560  *
561  * This would be one of the main functions used within gen\io.c
562  */
563 int
564 empth_select(int fd, int flags, struct timeval *timeout)
565 {
566     int handle;
567     WSAEVENT hEventObject[2];
568     long events;
569     DWORD result, msec;
570     empth_t *pThread = TlsGetValue(dwTLSIndex);
571     int res;
572
573     loc_debug("%s select on %d",
574               flags == EMPTH_FD_READ ? "read" : "write", fd);
575     loc_BlockThisThread();
576
577     hEventObject[0] = WSACreateEvent();
578     hEventObject[1] = pThread->hThreadEvent;
579
580     handle = posix_fd2socket(fd);
581     CANT_HAPPEN(handle < 0);
582
583     events = 0;
584     if (flags & EMPTH_FD_READ)
585         events |= FD_READ | FD_ACCEPT | FD_CLOSE;
586     if (flags & EMPTH_FD_WRITE)
587         events |= FD_WRITE | FD_CLOSE;
588     WSAEventSelect(handle, hEventObject[0], events);
589
590     if (timeout)
591         msec = timeout->tv_sec * 1000L + timeout->tv_usec / 1000L;
592     else
593         msec = WSA_INFINITE;
594     result = WSAWaitForMultipleEvents(2, hEventObject, FALSE, msec, FALSE);
595
596     switch (result) {
597     case WSA_WAIT_TIMEOUT:
598         res = 0;
599         break;
600     case WSA_WAIT_FAILED:
601         errno = WSAGetLastError();
602         res = -1;
603         break;
604     default:
605         res = 1;
606     }
607
608     WSAEventSelect(handle, hEventObject[0], 0);
609
610     WSACloseEvent(hEventObject[0]);
611
612     loc_RunThisThread(NULL);
613     return res;
614 }
615
616 /************************
617  * empth_wakeup
618  *
619  * Wake up the specified thread.
620  */
621 void
622 empth_wakeup(empth_t *pThread)
623 {
624     loc_debug("waking up thread %s", pThread->szName);
625
626     /* Let it run if it is blocked... */
627     SetEvent(pThread->hThreadEvent);
628 }
629
630 /************************
631  * empth_sleep
632  *
633  * Put the given thread to sleep...
634  */
635 int
636 empth_sleep(time_t until)
637 {
638     long lSec = until - time(0) > 0 ? until - time(0) : 0;
639     empth_t *pThread = TlsGetValue(dwTLSIndex);
640     int iReturn = 0;
641
642     do {
643         loc_BlockThisThread();
644         loc_debug("going to sleep %ld sec", lSec);
645
646         if (WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L) !=
647             WAIT_TIMEOUT)
648             iReturn = -1;
649
650         loc_debug("sleep done. Waiting to run.");
651         loc_RunThisThread(NULL);
652     } while (!iReturn && ((lSec = until - time(0)) > 0));
653
654     return iReturn;
655 }
656
657 /************************
658  * empth_request_shutdown
659  *
660  * This wakes up empth_wait_for_signal() so shutdown can proceed.
661  * This is done by signalling hShutdownEvent.
662  */
663 void
664 empth_request_shutdown(void)
665 {
666     SetEvent(hShutdownEvent);
667 }
668
669 int
670 empth_wait_for_signal(void)
671 {
672     loc_BlockThisThread();
673     loc_RunThisThread(hShutdownEvent);
674     return SIGTERM;
675 }
676
677 empth_rwlock_t *
678 empth_rwlock_create(char *name)
679 {
680     empth_rwlock_t *rwlock;
681
682     rwlock = malloc(sizeof(*rwlock));
683     if (!rwlock)
684         return NULL;
685
686     memset(rwlock, 0, sizeof(*rwlock));
687     rwlock->name = strdup(name);
688
689     if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
690         logerror("rwlock_create: failed to create reader event %s at %s:%d",
691             name, __FILE__, __LINE__);
692         free(rwlock->name);
693         free(rwlock);
694         return NULL;
695     }
696
697     if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
698         logerror("rwlock_create: failed to create writer event %s at %s:%d",
699             name, __FILE__, __LINE__);
700         free(rwlock->name);
701         CloseHandle(rwlock->can_read);
702         free(rwlock);
703         return NULL;
704     }
705     return rwlock;
706 }
707
708 void
709 empth_rwlock_destroy(empth_rwlock_t *rwlock)
710 {
711     if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
712         return;
713     if (rwlock->name != NULL)
714         free(rwlock->name);
715     CloseHandle(rwlock->can_read);
716     CloseHandle(rwlock->can_write);
717     free(rwlock);
718 }
719
720 void
721 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
722 {
723     /* block any new readers */
724     ResetEvent(rwlock->can_read);
725     rwlock->nwrite++;
726     loc_BlockThisThread();
727     loc_RunThisThread(rwlock->can_write);
728     CANT_HAPPEN(rwlock->nread != 0);
729 }
730
731 void
732 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
733 {
734     loc_BlockThisThread();
735     loc_RunThisThread(rwlock->can_read);
736     ResetEvent(rwlock->can_write);
737     rwlock->nread++;
738 }
739
740 void
741 empth_rwlock_unlock(empth_rwlock_t *rwlock)
742 {
743     if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
744         return;
745    if (rwlock->nread) { /* holding read lock */
746         rwlock->nread--;
747         if (rwlock->nread == 0)
748             SetEvent(rwlock->can_write);
749     } else {
750         rwlock->nwrite--;
751         SetEvent(rwlock->can_write);
752     }
753     if (rwlock->nwrite == 0)
754         SetEvent(rwlock->can_read);
755 }