1 /* -----------------------------------------------------------------------------
2 * $Id: Select.c,v 1.29 2003/06/26 12:22:59 stolz 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>
41 #ifdef RTS_SUPPORTS_THREADS
42 static rtsBool isWorkerBlockedInAwaitEvent = rtsFalse;
43 static rtsBool workerWakeupPending = rtsFalse;
44 static int workerWakeupPipe[2];
45 static rtsBool workerWakeupInited = rtsFalse;
48 /* There's a clever trick here to avoid problems when the time wraps
49 * around. Since our maximum delay is smaller than 31 bits of ticks
50 * (it's actually 31 bits of microseconds), we can safely check
51 * whether a timer has expired even if our timer will wrap around
52 * before the target is reached, using the following formula:
54 * (int)((uint)current_time - (uint)target_time) < 0
56 * if this is true, then our time has expired.
57 * (idea due to Andy Gill).
60 wakeUpSleepingThreads(nat ticks)
63 rtsBool flag = rtsFalse;
65 while (sleeping_queue != END_TSO_QUEUE &&
66 (int)(ticks - sleeping_queue->block_info.target) > 0) {
68 sleeping_queue = tso->link;
69 tso->why_blocked = NotBlocked;
70 tso->link = END_TSO_QUEUE;
71 IF_DEBUG(scheduler,belch("Waking up sleeping thread %d\n", tso->id));
72 PUSH_ON_RUN_QUEUE(tso);
78 /* Argument 'wait' says whether to wait for I/O to become available,
79 * or whether to just check and return immediately. If there are
80 * other threads ready to run, we normally do the non-waiting variety,
81 * otherwise we wait (see Schedule.c).
83 * SMP note: must be called with sched_mutex locked.
85 * Windows: select only works on sockets, so this doesn't really work,
86 * though it makes things better than before. MsgWaitForMultipleObjects
87 * should really be used, though it only seems to work for read handles,
92 awaitEvent(rtsBool wait)
94 StgTSO *tso, *prev, *next;
99 rtsBool select_succeeded = rtsTrue;
100 rtsBool unblock_all = rtsFalse;
108 belch("scheduler: checking for threads blocked on I/O");
115 /* loop until we've woken up some threads. This loop is needed
116 * because the select timing isn't accurate, we sometimes sleep
117 * for a while but not long enough to wake up a thread in
122 ticks = timestamp = getourtimeofday();
123 if (wakeUpSleepingThreads(ticks)) {
129 } else if (sleeping_queue != END_TSO_QUEUE) {
130 min = (sleeping_queue->block_info.target - ticks)
131 * TICK_MILLISECS * 1000;
137 * Collect all of the fd's that we're interested in
142 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
145 switch (tso->why_blocked) {
148 int fd = tso->block_info.fd;
149 maxfd = (fd > maxfd) ? fd : maxfd;
156 int fd = tso->block_info.fd;
157 maxfd = (fd > maxfd) ? fd : maxfd;
167 #ifdef RTS_SUPPORTS_THREADS
168 if(!workerWakeupInited) {
169 pipe(workerWakeupPipe);
170 workerWakeupInited = rtsTrue;
172 FD_SET(workerWakeupPipe[0], &rfd);
173 maxfd = workerWakeupPipe[0] > maxfd ? workerWakeupPipe[0] : maxfd;
176 /* Release the scheduler lock while we do the poll.
177 * this means that someone might muck with the blocked_queue
178 * while we do this, but it shouldn't matter:
180 * - another task might poll for I/O and remove one
181 * or more threads from the blocked_queue.
182 * - more I/O threads may be added to blocked_queue.
183 * - more delayed threads may be added to blocked_queue. We'll
184 * just subtract delta from their delays after the poll.
186 * I believe none of these cases lead to trouble --SDM.
189 #ifdef RTS_SUPPORTS_THREADS
190 isWorkerBlockedInAwaitEvent = rtsTrue;
191 workerWakeupPending = rtsFalse;
193 RELEASE_LOCK(&sched_mutex);
195 /* Check for any interesting events */
197 tv.tv_sec = min / 1000000;
198 tv.tv_usec = min % 1000000;
200 while ((numFound = select(maxfd+1, &rfd, &wfd, NULL, &tv)) < 0) {
201 if (errno != EINTR) {
202 /* Handle bad file descriptors by unblocking all the
203 waiting threads. Why? Because a thread might have been
204 a bit naughty and closed a file descriptor while another
205 was blocked waiting. This is less-than-good programming
206 practice, but having the RTS as a result fall over isn't
207 acceptable, so we simply unblock all the waiting threads
208 should we see a bad file descriptor & give the threads
209 a chance to clean up their act.
211 Note: assume here that threads becoming unblocked
212 will try to read/write the file descriptor before trying
213 to issue a threadWaitRead/threadWaitWrite again (==> an
214 IOError will result for the thread that's got the bad
215 file descriptor.) Hence, there's no danger of a bad
216 file descriptor being repeatedly select()'ed on, so
219 if ( errno == EBADF ) {
220 unblock_all = rtsTrue;
223 fprintf(stderr,"%d\n", errno);
226 barf("select failed");
229 ACQUIRE_LOCK(&sched_mutex);
230 #ifdef RTS_SUPPORTS_THREADS
231 isWorkerBlockedInAwaitEvent = rtsFalse;
234 /* We got a signal; could be one of ours. If so, we need
235 * to start up the signal handler straight away, otherwise
236 * we could block for a long time before the signal is
239 #if defined(RTS_USER_SIGNALS)
240 if (signals_pending()) {
241 RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
242 startSignalHandlers();
243 ACQUIRE_LOCK(&sched_mutex);
244 return; /* still hold the lock */
248 /* we were interrupted, return to the scheduler immediately.
251 return; /* still hold the lock */
254 /* check for threads that need waking up
256 wakeUpSleepingThreads(getourtimeofday());
258 /* If new runnable threads have arrived, stop waiting for
261 if (run_queue_hd != END_TSO_QUEUE) {
262 return; /* still hold the lock */
265 #ifdef RTS_SUPPORTS_THREADS
266 /* If another worker thread wants to take over,
267 * return to the scheduler
269 if (needToYieldToReturningWorker()) {
270 return; /* still hold the lock */
274 #ifdef RTS_SUPPORTS_THREADS
275 isWorkerBlockedInAwaitEvent = rtsTrue;
277 RELEASE_LOCK(&sched_mutex);
280 ACQUIRE_LOCK(&sched_mutex);
282 /* Step through the waiting queue, unblocking every thread that now has
283 * a file descriptor in a ready state.
287 if (select_succeeded || unblock_all) {
288 for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
290 switch (tso->why_blocked) {
292 ready = unblock_all || FD_ISSET(tso->block_info.fd, &rfd);
295 ready = unblock_all || FD_ISSET(tso->block_info.fd, &wfd);
302 IF_DEBUG(scheduler,belch("Waking up blocked thread %d\n", tso->id));
303 tso->why_blocked = NotBlocked;
304 tso->link = END_TSO_QUEUE;
305 PUSH_ON_RUN_QUEUE(tso);
308 blocked_queue_hd = tso;
316 blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
318 prev->link = END_TSO_QUEUE;
319 blocked_queue_tl = prev;
323 #if defined(RTS_SUPPORTS_THREADS)
324 // if we were woken up by wakeBlockedWorkerThread,
325 // read the dummy byte from the pipe
326 if(select_succeeded && FD_ISSET(workerWakeupPipe[0], &rfd)) {
329 read(workerWakeupPipe[0],&dummy,1);
332 } while (wait && !interrupted && run_queue_hd == END_TSO_QUEUE);
336 #ifdef RTS_SUPPORTS_THREADS
337 /* wakeBlockedWorkerThread
339 * If a worker thread is currently blocked within awaitEvent,
341 * Must be called with sched_mutex held.
344 wakeBlockedWorkerThread()
346 if(isWorkerBlockedInAwaitEvent && !workerWakeupPending) {
347 unsigned char dummy = 42; // Any value will do here
349 // write something so that select() wakes up
350 write(workerWakeupPipe[1],&dummy,1);
351 workerWakeupPending = rtsTrue;