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