fix comment
[ghc-base.git] / GHC / Conc.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.Conc
6 -- Copyright   :  (c) The University of Glasgow, 1994-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC extensions)
12 --
13 -- Basic concurrency stuff.
14 -- 
15 -----------------------------------------------------------------------------
16
17 -- No: #hide, because bits of this module are exposed by the stm package.
18 -- However, we don't want this module to be the home location for the
19 -- bits it exports, we'd rather have Control.Concurrent and the other
20 -- higher level modules be the home.  Hence:
21
22 #include "Typeable.h"
23
24 -- #not-home
25 module GHC.Conc
26         ( ThreadId(..)
27
28         -- * Forking and suchlike
29         , forkIO        -- :: IO a -> IO ThreadId
30         , forkOnIO      -- :: Int -> IO a -> IO ThreadId
31         , numCapabilities -- :: Int
32         , childHandler  -- :: Exception -> IO ()
33         , myThreadId    -- :: IO ThreadId
34         , killThread    -- :: ThreadId -> IO ()
35         , throwTo       -- :: ThreadId -> Exception -> IO ()
36         , par           -- :: a -> b -> b
37         , pseq          -- :: a -> b -> b
38         , yield         -- :: IO ()
39         , labelThread   -- :: ThreadId -> String -> IO ()
40
41         -- * Waiting
42         , threadDelay           -- :: Int -> IO ()
43         , registerDelay         -- :: Int -> IO (TVar Bool)
44         , threadWaitRead        -- :: Int -> IO ()
45         , threadWaitWrite       -- :: Int -> IO ()
46
47         -- * MVars
48         , MVar          -- abstract
49         , newMVar       -- :: a -> IO (MVar a)
50         , newEmptyMVar  -- :: IO (MVar a)
51         , takeMVar      -- :: MVar a -> IO a
52         , putMVar       -- :: MVar a -> a -> IO ()
53         , tryTakeMVar   -- :: MVar a -> IO (Maybe a)
54         , tryPutMVar    -- :: MVar a -> a -> IO Bool
55         , isEmptyMVar   -- :: MVar a -> IO Bool
56         , addMVarFinalizer -- :: MVar a -> IO () -> IO ()
57
58         -- * TVars
59         , STM           -- abstract
60         , atomically    -- :: STM a -> IO a
61         , retry         -- :: STM a
62         , orElse        -- :: STM a -> STM a -> STM a
63         , catchSTM      -- :: STM a -> (Exception -> STM a) -> STM a
64         , alwaysSucceeds -- :: STM a -> STM ()
65         , always        -- :: STM Bool -> STM ()
66         , TVar          -- abstract
67         , newTVar       -- :: a -> STM (TVar a)
68         , newTVarIO     -- :: a -> STM (TVar a)
69         , readTVar      -- :: TVar a -> STM a
70         , writeTVar     -- :: a -> TVar a -> STM ()
71         , unsafeIOToSTM -- :: IO a -> STM a
72
73         -- * Miscellaneous
74 #ifdef mingw32_HOST_OS
75         , asyncRead     -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
76         , asyncWrite    -- :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
77         , asyncDoProc   -- :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
78
79         , asyncReadBA   -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
80         , asyncWriteBA  -- :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int, Int)
81 #endif
82
83         , ensureIOManagerIsRunning
84         ) where
85
86 import System.Posix.Types
87 #ifndef mingw32_HOST_OS
88 import System.Posix.Internals
89 #endif
90 import Foreign
91 import Foreign.C
92
93 #ifndef __HADDOCK__
94 import {-# SOURCE #-} GHC.TopHandler ( reportError, reportStackOverflow )
95 #endif
96
97 import Data.Maybe
98
99 import GHC.Base
100 import GHC.IOBase
101 import GHC.Num          ( Num(..) )
102 import GHC.Real         ( fromIntegral, div )
103 #ifndef mingw32_HOST_OS
104 import GHC.Base         ( Int(..) )
105 #endif
106 import GHC.Exception    ( catchException, Exception(..), AsyncException(..) )
107 import GHC.Pack         ( packCString# )
108 import GHC.Ptr          ( Ptr(..), plusPtr, FunPtr(..) )
109 import GHC.STRef
110 import GHC.Show         ( Show(..), showString )
111 import Data.Typeable
112
113 infixr 0 `par`, `pseq`
114 \end{code}
115
116 %************************************************************************
117 %*                                                                      *
118 \subsection{@ThreadId@, @par@, and @fork@}
119 %*                                                                      *
120 %************************************************************************
121
122 \begin{code}
123 data ThreadId = ThreadId ThreadId# deriving( Typeable )
124 -- ToDo: data ThreadId = ThreadId (Weak ThreadId#)
125 -- But since ThreadId# is unlifted, the Weak type must use open
126 -- type variables.
127 {- ^
128 A 'ThreadId' is an abstract type representing a handle to a thread.
129 'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where
130 the 'Ord' instance implements an arbitrary total ordering over
131 'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued
132 'ThreadId' to string form; showing a 'ThreadId' value is occasionally
133 useful when debugging or diagnosing the behaviour of a concurrent
134 program.
135
136 /Note/: in GHC, if you have a 'ThreadId', you essentially have
137 a pointer to the thread itself.  This means the thread itself can\'t be
138 garbage collected until you drop the 'ThreadId'.
139 This misfeature will hopefully be corrected at a later date.
140
141 /Note/: Hugs does not provide any operations on other threads;
142 it defines 'ThreadId' as a synonym for ().
143 -}
144
145 instance Show ThreadId where
146    showsPrec d t = 
147         showString "ThreadId " . 
148         showsPrec d (getThreadId (id2TSO t))
149
150 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt
151
152 id2TSO :: ThreadId -> ThreadId#
153 id2TSO (ThreadId t) = t
154
155 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> CInt
156 -- Returns -1, 0, 1
157
158 cmpThread :: ThreadId -> ThreadId -> Ordering
159 cmpThread t1 t2 = 
160    case cmp_thread (id2TSO t1) (id2TSO t2) of
161       -1 -> LT
162       0  -> EQ
163       _  -> GT -- must be 1
164
165 instance Eq ThreadId where
166    t1 == t2 = 
167       case t1 `cmpThread` t2 of
168          EQ -> True
169          _  -> False
170
171 instance Ord ThreadId where
172    compare = cmpThread
173
174 {- |
175 This sparks off a new thread to run the 'IO' computation passed as the
176 first argument, and returns the 'ThreadId' of the newly created
177 thread.
178
179 The new thread will be a lightweight thread; if you want to use a foreign
180 library that uses thread-local storage, use 'forkOS' instead.
181 -}
182 forkIO :: IO () -> IO ThreadId
183 forkIO action = IO $ \ s -> 
184    case (fork# action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
185  where
186   action_plus = catchException action childHandler
187
188 forkOnIO :: Int -> IO () -> IO ThreadId
189 forkOnIO (I# cpu) action = IO $ \ s -> 
190    case (forkOn# cpu action_plus s) of (# s1, id #) -> (# s1, ThreadId id #)
191  where
192   action_plus = catchException action childHandler
193
194 -- | the value passed to the @+RTS -N@ flag.  This is the number of
195 -- Haskell threads that can run truly simultaneously at any given
196 -- time, and is typically set to the number of physical CPU cores on
197 -- the machine.
198 numCapabilities :: Int
199 numCapabilities = unsafePerformIO $  do 
200                     n <- peek n_capabilities
201                     return (fromIntegral n)
202
203 foreign import ccall "&n_capabilities" n_capabilities :: Ptr CInt
204
205 childHandler :: Exception -> IO ()
206 childHandler err = catchException (real_handler err) childHandler
207
208 real_handler :: Exception -> IO ()
209 real_handler ex =
210   case ex of
211         -- ignore thread GC and killThread exceptions:
212         BlockedOnDeadMVar            -> return ()
213         BlockedIndefinitely          -> return ()
214         AsyncException ThreadKilled  -> return ()
215
216         -- report all others:
217         AsyncException StackOverflow -> reportStackOverflow
218         other       -> reportError other
219
220 {- | 'killThread' terminates the given thread (GHC only).
221 Any work already done by the thread isn\'t
222 lost: the computation is suspended until required by another thread.
223 The memory used by the thread will be garbage collected if it isn\'t
224 referenced from anywhere.  The 'killThread' function is defined in
225 terms of 'throwTo':
226
227 > killThread tid = throwTo tid (AsyncException ThreadKilled)
228
229 -}
230 killThread :: ThreadId -> IO ()
231 killThread tid = throwTo tid (AsyncException ThreadKilled)
232
233 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
234
235 'throwTo' does not return until the exception has been raised in the
236 target thread. 
237 The calling thread can thus be certain that the target
238 thread has received the exception.  This is a useful property to know
239 when dealing with race conditions: eg. if there are two threads that
240 can kill each other, it is guaranteed that only one of the threads
241 will get to kill the other.
242
243 If the target thread is currently making a foreign call, then the
244 exception will not be raised (and hence 'throwTo' will not return)
245 until the call has completed.  This is the case regardless of whether
246 the call is inside a 'block' or not.
247
248 Important note: the behaviour of 'throwTo' differs from that described in
249 the paper "Asynchronous exceptions in Haskell" 
250 (<http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm>).
251 In the paper, 'throwTo' is non-blocking; but the library implementation adopts
252 a more synchronous design in which 'throwTo' does not return until the exception
253 is received by the target thread.  The trade-off is discussed in Section 8 of the paper.
254 Like any blocking operation, 'throwTo' is therefore interruptible (see Section 4.3 of
255 the paper).
256
257 There is currently no guarantee that the exception delivered by 'throwTo' will be
258 delivered at the first possible opportunity.  In particular, if a thread may 
259 unblock and then re-block exceptions (using 'unblock' and 'block') without receiving
260 a pending 'throwTo'.  This is arguably undesirable behaviour.
261
262  -}
263 throwTo :: ThreadId -> Exception -> IO ()
264 throwTo (ThreadId id) ex = IO $ \ s ->
265    case (killThread# id ex s) of s1 -> (# s1, () #)
266
267 -- | Returns the 'ThreadId' of the calling thread (GHC only).
268 myThreadId :: IO ThreadId
269 myThreadId = IO $ \s ->
270    case (myThreadId# s) of (# s1, id #) -> (# s1, ThreadId id #)
271
272
273 -- |The 'yield' action allows (forces, in a co-operative multitasking
274 -- implementation) a context-switch to any other currently runnable
275 -- threads (if any), and is occasionally useful when implementing
276 -- concurrency abstractions.
277 yield :: IO ()
278 yield = IO $ \s -> 
279    case (yield# s) of s1 -> (# s1, () #)
280
281 {- | 'labelThread' stores a string as identifier for this thread if
282 you built a RTS with debugging support. This identifier will be used in
283 the debugging output to make distinction of different threads easier
284 (otherwise you only have the thread state object\'s address in the heap).
285
286 Other applications like the graphical Concurrent Haskell Debugger
287 (<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload
288 'labelThread' for their purposes as well.
289 -}
290
291 labelThread :: ThreadId -> String -> IO ()
292 labelThread (ThreadId t) str = IO $ \ s ->
293    let ps  = packCString# str
294        adr = byteArrayContents# ps in
295      case (labelThread# t adr s) of s1 -> (# s1, () #)
296
297 --      Nota Bene: 'pseq' used to be 'seq'
298 --                 but 'seq' is now defined in PrelGHC
299 --
300 -- "pseq" is defined a bit weirdly (see below)
301 --
302 -- The reason for the strange "lazy" call is that
303 -- it fools the compiler into thinking that pseq  and par are non-strict in
304 -- their second argument (even if it inlines pseq at the call site).
305 -- If it thinks pseq is strict in "y", then it often evaluates
306 -- "y" before "x", which is totally wrong.  
307
308 {-# INLINE pseq  #-}
309 pseq :: a -> b -> b
310 pseq  x y = x `seq` lazy y
311
312 {-# INLINE par  #-}
313 par :: a -> b -> b
314 par  x y = case (par# x) of { _ -> lazy y }
315 \end{code}
316
317
318 %************************************************************************
319 %*                                                                      *
320 \subsection[stm]{Transactional heap operations}
321 %*                                                                      *
322 %************************************************************************
323
324 TVars are shared memory locations which support atomic memory
325 transactions.
326
327 \begin{code}
328 -- |A monad supporting atomic memory transactions.
329 newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))
330
331 unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
332 unSTM (STM a) = a
333
334 INSTANCE_TYPEABLE1(STM,stmTc,"STM")
335
336 instance  Functor STM where
337    fmap f x = x >>= (return . f)
338
339 instance  Monad STM  where
340     {-# INLINE return #-}
341     {-# INLINE (>>)   #-}
342     {-# INLINE (>>=)  #-}
343     m >> k      = thenSTM m k
344     return x    = returnSTM x
345     m >>= k     = bindSTM m k
346
347 bindSTM :: STM a -> (a -> STM b) -> STM b
348 bindSTM (STM m) k = STM ( \s ->
349   case m s of 
350     (# new_s, a #) -> unSTM (k a) new_s
351   )
352
353 thenSTM :: STM a -> STM b -> STM b
354 thenSTM (STM m) k = STM ( \s ->
355   case m s of 
356     (# new_s, a #) -> unSTM k new_s
357   )
358
359 returnSTM :: a -> STM a
360 returnSTM x = STM (\s -> (# s, x #))
361
362 -- | Unsafely performs IO in the STM monad.
363 unsafeIOToSTM :: IO a -> STM a
364 unsafeIOToSTM (IO m) = STM m
365
366 -- |Perform a series of STM actions atomically.
367 --
368 -- You cannot use 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'. 
369 -- Any attempt to do so will result in a runtime error.  (Reason: allowing
370 -- this would effectively allow a transaction inside a transaction, depending
371 -- on exactly when the thunk is evaluated.)
372 --
373 -- However, see 'newTVarIO', which can be called inside 'unsafePerformIO',
374 -- and which allows top-level TVars to be allocated.
375
376 atomically :: STM a -> IO a
377 atomically (STM m) = IO (\s -> (atomically# m) s )
378
379 -- |Retry execution of the current memory transaction because it has seen
380 -- values in TVars which mean that it should not continue (e.g. the TVars
381 -- represent a shared buffer that is now empty).  The implementation may
382 -- block the thread until one of the TVars that it has read from has been
383 -- udpated. (GHC only)
384 retry :: STM a
385 retry = STM $ \s# -> retry# s#
386
387 -- |Compose two alternative STM actions (GHC only).  If the first action
388 -- completes without retrying then it forms the result of the orElse.
389 -- Otherwise, if the first action retries, then the second action is
390 -- tried in its place.  If both actions retry then the orElse as a
391 -- whole retries.
392 orElse :: STM a -> STM a -> STM a
393 orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
394
395 -- |Exception handling within STM actions.
396 catchSTM :: STM a -> (Exception -> STM a) -> STM a
397 catchSTM (STM m) k = STM $ \s -> catchSTM# m (\ex -> unSTM (k ex)) s
398
399 -- | Low-level primitive on which always and alwaysSucceeds are built.
400 -- checkInv differs form these in that (i) the invariant is not 
401 -- checked when checkInv is called, only at the end of this and
402 -- subsequent transcations, (ii) the invariant failure is indicated
403 -- by raising an exception.
404 checkInv :: STM a -> STM ()
405 checkInv (STM m) = STM (\s -> (check# m) s)
406
407 -- | alwaysSucceeds adds a new invariant that must be true when passed
408 -- to alwaysSucceeds, at the end of the current transaction, and at
409 -- the end of every subsequent transaction.  If it fails at any
410 -- of those points then the transaction violating it is aborted
411 -- and the exception raised by the invariant is propagated.
412 alwaysSucceeds :: STM a -> STM ()
413 alwaysSucceeds i = do ( do i ; retry ) `orElse` ( return () ) 
414                       checkInv i
415
416 -- | always is a variant of alwaysSucceeds in which the invariant is
417 -- expressed as an STM Bool action that must return True.  Returning
418 -- False or raising an exception are both treated as invariant failures.
419 always :: STM Bool -> STM ()
420 always i = alwaysSucceeds ( do v <- i
421                                if (v) then return () else ( error "Transacional invariant violation" ) )
422
423 -- |Shared memory locations that support atomic memory transactions.
424 data TVar a = TVar (TVar# RealWorld a)
425
426 INSTANCE_TYPEABLE1(TVar,tvarTc,"TVar")
427
428 instance Eq (TVar a) where
429         (TVar tvar1#) == (TVar tvar2#) = sameTVar# tvar1# tvar2#
430
431 -- |Create a new TVar holding a value supplied
432 newTVar :: a -> STM (TVar a)
433 newTVar val = STM $ \s1# ->
434     case newTVar# val s1# of
435          (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
436
437 -- |@IO@ version of 'newTVar'.  This is useful for creating top-level
438 -- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using
439 -- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
440 -- possible.
441 newTVarIO :: a -> IO (TVar a)
442 newTVarIO val = IO $ \s1# ->
443     case newTVar# val s1# of
444          (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
445
446 -- |Return the current value stored in a TVar
447 readTVar :: TVar a -> STM a
448 readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
449
450 -- |Write the supplied value into a TVar
451 writeTVar :: TVar a -> a -> STM ()
452 writeTVar (TVar tvar#) val = STM $ \s1# ->
453     case writeTVar# tvar# val s1# of
454          s2# -> (# s2#, () #)
455   
456 \end{code}
457
458 %************************************************************************
459 %*                                                                      *
460 \subsection[mvars]{M-Structures}
461 %*                                                                      *
462 %************************************************************************
463
464 M-Vars are rendezvous points for concurrent threads.  They begin
465 empty, and any attempt to read an empty M-Var blocks.  When an M-Var
466 is written, a single blocked thread may be freed.  Reading an M-Var
467 toggles its state from full back to empty.  Therefore, any value
468 written to an M-Var may only be read once.  Multiple reads and writes
469 are allowed, but there must be at least one read between any two
470 writes.
471
472 \begin{code}
473 --Defined in IOBase to avoid cycle: data MVar a = MVar (SynchVar# RealWorld a)
474
475 -- |Create an 'MVar' which is initially empty.
476 newEmptyMVar  :: IO (MVar a)
477 newEmptyMVar = IO $ \ s# ->
478     case newMVar# s# of
479          (# s2#, svar# #) -> (# s2#, MVar svar# #)
480
481 -- |Create an 'MVar' which contains the supplied value.
482 newMVar :: a -> IO (MVar a)
483 newMVar value =
484     newEmptyMVar        >>= \ mvar ->
485     putMVar mvar value  >>
486     return mvar
487
488 -- |Return the contents of the 'MVar'.  If the 'MVar' is currently
489 -- empty, 'takeMVar' will wait until it is full.  After a 'takeMVar', 
490 -- the 'MVar' is left empty.
491 -- 
492 -- There are two further important properties of 'takeMVar':
493 --
494 --   * 'takeMVar' is single-wakeup.  That is, if there are multiple
495 --     threads blocked in 'takeMVar', and the 'MVar' becomes full,
496 --     only one thread will be woken up.  The runtime guarantees that
497 --     the woken thread completes its 'takeMVar' operation.
498 --
499 --   * When multiple threads are blocked on an 'MVar', they are
500 --     woken up in FIFO order.  This is useful for providing
501 --     fairness properties of abstractions built using 'MVar's.
502 --
503 takeMVar :: MVar a -> IO a
504 takeMVar (MVar mvar#) = IO $ \ s# -> takeMVar# mvar# s#
505
506 -- |Put a value into an 'MVar'.  If the 'MVar' is currently full,
507 -- 'putMVar' will wait until it becomes empty.
508 --
509 -- There are two further important properties of 'putMVar':
510 --
511 --   * 'putMVar' is single-wakeup.  That is, if there are multiple
512 --     threads blocked in 'putMVar', and the 'MVar' becomes empty,
513 --     only one thread will be woken up.  The runtime guarantees that
514 --     the woken thread completes its 'putMVar' operation.
515 --
516 --   * When multiple threads are blocked on an 'MVar', they are
517 --     woken up in FIFO order.  This is useful for providing
518 --     fairness properties of abstractions built using 'MVar's.
519 --
520 putMVar  :: MVar a -> a -> IO ()
521 putMVar (MVar mvar#) x = IO $ \ s# ->
522     case putMVar# mvar# x s# of
523         s2# -> (# s2#, () #)
524
525 -- |A non-blocking version of 'takeMVar'.  The 'tryTakeMVar' function
526 -- returns immediately, with 'Nothing' if the 'MVar' was empty, or
527 -- @'Just' a@ if the 'MVar' was full with contents @a@.  After 'tryTakeMVar',
528 -- the 'MVar' is left empty.
529 tryTakeMVar :: MVar a -> IO (Maybe a)
530 tryTakeMVar (MVar m) = IO $ \ s ->
531     case tryTakeMVar# m s of
532         (# s, 0#, _ #) -> (# s, Nothing #)      -- MVar is empty
533         (# s, _,  a #) -> (# s, Just a  #)      -- MVar is full
534
535 -- |A non-blocking version of 'putMVar'.  The 'tryPutMVar' function
536 -- attempts to put the value @a@ into the 'MVar', returning 'True' if
537 -- it was successful, or 'False' otherwise.
538 tryPutMVar  :: MVar a -> a -> IO Bool
539 tryPutMVar (MVar mvar#) x = IO $ \ s# ->
540     case tryPutMVar# mvar# x s# of
541         (# s, 0# #) -> (# s, False #)
542         (# s, _  #) -> (# s, True #)
543
544 -- |Check whether a given 'MVar' is empty.
545 --
546 -- Notice that the boolean value returned  is just a snapshot of
547 -- the state of the MVar. By the time you get to react on its result,
548 -- the MVar may have been filled (or emptied) - so be extremely
549 -- careful when using this operation.   Use 'tryTakeMVar' instead if possible.
550 isEmptyMVar :: MVar a -> IO Bool
551 isEmptyMVar (MVar mv#) = IO $ \ s# -> 
552     case isEmptyMVar# mv# s# of
553         (# s2#, flg #) -> (# s2#, not (flg ==# 0#) #)
554
555 -- |Add a finalizer to an 'MVar' (GHC only).  See "Foreign.ForeignPtr" and
556 -- "System.Mem.Weak" for more about finalizers.
557 addMVarFinalizer :: MVar a -> IO () -> IO ()
558 addMVarFinalizer (MVar m) finalizer = 
559   IO $ \s -> case mkWeak# m () finalizer s of { (# s1, w #) -> (# s1, () #) }
560 \end{code}
561
562
563 %************************************************************************
564 %*                                                                      *
565 \subsection{Thread waiting}
566 %*                                                                      *
567 %************************************************************************
568
569 \begin{code}
570 #ifdef mingw32_HOST_OS
571
572 -- Note: threadWaitRead and threadWaitWrite aren't really functional
573 -- on Win32, but left in there because lib code (still) uses them (the manner
574 -- in which they're used doesn't cause problems on a Win32 platform though.)
575
576 asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
577 asyncRead  (I# fd) (I# isSock) (I# len) (Ptr buf) =
578   IO $ \s -> case asyncRead# fd isSock len buf s of 
579                (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
580
581 asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)
582 asyncWrite  (I# fd) (I# isSock) (I# len) (Ptr buf) =
583   IO $ \s -> case asyncWrite# fd isSock len buf s of 
584                (# s, len#, err# #) -> (# s, (I# len#, I# err#) #)
585
586 asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int
587 asyncDoProc (FunPtr proc) (Ptr param) = 
588     -- the 'length' value is ignored; simplifies implementation of
589     -- the async*# primops to have them all return the same result.
590   IO $ \s -> case asyncDoProc# proc param s  of 
591                (# s, len#, err# #) -> (# s, I# err# #)
592
593 -- to aid the use of these primops by the IO Handle implementation,
594 -- provide the following convenience funs:
595
596 -- this better be a pinned byte array!
597 asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
598 asyncReadBA fd isSock len off bufB = 
599   asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
600   
601 asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)
602 asyncWriteBA fd isSock len off bufB = 
603   asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)
604
605 #endif
606
607 -- -----------------------------------------------------------------------------
608 -- Thread IO API
609
610 -- | Block the current thread until data is available to read on the
611 -- given file descriptor (GHC only).
612 threadWaitRead :: Fd -> IO ()
613 threadWaitRead fd
614 #ifndef mingw32_HOST_OS
615   | threaded  = waitForReadEvent fd
616 #endif
617   | otherwise = IO $ \s -> 
618         case fromIntegral fd of { I# fd# ->
619         case waitRead# fd# s of { s -> (# s, () #)
620         }}
621
622 -- | Block the current thread until data can be written to the
623 -- given file descriptor (GHC only).
624 threadWaitWrite :: Fd -> IO ()
625 threadWaitWrite fd
626 #ifndef mingw32_HOST_OS
627   | threaded  = waitForWriteEvent fd
628 #endif
629   | otherwise = IO $ \s -> 
630         case fromIntegral fd of { I# fd# ->
631         case waitWrite# fd# s of { s -> (# s, () #)
632         }}
633
634 -- | Suspends the current thread for a given number of microseconds
635 -- (GHC only).
636 --
637 -- There is no guarantee that the thread will be rescheduled promptly
638 -- when the delay has expired, but the thread will never continue to
639 -- run /earlier/ than specified.
640 --
641 threadDelay :: Int -> IO ()
642 threadDelay time
643   | threaded  = waitForDelayEvent time
644   | otherwise = IO $ \s -> 
645         case fromIntegral time of { I# time# ->
646         case delay# time# s of { s -> (# s, () #)
647         }}
648
649
650 -- | Set the value of returned TVar to True after a given number of
651 -- microseconds. The caveats associated with threadDelay also apply.
652 --
653 registerDelay :: Int -> IO (TVar Bool)
654 registerDelay usecs 
655   | threaded = waitForDelayEventSTM usecs
656   | otherwise = error "registerDelay: requires -threaded"
657
658 foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
659
660 waitForDelayEvent :: Int -> IO ()
661 waitForDelayEvent usecs = do
662   m <- newEmptyMVar
663   target <- calculateTarget usecs
664   atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))
665   prodServiceThread
666   takeMVar m
667
668 -- Delays for use in STM
669 waitForDelayEventSTM :: Int -> IO (TVar Bool)
670 waitForDelayEventSTM usecs = do
671    t <- atomically $ newTVar False
672    target <- calculateTarget usecs
673    atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ()))
674    prodServiceThread
675    return t  
676     
677 calculateTarget :: Int -> IO USecs
678 calculateTarget usecs = do
679     now <- getUSecOfDay
680     return $ now + (fromIntegral usecs)
681
682
683 -- ----------------------------------------------------------------------------
684 -- Threaded RTS implementation of threadWaitRead, threadWaitWrite, threadDelay
685
686 -- In the threaded RTS, we employ a single IO Manager thread to wait
687 -- for all outstanding IO requests (threadWaitRead,threadWaitWrite)
688 -- and delays (threadDelay).  
689 --
690 -- We can do this because in the threaded RTS the IO Manager can make
691 -- a non-blocking call to select(), so we don't have to do select() in
692 -- the scheduler as we have to in the non-threaded RTS.  We get performance
693 -- benefits from doing it this way, because we only have to restart the select()
694 -- when a new request arrives, rather than doing one select() each time
695 -- around the scheduler loop.  Furthermore, the scheduler can be simplified
696 -- by not having to check for completed IO requests.
697
698 -- Issues, possible problems:
699 --
700 --      - we might want bound threads to just do the blocking
701 --        operation rather than communicating with the IO manager
702 --        thread.  This would prevent simgle-threaded programs which do
703 --        IO from requiring multiple OS threads.  However, it would also
704 --        prevent bound threads waiting on IO from being killed or sent
705 --        exceptions.
706 --
707 --      - Apprently exec() doesn't work on Linux in a multithreaded program.
708 --        I couldn't repeat this.
709 --
710 --      - How do we handle signal delivery in the multithreaded RTS?
711 --
712 --      - forkProcess will kill the IO manager thread.  Let's just
713 --        hope we don't need to do any blocking IO between fork & exec.
714
715 #ifndef mingw32_HOST_OS
716 data IOReq
717   = Read   {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
718   | Write  {-# UNPACK #-} !Fd {-# UNPACK #-} !(MVar ())
719 #endif
720
721 data DelayReq
722   = Delay    {-# UNPACK #-} !USecs {-# UNPACK #-} !(MVar ())
723   | DelaySTM {-# UNPACK #-} !USecs {-# UNPACK #-} !(TVar Bool)
724
725 #ifndef mingw32_HOST_OS
726 pendingEvents :: IORef [IOReq]
727 #endif
728 pendingDelays :: IORef [DelayReq]
729         -- could use a strict list or array here
730 {-# NOINLINE pendingEvents #-}
731 {-# NOINLINE pendingDelays #-}
732 (pendingEvents,pendingDelays) = unsafePerformIO $ do
733   startIOManagerThread
734   reqs <- newIORef []
735   dels <- newIORef []
736   return (reqs, dels)
737         -- the first time we schedule an IO request, the service thread
738         -- will be created (cool, huh?)
739
740 ensureIOManagerIsRunning :: IO ()
741 ensureIOManagerIsRunning 
742   | threaded  = seq pendingEvents $ return ()
743   | otherwise = return ()
744
745 insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]
746 insertDelay d [] = [d]
747 insertDelay d1 ds@(d2 : rest)
748   | delayTime d1 <= delayTime d2 = d1 : ds
749   | otherwise                    = d2 : insertDelay d1 rest
750
751 delayTime :: DelayReq -> USecs
752 delayTime (Delay t _) = t
753 delayTime (DelaySTM t _) = t
754
755 type USecs = Word64
756
757 -- XXX: move into GHC.IOBase from Data.IORef?
758 atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b
759 atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s
760
761 foreign import ccall unsafe "getUSecOfDay" 
762   getUSecOfDay :: IO USecs
763
764 prodding :: IORef Bool
765 {-# NOINLINE prodding #-}
766 prodding = unsafePerformIO (newIORef False)
767
768 prodServiceThread :: IO ()
769 prodServiceThread = do
770   was_set <- atomicModifyIORef prodding (\a -> (True,a))
771   if (not (was_set)) then wakeupIOManager else return ()
772
773 #ifdef mingw32_HOST_OS
774 -- ----------------------------------------------------------------------------
775 -- Windows IO manager thread
776
777 startIOManagerThread :: IO ()
778 startIOManagerThread = do
779   wakeup <- c_getIOManagerEvent
780   forkIO $ service_loop wakeup []
781   return ()
782
783 service_loop :: HANDLE          -- read end of pipe
784              -> [DelayReq]      -- current delay requests
785              -> IO ()
786
787 service_loop wakeup old_delays = do
788   -- pick up new delay requests
789   new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
790   let  delays = foldr insertDelay old_delays new_delays
791
792   now <- getUSecOfDay
793   (delays', timeout) <- getDelay now delays
794
795   r <- c_WaitForSingleObject wakeup timeout
796   case r of
797     0xffffffff -> do c_maperrno; throwErrno "service_loop"
798     0 -> do
799         r <- c_readIOManagerEvent
800         exit <- 
801               case r of
802                 _ | r == io_MANAGER_WAKEUP -> return False
803                 _ | r == io_MANAGER_DIE    -> return True
804                 0 -> return False -- spurious wakeup
805                 r -> do start_console_handler (r `shiftR` 1); return False
806         if exit
807           then return ()
808           else service_cont wakeup delays'
809
810     _other -> service_cont wakeup delays' -- probably timeout        
811
812 service_cont wakeup delays = do
813   atomicModifyIORef prodding (\_ -> (False,False))
814   service_loop wakeup delays
815
816 -- must agree with rts/win32/ThrIOManager.c
817 io_MANAGER_WAKEUP = 0xffffffff :: Word32
818 io_MANAGER_DIE    = 0xfffffffe :: Word32
819
820 start_console_handler :: Word32 -> IO ()
821 start_console_handler r = do                   
822   stableptr <- peek console_handler
823   forkIO $ do io <- deRefStablePtr stableptr; io (fromIntegral r)
824   return ()
825
826 foreign import ccall "&console_handler" 
827    console_handler :: Ptr (StablePtr (CInt -> IO ()))
828
829 stick :: IORef HANDLE
830 {-# NOINLINE stick #-}
831 stick = unsafePerformIO (newIORef nullPtr)
832
833 wakeupIOManager = do 
834   hdl <- readIORef stick
835   c_sendIOManagerEvent io_MANAGER_WAKEUP
836
837 -- Walk the queue of pending delays, waking up any that have passed
838 -- and return the smallest delay to wait for.  The queue of pending
839 -- delays is kept ordered.
840 getDelay :: USecs -> [DelayReq] -> IO ([DelayReq], DWORD)
841 getDelay now [] = return ([], iNFINITE)
842 getDelay now all@(d : rest) 
843   = case d of
844      Delay time m | now >= time -> do
845         putMVar m ()
846         getDelay now rest
847      DelaySTM time t | now >= time -> do
848         atomically $ writeTVar t True
849         getDelay now rest
850      _otherwise ->
851         -- delay is in millisecs for WaitForSingleObject
852         let micro_seconds = delayTime d - now
853             milli_seconds = (micro_seconds + 999) `div` 1000
854         in return (all, fromIntegral milli_seconds)
855
856 -- ToDo: this just duplicates part of System.Win32.Types, which isn't
857 -- available yet.  We should move some Win32 functionality down here,
858 -- maybe as part of the grand reorganisation of the base package...
859 type HANDLE       = Ptr ()
860 type DWORD        = Word32
861
862 iNFINITE = 0xFFFFFFFF :: DWORD -- urgh
863
864 foreign import ccall unsafe "getIOManagerEvent" -- in the RTS (ThrIOManager.c)
865   c_getIOManagerEvent :: IO HANDLE
866
867 foreign import ccall unsafe "readIOManagerEvent" -- in the RTS (ThrIOManager.c)
868   c_readIOManagerEvent :: IO Word32
869
870 foreign import ccall unsafe "sendIOManagerEvent" -- in the RTS (ThrIOManager.c)
871   c_sendIOManagerEvent :: Word32 -> IO ()
872
873 foreign import ccall unsafe "maperrno"             -- in Win32Utils.c
874    c_maperrno :: IO ()
875
876 foreign import stdcall "WaitForSingleObject"
877    c_WaitForSingleObject :: HANDLE -> DWORD -> IO DWORD
878
879 #else
880 -- ----------------------------------------------------------------------------
881 -- Unix IO manager thread, using select()
882
883 startIOManagerThread :: IO ()
884 startIOManagerThread = do
885         allocaArray 2 $ \fds -> do
886         throwErrnoIfMinus1 "startIOManagerThread" (c_pipe fds)
887         rd_end <- peekElemOff fds 0
888         wr_end <- peekElemOff fds 1
889         writeIORef stick (fromIntegral wr_end)
890         c_setIOManagerPipe wr_end
891         forkIO $ do
892             allocaBytes sizeofFdSet   $ \readfds -> do
893             allocaBytes sizeofFdSet   $ \writefds -> do 
894             allocaBytes sizeofTimeVal $ \timeval -> do
895             service_loop (fromIntegral rd_end) readfds writefds timeval [] []
896         return ()
897
898 service_loop
899    :: Fd                -- listen to this for wakeup calls
900    -> Ptr CFdSet
901    -> Ptr CFdSet
902    -> Ptr CTimeVal
903    -> [IOReq]
904    -> [DelayReq]
905    -> IO ()
906 service_loop wakeup readfds writefds ptimeval old_reqs old_delays = do
907
908   -- pick up new IO requests
909   new_reqs <- atomicModifyIORef pendingEvents (\a -> ([],a))
910   let reqs = new_reqs ++ old_reqs
911
912   -- pick up new delay requests
913   new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))
914   let  delays = foldr insertDelay old_delays new_delays
915
916   -- build the FDSets for select()
917   fdZero readfds
918   fdZero writefds
919   fdSet wakeup readfds
920   maxfd <- buildFdSets 0 readfds writefds reqs
921
922   -- perform the select()
923   let do_select delays = do
924           -- check the current time and wake up any thread in
925           -- threadDelay whose timeout has expired.  Also find the
926           -- timeout value for the select() call.
927           now <- getUSecOfDay
928           (delays', timeout) <- getDelay now ptimeval delays
929
930           res <- c_select (fromIntegral ((max wakeup maxfd)+1)) readfds writefds 
931                         nullPtr timeout
932           if (res == -1)
933              then do
934                 err <- getErrno
935                 case err of
936                   _ | err == eINTR ->  do_select delays'
937                         -- EINTR: just redo the select()
938                   _ | err == eBADF ->  return (True, delays)
939                         -- EBADF: one of the file descriptors is closed or bad,
940                         -- we don't know which one, so wake everyone up.
941                   _ | otherwise    ->  throwErrno "select"
942                         -- otherwise (ENOMEM or EINVAL) something has gone
943                         -- wrong; report the error.
944              else
945                 return (False,delays')
946
947   (wakeup_all,delays') <- do_select delays
948
949   exit <-
950     if wakeup_all then return False
951       else do
952         b <- fdIsSet wakeup readfds
953         if b == 0 
954           then return False
955           else alloca $ \p -> do 
956                  c_read (fromIntegral wakeup) p 1; return ()
957                  s <- peek p            
958                  case s of
959                   _ | s == io_MANAGER_WAKEUP -> return False
960                   _ | s == io_MANAGER_DIE    -> return True
961                   _ -> do handler_tbl <- peek handlers
962                           sp <- peekElemOff handler_tbl (fromIntegral s)
963                           forkIO (do io <- deRefStablePtr sp; io)
964                           return False
965
966   if exit then return () else do
967
968   atomicModifyIORef prodding (\_ -> (False,False))
969
970   reqs' <- if wakeup_all then do wakeupAll reqs; return []
971                          else completeRequests reqs readfds writefds []
972
973   service_loop wakeup readfds writefds ptimeval reqs' delays'
974
975 io_MANAGER_WAKEUP = 0xff :: CChar
976 io_MANAGER_DIE    = 0xfe :: CChar
977
978 stick :: IORef Fd
979 {-# NOINLINE stick #-}
980 stick = unsafePerformIO (newIORef 0)
981
982 wakeupIOManager :: IO ()
983 wakeupIOManager = do
984   fd <- readIORef stick
985   with io_MANAGER_WAKEUP $ \pbuf -> do 
986     c_write (fromIntegral fd) pbuf 1; return ()
987
988 foreign import ccall "&signal_handlers" handlers :: Ptr (Ptr (StablePtr (IO ())))
989
990 foreign import ccall "setIOManagerPipe"
991   c_setIOManagerPipe :: CInt -> IO ()
992
993 -- -----------------------------------------------------------------------------
994 -- IO requests
995
996 buildFdSets maxfd readfds writefds [] = return maxfd
997 buildFdSets maxfd readfds writefds (Read fd m : reqs)
998   | fd >= fD_SETSIZE =  error "buildFdSets: file descriptor out of range"
999   | otherwise        =  do
1000         fdSet fd readfds
1001         buildFdSets (max maxfd fd) readfds writefds reqs
1002 buildFdSets maxfd readfds writefds (Write fd m : reqs)
1003   | fd >= fD_SETSIZE =  error "buildFdSets: file descriptor out of range"
1004   | otherwise        =  do
1005         fdSet fd writefds
1006         buildFdSets (max maxfd fd) readfds writefds reqs
1007
1008 completeRequests [] _ _ reqs' = return reqs'
1009 completeRequests (Read fd m : reqs) readfds writefds reqs' = do
1010   b <- fdIsSet fd readfds
1011   if b /= 0
1012     then do putMVar m (); completeRequests reqs readfds writefds reqs'
1013     else completeRequests reqs readfds writefds (Read fd m : reqs')
1014 completeRequests (Write fd m : reqs) readfds writefds reqs' = do
1015   b <- fdIsSet fd writefds
1016   if b /= 0
1017     then do putMVar m (); completeRequests reqs readfds writefds reqs'
1018     else completeRequests reqs readfds writefds (Write fd m : reqs')
1019
1020 wakeupAll [] = return ()
1021 wakeupAll (Read  fd m : reqs) = do putMVar m (); wakeupAll reqs
1022 wakeupAll (Write fd m : reqs) = do putMVar m (); wakeupAll reqs
1023
1024 waitForReadEvent :: Fd -> IO ()
1025 waitForReadEvent fd = do
1026   m <- newEmptyMVar
1027   atomicModifyIORef pendingEvents (\xs -> (Read fd m : xs, ()))
1028   prodServiceThread
1029   takeMVar m
1030
1031 waitForWriteEvent :: Fd -> IO ()
1032 waitForWriteEvent fd = do
1033   m <- newEmptyMVar
1034   atomicModifyIORef pendingEvents (\xs -> (Write fd m : xs, ()))
1035   prodServiceThread
1036   takeMVar m
1037
1038 -- -----------------------------------------------------------------------------
1039 -- Delays
1040
1041 -- Walk the queue of pending delays, waking up any that have passed
1042 -- and return the smallest delay to wait for.  The queue of pending
1043 -- delays is kept ordered.
1044 getDelay :: USecs -> Ptr CTimeVal -> [DelayReq] -> IO ([DelayReq], Ptr CTimeVal)
1045 getDelay now ptimeval [] = return ([],nullPtr)
1046 getDelay now ptimeval all@(d : rest) 
1047   = case d of
1048      Delay time m | now >= time -> do
1049         putMVar m ()
1050         getDelay now ptimeval rest
1051      DelaySTM time t | now >= time -> do
1052         atomically $ writeTVar t True
1053         getDelay now ptimeval rest
1054      _otherwise -> do
1055         setTimevalTicks ptimeval (delayTime d - now)
1056         return (all,ptimeval)
1057
1058 newtype CTimeVal = CTimeVal ()
1059
1060 foreign import ccall unsafe "sizeofTimeVal"
1061   sizeofTimeVal :: Int
1062
1063 foreign import ccall unsafe "setTimevalTicks" 
1064   setTimevalTicks :: Ptr CTimeVal -> USecs -> IO ()
1065
1066 {- 
1067   On Win32 we're going to have a single Pipe, and a
1068   waitForSingleObject with the delay time.  For signals, we send a
1069   byte down the pipe just like on Unix.
1070 -}
1071
1072 -- ----------------------------------------------------------------------------
1073 -- select() interface
1074
1075 -- ToDo: move to System.Posix.Internals?
1076
1077 newtype CFdSet = CFdSet ()
1078
1079 foreign import ccall safe "select"
1080   c_select :: CInt -> Ptr CFdSet -> Ptr CFdSet -> Ptr CFdSet -> Ptr CTimeVal
1081            -> IO CInt
1082
1083 foreign import ccall unsafe "hsFD_SETSIZE"
1084   c_fD_SETSIZE :: CInt
1085
1086 fD_SETSIZE :: Fd
1087 fD_SETSIZE = fromIntegral c_fD_SETSIZE
1088
1089 foreign import ccall unsafe "hsFD_CLR"
1090   c_fdClr :: CInt -> Ptr CFdSet -> IO ()
1091
1092 fdClr :: Fd -> Ptr CFdSet -> IO ()
1093 fdClr (Fd fd) fdset = c_fdClr fd fdset
1094
1095 foreign import ccall unsafe "hsFD_ISSET"
1096   c_fdIsSet :: CInt -> Ptr CFdSet -> IO CInt
1097
1098 fdIsSet :: Fd -> Ptr CFdSet -> IO CInt
1099 fdIsSet (Fd fd) fdset = c_fdIsSet fd fdset
1100
1101 foreign import ccall unsafe "hsFD_SET"
1102   c_fdSet :: CInt -> Ptr CFdSet -> IO ()
1103
1104 fdSet :: Fd -> Ptr CFdSet -> IO ()
1105 fdSet (Fd fd) fdset = c_fdSet fd fdset
1106
1107 foreign import ccall unsafe "hsFD_ZERO"
1108   fdZero :: Ptr CFdSet -> IO ()
1109
1110 foreign import ccall unsafe "sizeof_fd_set"
1111   sizeofFdSet :: Int
1112
1113 #endif
1114
1115 \end{code}