{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns, NoImplicitPrelude #-}

module GHC.Event.Thread
    ( getSystemEventManager
    , getSystemTimerManager
    , ensureIOManagerIsRunning
    , ioManagerCapabilitiesChanged
    , threadWaitRead
    , threadWaitWrite
    , threadWaitReadSTM
    , threadWaitWriteSTM
    , closeFdWith
    , threadDelay
    , registerDelay
    , blockedOnBadFD -- used by RTS
    ) where
-- TODO: Use new Windows I/O manager
import Control.Exception (finally, SomeException, toException)
import Data.Foldable (forM_, mapM_, sequence_)
import Data.IORef (IORef, newIORef, readIORef, writeIORef, atomicWriteIORef)
import Data.Maybe (fromMaybe)
import Data.Tuple (snd)
import Foreign.C.Error (eBADF, errnoToIOError)
import Foreign.C.Types (CInt(..), CUInt(..))
import Foreign.Ptr (Ptr)
import GHC.Base
import GHC.List (zipWith, zipWith3)
import GHC.Conc.Sync (TVar, ThreadId, ThreadStatus(..), atomically, forkIO,
                      labelThread, modifyMVar_, withMVar, newTVar, sharedCAF,
                      getNumCapabilities, threadCapability, myThreadId, forkOn,
                      threadStatus, writeTVar, newTVarIO, readTVar, retry,
                      throwSTM, STM, yield)
import GHC.IO (mask_, uninterruptibleMask_, onException)
import GHC.IO.Exception (ioError)
import GHC.IOArray (IOArray, newIOArray, readIOArray, writeIOArray,
                    boundsIOArray)
import GHC.MVar (MVar, newEmptyMVar, newMVar, putMVar, takeMVar)
import GHC.Event.Control (controlWriteFd)
import GHC.Event.Internal (eventIs, evtClose)
import GHC.Event.Manager (Event, EventManager, evtRead, evtWrite, loop,
                             new, registerFd, unregisterFd_)
import qualified GHC.Event.Manager as M
import qualified GHC.Event.TimerManager as TM
import GHC.Ix (inRange)
import GHC.Num ((-), (+))
import GHC.Real (fromIntegral)
import GHC.Show (showSignedInt)
import System.IO.Unsafe (unsafePerformIO)
import System.Posix.Types (Fd)

-- | Suspends the current thread for a given number of microseconds
-- (GHC only).
--
-- There is no guarantee that the thread will be rescheduled promptly
-- when the delay has expired, but the thread will never continue to
-- run /earlier/ than specified.
threadDelay :: Int -> IO ()
threadDelay :: Int -> IO ()
threadDelay Int
usecs = forall a. IO a -> IO a
mask_ forall a b. (a -> b) -> a -> b
$ do
  TimerManager
mgr <- IO TimerManager
getSystemTimerManager
  MVar ()
m <- forall a. IO (MVar a)
newEmptyMVar
  TimeoutKey
reg <- TimerManager -> Int -> IO () -> IO TimeoutKey
TM.registerTimeout TimerManager
mgr Int
usecs (forall a. MVar a -> a -> IO ()
putMVar MVar ()
m ())
  forall a. MVar a -> IO a
takeMVar MVar ()
m forall a b. IO a -> IO b -> IO a
`onException` TimerManager -> TimeoutKey -> IO ()
TM.unregisterTimeout TimerManager
mgr TimeoutKey
reg

-- | Set the value of returned TVar to True after a given number of
-- microseconds. The caveats associated with threadDelay also apply.
--
registerDelay :: Int -> IO (TVar Bool)
registerDelay :: Int -> IO (TVar Bool)
registerDelay Int
usecs = do
  TVar Bool
t <- forall a. STM a -> IO a
atomically forall a b. (a -> b) -> a -> b
$ forall a. a -> STM (TVar a)
newTVar Bool
False
  TimerManager
mgr <- IO TimerManager
getSystemTimerManager
  TimeoutKey
_ <- TimerManager -> Int -> IO () -> IO TimeoutKey
TM.registerTimeout TimerManager
mgr Int
usecs forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. STM a -> IO a
atomically forall a b. (a -> b) -> a -> b
$ forall a. TVar a -> a -> STM ()
writeTVar TVar Bool
t Bool
True
  forall (m :: * -> *) a. Monad m => a -> m a
return TVar Bool
t

-- | Block the current thread until data is available to read from the
-- given file descriptor.
--
-- This will throw an 'Prelude.IOError' if the file descriptor was closed
-- while this thread was blocked.  To safely close a file descriptor
-- that has been used with 'threadWaitRead', use 'closeFdWith'.
threadWaitRead :: Fd -> IO ()
threadWaitRead :: Fd -> IO ()
threadWaitRead = Event -> Fd -> IO ()
threadWait Event
evtRead
{-# INLINE threadWaitRead #-}

-- | Block the current thread until the given file descriptor can
-- accept data to write.
--
-- This will throw an 'Prelude.IOError' if the file descriptor was closed
-- while this thread was blocked.  To safely close a file descriptor
-- that has been used with 'threadWaitWrite', use 'closeFdWith'.
threadWaitWrite :: Fd -> IO ()
threadWaitWrite :: Fd -> IO ()
threadWaitWrite = Event -> Fd -> IO ()
threadWait Event
evtWrite
{-# INLINE threadWaitWrite #-}

-- | Close a file descriptor in a concurrency-safe way.
--
-- Any threads that are blocked on the file descriptor via
-- 'threadWaitRead' or 'threadWaitWrite' will be unblocked by having
-- IO exceptions thrown.
closeFdWith :: (Fd -> IO ())        -- ^ Action that performs the close.
            -> Fd                   -- ^ File descriptor to close.
            -> IO ()
closeFdWith :: (Fd -> IO ()) -> Fd -> IO ()
closeFdWith Fd -> IO ()
close Fd
fd = IO ()
close_loop
  where
    finish :: EventManager -> IntTable [FdData] -> IO b -> IO b
finish EventManager
mgr IntTable [FdData]
table IO b
cbApp = forall a. MVar a -> a -> IO ()
putMVar (EventManager -> Fd -> MVar (IntTable [FdData])
M.callbackTableVar EventManager
mgr Fd
fd) IntTable [FdData]
table forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> IO b
cbApp
    zipWithM :: (a -> b -> m a) -> [a] -> [b] -> m [a]
zipWithM a -> b -> m a
f [a]
xs [b]
ys = forall (m :: * -> *) a. Monad m => [m a] -> m [a]
sequence (forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith a -> b -> m a
f [a]
xs [b]
ys)
      -- The array inside 'eventManager' can be swapped out at any time, see
      -- 'ioManagerCapabilitiesChanged'. See #21651. We detect this case by
      -- checking the array bounds before and after. When such a swap has
      -- happened we cleanup and try again
    close_loop :: IO ()
close_loop = do
      IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray <- forall a. IORef a -> IO a
readIORef IORef (IOArray Int (Maybe (ThreadId, EventManager)))
eventManager
      let ema_bounds :: (Int, Int)
ema_bounds@(Int
low, Int
high) = forall i e. IOArray i e -> (i, i)
boundsIOArray IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray
      [EventManager]
mgrs <- forall a b c. (a -> b -> c) -> b -> a -> c
flip forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM [Int
low..Int
high] forall a b. (a -> b) -> a -> b
$ \Int
i -> do
        Just (ThreadId
_,!EventManager
mgr) <- forall i e. Ix i => IOArray i e -> i -> IO e
readIOArray IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray Int
i
        forall (m :: * -> *) a. Monad m => a -> m a
return EventManager
mgr

      -- 'takeMVar', and 'M.closeFd_' might block, although for a very short time.
      -- To make 'closeFdWith' safe in presence of asynchronous exceptions we have
      -- to use uninterruptible mask.
      forall (m :: * -> *) a. Monad m => m (m a) -> m a
join forall a b. (a -> b) -> a -> b
$ forall a. IO a -> IO a
uninterruptibleMask_ forall a b. (a -> b) -> a -> b
$ do
        [IntTable [FdData]]
tables <- forall a b c. (a -> b -> c) -> b -> a -> c
flip forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM [EventManager]
mgrs forall a b. (a -> b) -> a -> b
$ \EventManager
mgr -> forall a. MVar a -> IO a
takeMVar forall a b. (a -> b) -> a -> b
$ EventManager -> Fd -> MVar (IntTable [FdData])
M.callbackTableVar EventManager
mgr Fd
fd
        (Int, Int)
new_ema_bounds <- forall i e. IOArray i e -> (i, i)
boundsIOArray forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` forall a. IORef a -> IO a
readIORef IORef (IOArray Int (Maybe (ThreadId, EventManager)))
eventManager
        -- Here we exploit Note [The eventManager Array]
        if (Int, Int)
new_ema_bounds forall a. Eq a => a -> a -> Bool
/= (Int, Int)
ema_bounds
          then do
            -- the array has been modified.
            -- mgrs still holds the right EventManagers, by the Note.
            -- new_ema_bounds must be larger than ema_bounds, by the note.
            -- return the MVars we took and try again
            forall (t :: * -> *) (m :: * -> *) a.
(Foldable t, Monad m) =>
t (m a) -> m ()
sequence_ forall a b. (a -> b) -> a -> b
$ forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith (\EventManager
mgr IntTable [FdData]
table -> forall {b}. EventManager -> IntTable [FdData] -> IO b -> IO b
finish EventManager
mgr IntTable [FdData]
table (forall (f :: * -> *) a. Applicative f => a -> f a
pure ())) [EventManager]
mgrs [IntTable [FdData]]
tables
            forall (f :: * -> *) a. Applicative f => a -> f a
pure IO ()
close_loop
          else do
            -- We surely have taken all the appropriate MVars. Even if the array
            -- has been swapped, our mgrs is still correct.
            -- Remove the Fd from all callback tables, close the Fd, and run all
            -- callbacks.
            [IO ()]
cbApps <- forall {m :: * -> *} {a} {b} {a}.
Monad m =>
(a -> b -> m a) -> [a] -> [b] -> m [a]
zipWithM (\EventManager
mgr IntTable [FdData]
table -> EventManager -> IntTable [FdData] -> Fd -> IO (IO ())
M.closeFd_ EventManager
mgr IntTable [FdData]
table Fd
fd) [EventManager]
mgrs [IntTable [FdData]]
tables
            Fd -> IO ()
close Fd
fd forall a b. IO a -> IO b -> IO a
`finally` forall (t :: * -> *) (m :: * -> *) a.
(Foldable t, Monad m) =>
t (m a) -> m ()
sequence_ (forall a b c d. (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith3 forall {b}. EventManager -> IntTable [FdData] -> IO b -> IO b
finish [EventManager]
mgrs [IntTable [FdData]]
tables [IO ()]
cbApps)
            forall (f :: * -> *) a. Applicative f => a -> f a
pure (forall (f :: * -> *) a. Applicative f => a -> f a
pure ())

threadWait :: Event -> Fd -> IO ()
threadWait :: Event -> Fd -> IO ()
threadWait Event
evt Fd
fd = forall a. IO a -> IO a
mask_ forall a b. (a -> b) -> a -> b
$ do
  MVar Event
m <- forall a. IO (MVar a)
newEmptyMVar
  EventManager
mgr <- IO EventManager
getSystemEventManager_
  FdKey
reg <- EventManager -> IOCallback -> Fd -> Event -> Lifetime -> IO FdKey
registerFd EventManager
mgr (\FdKey
_ Event
e -> forall a. MVar a -> a -> IO ()
putMVar MVar Event
m Event
e) Fd
fd Event
evt Lifetime
M.OneShot
  Event
evt' <- forall a. MVar a -> IO a
takeMVar MVar Event
m forall a b. IO a -> IO b -> IO a
`onException` EventManager -> FdKey -> IO Bool
unregisterFd_ EventManager
mgr FdKey
reg
  if Event
evt' Event -> Event -> Bool
`eventIs` Event
evtClose
    then forall a. IOError -> IO a
ioError forall a b. (a -> b) -> a -> b
$ String -> Errno -> Maybe Handle -> Maybe String -> IOError
errnoToIOError String
"threadWait" Errno
eBADF forall a. Maybe a
Nothing forall a. Maybe a
Nothing
    else forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- used at least by RTS in 'select()' IO manager backend
blockedOnBadFD :: SomeException
blockedOnBadFD :: SomeException
blockedOnBadFD = forall e. Exception e => e -> SomeException
toException forall a b. (a -> b) -> a -> b
$ String -> Errno -> Maybe Handle -> Maybe String -> IOError
errnoToIOError String
"awaitEvent" Errno
eBADF forall a. Maybe a
Nothing forall a. Maybe a
Nothing

threadWaitSTM :: Event -> Fd -> IO (STM (), IO ())
threadWaitSTM :: Event -> Fd -> IO (STM (), IO ())
threadWaitSTM Event
evt Fd
fd = forall a. IO a -> IO a
mask_ forall a b. (a -> b) -> a -> b
$ do
  TVar (Maybe Event)
m <- forall a. a -> IO (TVar a)
newTVarIO forall a. Maybe a
Nothing
  EventManager
mgr <- IO EventManager
getSystemEventManager_
  FdKey
reg <- EventManager -> IOCallback -> Fd -> Event -> Lifetime -> IO FdKey
registerFd EventManager
mgr (\FdKey
_ Event
e -> forall a. STM a -> IO a
atomically (forall a. TVar a -> a -> STM ()
writeTVar TVar (Maybe Event)
m (forall a. a -> Maybe a
Just Event
e))) Fd
fd Event
evt Lifetime
M.OneShot
  let waitAction :: STM ()
waitAction =
        do Maybe Event
mevt <- forall a. TVar a -> STM a
readTVar TVar (Maybe Event)
m
           case Maybe Event
mevt of
             Maybe Event
Nothing -> forall a. STM a
retry
             Just Event
evt' ->
               if Event
evt' Event -> Event -> Bool
`eventIs` Event
evtClose
               then forall e a. Exception e => e -> STM a
throwSTM forall a b. (a -> b) -> a -> b
$ String -> Errno -> Maybe Handle -> Maybe String -> IOError
errnoToIOError String
"threadWaitSTM" Errno
eBADF forall a. Maybe a
Nothing forall a. Maybe a
Nothing
               else forall (m :: * -> *) a. Monad m => a -> m a
return ()
  forall (m :: * -> *) a. Monad m => a -> m a
return (STM ()
waitAction, EventManager -> FdKey -> IO Bool
unregisterFd_ EventManager
mgr FdKey
reg forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> forall (m :: * -> *) a. Monad m => a -> m a
return ())

-- | Allows a thread to use an STM action to wait for a file descriptor to be readable.
-- The STM action will retry until the file descriptor has data ready.
-- The second element of the return value pair is an IO action that can be used
-- to deregister interest in the file descriptor.
--
-- The STM action will throw an 'Prelude.IOError' if the file descriptor was closed
-- while the STM action is being executed.  To safely close a file descriptor
-- that has been used with 'threadWaitReadSTM', use 'closeFdWith'.
threadWaitReadSTM :: Fd -> IO (STM (), IO ())
threadWaitReadSTM :: Fd -> IO (STM (), IO ())
threadWaitReadSTM = Event -> Fd -> IO (STM (), IO ())
threadWaitSTM Event
evtRead
{-# INLINE threadWaitReadSTM #-}

-- | Allows a thread to use an STM action to wait until a file descriptor can accept a write.
-- The STM action will retry while the file until the given file descriptor can accept a write.
-- The second element of the return value pair is an IO action that can be used to deregister
-- interest in the file descriptor.
--
-- The STM action will throw an 'Prelude.IOError' if the file descriptor was closed
-- while the STM action is being executed.  To safely close a file descriptor
-- that has been used with 'threadWaitWriteSTM', use 'closeFdWith'.
threadWaitWriteSTM :: Fd -> IO (STM (), IO ())
threadWaitWriteSTM :: Fd -> IO (STM (), IO ())
threadWaitWriteSTM = Event -> Fd -> IO (STM (), IO ())
threadWaitSTM Event
evtWrite
{-# INLINE threadWaitWriteSTM #-}


-- | Retrieve the system event manager for the capability on which the
-- calling thread is running.
--
-- This function always returns 'Just' the current thread's event manager
-- when using the threaded RTS and 'Nothing' otherwise.
getSystemEventManager :: IO (Maybe EventManager)
getSystemEventManager :: IO (Maybe EventManager)
getSystemEventManager = do
  ThreadId
t <- IO ThreadId
myThreadId
  IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray <- forall a. IORef a -> IO a
readIORef IORef (IOArray Int (Maybe (ThreadId, EventManager)))
eventManager
  let r :: (Int, Int)
r = forall i e. IOArray i e -> (i, i)
boundsIOArray IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray
  (Int
cap, Bool
_) <- ThreadId -> IO (Int, Bool)
threadCapability ThreadId
t
  -- It is possible that we've just increased the number of capabilities and the
  -- new EventManager has not yet been constructed by
  -- 'ioManagerCapabilitiesChanged'. We expect this to happen very rarely.
  -- T21561 exercises this.
  -- Two options to proceed:
  --  1) return the EventManager for capability 0. This is guaranteed to exist,
  --     and "shouldn't" cause any correctness issues.
  --  2) Busy wait, with or without a call to 'yield'. This can't deadlock,
  --     because we must be on a brand capability and there must be a call to
  --     'ioManagerCapabilitiesChanged' pending.
  --
  -- We take the second option, with the yield, judging it the most robust.
  if Bool -> Bool
not (forall a. Ix a => (a, a) -> a -> Bool
inRange (Int, Int)
r Int
cap)
    then IO ()
yield forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> IO (Maybe EventManager)
getSystemEventManager
    else forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b. (a, b) -> b
snd forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` forall i e. Ix i => IOArray i e -> i -> IO e
readIOArray IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray Int
cap

getSystemEventManager_ :: IO EventManager
getSystemEventManager_ :: IO EventManager
getSystemEventManager_ = do
  Just EventManager
mgr <- IO (Maybe EventManager)
getSystemEventManager
  forall (m :: * -> *) a. Monad m => a -> m a
return EventManager
mgr
{-# INLINE getSystemEventManager_ #-}

foreign import ccall unsafe "getOrSetSystemEventThreadEventManagerStore"
    getOrSetSystemEventThreadEventManagerStore :: Ptr a -> IO (Ptr a)

-- Note [The eventManager Array]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- A mutable array holding the current EventManager for each capability
-- An entry is Nothing only while the eventmanagers are initialised, see
-- 'startIOManagerThread' and 'ioManagerCapabilitiesChanged'.
-- The 'ThreadId' at array position 'cap'  will have been 'forkOn'ed capabality
-- 'cap'.
-- The array will be swapped with newer arrays when the number of capabilities
-- changes(via 'setNumCapabilities'). However:
--   * the size of the arrays will never decrease; and
--   * The 'EventManager's in the array are not replaced with other
--     'EventManager' constructors.
--
-- This is a similar strategy as the rts uses for it's
-- capabilities array (n_capabilities is the size of the array,
-- enabled_capabilities' is the number of active capabilities).
eventManager :: IORef (IOArray Int (Maybe (ThreadId, EventManager)))
eventManager :: IORef (IOArray Int (Maybe (ThreadId, EventManager)))
eventManager = forall a. IO a -> a
unsafePerformIO forall a b. (a -> b) -> a -> b
$ do
    Int
numCaps <- IO Int
getNumCapabilities
    IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray <- forall i e. Ix i => (i, i) -> e -> IO (IOArray i e)
newIOArray (Int
0, Int
numCaps forall a. Num a => a -> a -> a
- Int
1) forall a. Maybe a
Nothing
    IORef (IOArray Int (Maybe (ThreadId, EventManager)))
em <- forall a. a -> IO (IORef a)
newIORef IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray
    forall a. a -> (Ptr a -> IO (Ptr a)) -> IO a
sharedCAF IORef (IOArray Int (Maybe (ThreadId, EventManager)))
em forall a. Ptr a -> IO (Ptr a)
getOrSetSystemEventThreadEventManagerStore
{-# NOINLINE eventManager #-}

numEnabledEventManagers :: IORef Int
numEnabledEventManagers :: IORef Int
numEnabledEventManagers = forall a. IO a -> a
unsafePerformIO forall a b. (a -> b) -> a -> b
$ forall a. a -> IO (IORef a)
newIORef Int
0
{-# NOINLINE numEnabledEventManagers #-}

foreign import ccall unsafe "getOrSetSystemEventThreadIOManagerThreadStore"
    getOrSetSystemEventThreadIOManagerThreadStore :: Ptr a -> IO (Ptr a)

-- | The ioManagerLock protects the 'eventManager' value:
-- Only one thread at a time can start or shutdown event managers.
{-# NOINLINE ioManagerLock #-}
ioManagerLock :: MVar ()
ioManagerLock :: MVar ()
ioManagerLock = forall a. IO a -> a
unsafePerformIO forall a b. (a -> b) -> a -> b
$ do
   MVar ()
m <- forall a. a -> IO (MVar a)
newMVar ()
   forall a. a -> (Ptr a -> IO (Ptr a)) -> IO a
sharedCAF MVar ()
m forall a. Ptr a -> IO (Ptr a)
getOrSetSystemEventThreadIOManagerThreadStore

getSystemTimerManager :: IO TM.TimerManager
getSystemTimerManager :: IO TimerManager
getSystemTimerManager =
  forall a. a -> Maybe a -> a
fromMaybe forall {a}. a
err forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` forall a. IORef a -> IO a
readIORef IORef (Maybe TimerManager)
timerManager
    where
      err :: a
err = forall a. HasCallStack => String -> a
error String
"GHC.Event.Thread.getSystemTimerManager: the TimerManager requires linking against the threaded runtime"

foreign import ccall unsafe "getOrSetSystemTimerThreadEventManagerStore"
    getOrSetSystemTimerThreadEventManagerStore :: Ptr a -> IO (Ptr a)

timerManager :: IORef (Maybe TM.TimerManager)
timerManager :: IORef (Maybe TimerManager)
timerManager = forall a. IO a -> a
unsafePerformIO forall a b. (a -> b) -> a -> b
$ do
    IORef (Maybe TimerManager)
em <- forall a. a -> IO (IORef a)
newIORef forall a. Maybe a
Nothing
    forall a. a -> (Ptr a -> IO (Ptr a)) -> IO a
sharedCAF IORef (Maybe TimerManager)
em forall a. Ptr a -> IO (Ptr a)
getOrSetSystemTimerThreadEventManagerStore
{-# NOINLINE timerManager #-}

foreign import ccall unsafe "getOrSetSystemTimerThreadIOManagerThreadStore"
    getOrSetSystemTimerThreadIOManagerThreadStore :: Ptr a -> IO (Ptr a)

{-# NOINLINE timerManagerThreadVar #-}
timerManagerThreadVar :: MVar (Maybe ThreadId)
timerManagerThreadVar :: MVar (Maybe ThreadId)
timerManagerThreadVar = forall a. IO a -> a
unsafePerformIO forall a b. (a -> b) -> a -> b
$ do
   MVar (Maybe ThreadId)
m <- forall a. a -> IO (MVar a)
newMVar forall a. Maybe a
Nothing
   forall a. a -> (Ptr a -> IO (Ptr a)) -> IO a
sharedCAF MVar (Maybe ThreadId)
m forall a. Ptr a -> IO (Ptr a)
getOrSetSystemTimerThreadIOManagerThreadStore

ensureIOManagerIsRunning :: IO ()
ensureIOManagerIsRunning :: IO ()
ensureIOManagerIsRunning
  | Bool -> Bool
not Bool
threaded = forall (m :: * -> *) a. Monad m => a -> m a
return ()
  | Bool
otherwise = do
      IO ()
startIOManagerThreads
      IO ()
startTimerManagerThread

startIOManagerThreads :: IO ()
startIOManagerThreads :: IO ()
startIOManagerThreads =
  forall a b. MVar a -> (a -> IO b) -> IO b
withMVar MVar ()
ioManagerLock forall a b. (a -> b) -> a -> b
$ \()
_ -> do
    IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray <- forall a. IORef a -> IO a
readIORef IORef (IOArray Int (Maybe (ThreadId, EventManager)))
eventManager
    let (Int
_, Int
high) = forall i e. IOArray i e -> (i, i)
boundsIOArray IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray
    forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (IOArray Int (Maybe (ThreadId, EventManager)) -> Int -> IO ()
startIOManagerThread IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray) [Int
0..Int
high]
    forall a. IORef a -> a -> IO ()
writeIORef IORef Int
numEnabledEventManagers (Int
highforall a. Num a => a -> a -> a
+Int
1)

show_int :: Int -> String
show_int :: Int -> String
show_int Int
i = Int -> Int -> ShowS
showSignedInt Int
0 Int
i String
""

restartPollLoop :: EventManager -> Int -> IO ThreadId
restartPollLoop :: EventManager -> Int -> IO ThreadId
restartPollLoop EventManager
mgr Int
i = do
  EventManager -> IO ()
M.release EventManager
mgr
  !ThreadId
t <- Int -> IO () -> IO ThreadId
forkOn Int
i forall a b. (a -> b) -> a -> b
$ EventManager -> IO ()
loop EventManager
mgr
  ThreadId -> String -> IO ()
labelThread ThreadId
t (String
"IOManager on cap " forall a. [a] -> [a] -> [a]
++ Int -> String
show_int Int
i)
  forall (m :: * -> *) a. Monad m => a -> m a
return ThreadId
t

startIOManagerThread :: IOArray Int (Maybe (ThreadId, EventManager))
                        -> Int
                        -> IO ()
startIOManagerThread :: IOArray Int (Maybe (ThreadId, EventManager)) -> Int -> IO ()
startIOManagerThread IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray Int
i = do
  let create :: IO ()
create = do
        !EventManager
mgr <- IO EventManager
new
        !ThreadId
t <- Int -> IO () -> IO ThreadId
forkOn Int
i forall a b. (a -> b) -> a -> b
$ do
                CUInt -> CInt -> IO ()
c_setIOManagerControlFd
                  (forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i)
                  (forall a b. (Integral a, Num b) => a -> b
fromIntegral forall a b. (a -> b) -> a -> b
$ Control -> Fd
controlWriteFd forall a b. (a -> b) -> a -> b
$ EventManager -> Control
M.emControl EventManager
mgr)
                EventManager -> IO ()
loop EventManager
mgr
        ThreadId -> String -> IO ()
labelThread ThreadId
t (String
"IOManager on cap " forall a. [a] -> [a] -> [a]
++ Int -> String
show_int Int
i)
        forall i e. Ix i => IOArray i e -> i -> e -> IO ()
writeIOArray IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray Int
i (forall a. a -> Maybe a
Just (ThreadId
t,EventManager
mgr))
  Maybe (ThreadId, EventManager)
old <- forall i e. Ix i => IOArray i e -> i -> IO e
readIOArray IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray Int
i
  case Maybe (ThreadId, EventManager)
old of
    Maybe (ThreadId, EventManager)
Nothing     -> IO ()
create
    Just (ThreadId
t,EventManager
em) -> do
      ThreadStatus
s <- ThreadId -> IO ThreadStatus
threadStatus ThreadId
t
      case ThreadStatus
s of
        ThreadStatus
ThreadFinished -> IO ()
create
        ThreadStatus
ThreadDied     -> do
          -- Sanity check: if the thread has died, there is a chance
          -- that event manager is still alive. This could happened during
          -- the fork, for example. In this case we should clean up
          -- open pipes and everything else related to the event manager.
          -- See #4449
          CUInt -> CInt -> IO ()
c_setIOManagerControlFd (forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
i) (-CInt
1)
          EventManager -> IO ()
M.cleanup EventManager
em
          IO ()
create
        ThreadStatus
_other         -> forall (m :: * -> *) a. Monad m => a -> m a
return ()

startTimerManagerThread :: IO ()
startTimerManagerThread :: IO ()
startTimerManagerThread = forall a. MVar a -> (a -> IO a) -> IO ()
modifyMVar_ MVar (Maybe ThreadId)
timerManagerThreadVar forall a b. (a -> b) -> a -> b
$ \Maybe ThreadId
old -> do
  let create :: IO (Maybe ThreadId)
create = do
        !TimerManager
mgr <- IO TimerManager
TM.new
        CInt -> IO ()
c_setTimerManagerControlFd
          (forall a b. (Integral a, Num b) => a -> b
fromIntegral forall a b. (a -> b) -> a -> b
$ Control -> Fd
controlWriteFd forall a b. (a -> b) -> a -> b
$ TimerManager -> Control
TM.emControl TimerManager
mgr)
        forall a. IORef a -> a -> IO ()
writeIORef IORef (Maybe TimerManager)
timerManager forall a b. (a -> b) -> a -> b
$ forall a. a -> Maybe a
Just TimerManager
mgr
        !ThreadId
t <- IO () -> IO ThreadId
forkIO forall a b. (a -> b) -> a -> b
$ TimerManager -> IO ()
TM.loop TimerManager
mgr
        ThreadId -> String -> IO ()
labelThread ThreadId
t String
"TimerManager"
        forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a. a -> Maybe a
Just ThreadId
t
  case Maybe ThreadId
old of
    Maybe ThreadId
Nothing            -> IO (Maybe ThreadId)
create
    st :: Maybe ThreadId
st@(Just ThreadId
t) -> do
      ThreadStatus
s <- ThreadId -> IO ThreadStatus
threadStatus ThreadId
t
      case ThreadStatus
s of
        ThreadStatus
ThreadFinished -> IO (Maybe ThreadId)
create
        ThreadStatus
ThreadDied     -> do
          -- Sanity check: if the thread has died, there is a chance
          -- that event manager is still alive. This could happened during
          -- the fork, for example. In this case we should clean up
          -- open pipes and everything else related to the event manager.
          -- See #4449
          Maybe TimerManager
mem <- forall a. IORef a -> IO a
readIORef IORef (Maybe TimerManager)
timerManager
          ()
_ <- case Maybe TimerManager
mem of
                 Maybe TimerManager
Nothing -> forall (m :: * -> *) a. Monad m => a -> m a
return ()
                 Just TimerManager
em -> do CInt -> IO ()
c_setTimerManagerControlFd (-CInt
1)
                               TimerManager -> IO ()
TM.cleanup TimerManager
em
          IO (Maybe ThreadId)
create
        ThreadStatus
_other         -> forall (m :: * -> *) a. Monad m => a -> m a
return Maybe ThreadId
st

foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool

ioManagerCapabilitiesChanged :: IO ()
ioManagerCapabilitiesChanged :: IO ()
ioManagerCapabilitiesChanged =
  forall a b. MVar a -> (a -> IO b) -> IO b
withMVar MVar ()
ioManagerLock forall a b. (a -> b) -> a -> b
$ \()
_ -> do
    Int
new_n_caps <- IO Int
getNumCapabilities
    Int
numEnabled <- forall a. IORef a -> IO a
readIORef IORef Int
numEnabledEventManagers
    forall a. IORef a -> a -> IO ()
writeIORef IORef Int
numEnabledEventManagers Int
new_n_caps
    IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray <- forall a. IORef a -> IO a
readIORef IORef (IOArray Int (Maybe (ThreadId, EventManager)))
eventManager
    let (Int
_, Int
high) = forall i e. IOArray i e -> (i, i)
boundsIOArray IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray
    let old_n_caps :: Int
old_n_caps = Int
high forall a. Num a => a -> a -> a
+ Int
1
    if Int
new_n_caps forall a. Ord a => a -> a -> Bool
> Int
old_n_caps
      then do IOArray Int (Maybe (ThreadId, EventManager))
new_eventManagerArray <- forall i e. Ix i => (i, i) -> e -> IO (IOArray i e)
newIOArray (Int
0, Int
new_n_caps forall a. Num a => a -> a -> a
- Int
1) forall a. Maybe a
Nothing

              -- copy the existing values into the new array:
              forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [Int
0..Int
high] forall a b. (a -> b) -> a -> b
$ \Int
i -> do
                Just (ThreadId
tid,EventManager
mgr) <- forall i e. Ix i => IOArray i e -> i -> IO e
readIOArray IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray Int
i
                if Int
i forall a. Ord a => a -> a -> Bool
< Int
numEnabled
                  then forall i e. Ix i => IOArray i e -> i -> e -> IO ()
writeIOArray IOArray Int (Maybe (ThreadId, EventManager))
new_eventManagerArray Int
i (forall a. a -> Maybe a
Just (ThreadId
tid,EventManager
mgr))
                  else do ThreadId
tid' <- EventManager -> Int -> IO ThreadId
restartPollLoop EventManager
mgr Int
i
                          forall i e. Ix i => IOArray i e -> i -> e -> IO ()
writeIOArray IOArray Int (Maybe (ThreadId, EventManager))
new_eventManagerArray Int
i (forall a. a -> Maybe a
Just (ThreadId
tid',EventManager
mgr))

              -- create new IO managers for the new caps:
              forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [Int
old_n_caps..Int
new_n_capsforall a. Num a => a -> a -> a
-Int
1] forall a b. (a -> b) -> a -> b
$
                IOArray Int (Maybe (ThreadId, EventManager)) -> Int -> IO ()
startIOManagerThread IOArray Int (Maybe (ThreadId, EventManager))
new_eventManagerArray

              -- update the event manager array reference:
              forall a. IORef a -> a -> IO ()
atomicWriteIORef IORef (IOArray Int (Maybe (ThreadId, EventManager)))
eventManager IOArray Int (Maybe (ThreadId, EventManager))
new_eventManagerArray
              -- We need an atomic write here because 'eventManager' is accessed
              -- unsynchronized in 'getSystemEventManager' and 'closeFdWith'
      else forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
new_n_caps forall a. Ord a => a -> a -> Bool
> Int
numEnabled) forall a b. (a -> b) -> a -> b
$
            forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [Int
numEnabled..Int
new_n_capsforall a. Num a => a -> a -> a
-Int
1] forall a b. (a -> b) -> a -> b
$ \Int
i -> do
              Just (ThreadId
_,EventManager
mgr) <- forall i e. Ix i => IOArray i e -> i -> IO e
readIOArray IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray Int
i
              ThreadId
tid <- EventManager -> Int -> IO ThreadId
restartPollLoop EventManager
mgr Int
i
              forall i e. Ix i => IOArray i e -> i -> e -> IO ()
writeIOArray IOArray Int (Maybe (ThreadId, EventManager))
eventManagerArray Int
i (forall a. a -> Maybe a
Just (ThreadId
tid,EventManager
mgr))

-- Used to tell the RTS how it can send messages to the I/O manager.
foreign import ccall unsafe "setIOManagerControlFd"
   c_setIOManagerControlFd :: CUInt -> CInt -> IO ()

foreign import ccall unsafe "setTimerManagerControlFd"
   c_setTimerManagerControlFd :: CInt -> IO ()