[project @ 2002-07-17 09:21:48 by simonmar]
[ghc-hetmet.git] / ghc / rts / Select.c
1 /* -----------------------------------------------------------------------------
2  * $Id: Select.c,v 1.21 2002/07/17 09:21:51 simonmar 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 /* we're outside the realms of POSIX here... */
11 /* #include "PosixSource.h" */
12
13 #include "Rts.h"
14 #include "Schedule.h"
15 #include "RtsUtils.h"
16 #include "RtsFlags.h"
17 #include "Itimer.h"
18 #include "Signals.h"
19
20 # ifdef HAVE_SYS_TYPES_H
21 #  include <sys/types.h>
22 # endif
23
24 # ifdef HAVE_SYS_TIME_H
25 #  include <sys/time.h>
26 # endif
27
28 # ifdef mingw32_TARGET_OS
29 #  include <windows.h>
30 # endif
31
32 #include <errno.h>
33 #include <string.h>
34
35 /* last timestamp */
36 nat timestamp = 0;
37
38 /* There's a clever trick here to avoid problems when the time wraps
39  * around.  Since our maximum delay is smaller than 31 bits of ticks
40  * (it's actually 31 bits of microseconds), we can safely check
41  * whether a timer has expired even if our timer will wrap around
42  * before the target is reached, using the following formula:
43  *
44  *        (int)((uint)current_time - (uint)target_time) < 0
45  *
46  * if this is true, then our time has expired.
47  * (idea due to Andy Gill).
48  */
49 rtsBool
50 wakeUpSleepingThreads(nat ticks)
51 {
52     StgTSO *tso;
53     rtsBool flag = rtsFalse;
54
55     while (sleeping_queue != END_TSO_QUEUE &&
56            (int)(ticks - sleeping_queue->block_info.target) > 0) {
57         tso = sleeping_queue;
58         sleeping_queue = tso->link;
59         tso->why_blocked = NotBlocked;
60         tso->link = END_TSO_QUEUE;
61         IF_DEBUG(scheduler,belch("Waking up sleeping thread %d\n", tso->id));
62         PUSH_ON_RUN_QUEUE(tso);
63         flag = rtsTrue;
64     }
65     return flag;
66 }
67
68 /* Argument 'wait' says whether to wait for I/O to become available,
69  * or whether to just check and return immediately.  If there are
70  * other threads ready to run, we normally do the non-waiting variety,
71  * otherwise we wait (see Schedule.c).
72  *
73  * SMP note: must be called with sched_mutex locked.
74  *
75  * Windows: select only works on sockets, so this doesn't really work,
76  * though it makes things better than before. MsgWaitForMultipleObjects
77  * should really be used, though it only seems to work for read handles,
78  * not write handles.
79  *
80  */
81 void
82 awaitEvent(rtsBool wait)
83 {
84     StgTSO *tso, *prev, *next;
85     rtsBool ready;
86     fd_set rfd,wfd;
87 #ifndef mingw32_TARGET_OS
88     int numFound;
89     int maxfd = -1;
90 #endif
91     rtsBool select_succeeded = rtsTrue;
92     rtsBool unblock_all = rtsFalse;
93     static rtsBool prev_unblocked_all = rtsFalse;
94     struct timeval tv;
95     lnat min, ticks;
96
97     tv.tv_sec  = 0;
98     tv.tv_usec = 0;
99     
100     IF_DEBUG(scheduler,
101              belch("scheduler: checking for threads blocked on I/O");
102              if (wait) {
103                  belch(" (waiting)");
104              }
105              belch("\n");
106              );
107
108     /* loop until we've woken up some threads.  This loop is needed
109      * because the select timing isn't accurate, we sometimes sleep
110      * for a while but not long enough to wake up a thread in
111      * a threadDelay.
112      */
113     do {
114
115       ticks = timestamp = getourtimeofday();
116       if (wakeUpSleepingThreads(ticks)) { 
117           return;
118       }
119
120       if (!wait) {
121           min = 0;
122       } else if (sleeping_queue != END_TSO_QUEUE) {
123           min = (sleeping_queue->block_info.target - ticks) 
124               * TICK_MILLISECS * 1000;
125       } else {
126           min = 0x7ffffff;
127       }
128
129 #ifndef mingw32_TARGET_OS
130       /* 
131        * Collect all of the fd's that we're interested in
132        */
133       FD_ZERO(&rfd);
134       FD_ZERO(&wfd);
135
136       for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
137         next = tso->link;
138
139         switch (tso->why_blocked) {
140         case BlockedOnRead:
141           { 
142             int fd = tso->block_info.fd;
143             maxfd = (fd > maxfd) ? fd : maxfd;
144             FD_SET(fd, &rfd);
145             continue;
146           }
147
148         case BlockedOnWrite:
149           { 
150             int fd = tso->block_info.fd;
151             maxfd = (fd > maxfd) ? fd : maxfd;
152             FD_SET(fd, &wfd);
153             continue;
154           }
155
156         default:
157           barf("AwaitEvent");
158         }
159       }
160
161       /* Release the scheduler lock while we do the poll.
162        * this means that someone might muck with the blocked_queue
163        * while we do this, but it shouldn't matter:
164        *
165        *   - another task might poll for I/O and remove one
166        *     or more threads from the blocked_queue.
167        *   - more I/O threads may be added to blocked_queue.
168        *   - more delayed threads may be added to blocked_queue. We'll
169        *     just subtract delta from their delays after the poll.
170        *
171        * I believe none of these cases lead to trouble --SDM.
172        */
173       RELEASE_LOCK(&sched_mutex);
174
175       /* Check for any interesting events */
176       
177       tv.tv_sec  = min / 1000000;
178       tv.tv_usec = min % 1000000;
179
180       while ((numFound = select(maxfd+1, &rfd, &wfd, NULL, &tv)) < 0) {
181           if (errno != EINTR) {
182             /* Handle bad file descriptors by unblocking all the
183                waiting threads. Why? Because a thread might have been
184                a bit naughty and closed a file descriptor while another
185                was blocked waiting. This is less-than-good programming
186                practice, but having the RTS as a result fall over isn't
187                acceptable, so we simply unblock all the waiting threads
188                should we see a bad file descriptor & give the threads
189                a chance to clean up their act. 
190                
191                To avoid getting stuck in a loop, repeated EBADF failures
192                are 'handled' through barfing.
193             */
194             if ( errno == EBADF && !prev_unblocked_all) {
195               unblock_all = rtsTrue;
196               prev_unblocked_all = rtsTrue;
197               break;
198             } else {
199               fprintf(stderr,"%d\n", errno);
200               fflush(stderr);
201               perror("select");
202               barf("select failed");
203             }
204           }
205 #else /* on mingwin */
206       while (1) {
207           Sleep(0); /* don't busy wait */
208 #endif /* mingw32_TARGET_OS */
209           ACQUIRE_LOCK(&sched_mutex);
210
211           prev_unblocked_all = rtsFalse;
212
213 #ifndef mingw32_TARGET_OS
214           /* We got a signal; could be one of ours.  If so, we need
215            * to start up the signal handler straight away, otherwise
216            * we could block for a long time before the signal is
217            * serviced.
218            */
219           if (signals_pending()) {
220               RELEASE_LOCK(&sched_mutex); /* ToDo: kill */
221               startSignalHandlers();
222               ACQUIRE_LOCK(&sched_mutex);
223               return; /* still hold the lock */
224           }
225 #endif
226
227           /* we were interrupted, return to the scheduler immediately.
228            */
229           if (interrupted) {
230               return; /* still hold the lock */
231           }
232           
233           /* check for threads that need waking up 
234            */
235           wakeUpSleepingThreads(getourtimeofday());
236           
237           /* If new runnable threads have arrived, stop waiting for
238            * I/O and run them.
239            */
240           if (run_queue_hd != END_TSO_QUEUE) {
241               return; /* still hold the lock */
242           }
243           
244           RELEASE_LOCK(&sched_mutex);
245       }
246
247       ACQUIRE_LOCK(&sched_mutex);
248
249       /* Step through the waiting queue, unblocking every thread that now has
250        * a file descriptor in a ready state.
251        */
252
253       prev = NULL;
254       if (select_succeeded || unblock_all) {
255           for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
256               next = tso->link;
257               switch (tso->why_blocked) {
258               case BlockedOnRead:
259                   ready = unblock_all || FD_ISSET(tso->block_info.fd, &rfd);
260                   break;
261               case BlockedOnWrite:
262                   ready = unblock_all || FD_ISSET(tso->block_info.fd, &wfd);
263                   break;
264               default:
265                   barf("awaitEvent");
266               }
267       
268               if (ready) {
269                   IF_DEBUG(scheduler,belch("Waking up blocked thread %d\n", tso->id));
270                   tso->why_blocked = NotBlocked;
271                   tso->link = END_TSO_QUEUE;
272                   PUSH_ON_RUN_QUEUE(tso);
273               } else {
274                   if (prev == NULL)
275                       blocked_queue_hd = tso;
276                   else
277                       prev->link = tso;
278                   prev = tso;
279               }
280           }
281
282           if (prev == NULL)
283               blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
284           else {
285               prev->link = END_TSO_QUEUE;
286               blocked_queue_tl = prev;
287           }
288       }
289
290     } while (wait && !interrupted && run_queue_hd == END_TSO_QUEUE);
291 }