1 /* -----------------------------------------------------------------------------
2 * $Id: Select.c,v 1.24 2003/02/21 05:34:16 sof Exp $
4 * (c) The GHC Team 1995-2002
6 * Support for concurrent non-blocking I/O and thread waiting.
8 * ---------------------------------------------------------------------------*/
10 /* we're outside the realms of POSIX here... */
11 /* #include "PosixSource.h" */
19 #include "Capability.h"
21 # ifdef HAVE_SYS_TYPES_H
22 # include <sys/types.h>
25 # ifdef HAVE_SYS_TIME_H
26 # include <sys/time.h>
29 # ifdef mingw32_TARGET_OS
31 # include "win32/AsyncIO.h"
40 #ifdef RTS_SUPPORTS_THREADS
41 static rtsBool isWorkerBlockedInAwaitEvent = rtsFalse;
42 static rtsBool workerWakeupPending = rtsFalse;
43 #ifndef mingw32_TARGET_OS
44 static int workerWakeupPipe[2];
45 static rtsBool workerWakeupInited = rtsFalse;
49 /* There's a clever trick here to avoid problems when the time wraps
50 * around. Since our maximum delay is smaller than 31 bits of ticks
51 * (it's actually 31 bits of microseconds), we can safely check
52 * whether a timer has expired even if our timer will wrap around
53 * before the target is reached, using the following formula:
55 * (int)((uint)current_time - (uint)target_time) < 0
57 * if this is true, then our time has expired.
58 * (idea due to Andy Gill).
61 wakeUpSleepingThreads(nat ticks)
64 rtsBool flag = rtsFalse;
66 while (sleeping_queue != END_TSO_QUEUE &&
67 (int)(ticks - sleeping_queue->block_info.target) > 0) {
69 sleeping_queue = tso->link;
70 tso->why_blocked = NotBlocked;
71 tso->link = END_TSO_QUEUE;
72 IF_DEBUG(scheduler,belch("Waking up sleeping thread %d\n", tso->id));
73 PUSH_ON_RUN_QUEUE(tso);
79 /* Argument 'wait' says whether to wait for I/O to become available,
80 * or whether to just check and return immediately. If there are
81 * other threads ready to run, we normally do the non-waiting variety,
82 * otherwise we wait (see Schedule.c).
84 * SMP note: must be called with sched_mutex locked.
86 * Windows: select only works on sockets, so this doesn't really work,
87 * though it makes things better than before. MsgWaitForMultipleObjects
88 * should really be used, though it only seems to work for read handles,
93 awaitEvent(rtsBool wait)
95 StgTSO *tso, *prev, *next;
98 #ifndef mingw32_TARGET_OS
102 rtsBool select_succeeded = rtsTrue;
103 rtsBool unblock_all = rtsFalse;
111 belch("scheduler: checking for threads blocked on I/O");
118 /* loop until we've woken up some threads. This loop is needed
119 * because the select timing isn't accurate, we sometimes sleep
120 * for a while but not long enough to wake up a thread in
125 ticks = timestamp = getourtimeofday();
126 if (wakeUpSleepingThreads(ticks)) {
132 } else if (sleeping_queue != END_TSO_QUEUE) {
133 min = (sleeping_queue->block_info.target - ticks)
134 * TICK_MILLISECS * 1000;
139 #ifndef mingw32_TARGET_OS
141 * Collect all of the fd's that we're interested in
146 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
149 switch (tso->why_blocked) {
152 int fd = tso->block_info.fd;
153 maxfd = (fd > maxfd) ? fd : maxfd;
160 int fd = tso->block_info.fd;
161 maxfd = (fd > maxfd) ? fd : maxfd;
171 #ifdef RTS_SUPPORTS_THREADS
172 if(!workerWakeupInited) {
173 pipe(workerWakeupPipe);
174 workerWakeupInited = rtsTrue;
176 FD_SET(workerWakeupPipe[0], &rfd);
177 maxfd = workerWakeupPipe[0] > maxfd ? workerWakeupPipe[0] : maxfd;
180 /* Release the scheduler lock while we do the poll.
181 * this means that someone might muck with the blocked_queue
182 * while we do this, but it shouldn't matter:
184 * - another task might poll for I/O and remove one
185 * or more threads from the blocked_queue.
186 * - more I/O threads may be added to blocked_queue.
187 * - more delayed threads may be added to blocked_queue. We'll
188 * just subtract delta from their delays after the poll.
190 * I believe none of these cases lead to trouble --SDM.
193 #ifdef RTS_SUPPORTS_THREADS
194 isWorkerBlockedInAwaitEvent = rtsTrue;
195 workerWakeupPending = rtsFalse;
197 RELEASE_LOCK(&sched_mutex);
199 /* Check for any interesting events */
201 tv.tv_sec = min / 1000000;
202 tv.tv_usec = min % 1000000;
204 while ((numFound = select(maxfd+1, &rfd, &wfd, NULL, &tv)) < 0) {
205 if (errno != EINTR) {
206 /* Handle bad file descriptors by unblocking all the
207 waiting threads. Why? Because a thread might have been
208 a bit naughty and closed a file descriptor while another
209 was blocked waiting. This is less-than-good programming
210 practice, but having the RTS as a result fall over isn't
211 acceptable, so we simply unblock all the waiting threads
212 should we see a bad file descriptor & give the threads
213 a chance to clean up their act.
215 Note: assume here that threads becoming unblocked
216 will try to read/write the file descriptor before trying
217 to issue a threadWaitRead/threadWaitWrite again (==> an
218 IOError will result for the thread that's got the bad
219 file descriptor.) Hence, there's no danger of a bad
220 file descriptor being repeatedly select()'ed on, so
223 if ( errno == EBADF ) {
224 unblock_all = rtsTrue;
227 fprintf(stderr,"%d\n", errno);
230 barf("select failed");
233 #else /* on mingwin */
234 #ifdef RTS_SUPPORTS_THREADS
235 isWorkerBlockedInAwaitEvent = rtsTrue;
237 RELEASE_LOCK(&sched_mutex);
239 if (!awaitRequests(wait)) {
240 Sleep(0); /* don't busy wait */
242 #endif /* mingw32_TARGET_OS */
243 ACQUIRE_LOCK(&sched_mutex);
244 #ifdef RTS_SUPPORTS_THREADS
245 isWorkerBlockedInAwaitEvent = rtsFalse;
248 #ifndef mingw32_TARGET_OS
249 /* We got a signal; could be one of ours. If so, we need
250 * to start up the signal handler straight away, otherwise
251 * we could block for a long time before the signal is
254 if (signals_pending()) {
255 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
256 startSignalHandlers();
257 ACQUIRE_LOCK(&sched_mutex);
258 return; /* still hold the lock */
262 /* we were interrupted, return to the scheduler immediately.
265 return; /* still hold the lock */
268 /* check for threads that need waking up
270 wakeUpSleepingThreads(getourtimeofday());
272 /* If new runnable threads have arrived, stop waiting for
275 if (run_queue_hd != END_TSO_QUEUE) {
276 return; /* still hold the lock */
279 #ifdef RTS_SUPPORTS_THREADS
280 /* If another worker thread wants to take over,
281 * return to the scheduler
283 if (needToYieldToReturningWorker()) {
284 return; /* still hold the lock */
288 #ifdef RTS_SUPPORTS_THREADS
289 isWorkerBlockedInAwaitEvent = rtsTrue;
291 RELEASE_LOCK(&sched_mutex);
294 ACQUIRE_LOCK(&sched_mutex);
296 /* Step through the waiting queue, unblocking every thread that now has
297 * a file descriptor in a ready state.
301 if (select_succeeded || unblock_all) {
302 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
304 switch (tso->why_blocked) {
306 ready = unblock_all || FD_ISSET(tso->block_info.fd, &rfd);
309 ready = unblock_all || FD_ISSET(tso->block_info.fd, &wfd);
316 IF_DEBUG(scheduler,belch("Waking up blocked thread %d\n", tso->id));
317 tso->why_blocked = NotBlocked;
318 tso->link = END_TSO_QUEUE;
319 PUSH_ON_RUN_QUEUE(tso);
322 blocked_queue_hd = tso;
330 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
332 prev->link = END_TSO_QUEUE;
333 blocked_queue_tl = prev;
337 #if defined(RTS_SUPPORTS_THREADS) && !defined(mingw32_TARGET_OS)
338 // if we were woken up by wakeBlockedWorkerThread,
339 // read the dummy byte from the pipe
340 if(select_succeeded && FD_ISSET(workerWakeupPipe[0], &rfd)) {
343 read(workerWakeupPipe[0],&dummy,1);
346 } while (wait && !interrupted && run_queue_hd == END_TSO_QUEUE);
350 #ifdef RTS_SUPPORTS_THREADS
351 /* wakeBlockedWorkerThread
353 * If a worker thread is currently blocked within awaitEvent,
355 * Must be called with sched_mutex held.
359 wakeBlockedWorkerThread()
361 #ifndef mingw32_TARGET_OS
362 if(isWorkerBlockedInAwaitEvent && !workerWakeupPending) {
363 unsigned char dummy = 42; // Any value will do here
365 // write something so that select() wakes up
366 write(workerWakeupPipe[1],&dummy,1);
367 workerWakeupPending = rtsTrue;
370 // The Win32 implementation currently uses a polling loop,
371 // so there is no need to explicitly wake it