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