Rollback #1185 fix
[ghc-base.git] / GHC / Conc.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_GHC -fno-warn-missing-signatures #-}
4 {-# OPTIONS_HADDOCK not-home #-}
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module      :  GHC.Conc
8 -- Copyright   :  (c) The University of Glasgow, 1994-2002
9 -- License     :  see libraries/base/LICENSE
10 -- 
11 -- Maintainer  :  cvs-ghc@haskell.org
12 -- Stability   :  internal
13 -- Portability :  non-portable (GHC extensions)
14 --
15 -- Basic concurrency stuff.
16 -- 
17 -----------------------------------------------------------------------------
18
19 -- No: #hide, because bits of this module are exposed by the stm package.
20 -- However, we don't want this module to be the home location for the
21 -- bits it exports, we'd rather have Control.Concurrent and the other
22 -- higher level modules be the home.  Hence:
23
24 #include "Typeable.h"
25
26 -- #not-home
27 module GHC.Conc
28         ( ThreadId(..)
29
30         -- * Forking and suchlike
31         , forkIO        -- :: IO a -> IO ThreadId
32         , forkOnIO      -- :: Int -> IO a -> IO ThreadId
33         , numCapabilities -- :: Int
34         , childHandler  -- :: Exception -> IO ()
35         , myThreadId    -- :: IO ThreadId
36         , killThread    -- :: ThreadId -> IO ()
37         , throwTo       -- :: ThreadId -> Exception -> IO ()
38         , par           -- :: a -> b -> b
39         , pseq          -- :: a -> b -> b
40         , runSparks
41         , yield         -- :: IO ()
42         , labelThread   -- :: ThreadId -> String -> IO ()
43
44         , ThreadStatus(..), BlockReason(..)
45         , threadStatus  -- :: ThreadId -> IO ThreadStatus
46
47         -- * Waiting
48         , threadDelay           -- :: Int -> IO ()
49         , registerDelay         -- :: Int -> IO (TVar Bool)
50         , threadWaitRead        -- :: Int -> IO ()
51         , threadWaitWrite       -- :: Int -> IO ()
52
53         -- * TVars
54         , STM(..)
55         , atomically    -- :: STM a -> IO a
56         , retry         -- :: STM a
57         , orElse        -- :: STM a -> STM a -> STM a
58         , catchSTM      -- :: STM a -> (Exception -> STM a) -> STM a
59         , alwaysSucceeds -- :: STM a -> STM ()
60         , always        -- :: STM Bool -> STM ()
61         , TVar(..)
62         , newTVar       -- :: a -> STM (TVar a)
63         , newTVarIO     -- :: a -> STM (TVar a)
64         , readTVar      -- :: TVar a -> STM a
65         , readTVarIO    -- :: TVar a -> IO a
66         , writeTVar     -- :: a -> TVar a -> STM ()
67         , unsafeIOToSTM -- :: IO a -> STM a
68
69         -- * Miscellaneous
70         , withMVar
71 #ifdef mingw32_HOST_OS
72         , asyncRead     -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
73         , asyncWrite    -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
74         , asyncDoProc   -- :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
75
76         , asyncReadBA   -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
77         , asyncWriteBA  -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
78 #endif
79
80 #ifndef mingw32_HOST_OS
81         , Signal, HandlerFun, setHandler, runHandlers
82 #endif
83
84         , ensureIOManagerIsRunning
85 #ifndef mingw32_HOST_OS
86         , syncIOManager
87 #endif
88
89 #ifdef mingw32_HOST_OS
90         , ConsoleEvent(..)
91         , win32ConsoleHandler
92         , toWin32ConsoleEvent
93 #endif
94         , setUncaughtExceptionHandler      -- :: (Exception -> IO ()) -> IO ()
95         , getUncaughtExceptionHandler      -- :: IO (Exception -> IO ())
96
97         , reportError, reportStackOverflow
98         ) where
99
100 import System.Posix.Types
101 #ifndef mingw32_HOST_OS
102 import System.Posix.Internals
103 #endif
104 import Foreign
105 import Foreign.C
106
107 #ifdef mingw32_HOST_OS
108 import Data.Typeable
109 #endif
110
111 #ifndef mingw32_HOST_OS
112 import Data.Dynamic
113 #endif
114 import Control.Monad
115 import Data.Maybe
116
117 import GHC.Base
118 #ifndef mingw32_HOST_OS
119 import GHC.Debug
120 #endif
121 import {-# SOURCE #-} GHC.IO.Handle ( hFlush )
122 import {-# SOURCE #-} GHC.IO.Handle.FD ( stdout )
123 import GHC.IO
124 import GHC.IO.Exception
125 import GHC.Exception
126 import GHC.IORef
127 import GHC.MVar
128 import GHC.Num          ( Num(..) )
129 import GHC.Real         ( fromIntegral )
130 #ifndef mingw32_HOST_OS
131 import GHC.IOArray
132 import GHC.Arr          ( inRange )
133 #endif
134 #ifdef mingw32_HOST_OS
135 import GHC.Real         ( div )
136 import GHC.Ptr
137 #endif
138 #ifdef mingw32_HOST_OS
139 import GHC.Read         ( Read )
140 import GHC.Enum         ( Enum )
141 #endif
142 import GHC.Pack         ( packCString# )
143 import GHC.Show         ( Show(..), showString )
144
145 infixr 0 `par`, `pseq`
146 \end{code}
147
148 %************************************************************************
149 %*                                                                      *
150 \subsection{@ThreadId@, @par@, and @fork@}
151 %*                                                                      *
152 %************************************************************************
153
154 \begin{code}
155 data ThreadId = ThreadId ThreadId# deriving( Typeable )
156 -- ToDo: data ThreadId = ThreadId (Weak ThreadId#)
157 -- But since ThreadId# is unlifted, the Weak type must use open
158 -- type variables.
159 {- ^
160 A 'ThreadId' is an abstract type representing a handle to a thread.
161 'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where
162 the 'Ord' instance implements an arbitrary total ordering over
163 'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued
164 'ThreadId' to string form; showing a 'ThreadId' value is occasionally
165 useful when debugging or diagnosing the behaviour of a concurrent
166 program.
167
168 /Note/: in GHC, if you have a 'ThreadId', you essentially have
169 a pointer to the thread itself.  This means the thread itself can\'t be
170 garbage collected until you drop the 'ThreadId'.
171 This misfeature will hopefully be corrected at a later date.
172
173 /Note/: Hugs does not provide any operations on other threads;
174 it defines 'ThreadId' as a synonym for ().
175 -}
176
177 instance Show ThreadId where
178    showsPrec d t = 
179         showString "ThreadId " . 
180         showsPrec d (getThreadId (id2TSO t))
181
182 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt
183
184 id2TSO :: ThreadId -> ThreadId#
185 id2TSO (ThreadId t) = t
186
187 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> CInt
188 -- Returns -1, 0, 1
189
190 cmpThread :: ThreadId -> ThreadId -> Ordering
191 cmpThread t1 t2 = 
192    case cmp_thread (id2TSO t1) (id2TSO t2) of
193       -1 -> LT
194       0  -> EQ
195       _  -> GT -- must be 1
196
197 instance Eq ThreadId where
198    t1 == t2 = 
199       case t1 `cmpThread` t2 of
200          EQ -> True
201          _  -> False
202
203 instance Ord ThreadId where
204    compare = cmpThread
205
206 {- |
207 Sparks off a new thread to run the 'IO' computation passed as the
208 first argument, and returns the 'ThreadId' of the newly created
209 thread.
210
211 The new thread will be a lightweight thread; if you want to use a foreign
212 library that uses thread-local storage, use 'Control.Concurrent.forkOS' instead.
213
214 GHC note: the new thread inherits the /blocked/ state of the parent 
215 (see 'Control.Exception.block').
216
217 The newly created thread has an exception handler that discards the
218 exceptions 'BlockedOnDeadMVar', 'BlockedIndefinitely', and
219 'ThreadKilled', and passes all other exceptions to the uncaught
220 exception handler (see 'setUncaughtExceptionHandler').
221 -}
222 forkIO :: IO () -> IO ThreadId
223 forkIO action = IO $ \ s -> 
224    case (fork# action_plus s) of (# s1, tid #) -> (# s1, ThreadId tid #)
225  where
226   action_plus = catchException action childHandler
227
228 {- |
229 Like 'forkIO', but lets you specify on which CPU the thread is
230 created.  Unlike a `forkIO` thread, a thread created by `forkOnIO`
231 will stay on the same CPU for its entire lifetime (`forkIO` threads
232 can migrate between CPUs according to the scheduling policy).
233 `forkOnIO` is useful for overriding the scheduling policy when you
234 know in advance how best to distribute the threads.
235
236 The `Int` argument specifies the CPU number; it is interpreted modulo
237 'numCapabilities' (note that it actually specifies a capability number
238 rather than a CPU number, but to a first approximation the two are
239 equivalent).
240 -}
241 forkOnIO :: Int -> IO () -> IO ThreadId
242 forkOnIO (I# cpu) action = IO $ \ s -> 
243    case (forkOn# cpu action_plus s) of (# s1, tid #) -> (# s1, ThreadId tid #)
244  where
245   action_plus = catchException action childHandler
246
247 -- | the value passed to the @+RTS -N@ flag.  This is the number of
248 -- Haskell threads that can run truly simultaneously at any given
249 -- time, and is typically set to the number of physical CPU cores on
250 -- the machine.
251 numCapabilities :: Int
252 numCapabilities = unsafePerformIO $  do 
253                     n <- peek n_capabilities
254                     return (fromIntegral n)
255
256 #if defined(mingw32_HOST_OS) && defined(__PIC__)
257 foreign import ccall "_imp__n_capabilities" n_capabilities :: Ptr CInt
258 #else
259 foreign import ccall "&n_capabilities" n_capabilities :: Ptr CInt
260 #endif
261 childHandler :: SomeException -> IO ()
262 childHandler err = catchException (real_handler err) childHandler
263
264 real_handler :: SomeException -> IO ()
265 real_handler se@(SomeException ex) =
266   -- ignore thread GC and killThread exceptions:
267   case cast ex of
268   Just BlockedIndefinitelyOnMVar        -> return ()
269   _ -> case cast ex of
270        Just BlockedIndefinitelyOnSTM    -> return ()
271        _ -> case cast ex of
272             Just ThreadKilled           -> return ()
273             _ -> case cast ex of
274                  -- report all others:
275                  Just StackOverflow     -> reportStackOverflow
276                  _                      -> reportError se
277
278 {- | 'killThread' terminates the given thread (GHC only).
279 Any work already done by the thread isn\'t
280 lost: the computation is suspended until required by another thread.
281 The memory used by the thread will be garbage collected if it isn\'t
282 referenced from anywhere.  The 'killThread' function is defined in
283 terms of 'throwTo':
284
285 > killThread tid = throwTo tid ThreadKilled
286
287 Killthread is a no-op if the target thread has already completed.
288 -}
289 killThread :: ThreadId -> IO ()
290 killThread tid = throwTo tid ThreadKilled
291
292 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
293
294 'throwTo' does not return until the exception has been raised in the
295 target thread. 
296 The calling thread can thus be certain that the target
297 thread has received the exception.  This is a useful property to know
298 when dealing with race conditions: eg. if there are two threads that
299 can kill each other, it is guaranteed that only one of the threads
300 will get to kill the other.
301
302 If the target thread is currently making a foreign call, then the
303 exception will not be raised (and hence 'throwTo' will not return)
304 until the call has completed.  This is the case regardless of whether
305 the call is inside a 'block' or not.
306
307 Important note: the behaviour of 'throwTo' differs from that described in
308 the paper \"Asynchronous exceptions in Haskell\"
309 (<http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm>).
310 In the paper, 'throwTo' is non-blocking; but the library implementation adopts
311 a more synchronous design in which 'throwTo' does not return until the exception
312 is received by the target thread.  The trade-off is discussed in Section 9 of the paper.
313 Like any blocking operation, 'throwTo' is therefore interruptible (see Section 5.3 of
314 the paper).
315
316 There is currently no guarantee that the exception delivered by 'throwTo' will be
317 delivered at the first possible opportunity.  In particular, a thread may 
318 unblock and then re-block exceptions (using 'unblock' and 'block') without receiving
319 a pending 'throwTo'.  This is arguably undesirable behaviour.
320
321  -}
322 throwTo :: Exception e => ThreadId -> e -> IO ()
323 throwTo (ThreadId tid) ex = IO $ \ s ->
324    case (killThread# tid (toException ex) s) of s1 -> (# s1, () #)
325
326 -- | Returns the 'ThreadId' of the calling thread (GHC only).
327 myThreadId :: IO ThreadId
328 myThreadId = IO $ \s ->
329    case (myThreadId# s) of (# s1, tid #) -> (# s1, ThreadId tid #)
330
331
332 -- |The 'yield' action allows (forces, in a co-operative multitasking
333 -- implementation) a context-switch to any other currently runnable
334 -- threads (if any), and is occasionally useful when implementing
335 -- concurrency abstractions.
336 yield :: IO ()
337 yield = IO $ \s -> 
338    case (yield# s) of s1 -> (# s1, () #)
339
340 {- | 'labelThread' stores a string as identifier for this thread if
341 you built a RTS with debugging support. This identifier will be used in
342 the debugging output to make distinction of different threads easier
343 (otherwise you only have the thread state object\'s address in the heap).
344
345 Other applications like the graphical Concurrent Haskell Debugger
346 (<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload
347 'labelThread' for their purposes as well.
348 -}
349
350 labelThread :: ThreadId -> String -> IO ()
351 labelThread (ThreadId t) str = IO $ \ s ->
352    let !ps  = packCString# str
353        !adr = byteArrayContents# ps in
354      case (labelThread# t adr s) of s1 -> (# s1, () #)
355
356 --      Nota Bene: 'pseq' used to be 'seq'
357 --                 but 'seq' is now defined in PrelGHC
358 --
359 -- "pseq" is defined a bit weirdly (see below)
360 --
361 -- The reason for the strange "lazy" call is that
362 -- it fools the compiler into thinking that pseq  and par are non-strict in
363 -- their second argument (even if it inlines pseq at the call site).
364 -- If it thinks pseq is strict in "y", then it often evaluates
365 -- "y" before "x", which is totally wrong.  
366
367 {-# INLINE pseq  #-}
368 pseq :: a -> b -> b
369 pseq  x y = x `seq` lazy y
370
371 {-# INLINE par  #-}
372 par :: a -> b -> b
373 par  x y = case (par# x) of { _ -> lazy y }
374
375 -- | Internal function used by the RTS to run sparks.
376 runSparks :: IO ()
377 runSparks = IO loop
378   where loop s = case getSpark# s of
379                    (# s', n, p #) ->
380                       if n ==# 0# then (# s', () #)
381                                   else p `seq` loop s'
382
383 data BlockReason
384   = BlockedOnMVar
385         -- ^blocked on on 'MVar'
386   | BlockedOnBlackHole
387         -- ^blocked on a computation in progress by another thread
388   | BlockedOnException
389         -- ^blocked in 'throwTo'
390   | BlockedOnSTM
391         -- ^blocked in 'retry' in an STM transaction
392   | BlockedOnForeignCall
393         -- ^currently in a foreign call
394   | BlockedOnOther
395         -- ^blocked on some other resource.  Without @-threaded@,
396         -- I\/O and 'threadDelay' show up as 'BlockedOnOther', with @-threaded@
397         -- they show up as 'BlockedOnMVar'.
398   deriving (Eq,Ord,Show)
399
400 -- | The current status of a thread
401 data ThreadStatus
402   = ThreadRunning
403         -- ^the thread is currently runnable or running
404   | ThreadFinished
405         -- ^the thread has finished
406   | ThreadBlocked  BlockReason
407         -- ^the thread is blocked on some resource
408   | ThreadDied
409         -- ^the thread received an uncaught exception
410   deriving (Eq,Ord,Show)
411
412 threadStatus :: ThreadId -> IO ThreadStatus
413 threadStatus (ThreadId t) = IO $ \s ->
414    case threadStatus# t s of
415      (# s', stat #) -> (# s', mk_stat (I# stat) #)
416    where
417         -- NB. keep these in sync with includes/Constants.h
418      mk_stat 0  = ThreadRunning
419      mk_stat 1  = ThreadBlocked BlockedOnMVar
420      mk_stat 2  = ThreadBlocked BlockedOnBlackHole
421      mk_stat 3  = ThreadBlocked BlockedOnException
422      mk_stat 7  = ThreadBlocked BlockedOnSTM
423      mk_stat 11 = ThreadBlocked BlockedOnForeignCall
424      mk_stat 12 = ThreadBlocked BlockedOnForeignCall
425      mk_stat 16 = ThreadFinished
426      mk_stat 17 = ThreadDied
427      mk_stat _  = ThreadBlocked BlockedOnOther
428 \end{code}
429
430
431 %************************************************************************
432 %*                                                                      *
433 \subsection[stm]{Transactional heap operations}
434 %*                                                                      *
435 %************************************************************************
436
437 TVars are shared memory locations which support atomic memory
438 transactions.
439
440 \begin{code}
441 -- |A monad supporting atomic memory transactions.
442 newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))
443
444 unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
445 unSTM (STM a) = a
446
447 INSTANCE_TYPEABLE1(STM,stmTc,"STM")
448
449 instance  Functor STM where
450    fmap f x = x >>= (return . f)
451
452 instance  Monad STM  where
453     {-# INLINE return #-}
454     {-# INLINE (>>)   #-}
455     {-# INLINE (>>=)  #-}
456     m >> k      = thenSTM m k
457     return x    = returnSTM x
458     m >>= k     = bindSTM m k
459
460 bindSTM :: STM a -> (a -> STM b) -> STM b
461 bindSTM (STM m) k = STM ( \s ->
462   case m s of 
463     (# new_s, a #) -> unSTM (k a) new_s
464   )
465
466 thenSTM :: STM a -> STM b -> STM b
467 thenSTM (STM m) k = STM ( \s ->
468   case m s of 
469     (# new_s, _ #) -> unSTM k new_s
470   )
471
472 returnSTM :: a -> STM a
473 returnSTM x = STM (\s -> (# s, x #))
474
475 -- | Unsafely performs IO in the STM monad.  Beware: this is a highly
476 -- dangerous thing to do.  
477 --
478 --   * The STM implementation will often run transactions multiple
479 --     times, so you need to be prepared for this if your IO has any
480 --     side effects.
481 --
482 --   * The STM implementation will abort transactions that are known to
483 --     be invalid and need to be restarted.  This may happen in the middle
484 --     of `unsafeIOToSTM`, so make sure you don't acquire any resources
485 --     that need releasing (exception handlers are ignored when aborting
486 --     the transaction).  That includes doing any IO using Handles, for
487 --     example.  Getting this wrong will probably lead to random deadlocks.
488 --
489 --   * The transaction may have seen an inconsistent view of memory when
490 --     the IO runs.  Invariants that you expect to be true throughout
491 --     your program may not be true inside a transaction, due to the
492 --     way transactions are implemented.  Normally this wouldn't be visible
493 --     to the programmer, but using `unsafeIOToSTM` can expose it.
494 --
495 unsafeIOToSTM :: IO a -> STM a
496 unsafeIOToSTM (IO m) = STM m
497
498 -- |Perform a series of STM actions atomically.
499 --
500 -- You cannot use 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'. 
501 -- Any attempt to do so will result in a runtime error.  (Reason: allowing
502 -- this would effectively allow a transaction inside a transaction, depending
503 -- on exactly when the thunk is evaluated.)
504 --
505 -- However, see 'newTVarIO', which can be called inside 'unsafePerformIO',
506 -- and which allows top-level TVars to be allocated.
507
508 atomically :: STM a -> IO a
509 atomically (STM m) = IO (\s -> (atomically# m) s )
510
511 -- |Retry execution of the current memory transaction because it has seen
512 -- values in TVars which mean that it should not continue (e.g. the TVars
513 -- represent a shared buffer that is now empty).  The implementation may
514 -- block the thread until one of the TVars that it has read from has been
515 -- udpated. (GHC only)
516 retry :: STM a
517 retry = STM $ \s# -> retry# s#
518
519 -- |Compose two alternative STM actions (GHC only).  If the first action
520 -- completes without retrying then it forms the result of the orElse.
521 -- Otherwise, if the first action retries, then the second action is
522 -- tried in its place.  If both actions retry then the orElse as a
523 -- whole retries.
524 orElse :: STM a -> STM a -> STM a
525 orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
526
527 -- |Exception handling within STM actions.
528 catchSTM :: STM a -> (SomeException -> STM a) -> STM a
529 catchSTM (STM m) k = STM $ \s -> catchSTM# m (\ex -> unSTM (k ex)) s
530
531 -- | Low-level primitive on which always and alwaysSucceeds are built.
532 -- checkInv differs form these in that (i) the invariant is not 
533 -- checked when checkInv is called, only at the end of this and
534 -- subsequent transcations, (ii) the invariant failure is indicated
535 -- by raising an exception.
536 checkInv :: STM a -> STM ()
537 checkInv (STM m) = STM (\s -> (check# m) s)
538
539 -- | alwaysSucceeds adds a new invariant that must be true when passed
540 -- to alwaysSucceeds, at the end of the current transaction, and at
541 -- the end of every subsequent transaction.  If it fails at any
542 -- of those points then the transaction violating it is aborted
543 -- and the exception raised by the invariant is propagated.
544 alwaysSucceeds :: STM a -> STM ()
545 alwaysSucceeds i = do ( i >> retry ) `orElse` ( return () ) 
546                       checkInv i
547
548 -- | always is a variant of alwaysSucceeds in which the invariant is
549 -- expressed as an STM Bool action that must return True.  Returning
550 -- False or raising an exception are both treated as invariant failures.
551 always :: STM Bool -> STM ()
552 always i = alwaysSucceeds ( do v <- i
553                                if (v) then return () else ( error "Transacional invariant violation" ) )
554
555 -- |Shared memory locations that support atomic memory transactions.
556 data TVar a = TVar (TVar# RealWorld a)
557
558 INSTANCE_TYPEABLE1(TVar,tvarTc,"TVar")
559
560 instance Eq (TVar a) where
561         (TVar tvar1#) == (TVar tvar2#) = sameTVar# tvar1# tvar2#
562
563 -- |Create a new TVar holding a value supplied
564 newTVar :: a -> STM (TVar a)
565 newTVar val = STM $ \s1# ->
566     case newTVar# val s1# of
567          (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
568
569 -- |@IO@ version of 'newTVar'.  This is useful for creating top-level
570 -- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using
571 -- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
572 -- possible.
573 newTVarIO :: a -> IO (TVar a)
574 newTVarIO val = IO $ \s1# ->
575     case newTVar# val s1# of
576          (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
577
578 -- |Return the current value stored in a TVar.
579 -- This is equivalent to
580 --
581 -- >  readTVarIO = atomically . readTVar
582 --
583 -- but works much faster, because it doesn't perform a complete
584 -- transaction, it just reads the current value of the 'TVar'.
585 readTVarIO :: TVar a -> IO a
586 readTVarIO (TVar tvar#) = IO $ \s# -> readTVarIO# tvar# s#
587
588 -- |Return the current value stored in a TVar
589 readTVar :: TVar a -> STM a
590 readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
591
592 -- |Write the supplied value into a TVar
593 writeTVar :: TVar a -> a -> STM ()
594 writeTVar (TVar tvar#) val = STM $ \s1# ->
595     case writeTVar# tvar# val s1# of
596          s2# -> (# s2#, () #)
597   
598 \end{code}
599
600 MVar utilities
601
602 \begin{code}
603 withMVar :: MVar a -> (a -> IO b) -> IO b
604 withMVar m io = 
605   block $ do
606     a <- takeMVar m
607     b <- catchAny (unblock (io a))
608             (\e -> do putMVar m a; throw e)
609     putMVar m a
610     return b
611 \end{code}
612
613 %************************************************************************
614 %*                                                                      *
615 \subsection{Thread waiting}
616 %*                                                                      *
617 %************************************************************************
618
619 \begin{code}
620 #ifdef mingw32_HOST_OS
621
622 -- Note: threadWaitRead and threadWaitWrite aren't really functional
623 -- on Win32, but left in there because lib code (still) uses them (the manner
624 -- in which they're used doesn't cause problems on a Win32 platform though.)
625
626 asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
627 asyncRead  (I# fd) (I# isSock) (I# len) (Ptr buf) =
628   IO $ \s -> case asyncRead# fd isSock len buf s of 
629                (# s', len#, err# #) -> (# s', (I# len#, I# err#) #)
630
631 asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
632 asyncWrite  (I# fd) (I# isSock) (I# len) (Ptr buf) =
633   IO $ \s -> case asyncWrite# fd isSock len buf s of 
634                (# s', len#, err# #) -> (# s', (I# len#, I# err#) #)
635
636 asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
637 asyncDoProc (FunPtr proc) (Ptr param) = 
638     -- the 'length' value is ignored; simplifies implementation of
639     -- the async*# primops to have them all return the same result.
640   IO $ \s -> case asyncDoProc# proc param s  of 
641                (# s', _len#, err# #) -> (# s', I# err# #)
642
643 -- to aid the use of these primops by the IO Handle implementation,
644 -- provide the following convenience funs:
645
646 -- this better be a pinned byte array!
647 asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
648 asyncReadBA fd isSock len off bufB = 
649   asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
650   
651 asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
652 asyncWriteBA fd isSock len off bufB = 
653   asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
654
655 #endif
656
657 -- -----------------------------------------------------------------------------
658 -- Thread IO API
659
660 -- | Block the current thread until data is available to read on the
661 -- given file descriptor (GHC only).
662 threadWaitRead :: Fd -> IO ()
663 threadWaitRead fd
664 #ifndef mingw32_HOST_OS
665   | threaded  = waitForReadEvent fd
666 #endif
667   | otherwise = IO $ \s -> 
668         case fromIntegral fd of { I# fd# ->
669         case waitRead# fd# s of { s' -> (# s', () #)
670         }}
671
672 -- | Block the current thread until data can be written to the
673 -- given file descriptor (GHC only).
674 threadWaitWrite :: Fd -> IO ()
675 threadWaitWrite fd
676 #ifndef mingw32_HOST_OS
677   | threaded  = waitForWriteEvent fd
678 #endif
679   | otherwise = IO $ \s -> 
680         case fromIntegral fd of { I# fd# ->
681         case waitWrite# fd# s of { s' -> (# s', () #)
682         }}
683
684 -- | Suspends the current thread for a given number of microseconds
685 -- (GHC only).
686 --
687 -- There is no guarantee that the thread will be rescheduled promptly
688 -- when the delay has expired, but the thread will never continue to
689 -- run /earlier/ than specified.
690 --
691 threadDelay :: Int -> IO ()
692 threadDelay time
693   | threaded  = waitForDelayEvent time
694   | otherwise = IO $ \s -> 
695         case fromIntegral time of { I# time# ->
696         case delay# time# s of { s' -> (# s', () #)
697         }}
698
699
700 -- | Set the value of returned TVar to True after a given number of
701 -- microseconds. The caveats associated with threadDelay also apply.
702 --
703 registerDelay :: Int -> IO (TVar Bool)
704 registerDelay usecs 
705   | threaded = waitForDelayEventSTM usecs
706   | otherwise = error "registerDelay: requires -threaded"
707
708 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
709
710 waitForDelayEvent :: Int -> IO ()
711 waitForDelayEvent usecs = do
712   m <- newEmptyMVar
713   target <- calculateTarget usecs
714   atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))
715   prodServiceThread
716   takeMVar m
717
718 -- Delays for use in STM
719 waitForDelayEventSTM :: Int -> IO (TVar Bool)
720 waitForDelayEventSTM usecs = do
721    t <- atomically $ newTVar False
722    target <- calculateTarget usecs
723    atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ()))
724    prodServiceThread
725    return t  
726     
727 calculateTarget :: Int -> IO USecs
728 calculateTarget usecs = do
729     now <- getUSecOfDay
730     return $ now + (fromIntegral usecs)
731
732
733 -- ----------------------------------------------------------------------------
734 -- Threaded RTS implementation of threadWaitRead, threadWaitWrite, threadDelay
735
736 -- In the threaded RTS, we employ a single IO Manager thread to wait
737 -- for all outstanding IO requests (threadWaitRead,threadWaitWrite)
738 -- and delays (threadDelay).  
739 --
740 -- We can do this because in the threaded RTS the IO Manager can make
741 -- a non-blocking call to select(), so we don't have to do select() in
742 -- the scheduler as we have to in the non-threaded RTS.  We get performance
743 -- benefits from doing it this way, because we only have to restart the select()
744 -- when a new request arrives, rather than doing one select() each time
745 -- around the scheduler loop.  Furthermore, the scheduler can be simplified
746 -- by not having to check for completed IO requests.
747
748 -- Issues, possible problems:
749 --
750 --      - we might want bound threads to just do the blocking
751 --        operation rather than communicating with the IO manager
752 --        thread.  This would prevent simgle-threaded programs which do
753 --        IO from requiring multiple OS threads.  However, it would also
754 --        prevent bound threads waiting on IO from being killed or sent
755 --        exceptions.
756 --
757 --      - Apprently exec() doesn't work on Linux in a multithreaded program.
758 --        I couldn't repeat this.
759 --
760 --      - How do we handle signal delivery in the multithreaded RTS?
761 --
762 --      - forkProcess will kill the IO manager thread.  Let's just
763 --        hope we don't need to do any blocking IO between fork & exec.
764
765 #ifndef mingw32_HOST_OS
766 data IOReq
767   = Read   {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
768   | Write  {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
769 #endif
770
771 data DelayReq
772   = Delay    {-# UNPACK #-} !USecs {-# UNPACK #-} !(MVar ())
773   | DelaySTM {-# UNPACK #-} !USecs {-# UNPACK #-} !(TVar Bool)
774
775 #ifndef mingw32_HOST_OS
776 pendingEvents :: IORef [IOReq]
777 #endif
778 pendingDelays :: IORef [DelayReq]
779         -- could use a strict list or array here
780 {-# NOINLINE pendingEvents #-}
781 {-# NOINLINE pendingDelays #-}
782 (pendingEvents,pendingDelays) = unsafePerformIO $ do
783   startIOManagerThread
784   reqs <- newIORef []
785   dels <- newIORef []
786   return (reqs, dels)
787         -- the first time we schedule an IO request, the service thread
788         -- will be created (cool, huh?)
789
790 ensureIOManagerIsRunning :: IO ()
791 ensureIOManagerIsRunning 
792   | threaded  = seq pendingEvents $ return ()
793   | otherwise = return ()
794
795 insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]
796 insertDelay d [] = [d]
797 insertDelay d1 ds@(d2 : rest)
798   | delayTime d1 <= delayTime d2 = d1 : ds
799   | otherwise                    = d2 : insertDelay d1 rest
800
801 delayTime :: DelayReq -> USecs
802 delayTime (Delay t _) = t
803 delayTime (DelaySTM t _) = t
804
805 type USecs = Word64
806
807 foreign import ccall unsafe "getUSecOfDay" 
808   getUSecOfDay :: IO USecs
809
810 prodding :: IORef Bool
811 {-# NOINLINE prodding #-}
812 prodding = unsafePerformIO (newIORef False)
813
814 prodServiceThread :: IO ()
815 prodServiceThread = do
816   was_set <- atomicModifyIORef prodding (\a -> (True,a))
817   if (not (was_set)) then wakeupIOManager else return ()
818
819 #ifdef mingw32_HOST_OS
820 -- ----------------------------------------------------------------------------
821 -- Windows IO manager thread
822
823 startIOManagerThread :: IO ()
824 startIOManagerThread = do
825   wakeup <- c_getIOManagerEvent
826   _ <- forkIO $ service_loop wakeup []
827   return ()
828
829 service_loop :: HANDLE          -- read end of pipe
830              -> [DelayReq]      -- current delay requests
831              -> IO ()
832
833 service_loop wakeup old_delays = do
834   -- pick up new delay requests
835   new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
836   let  delays = foldr insertDelay old_delays new_delays
837
838   now <- getUSecOfDay
839   (delays', timeout) <- getDelay now delays
840
841   r <- c_WaitForSingleObject wakeup timeout
842   case r of
843     0xffffffff -> do c_maperrno; throwErrno "service_loop"
844     0 -> do
845         r2 <- c_readIOManagerEvent
846         exit <- 
847               case r2 of
848                 _ | r2 == io_MANAGER_WAKEUP -> return False
849                 _ | r2 == io_MANAGER_DIE    -> return True
850                 0 -> return False -- spurious wakeup
851                 _ -> do start_console_handler (r2 `shiftR` 1); return False
852         unless exit $ service_cont wakeup delays'
853
854     _other -> service_cont wakeup delays' -- probably timeout        
855
856 service_cont :: HANDLE -> [DelayReq] -> IO ()
857 service_cont wakeup delays = do
858   r <- atomicModifyIORef prodding (\_ -> (False,False))
859   r `seq` return () -- avoid space leak
860   service_loop wakeup delays
861
862 -- must agree with rts/win32/ThrIOManager.c
863 io_MANAGER_WAKEUP, io_MANAGER_DIE :: Word32
864 io_MANAGER_WAKEUP = 0xffffffff
865 io_MANAGER_DIE    = 0xfffffffe
866
867 data ConsoleEvent
868  = ControlC
869  | Break
870  | Close
871     -- these are sent to Services only.
872  | Logoff
873  | Shutdown
874  deriving (Eq, Ord, Enum, Show, Read, Typeable)
875
876 start_console_handler :: Word32 -> IO ()
877 start_console_handler r =
878   case toWin32ConsoleEvent r of
879      Just x  -> withMVar win32ConsoleHandler $ \handler -> do
880                     _ <- forkIO (handler x)
881                     return ()
882      Nothing -> return ()
883
884 toWin32ConsoleEvent :: Num a => a -> Maybe ConsoleEvent
885 toWin32ConsoleEvent ev = 
886    case ev of
887        0 {- CTRL_C_EVENT-}        -> Just ControlC
888        1 {- CTRL_BREAK_EVENT-}    -> Just Break
889        2 {- CTRL_CLOSE_EVENT-}    -> Just Close
890        5 {- CTRL_LOGOFF_EVENT-}   -> Just Logoff
891        6 {- CTRL_SHUTDOWN_EVENT-} -> Just Shutdown
892        _ -> Nothing
893
894 win32ConsoleHandler :: MVar (ConsoleEvent -> IO ())
895 win32ConsoleHandler = unsafePerformIO (newMVar (error "win32ConsoleHandler"))
896
897 -- XXX Is this actually needed?
898 stick :: IORef HANDLE
899 {-# NOINLINE stick #-}
900 stick = unsafePerformIO (newIORef nullPtr)
901
902 wakeupIOManager :: IO ()
903 wakeupIOManager = do 
904   _hdl <- readIORef stick
905   c_sendIOManagerEvent io_MANAGER_WAKEUP
906
907 -- Walk the queue of pending delays, waking up any that have passed
908 -- and return the smallest delay to wait for.  The queue of pending
909 -- delays is kept ordered.
910 getDelay :: USecs -> [DelayReq] -> IO ([DelayReq], DWORD)
911 getDelay _   [] = return ([], iNFINITE)
912 getDelay now all@(d : rest) 
913   = case d of
914      Delay time m | now >= time -> do
915         putMVar m ()
916         getDelay now rest
917      DelaySTM time t | now >= time -> do
918         atomically $ writeTVar t True
919         getDelay now rest
920      _otherwise ->
921         -- delay is in millisecs for WaitForSingleObject
922         let micro_seconds = delayTime d - now
923             milli_seconds = (micro_seconds + 999) `div` 1000
924         in return (all, fromIntegral milli_seconds)
925
926 -- ToDo: this just duplicates part of System.Win32.Types, which isn't
927 -- available yet.  We should move some Win32 functionality down here,
928 -- maybe as part of the grand reorganisation of the base package...
929 type HANDLE       = Ptr ()
930 type DWORD        = Word32
931
932 iNFINITE :: DWORD
933 iNFINITE = 0xFFFFFFFF -- urgh
934
935 foreign import ccall unsafe "getIOManagerEvent" -- in the RTS (ThrIOManager.c)
936   c_getIOManagerEvent :: IO HANDLE
937
938 foreign import ccall unsafe "readIOManagerEvent" -- in the RTS (ThrIOManager.c)
939   c_readIOManagerEvent :: IO Word32
940
941 foreign import ccall unsafe "sendIOManagerEvent" -- in the RTS (ThrIOManager.c)
942   c_sendIOManagerEvent :: Word32 -> IO ()
943
944 foreign import ccall unsafe "maperrno"             -- in Win32Utils.c
945    c_maperrno :: IO ()
946
947 foreign import stdcall "WaitForSingleObject"
948    c_WaitForSingleObject :: HANDLE -> DWORD -> IO DWORD
949
950 #else
951 -- ----------------------------------------------------------------------------
952 -- Unix IO manager thread, using select()
953
954 startIOManagerThread :: IO ()
955 startIOManagerThread = do
956         allocaArray 2 $ \fds -> do
957         throwErrnoIfMinus1_ "startIOManagerThread" (c_pipe fds)
958         rd_end <- peekElemOff fds 0
959         wr_end <- peekElemOff fds 1
960         setNonBlockingFD wr_end True -- writes happen in a signal handler, we
961                                      -- don't want them to block.
962         setCloseOnExec rd_end
963         setCloseOnExec wr_end
964         writeIORef stick (fromIntegral wr_end)
965         c_setIOManagerPipe wr_end
966         _ <- forkIO $ do
967             allocaBytes sizeofFdSet   $ \readfds -> do
968             allocaBytes sizeofFdSet   $ \writefds -> do 
969             allocaBytes sizeofTimeVal $ \timeval -> do
970             service_loop (fromIntegral rd_end) readfds writefds timeval [] []
971         return ()
972
973 service_loop
974    :: Fd                -- listen to this for wakeup calls
975    -> Ptr CFdSet
976    -> Ptr CFdSet
977    -> Ptr CTimeVal
978    -> [IOReq]
979    -> [DelayReq]
980    -> IO ()
981 service_loop wakeup readfds writefds ptimeval old_reqs old_delays = do
982
983   -- pick up new IO requests
984   new_reqs <- atomicModifyIORef pendingEvents (\a -> ([],a))
985   let reqs = new_reqs ++ old_reqs
986
987   -- pick up new delay requests
988   new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
989   let  delays0 = foldr insertDelay old_delays new_delays
990
991   -- build the FDSets for select()
992   fdZero readfds
993   fdZero writefds
994   fdSet wakeup readfds
995   maxfd <- buildFdSets 0 readfds writefds reqs
996
997   -- perform the select()
998   let do_select delays = do
999           -- check the current time and wake up any thread in
1000           -- threadDelay whose timeout has expired.  Also find the
1001           -- timeout value for the select() call.
1002           now <- getUSecOfDay
1003           (delays', timeout) <- getDelay now ptimeval delays
1004
1005           res <- c_select (fromIntegral ((max wakeup maxfd)+1)) readfds writefds 
1006                         nullPtr timeout
1007           if (res == -1)
1008              then do
1009                 err <- getErrno
1010                 case err of
1011                   _ | err == eINTR ->  do_select delays'
1012                         -- EINTR: just redo the select()
1013                   _ | err == eBADF ->  return (True, delays)
1014                         -- EBADF: one of the file descriptors is closed or bad,
1015                         -- we don't know which one, so wake everyone up.
1016                   _ | otherwise    ->  throwErrno "select"
1017                         -- otherwise (ENOMEM or EINVAL) something has gone
1018                         -- wrong; report the error.
1019              else
1020                 return (False,delays')
1021
1022   (wakeup_all,delays') <- do_select delays0
1023
1024   exit <-
1025     if wakeup_all then return False
1026       else do
1027         b <- fdIsSet wakeup readfds
1028         if b == 0 
1029           then return False
1030           else alloca $ \p -> do 
1031                  warnErrnoIfMinus1_ "service_loop" $
1032                      c_read (fromIntegral wakeup) p 1
1033                  s <- peek p            
1034                  case s of
1035                   _ | s == io_MANAGER_WAKEUP -> return False
1036                   _ | s == io_MANAGER_DIE    -> return True
1037                   _ | s == io_MANAGER_SYNC   -> do
1038                        mvars <- readIORef sync
1039                        mapM_ (flip putMVar ()) mvars
1040                        return False
1041                   _ -> do
1042                        fp <- mallocForeignPtrBytes (fromIntegral sizeof_siginfo_t)
1043                        withForeignPtr fp $ \p_siginfo -> do
1044                          r <- c_read (fromIntegral wakeup) (castPtr p_siginfo)
1045                                  sizeof_siginfo_t
1046                          when (r /= fromIntegral sizeof_siginfo_t) $
1047                             error "failed to read siginfo_t"
1048                        runHandlers' fp (fromIntegral s)
1049                        return False
1050
1051   unless exit $ do
1052
1053   atomicModifyIORef prodding (\_ -> (False, ()))
1054
1055   reqs' <- if wakeup_all then do wakeupAll reqs; return []
1056                          else completeRequests reqs readfds writefds []
1057
1058   service_loop wakeup readfds writefds ptimeval reqs' delays'
1059
1060 io_MANAGER_WAKEUP, io_MANAGER_DIE, io_MANAGER_SYNC :: Word8
1061 io_MANAGER_WAKEUP = 0xff
1062 io_MANAGER_DIE    = 0xfe
1063 io_MANAGER_SYNC   = 0xfd
1064
1065 -- | the stick is for poking the IO manager with
1066 stick :: IORef Fd
1067 {-# NOINLINE stick #-}
1068 stick = unsafePerformIO (newIORef 0)
1069
1070 {-# NOINLINE sync #-}
1071 sync :: IORef [MVar ()]
1072 sync = unsafePerformIO (newIORef [])
1073
1074 -- waits for the IO manager to drain the pipe
1075 syncIOManager :: IO ()
1076 syncIOManager = do
1077   m <- newEmptyMVar
1078   atomicModifyIORef sync (\old -> (m:old,()))
1079   fd <- readIORef stick
1080   with io_MANAGER_SYNC $ \pbuf -> do 
1081     warnErrnoIfMinus1_ "syncIOManager" $ c_write (fromIntegral fd) pbuf 1
1082   takeMVar m
1083
1084 wakeupIOManager :: IO ()
1085 wakeupIOManager = do
1086   fd <- readIORef stick
1087   with io_MANAGER_WAKEUP $ \pbuf -> do 
1088     warnErrnoIfMinus1_ "wakeupIOManager" $ c_write (fromIntegral fd) pbuf 1
1089
1090 -- For the non-threaded RTS
1091 runHandlers :: Ptr Word8 -> Int -> IO ()
1092 runHandlers p_info sig = do
1093   fp <- mallocForeignPtrBytes (fromIntegral sizeof_siginfo_t)
1094   withForeignPtr fp $ \p -> do
1095     copyBytes p p_info (fromIntegral sizeof_siginfo_t)
1096     free p_info
1097   runHandlers' fp (fromIntegral sig)
1098
1099 runHandlers' :: ForeignPtr Word8 -> Signal -> IO ()
1100 runHandlers' p_info sig = do
1101   let int = fromIntegral sig
1102   withMVar signal_handlers $ \arr ->
1103       if not (inRange (boundsIOArray arr) int)
1104          then return ()
1105          else do handler <- unsafeReadIOArray arr int
1106                  case handler of
1107                     Nothing -> return ()
1108                     Just (f,_)  -> do _ <- forkIO (f p_info)
1109                                       return ()
1110
1111 warnErrnoIfMinus1_ :: Num a => String -> IO a -> IO ()
1112 warnErrnoIfMinus1_ what io
1113     = do r <- io
1114          when (r == -1) $ do
1115              errno <- getErrno
1116              str <- strerror errno >>= peekCString
1117              when (r == -1) $
1118                  debugErrLn ("Warning: " ++ what ++ " failed: " ++ str)
1119
1120 foreign import ccall unsafe "string.h" strerror :: Errno -> IO (Ptr CChar)
1121
1122 foreign import ccall "setIOManagerPipe"
1123   c_setIOManagerPipe :: CInt -> IO ()
1124
1125 foreign import ccall "__hscore_sizeof_siginfo_t"
1126   sizeof_siginfo_t :: CSize
1127
1128 type Signal = CInt
1129
1130 maxSig = 64 :: Int
1131
1132 type HandlerFun = ForeignPtr Word8 -> IO ()
1133
1134 -- Lock used to protect concurrent access to signal_handlers.  Symptom of
1135 -- this race condition is #1922, although that bug was on Windows a similar
1136 -- bug also exists on Unix.
1137 {-# NOINLINE signal_handlers #-}
1138 signal_handlers :: MVar (IOArray Int (Maybe (HandlerFun,Dynamic)))
1139 signal_handlers = unsafePerformIO $ do
1140    arr <- newIOArray (0,maxSig) Nothing
1141    m <- newMVar arr
1142    block $ do
1143      stable_ref <- newStablePtr m
1144      let ref = castStablePtrToPtr stable_ref
1145      ref2 <- getOrSetSignalHandlerStore ref
1146      if ref==ref2
1147         then return m
1148         else do freeStablePtr stable_ref
1149                 deRefStablePtr (castPtrToStablePtr ref2)
1150
1151 foreign import ccall unsafe "getOrSetSignalHandlerStore"
1152     getOrSetSignalHandlerStore :: Ptr a -> IO (Ptr a)
1153
1154 setHandler :: Signal -> Maybe (HandlerFun,Dynamic) -> IO (Maybe (HandlerFun,Dynamic))
1155 setHandler sig handler = do
1156   let int = fromIntegral sig
1157   withMVar signal_handlers $ \arr -> 
1158      if not (inRange (boundsIOArray arr) int)
1159         then error "GHC.Conc.setHandler: signal out of range"
1160         else do old <- unsafeReadIOArray arr int
1161                 unsafeWriteIOArray arr int handler
1162                 return old
1163
1164 -- -----------------------------------------------------------------------------
1165 -- IO requests
1166
1167 buildFdSets :: Fd -> Ptr CFdSet -> Ptr CFdSet -> [IOReq] -> IO Fd
1168 buildFdSets maxfd _       _        [] = return maxfd
1169 buildFdSets maxfd readfds writefds (Read fd _ : reqs)
1170   | fd >= fD_SETSIZE =  error "buildFdSets: file descriptor out of range"
1171   | otherwise        =  do
1172         fdSet fd readfds
1173         buildFdSets (max maxfd fd) readfds writefds reqs
1174 buildFdSets maxfd readfds writefds (Write fd _ : reqs)
1175   | fd >= fD_SETSIZE =  error "buildFdSets: file descriptor out of range"
1176   | otherwise        =  do
1177         fdSet fd writefds
1178         buildFdSets (max maxfd fd) readfds writefds reqs
1179
1180 completeRequests :: [IOReq] -> Ptr CFdSet -> Ptr CFdSet -> [IOReq]
1181                  -> IO [IOReq]
1182 completeRequests [] _ _ reqs' = return reqs'
1183 completeRequests (Read fd m : reqs) readfds writefds reqs' = do
1184   b <- fdIsSet fd readfds
1185   if b /= 0
1186     then do putMVar m (); completeRequests reqs readfds writefds reqs'
1187     else completeRequests reqs readfds writefds (Read fd m : reqs')
1188 completeRequests (Write fd m : reqs) readfds writefds reqs' = do
1189   b <- fdIsSet fd writefds
1190   if b /= 0
1191     then do putMVar m (); completeRequests reqs readfds writefds reqs'
1192     else completeRequests reqs readfds writefds (Write fd m : reqs')
1193
1194 wakeupAll :: [IOReq] -> IO ()
1195 wakeupAll [] = return ()
1196 wakeupAll (Read  _ m : reqs) = do putMVar m (); wakeupAll reqs
1197 wakeupAll (Write _ m : reqs) = do putMVar m (); wakeupAll reqs
1198
1199 waitForReadEvent :: Fd -> IO ()
1200 waitForReadEvent fd = do
1201   m <- newEmptyMVar
1202   atomicModifyIORef pendingEvents (\xs -> (Read fd m : xs, ()))
1203   prodServiceThread
1204   takeMVar m
1205
1206 waitForWriteEvent :: Fd -> IO ()
1207 waitForWriteEvent fd = do
1208   m <- newEmptyMVar
1209   atomicModifyIORef pendingEvents (\xs -> (Write fd m : xs, ()))
1210   prodServiceThread
1211   takeMVar m
1212
1213 -- -----------------------------------------------------------------------------
1214 -- Delays
1215
1216 -- Walk the queue of pending delays, waking up any that have passed
1217 -- and return the smallest delay to wait for.  The queue of pending
1218 -- delays is kept ordered.
1219 getDelay :: USecs -> Ptr CTimeVal -> [DelayReq] -> IO ([DelayReq], Ptr CTimeVal)
1220 getDelay _   _        [] = return ([],nullPtr)
1221 getDelay now ptimeval all@(d : rest) 
1222   = case d of
1223      Delay time m | now >= time -> do
1224         putMVar m ()
1225         getDelay now ptimeval rest
1226      DelaySTM time t | now >= time -> do
1227         atomically $ writeTVar t True
1228         getDelay now ptimeval rest
1229      _otherwise -> do
1230         setTimevalTicks ptimeval (delayTime d - now)
1231         return (all,ptimeval)
1232
1233 data CTimeVal
1234
1235 foreign import ccall unsafe "sizeofTimeVal"
1236   sizeofTimeVal :: Int
1237
1238 foreign import ccall unsafe "setTimevalTicks" 
1239   setTimevalTicks :: Ptr CTimeVal -> USecs -> IO ()
1240
1241 {- 
1242   On Win32 we're going to have a single Pipe, and a
1243   waitForSingleObject with the delay time.  For signals, we send a
1244   byte down the pipe just like on Unix.
1245 -}
1246
1247 -- ----------------------------------------------------------------------------
1248 -- select() interface
1249
1250 -- ToDo: move to System.Posix.Internals?
1251
1252 data CFdSet
1253
1254 foreign import ccall safe "__hscore_select"
1255   c_select :: CInt -> Ptr CFdSet -> Ptr CFdSet -> Ptr CFdSet -> Ptr CTimeVal
1256            -> IO CInt
1257
1258 foreign import ccall unsafe "hsFD_SETSIZE"
1259   c_fD_SETSIZE :: CInt
1260
1261 fD_SETSIZE :: Fd
1262 fD_SETSIZE = fromIntegral c_fD_SETSIZE
1263
1264 foreign import ccall unsafe "hsFD_ISSET"
1265   c_fdIsSet :: CInt -> Ptr CFdSet -> IO CInt
1266
1267 fdIsSet :: Fd -> Ptr CFdSet -> IO CInt
1268 fdIsSet (Fd fd) fdset = c_fdIsSet fd fdset
1269
1270 foreign import ccall unsafe "hsFD_SET"
1271   c_fdSet :: CInt -> Ptr CFdSet -> IO ()
1272
1273 fdSet :: Fd -> Ptr CFdSet -> IO ()
1274 fdSet (Fd fd) fdset = c_fdSet fd fdset
1275
1276 foreign import ccall unsafe "hsFD_ZERO"
1277   fdZero :: Ptr CFdSet -> IO ()
1278
1279 foreign import ccall unsafe "sizeof_fd_set"
1280   sizeofFdSet :: Int
1281
1282 #endif
1283
1284 reportStackOverflow :: IO ()
1285 reportStackOverflow = callStackOverflowHook
1286
1287 reportError :: SomeException -> IO ()
1288 reportError ex = do
1289    handler <- getUncaughtExceptionHandler
1290    handler ex
1291
1292 -- SUP: Are the hooks allowed to re-enter Haskell land?  If so, remove
1293 -- the unsafe below.
1294 foreign import ccall unsafe "stackOverflow"
1295         callStackOverflowHook :: IO ()
1296
1297 {-# NOINLINE uncaughtExceptionHandler #-}
1298 uncaughtExceptionHandler :: IORef (SomeException -> IO ())
1299 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
1300    where
1301       defaultHandler :: SomeException -> IO ()
1302       defaultHandler se@(SomeException ex) = do
1303          (hFlush stdout) `catchAny` (\ _ -> return ())
1304          let msg = case cast ex of
1305                Just Deadlock -> "no threads to run:  infinite loop or deadlock?"
1306                _ -> case cast ex of
1307                     Just (ErrorCall s) -> s
1308                     _                  -> showsPrec 0 se ""
1309          withCString "%s" $ \cfmt ->
1310           withCString msg $ \cmsg ->
1311             errorBelch cfmt cmsg
1312
1313 -- don't use errorBelch() directly, because we cannot call varargs functions
1314 -- using the FFI.
1315 foreign import ccall unsafe "HsBase.h errorBelch2"
1316    errorBelch :: CString -> CString -> IO ()
1317
1318 setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO ()
1319 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
1320
1321 getUncaughtExceptionHandler :: IO (SomeException -> IO ())
1322 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler
1323
1324 \end{code}