[project @ 2003-04-01 15:05:13 by sof]
[ghc-hetmet.git] / ghc / rts / Select.c
1 /* -----------------------------------------------------------------------------
2  * $Id: Select.c,v 1.28 2003/04/01 15:05:22 sof 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 /* last timestamp */
35 nat timestamp = 0;
36
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;
42 #endif
43
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:
49  *
50  *        (int)((uint)current_time - (uint)target_time) < 0
51  *
52  * if this is true, then our time has expired.
53  * (idea due to Andy Gill).
54  */
55 rtsBool
56 wakeUpSleepingThreads(nat ticks)
57 {
58     StgTSO *tso;
59     rtsBool flag = rtsFalse;
60
61     while (sleeping_queue != END_TSO_QUEUE &&
62            (int)(ticks - sleeping_queue->block_info.target) > 0) {
63         tso = sleeping_queue;
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);
69         flag = rtsTrue;
70     }
71     return flag;
72 }
73
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).
78  *
79  * SMP note: must be called with sched_mutex locked.
80  *
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,
84  * not write handles.
85  *
86  */
87 void
88 awaitEvent(rtsBool wait)
89 {
90     StgTSO *tso, *prev, *next;
91     rtsBool ready;
92     fd_set rfd,wfd;
93     int numFound;
94     int maxfd = -1;
95     rtsBool select_succeeded = rtsTrue;
96     rtsBool unblock_all = rtsFalse;
97     struct timeval tv;
98     lnat min, ticks;
99
100     tv.tv_sec  = 0;
101     tv.tv_usec = 0;
102     
103     IF_DEBUG(scheduler,
104              belch("scheduler: checking for threads blocked on I/O");
105              if (wait) {
106                  belch(" (waiting)");
107              }
108              belch("\n");
109              );
110
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
114      * a threadDelay.
115      */
116     do {
117
118       ticks = timestamp = getourtimeofday();
119       if (wakeUpSleepingThreads(ticks)) { 
120           return;
121       }
122
123       if (!wait) {
124           min = 0;
125       } else if (sleeping_queue != END_TSO_QUEUE) {
126           min = (sleeping_queue->block_info.target - ticks) 
127               * TICK_MILLISECS * 1000;
128       } else {
129           min = 0x7ffffff;
130       }
131
132       /* 
133        * Collect all of the fd's that we're interested in
134        */
135       FD_ZERO(&rfd);
136       FD_ZERO(&wfd);
137
138       for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
139         next = tso->link;
140
141         switch (tso->why_blocked) {
142         case BlockedOnRead:
143           { 
144             int fd = tso->block_info.fd;
145             maxfd = (fd > maxfd) ? fd : maxfd;
146             FD_SET(fd, &rfd);
147             continue;
148           }
149
150         case BlockedOnWrite:
151           { 
152             int fd = tso->block_info.fd;
153             maxfd = (fd > maxfd) ? fd : maxfd;
154             FD_SET(fd, &wfd);
155             continue;
156           }
157
158         default:
159           barf("AwaitEvent");
160         }
161       }
162
163 #ifdef RTS_SUPPORTS_THREADS
164       if(!workerWakeupInited) {
165           pipe(workerWakeupPipe);
166           workerWakeupInited = rtsTrue;
167       }
168       FD_SET(workerWakeupPipe[0], &rfd);
169       maxfd = workerWakeupPipe[0] > maxfd ? workerWakeupPipe[0] : maxfd;
170 #endif
171       
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:
175        *
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.
181        *
182        * I believe none of these cases lead to trouble --SDM.
183        */
184       
185 #ifdef RTS_SUPPORTS_THREADS
186       isWorkerBlockedInAwaitEvent = rtsTrue;
187       workerWakeupPending = rtsFalse;
188 #endif
189       RELEASE_LOCK(&sched_mutex);
190
191       /* Check for any interesting events */
192       
193       tv.tv_sec  = min / 1000000;
194       tv.tv_usec = min % 1000000;
195
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. 
206                
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
213                the RTS won't loop.
214             */
215             if ( errno == EBADF ) {
216               unblock_all = rtsTrue;
217               break;
218             } else {
219               fprintf(stderr,"%d\n", errno);
220               fflush(stderr);
221               perror("select");
222               barf("select failed");
223             }
224           }
225           ACQUIRE_LOCK(&sched_mutex);
226 #ifdef RTS_SUPPORTS_THREADS
227           isWorkerBlockedInAwaitEvent = rtsFalse;
228 #endif
229
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
233            * serviced.
234            */
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 */
241           }
242 #endif
243
244           /* we were interrupted, return to the scheduler immediately.
245            */
246           if (interrupted) {
247               return; /* still hold the lock */
248           }
249           
250           /* check for threads that need waking up 
251            */
252           wakeUpSleepingThreads(getourtimeofday());
253           
254           /* If new runnable threads have arrived, stop waiting for
255            * I/O and run them.
256            */
257           if (run_queue_hd != END_TSO_QUEUE) {
258               return; /* still hold the lock */
259           }
260           
261 #ifdef RTS_SUPPORTS_THREADS
262           /* If another worker thread wants to take over,
263            * return to the scheduler
264            */
265           if (needToYieldToReturningWorker()) {
266               return; /* still hold the lock */
267           }
268 #endif
269           
270 #ifdef RTS_SUPPORTS_THREADS
271           isWorkerBlockedInAwaitEvent = rtsTrue;
272 #endif
273           RELEASE_LOCK(&sched_mutex);
274       }
275
276       ACQUIRE_LOCK(&sched_mutex);
277
278       /* Step through the waiting queue, unblocking every thread that now has
279        * a file descriptor in a ready state.
280        */
281
282       prev = NULL;
283       if (select_succeeded || unblock_all) {
284           for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
285               next = tso->link;
286               switch (tso->why_blocked) {
287               case BlockedOnRead:
288                   ready = unblock_all || FD_ISSET(tso->block_info.fd, &rfd);
289                   break;
290               case BlockedOnWrite:
291                   ready = unblock_all || FD_ISSET(tso->block_info.fd, &wfd);
292                   break;
293               default:
294                   barf("awaitEvent");
295               }
296       
297               if (ready) {
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);
302               } else {
303                   if (prev == NULL)
304                       blocked_queue_hd = tso;
305                   else
306                       prev->link = tso;
307                   prev = tso;
308               }
309           }
310
311           if (prev == NULL)
312               blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
313           else {
314               prev->link = END_TSO_QUEUE;
315               blocked_queue_tl = prev;
316           }
317       }
318       
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)) {
323           unsigned char dummy;
324           wait = rtsFalse;
325           read(workerWakeupPipe[0],&dummy,1);
326       }
327 #endif
328     } while (wait && !interrupted && run_queue_hd == END_TSO_QUEUE);
329 }
330
331
332 #ifdef RTS_SUPPORTS_THREADS
333 /* wakeBlockedWorkerThread
334  *
335  * If a worker thread is currently blocked within awaitEvent,
336  * wake it.
337  * Must be called with sched_mutex held.
338  */
339 void
340 wakeBlockedWorkerThread()
341 {
342     if(isWorkerBlockedInAwaitEvent && !workerWakeupPending) {
343         unsigned char dummy = 42;       // Any value will do here
344         
345                         // write something so that select() wakes up
346         write(workerWakeupPipe[1],&dummy,1);
347         workerWakeupPending = rtsTrue;
348     }
349 }
350 #endif