1666b499f526192f39d181cccd9dc1559ea0a533
[ghc-hetmet.git] / ghc / rts / Select.c
1 /* -----------------------------------------------------------------------------
2  * $Id: Select.c,v 1.10 2000/03/20 09:42:50 andy Exp $
3  *
4  * (c) The GHC Team 1995-1999
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 #define NON_POSIX_SOURCE
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 # if defined(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 nat ticks_since_select = 0;
29
30 /* Argument 'wait' says whether to wait for I/O to become available,
31  * or whether to just check and return immediately.  If there are
32  * other threads ready to run, we normally do the non-waiting variety,
33  * otherwise we wait (see Schedule.c).
34  *
35  * SMP note: must be called with sched_mutex locked.
36  */
37 void
38 awaitEvent(rtsBool wait)
39 {
40 #ifdef mingw32_TARGET_OS
41 /*
42  * Win32 doesn't support select(). ToDo: use MsgWaitForMultipleObjects()
43  * to achieve (similar) effect.
44  *
45  */
46     return;
47 #else
48
49     StgTSO *tso, *prev, *next;
50     rtsBool ready;
51     fd_set rfd,wfd;
52     int numFound;
53     nat min, delta;
54     int maxfd = -1;
55    
56     struct timeval tv;
57 #ifndef linux_TARGET_OS
58     struct timeval tv_before,tv_after;
59 #endif
60
61     IF_DEBUG(scheduler,belch("Checking for threads blocked on I/O...\n"));
62
63     /* loop until we've woken up some threads.  This loop is needed
64      * because the select timing isn't accurate, we sometimes sleep
65      * for a while but not long enough to wake up a thread in
66      * a threadDelay.
67      */
68     do {
69
70       /* see how long it's been since we last checked the blocked queue.
71        * ToDo: make this check atomic, so we don't lose any ticks.
72        */
73       delta = ticks_since_select;
74       ticks_since_select = 0;
75       delta = delta * TICK_MILLISECS * 1000;
76
77       min = wait == rtsTrue ? 0x7fffffff : 0;
78
79       /* 
80        * Collect all of the fd's that we're interested in, and capture
81        * the minimum waiting time (in microseconds) for the delayed threads.
82        */
83       FD_ZERO(&rfd);
84       FD_ZERO(&wfd);
85
86       for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
87         next = tso->link;
88
89         switch (tso->why_blocked) {
90         case BlockedOnRead:
91           { 
92             int fd = tso->block_info.fd;
93             maxfd = (fd > maxfd) ? fd : maxfd;
94             FD_SET(fd, &rfd);
95             continue;
96           }
97
98         case BlockedOnWrite:
99           { 
100             int fd = tso->block_info.fd;
101             maxfd = (fd > maxfd) ? fd : maxfd;
102             FD_SET(fd, &wfd);
103             continue;
104           }
105
106         case BlockedOnDelay:
107           {
108             int candidate; /* signed int is intentional */
109 #if defined(HAVE_SETITIMER)
110             candidate = tso->block_info.delay;
111 #else
112             candidate = tso->block_info.target - getourtimeofday();
113             if (candidate < 0) {
114               candidate = 0;
115             }
116 #endif
117             if ((nat)candidate < min) {
118               min = candidate;
119             }
120             continue;
121           }
122
123         default:
124           barf("AwaitEvent");
125         }
126       }
127
128       /* Release the scheduler lock while we do the poll.
129        * this means that someone might muck with the blocked_queue
130        * while we do this, but it shouldn't matter:
131        *
132        *   - another task might poll for I/O and remove one
133        *     or more threads from the blocked_queue.
134        *   - more I/O threads may be added to blocked_queue.
135        *   - more delayed threads may be added to blocked_queue. We'll
136        *     just subtract delta from their delays after the poll.
137        *
138        * I believe none of these cases lead to trouble --SDM.
139        */
140       RELEASE_LOCK(&sched_mutex);
141
142       /* Check for any interesting events */
143
144       tv.tv_sec = min / 1000000;
145       tv.tv_usec = min % 1000000;
146
147 #ifndef linux_TARGET_OS
148       gettimeofday(&tv_before, (struct timezone *) NULL);
149 #endif
150
151       while (!interrupted &&
152              (numFound = select(maxfd+1, &rfd, &wfd, NULL, &tv)) < 0) {
153         if (errno != EINTR) {
154           /* fflush(stdout); */
155           perror("select");
156           barf("select failed");
157         }
158         ACQUIRE_LOCK(&sched_mutex);
159
160         /* We got a signal; could be one of ours.  If so, we need
161          * to start up the signal handler straight away, otherwise
162          * we could block for a long time before the signal is
163          * serviced.
164          */
165         if (signals_pending()) {
166           RELEASE_LOCK(&sched_mutex);
167           start_signal_handlers();
168           break;
169         }
170
171         /* If new runnable threads have arrived, stop waiting for
172          * I/O and run them.
173          */
174         if (run_queue_hd != END_TSO_QUEUE) {
175           RELEASE_LOCK(&sched_mutex);
176           break;
177         }
178         
179         RELEASE_LOCK(&sched_mutex);
180       } 
181
182 #ifdef linux_TARGET_OS
183       /* on Linux, tv is set to indicate the amount of time not
184        * slept, so we don't need to gettimeofday() to find out.
185        */
186       delta += min - (tv.tv_sec * 1000000 + tv.tv_usec);
187 #else
188       gettimeofday(&tv_after, (struct timezone *) NULL);
189       delta += (tv_after.tv_sec - tv_before.tv_sec) * 1000000 +
190         tv_after.tv_usec - tv_before.tv_usec;
191 #endif
192
193 #if 0
194       if (delta != 0) { fprintf(stderr,"waited: %d %d %d\n", min, delta,
195                                 interrupted); }
196 #endif
197
198       ACQUIRE_LOCK(&sched_mutex);
199
200       /* Step through the waiting queue, unblocking every thread that now has
201        * a file descriptor in a ready state.
202         
203        * For the delayed threads, decrement the number of microsecs
204        * we've been blocked for. Unblock the threads that have thusly expired.
205        */
206
207       prev = NULL;
208       for(tso = blocked_queue_hd; tso != END_TSO_QUEUE; tso = next) {
209         next = tso->link;
210         switch (tso->why_blocked) {
211         case BlockedOnRead:
212           ready = FD_ISSET(tso->block_info.fd, &rfd);
213           break;
214         
215         case BlockedOnWrite:
216           ready = FD_ISSET(tso->block_info.fd, &wfd);
217           break;
218         
219         case BlockedOnDelay:
220           {
221             int candidate; /* signed int is intentional */
222 #if defined(HAVE_SETITIMER)
223             if (tso->block_info.delay > delta) {
224               tso->block_info.delay -= delta;
225               ready = 0;
226             } else {
227               tso->block_info.delay = 0;
228               ready = 1;
229             }
230 #else
231             candidate = tso->block_info.target - getourtimeofday();
232             if (candidate < 0) {
233               candidate = 0;
234             }
235             if ((nat)candidate > delta) {
236               ready = 0;
237             } else {
238               ready = 1;
239             }
240 #endif
241             break;
242           }
243         
244         default:
245           barf("awaitEvent");
246         }
247       
248         if (ready) {
249           IF_DEBUG(scheduler,belch("Waking up thread %d\n", tso->id));
250           tso->why_blocked = NotBlocked;
251           tso->link = END_TSO_QUEUE;
252           PUSH_ON_RUN_QUEUE(tso);
253         } else {
254           if (prev == NULL)
255             blocked_queue_hd = tso;
256           else
257             prev->link = tso;
258           prev = tso;
259         }
260       }
261
262       if (prev == NULL)
263         blocked_queue_hd = blocked_queue_tl = END_TSO_QUEUE;
264       else {
265         prev->link = END_TSO_QUEUE;
266         blocked_queue_tl = prev;
267       }
268
269     } while (wait && run_queue_hd == END_TSO_QUEUE);
270 #endif
271 }