[project @ 2003-06-26 12:22:59 by stolz]
[ghc-hetmet.git] / ghc / rts / Select.c
1 /* -----------------------------------------------------------------------------
2  * $Id: Select.c,v 1.29 2003/06/26 12:22:59 stolz Exp $
3  *
4  * (c) The GHC Team 1995-2002
5  *
6  * Support for concurrent non-blocking I/O and thread waiting.
7  *
8  * ---------------------------------------------------------------------------*/
9
10
11 /* we're outside the realms of POSIX here... */
12 /* #include "PosixSource.h" */
13
14 #include "Rts.h"
15 #include "Schedule.h"
16 #include "RtsUtils.h"
17 #include "RtsFlags.h"
18 #include "Timer.h"
19 #include "Itimer.h"
20 #include "Signals.h"
21 #include "Capability.h"
22
23 # ifdef HAVE_SYS_TYPES_H
24 #  include <sys/types.h>
25 # endif
26
27 # ifdef HAVE_SYS_TIME_H
28 #  include <sys/time.h>
29 # endif
30
31 #include <errno.h>
32 #include <string.h>
33
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37
38 /* last timestamp */
39 nat timestamp = 0;
40
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;
46 #endif
47
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:
53  *
54  *        (int)((uint)current_time - (uint)target_time) < 0
55  *
56  * if this is true, then our time has expired.
57  * (idea due to Andy Gill).
58  */
59 rtsBool
60 wakeUpSleepingThreads(nat ticks)
61 {
62     StgTSO *tso;
63     rtsBool flag = rtsFalse;
64
65     while (sleeping_queue != END_TSO_QUEUE &&
66            (int)(ticks - sleeping_queue->block_info.target) > 0) {
67         tso = sleeping_queue;
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);
73         flag = rtsTrue;
74     }
75     return flag;
76 }
77
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).
82  *
83  * SMP note: must be called with sched_mutex locked.
84  *
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,
88  * not write handles.
89  *
90  */
91 void
92 awaitEvent(rtsBool wait)
93 {
94     StgTSO *tso, *prev, *next;
95     rtsBool ready;
96     fd_set rfd,wfd;
97     int numFound;
98     int maxfd = -1;
99     rtsBool select_succeeded = rtsTrue;
100     rtsBool unblock_all = rtsFalse;
101     struct timeval tv;
102     lnat min, ticks;
103
104     tv.tv_sec  = 0;
105     tv.tv_usec = 0;
106     
107     IF_DEBUG(scheduler,
108              belch("scheduler: checking for threads blocked on I/O");
109              if (wait) {
110                  belch(" (waiting)");
111              }
112              belch("\n");
113              );
114
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
118      * a threadDelay.
119      */
120     do {
121
122       ticks = timestamp = getourtimeofday();
123       if (wakeUpSleepingThreads(ticks)) { 
124           return;
125       }
126
127       if (!wait) {
128           min = 0;
129       } else if (sleeping_queue != END_TSO_QUEUE) {
130           min = (sleeping_queue->block_info.target - ticks) 
131               * TICK_MILLISECS * 1000;
132       } else {
133           min = 0x7ffffff;
134       }
135
136       /* 
137        * Collect all of the fd's that we're interested in
138        */
139       FD_ZERO(&rfd);
140       FD_ZERO(&wfd);
141
142       for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
143         next = tso->link;
144
145         switch (tso->why_blocked) {
146         case BlockedOnRead:
147           { 
148             int fd = tso->block_info.fd;
149             maxfd = (fd > maxfd) ? fd : maxfd;
150             FD_SET(fd, &rfd);
151             continue;
152           }
153
154         case BlockedOnWrite:
155           { 
156             int fd = tso->block_info.fd;
157             maxfd = (fd > maxfd) ? fd : maxfd;
158             FD_SET(fd, &wfd);
159             continue;
160           }
161
162         default:
163           barf("AwaitEvent");
164         }
165       }
166
167 #ifdef RTS_SUPPORTS_THREADS
168       if(!workerWakeupInited) {
169           pipe(workerWakeupPipe);
170           workerWakeupInited = rtsTrue;
171       }
172       FD_SET(workerWakeupPipe[0], &rfd);
173       maxfd = workerWakeupPipe[0] > maxfd ? workerWakeupPipe[0] : maxfd;
174 #endif
175       
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:
179        *
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.
185        *
186        * I believe none of these cases lead to trouble --SDM.
187        */
188       
189 #ifdef RTS_SUPPORTS_THREADS
190       isWorkerBlockedInAwaitEvent = rtsTrue;
191       workerWakeupPending = rtsFalse;
192 #endif
193       RELEASE_LOCK(&sched_mutex);
194
195       /* Check for any interesting events */
196       
197       tv.tv_sec  = min / 1000000;
198       tv.tv_usec = min % 1000000;
199
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. 
210                
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
217                the RTS won't loop.
218             */
219             if ( errno == EBADF ) {
220               unblock_all = rtsTrue;
221               break;
222             } else {
223               fprintf(stderr,"%d\n", errno);
224               fflush(stderr);
225               perror("select");
226               barf("select failed");
227             }
228           }
229           ACQUIRE_LOCK(&sched_mutex);
230 #ifdef RTS_SUPPORTS_THREADS
231           isWorkerBlockedInAwaitEvent = rtsFalse;
232 #endif
233
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
237            * serviced.
238            */
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 */
245           }
246 #endif
247
248           /* we were interrupted, return to the scheduler immediately.
249            */
250           if (interrupted) {
251               return; /* still hold the lock */
252           }
253           
254           /* check for threads that need waking up 
255            */
256           wakeUpSleepingThreads(getourtimeofday());
257           
258           /* If new runnable threads have arrived, stop waiting for
259            * I/O and run them.
260            */
261           if (run_queue_hd != END_TSO_QUEUE) {
262               return; /* still hold the lock */
263           }
264           
265 #ifdef RTS_SUPPORTS_THREADS
266           /* If another worker thread wants to take over,
267            * return to the scheduler
268            */
269           if (needToYieldToReturningWorker()) {
270               return; /* still hold the lock */
271           }
272 #endif
273           
274 #ifdef RTS_SUPPORTS_THREADS
275           isWorkerBlockedInAwaitEvent = rtsTrue;
276 #endif
277           RELEASE_LOCK(&sched_mutex);
278       }
279
280       ACQUIRE_LOCK(&sched_mutex);
281
282       /* Step through the waiting queue, unblocking every thread that now has
283        * a file descriptor in a ready state.
284        */
285
286       prev = NULL;
287       if (select_succeeded || unblock_all) {
288           for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
289               next = tso->link;
290               switch (tso->why_blocked) {
291               case BlockedOnRead:
292                   ready = unblock_all || FD_ISSET(tso->block_info.fd, &rfd);
293                   break;
294               case BlockedOnWrite:
295                   ready = unblock_all || FD_ISSET(tso->block_info.fd, &wfd);
296                   break;
297               default:
298                   barf("awaitEvent");
299               }
300       
301               if (ready) {
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);
306               } else {
307                   if (prev == NULL)
308                       blocked_queue_hd = tso;
309                   else
310                       prev->link = tso;
311                   prev = tso;
312               }
313           }
314
315           if (prev == NULL)
316               blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
317           else {
318               prev->link = END_TSO_QUEUE;
319               blocked_queue_tl = prev;
320           }
321       }
322       
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)) {
327           unsigned char dummy;
328           wait = rtsFalse;
329           read(workerWakeupPipe[0],&dummy,1);
330       }
331 #endif
332     } while (wait && !interrupted && run_queue_hd == END_TSO_QUEUE);
333 }
334
335
336 #ifdef RTS_SUPPORTS_THREADS
337 /* wakeBlockedWorkerThread
338  *
339  * If a worker thread is currently blocked within awaitEvent,
340  * wake it.
341  * Must be called with sched_mutex held.
342  */
343 void
344 wakeBlockedWorkerThread()
345 {
346     if(isWorkerBlockedInAwaitEvent && !workerWakeupPending) {
347         unsigned char dummy = 42;       // Any value will do here
348         
349                         // write something so that select() wakes up
350         write(workerWakeupPipe[1],&dummy,1);
351         workerWakeupPending = rtsTrue;
352     }
353 }
354 #endif