merge upstream HEAD
[ghc-hetmet.git] / rts / posix / Select.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team 1995-2002
4  *
5  * Support for concurrent non-blocking I/O and thread waiting.
6  *
7  * ---------------------------------------------------------------------------*/
8
9 #include "PosixSource.h"
10 #include "Rts.h"
11
12 #include "Signals.h"
13 #include "Schedule.h"
14 #include "RtsUtils.h"
15 #include "Itimer.h"
16 #include "Capability.h"
17 #include "Select.h"
18 #include "AwaitEvent.h"
19
20 # ifdef HAVE_SYS_SELECT_H
21 #  include <sys/select.h>
22 # endif
23
24 # ifdef HAVE_SYS_TYPES_H
25 #  include <sys/types.h>
26 # endif
27
28 # ifdef HAVE_SYS_TIME_H
29 #  include <sys/time.h>
30 # endif
31
32 #include <errno.h>
33 #include <string.h>
34
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38
39 #if !defined(THREADED_RTS)
40 /* last timestamp */
41 lnat timestamp = 0;
42
43 /* 
44  * The threaded RTS uses an IO-manager thread in Haskell instead (see GHC.Conc) 
45  */
46
47 /* There's a clever trick here to avoid problems when the time wraps
48  * around.  Since our maximum delay is smaller than 31 bits of ticks
49  * (it's actually 31 bits of microseconds), we can safely check
50  * whether a timer has expired even if our timer will wrap around
51  * before the target is reached, using the following formula:
52  *
53  *        (int)((uint)current_time - (uint)target_time) < 0
54  *
55  * if this is true, then our time has expired.
56  * (idea due to Andy Gill).
57  */
58 static rtsBool
59 wakeUpSleepingThreads(lnat ticks)
60 {
61     StgTSO *tso;
62     rtsBool flag = rtsFalse;
63
64     while (sleeping_queue != END_TSO_QUEUE) {
65         tso = sleeping_queue;
66         if (((long)ticks - (long)tso->block_info.target) < 0) {
67             break;
68         }
69         sleeping_queue = tso->_link;
70         tso->why_blocked = NotBlocked;
71         tso->_link = END_TSO_QUEUE;
72         IF_DEBUG(scheduler,debugBelch("Waking up sleeping thread %lu\n", (unsigned long)tso->id));
73         // MainCapability: this code is !THREADED_RTS
74         pushOnRunQueue(&MainCapability,tso);
75         flag = rtsTrue;
76     }
77     return flag;
78 }
79
80 static void GNUC3_ATTRIBUTE(__noreturn__)
81 fdOutOfRange (int fd)
82 {
83     errorBelch("file descriptor %d out of range for select (0--%d).\nRecompile with -threaded to work around this.", fd, (int)FD_SETSIZE);
84     stg_exit(EXIT_FAILURE);
85 }
86
87 /* Argument 'wait' says whether to wait for I/O to become available,
88  * or whether to just check and return immediately.  If there are
89  * other threads ready to run, we normally do the non-waiting variety,
90  * otherwise we wait (see Schedule.c).
91  *
92  * SMP note: must be called with sched_mutex locked.
93  *
94  * Windows: select only works on sockets, so this doesn't really work,
95  * though it makes things better than before. MsgWaitForMultipleObjects
96  * should really be used, though it only seems to work for read handles,
97  * not write handles.
98  *
99  */
100 void
101 awaitEvent(rtsBool wait)
102 {
103     StgTSO *tso, *prev, *next;
104     rtsBool ready;
105     fd_set rfd,wfd;
106     int numFound;
107     int maxfd = -1;
108     rtsBool select_succeeded = rtsTrue;
109     rtsBool unblock_all = rtsFalse;
110     struct timeval tv;
111     lnat min, ticks;
112
113     tv.tv_sec  = 0;
114     tv.tv_usec = 0;
115     
116     IF_DEBUG(scheduler,
117              debugBelch("scheduler: checking for threads blocked on I/O");
118              if (wait) {
119                  debugBelch(" (waiting)");
120              }
121              debugBelch("\n");
122              );
123
124     /* loop until we've woken up some threads.  This loop is needed
125      * because the select timing isn't accurate, we sometimes sleep
126      * for a while but not long enough to wake up a thread in
127      * a threadDelay.
128      */
129     do {
130
131       ticks = timestamp = getourtimeofday();
132       if (wakeUpSleepingThreads(ticks)) { 
133           return;
134       }
135
136       if (!wait) {
137           min = 0;
138       } else if (sleeping_queue != END_TSO_QUEUE) {
139           min = (sleeping_queue->block_info.target - ticks) 
140               * RtsFlags.MiscFlags.tickInterval * 1000;
141       } else {
142           min = 0x7ffffff;
143       }
144
145       /* 
146        * Collect all of the fd's that we're interested in
147        */
148       FD_ZERO(&rfd);
149       FD_ZERO(&wfd);
150
151       for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
152         next = tso->_link;
153
154       /* On FreeBSD FD_SETSIZE is unsigned. Cast it to signed int
155        * in order to switch off the 'comparison between signed and
156        * unsigned error message
157        */
158         switch (tso->why_blocked) {
159         case BlockedOnRead:
160           { 
161             int fd = tso->block_info.fd;
162             if ((fd >= (int)FD_SETSIZE) || (fd < 0)) {
163                 fdOutOfRange(fd);
164             }
165             maxfd = (fd > maxfd) ? fd : maxfd;
166             FD_SET(fd, &rfd);
167             continue;
168           }
169
170         case BlockedOnWrite:
171           { 
172             int fd = tso->block_info.fd;
173             if ((fd >= (int)FD_SETSIZE) || (fd < 0)) {
174                 fdOutOfRange(fd);
175             }
176             maxfd = (fd > maxfd) ? fd : maxfd;
177             FD_SET(fd, &wfd);
178             continue;
179           }
180
181         default:
182           barf("AwaitEvent");
183         }
184       }
185
186       /* Check for any interesting events */
187       
188       tv.tv_sec  = min / 1000000;
189       tv.tv_usec = min % 1000000;
190
191       while ((numFound = select(maxfd+1, &rfd, &wfd, NULL, &tv)) < 0) {
192           if (errno != EINTR) {
193             /* Handle bad file descriptors by unblocking all the
194                waiting threads. Why? Because a thread might have been
195                a bit naughty and closed a file descriptor while another
196                was blocked waiting. This is less-than-good programming
197                practice, but having the RTS as a result fall over isn't
198                acceptable, so we simply unblock all the waiting threads
199                should we see a bad file descriptor & give the threads
200                a chance to clean up their act. 
201                
202                Note: assume here that threads becoming unblocked
203                will try to read/write the file descriptor before trying
204                to issue a threadWaitRead/threadWaitWrite again (==> an
205                IOError will result for the thread that's got the bad
206                file descriptor.) Hence, there's no danger of a bad
207                file descriptor being repeatedly select()'ed on, so
208                the RTS won't loop.
209             */
210             if ( errno == EBADF ) {
211               unblock_all = rtsTrue;
212               break;
213             } else {
214               perror("select");
215               barf("select failed");
216             }
217           }
218
219           /* We got a signal; could be one of ours.  If so, we need
220            * to start up the signal handler straight away, otherwise
221            * we could block for a long time before the signal is
222            * serviced.
223            */
224 #if defined(RTS_USER_SIGNALS)
225           if (RtsFlags.MiscFlags.install_signal_handlers && signals_pending()) {
226               startSignalHandlers(&MainCapability);
227               return; /* still hold the lock */
228           }
229 #endif
230
231           /* we were interrupted, return to the scheduler immediately.
232            */
233           if (sched_state >= SCHED_INTERRUPTING) {
234               return; /* still hold the lock */
235           }
236           
237           /* check for threads that need waking up 
238            */
239           wakeUpSleepingThreads(getourtimeofday());
240           
241           /* If new runnable threads have arrived, stop waiting for
242            * I/O and run them.
243            */
244           if (!emptyRunQueue(&MainCapability)) {
245               return; /* still hold the lock */
246           }
247       }
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
258               switch (tso->why_blocked) {
259               case BlockedOnRead:
260                   ready = unblock_all || FD_ISSET(tso->block_info.fd, &rfd);
261                   break;
262               case BlockedOnWrite:
263                   ready = unblock_all || FD_ISSET(tso->block_info.fd, &wfd);
264                   break;
265               default:
266                   barf("awaitEvent");
267               }
268       
269               if (ready) {
270                 IF_DEBUG(scheduler,debugBelch("Waking up blocked thread %lu\n", (unsigned long)tso->id));
271                   tso->why_blocked = NotBlocked;
272                   tso->_link = END_TSO_QUEUE;
273                   pushOnRunQueue(&MainCapability,tso);
274               } else {
275                   if (prev == NULL)
276                       blocked_queue_hd = tso;
277                   else
278                       setTSOLink(&MainCapability, prev, tso);
279                   prev = tso;
280               }
281           }
282
283           if (prev == NULL)
284               blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
285           else {
286               prev->_link = END_TSO_QUEUE;
287               blocked_queue_tl = prev;
288           }
289       }
290       
291     } while (wait && sched_state == SCHED_RUNNING
292              && emptyRunQueue(&MainCapability));
293 }
294
295 #endif /* THREADED_RTS */
296