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