1 /* -----------------------------------------------------------------------------
2 * $Id: Select.c,v 1.28 2003/04/01 15:05:22 sof Exp $
4 * (c) The GHC Team 1995-2002
6 * Support for concurrent non-blocking I/O and thread waiting.
8 * ---------------------------------------------------------------------------*/
11 /* we're outside the realms of POSIX here... */
12 /* #include "PosixSource.h" */
21 #include "Capability.h"
23 # ifdef HAVE_SYS_TYPES_H
24 # include <sys/types.h>
27 # ifdef HAVE_SYS_TIME_H
28 # include <sys/time.h>
37 #ifdef RTS_SUPPORTS_THREADS
38 static rtsBool isWorkerBlockedInAwaitEvent = rtsFalse;
39 static rtsBool workerWakeupPending = rtsFalse;
40 static int workerWakeupPipe[2];
41 static rtsBool workerWakeupInited = rtsFalse;
44 /* There's a clever trick here to avoid problems when the time wraps
45 * around. Since our maximum delay is smaller than 31 bits of ticks
46 * (it's actually 31 bits of microseconds), we can safely check
47 * whether a timer has expired even if our timer will wrap around
48 * before the target is reached, using the following formula:
50 * (int)((uint)current_time - (uint)target_time) < 0
52 * if this is true, then our time has expired.
53 * (idea due to Andy Gill).
56 wakeUpSleepingThreads(nat ticks)
59 rtsBool flag = rtsFalse;
61 while (sleeping_queue != END_TSO_QUEUE &&
62 (int)(ticks - sleeping_queue->block_info.target) > 0) {
64 sleeping_queue = tso->link;
65 tso->why_blocked = NotBlocked;
66 tso->link = END_TSO_QUEUE;
67 IF_DEBUG(scheduler,belch("Waking up sleeping thread %d\n", tso->id));
68 PUSH_ON_RUN_QUEUE(tso);
74 /* Argument 'wait' says whether to wait for I/O to become available,
75 * or whether to just check and return immediately. If there are
76 * other threads ready to run, we normally do the non-waiting variety,
77 * otherwise we wait (see Schedule.c).
79 * SMP note: must be called with sched_mutex locked.
81 * Windows: select only works on sockets, so this doesn't really work,
82 * though it makes things better than before. MsgWaitForMultipleObjects
83 * should really be used, though it only seems to work for read handles,
88 awaitEvent(rtsBool wait)
90 StgTSO *tso, *prev, *next;
95 rtsBool select_succeeded = rtsTrue;
96 rtsBool unblock_all = rtsFalse;
104 belch("scheduler: checking for threads blocked on I/O");
111 /* loop until we've woken up some threads. This loop is needed
112 * because the select timing isn't accurate, we sometimes sleep
113 * for a while but not long enough to wake up a thread in
118 ticks = timestamp = getourtimeofday();
119 if (wakeUpSleepingThreads(ticks)) {
125 } else if (sleeping_queue != END_TSO_QUEUE) {
126 min = (sleeping_queue->block_info.target - ticks)
127 * TICK_MILLISECS * 1000;
133 * Collect all of the fd's that we're interested in
138 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
141 switch (tso->why_blocked) {
144 int fd = tso->block_info.fd;
145 maxfd = (fd > maxfd) ? fd : maxfd;
152 int fd = tso->block_info.fd;
153 maxfd = (fd > maxfd) ? fd : maxfd;
163 #ifdef RTS_SUPPORTS_THREADS
164 if(!workerWakeupInited) {
165 pipe(workerWakeupPipe);
166 workerWakeupInited = rtsTrue;
168 FD_SET(workerWakeupPipe[0], &rfd);
169 maxfd = workerWakeupPipe[0] > maxfd ? workerWakeupPipe[0] : maxfd;
172 /* Release the scheduler lock while we do the poll.
173 * this means that someone might muck with the blocked_queue
174 * while we do this, but it shouldn't matter:
176 * - another task might poll for I/O and remove one
177 * or more threads from the blocked_queue.
178 * - more I/O threads may be added to blocked_queue.
179 * - more delayed threads may be added to blocked_queue. We'll
180 * just subtract delta from their delays after the poll.
182 * I believe none of these cases lead to trouble --SDM.
185 #ifdef RTS_SUPPORTS_THREADS
186 isWorkerBlockedInAwaitEvent = rtsTrue;
187 workerWakeupPending = rtsFalse;
189 RELEASE_LOCK(&sched_mutex);
191 /* Check for any interesting events */
193 tv.tv_sec = min / 1000000;
194 tv.tv_usec = min % 1000000;
196 while ((numFound = select(maxfd+1, &rfd, &wfd, NULL, &tv)) < 0) {
197 if (errno != EINTR) {
198 /* Handle bad file descriptors by unblocking all the
199 waiting threads. Why? Because a thread might have been
200 a bit naughty and closed a file descriptor while another
201 was blocked waiting. This is less-than-good programming
202 practice, but having the RTS as a result fall over isn't
203 acceptable, so we simply unblock all the waiting threads
204 should we see a bad file descriptor & give the threads
205 a chance to clean up their act.
207 Note: assume here that threads becoming unblocked
208 will try to read/write the file descriptor before trying
209 to issue a threadWaitRead/threadWaitWrite again (==> an
210 IOError will result for the thread that's got the bad
211 file descriptor.) Hence, there's no danger of a bad
212 file descriptor being repeatedly select()'ed on, so
215 if ( errno == EBADF ) {
216 unblock_all = rtsTrue;
219 fprintf(stderr,"%d\n", errno);
222 barf("select failed");
225 ACQUIRE_LOCK(&sched_mutex);
226 #ifdef RTS_SUPPORTS_THREADS
227 isWorkerBlockedInAwaitEvent = rtsFalse;
230 /* We got a signal; could be one of ours. If so, we need
231 * to start up the signal handler straight away, otherwise
232 * we could block for a long time before the signal is
235 #if defined(RTS_USER_SIGNALS)
236 if (signals_pending()) {
237 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
238 startSignalHandlers();
239 ACQUIRE_LOCK(&sched_mutex);
240 return; /* still hold the lock */
244 /* we were interrupted, return to the scheduler immediately.
247 return; /* still hold the lock */
250 /* check for threads that need waking up
252 wakeUpSleepingThreads(getourtimeofday());
254 /* If new runnable threads have arrived, stop waiting for
257 if (run_queue_hd != END_TSO_QUEUE) {
258 return; /* still hold the lock */
261 #ifdef RTS_SUPPORTS_THREADS
262 /* If another worker thread wants to take over,
263 * return to the scheduler
265 if (needToYieldToReturningWorker()) {
266 return; /* still hold the lock */
270 #ifdef RTS_SUPPORTS_THREADS
271 isWorkerBlockedInAwaitEvent = rtsTrue;
273 RELEASE_LOCK(&sched_mutex);
276 ACQUIRE_LOCK(&sched_mutex);
278 /* Step through the waiting queue, unblocking every thread that now has
279 * a file descriptor in a ready state.
283 if (select_succeeded || unblock_all) {
284 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
286 switch (tso->why_blocked) {
288 ready = unblock_all || FD_ISSET(tso->block_info.fd, &rfd);
291 ready = unblock_all || FD_ISSET(tso->block_info.fd, &wfd);
298 IF_DEBUG(scheduler,belch("Waking up blocked thread %d\n", tso->id));
299 tso->why_blocked = NotBlocked;
300 tso->link = END_TSO_QUEUE;
301 PUSH_ON_RUN_QUEUE(tso);
304 blocked_queue_hd = tso;
312 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
314 prev->link = END_TSO_QUEUE;
315 blocked_queue_tl = prev;
319 #if defined(RTS_SUPPORTS_THREADS)
320 // if we were woken up by wakeBlockedWorkerThread,
321 // read the dummy byte from the pipe
322 if(select_succeeded && FD_ISSET(workerWakeupPipe[0], &rfd)) {
325 read(workerWakeupPipe[0],&dummy,1);
328 } while (wait && !interrupted && run_queue_hd == END_TSO_QUEUE);
332 #ifdef RTS_SUPPORTS_THREADS
333 /* wakeBlockedWorkerThread
335 * If a worker thread is currently blocked within awaitEvent,
337 * Must be called with sched_mutex held.
340 wakeBlockedWorkerThread()
342 if(isWorkerBlockedInAwaitEvent && !workerWakeupPending) {
343 unsigned char dummy = 42; // Any value will do here
345 // write something so that select() wakes up
346 write(workerWakeupPipe[1],&dummy,1);
347 workerWakeupPending = rtsTrue;