diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,7 @@
 ## 9.1401.0 -- yyyy-mm-dd
 
 * Introduce `dataToCodeQ` and `liftDataTyped`, typed variants of `dataToExpQ` and `liftData` respectively.
+* Add new `gc_sync_elapsed_ns` counter to GHC.Internal.Stats
 
 ## 9.1001.0 -- 2024-05-01
 
diff --git a/cbits/Stack.cmm b/cbits/Stack.cmm
--- a/cbits/Stack.cmm
+++ b/cbits/Stack.cmm
@@ -8,9 +8,11 @@
 // developed.
 #if defined(StgStack_marking)
 
-// Returns the next stackframe's StgStack* and offset in it. And, an indicator
-// if this frame is the last one (`hasNext` bit.)
-// (StgStack*, StgWord, StgWord) advanceStackFrameLocationzh(StgStack* stack, StgWord offsetWords)
+// Returns the next stackframe location as
+//   (# (# #) | (# StgStack*, StgWord #) #)
+// flattened to its runtime representation:
+//   (tag, StgStack*, StgWord)
+// where tag 1 means no next frame and tag 2 means the payload is present.
 advanceStackFrameLocationzh (P_ stack, W_ offsetWords) {
   W_ frameSize;
   (frameSize) = ccall stackFrameSize(stack, offsetWords);
@@ -27,27 +29,30 @@
   stackSizeInBytes = WDS(stackSize);
   stackBottom = stackSizeInBytes + stackArrayPtr;
 
+  W_ tag, newOffsetWords;
   P_ newStack;
-  W_ newOffsetWords, hasNext;
   if(nextClosurePtr < stackBottom) (likely: True) {
+    tag = 2;
     newStack = stack;
     newOffsetWords = offsetWords + frameSize;
-    hasNext = 1;
   } else {
     P_ underflowFrameStack;
     (underflowFrameStack) = ccall getUnderflowFrameStack(stack, offsetWords);
     if (underflowFrameStack == NULL) (likely: True) {
-      newStack = NULL;
-      newOffsetWords = NULL;
-      hasNext = NULL;
+      // The empty alternative still has dead payload slots in the flattened
+      // sum representation, so the pointer field must contain a valid closure
+      // pointer rather than NULL.
+      tag = 1;
+      newStack = stack;
+      newOffsetWords = 0;
     } else {
+      tag = 2;
       newStack = underflowFrameStack;
-      newOffsetWords = NULL;
-      hasNext = 1;
+      newOffsetWords = 0;
     }
   }
 
-  return (newStack, newOffsetWords, hasNext);
+  return (tag, newStack, newOffsetWords);
 }
 
 // (StgWord, StgWord) getSmallBitmapzh(StgStack* stack, StgWord offsetWords)
diff --git a/ghc-internal.cabal b/ghc-internal.cabal
--- a/ghc-internal.cabal
+++ b/ghc-internal.cabal
@@ -4,7 +4,7 @@
 name:           ghc-internal
 -- The project is ghc's version plus ghc-internal's version suffix.
 -- For example, for ghc=9.10.1, ghc-internal's version will be 9.1001.0.
-version:        9.1401.0
+version:        9.1402.0
 license:        BSD-3-Clause
 license-file:   LICENSE
 maintainer:     The GHC Developers <ghc-devs@haskell.org>
@@ -293,6 +293,7 @@
         GHC.Internal.StaticPtr
         GHC.Internal.STRef
         GHC.Internal.Show
+        GHC.Internal.STM
         GHC.Internal.Stable
         GHC.Internal.StableName
         GHC.Internal.Stack
@@ -354,7 +355,6 @@
         GHC.Internal.Types
 
     autogen-modules:
-        GHC.Internal.Prim
         GHC.Internal.PrimopWrappers
 
     other-modules:
diff --git a/src/GHC/Internal/Conc/IO.hs b/src/GHC/Internal/Conc/IO.hs
--- a/src/GHC/Internal/Conc/IO.hs
+++ b/src/GHC/Internal/Conc/IO.hs
@@ -60,6 +60,7 @@
 
 import GHC.Internal.Base
 import GHC.Internal.Conc.Sync as Sync
+import GHC.Internal.STM as STM
 import GHC.Internal.Real ( fromIntegral )
 import GHC.Internal.System.Posix.Types
 
@@ -142,17 +143,17 @@
 -- to read from a file descriptor. The second returned value
 -- is an IO action that can be used to deregister interest
 -- in the file descriptor.
-threadWaitReadSTM :: Fd -> IO (Sync.STM (), IO ())
+threadWaitReadSTM :: Fd -> IO (STM.STM (), IO ())
 threadWaitReadSTM fd
 #if !defined(mingw32_HOST_OS) && !defined(javascript_HOST_ARCH)
   | threaded  = Event.threadWaitReadSTM fd
 #endif
   | otherwise = do
-      m <- Sync.newTVarIO False
+      m <- STM.newTVarIO False
       t <- Sync.forkIO $ do
         threadWaitRead fd
-        Sync.atomically $ Sync.writeTVar m True
-      let waitAction = do b <- Sync.readTVar m
+        STM.atomically $ STM.writeTVar m True
+      let waitAction = do b <- STM.readTVar m
                           if b then return () else retry
       let killAction = Sync.killThread t
       return (waitAction, killAction)
@@ -161,17 +162,17 @@
 -- can be written to a file descriptor. The second returned value
 -- is an IO action that can be used to deregister interest
 -- in the file descriptor.
-threadWaitWriteSTM :: Fd -> IO (Sync.STM (), IO ())
+threadWaitWriteSTM :: Fd -> IO (STM.STM (), IO ())
 threadWaitWriteSTM fd
 #if !defined(mingw32_HOST_OS) && !defined(javascript_HOST_ARCH)
   | threaded  = Event.threadWaitWriteSTM fd
 #endif
   | otherwise = do
-      m <- Sync.newTVarIO False
+      m <- STM.newTVarIO False
       t <- Sync.forkIO $ do
         threadWaitWrite fd
-        Sync.atomically $ Sync.writeTVar m True
-      let waitAction = do b <- Sync.readTVar m
+        STM.atomically $ STM.writeTVar m True
+      let waitAction = do b <- STM.readTVar m
                           if b then return () else retry
       let killAction = Sync.killThread t
       return (waitAction, killAction)
diff --git a/src/GHC/Internal/Conc/POSIX.hs b/src/GHC/Internal/Conc/POSIX.hs
--- a/src/GHC/Internal/Conc/POSIX.hs
+++ b/src/GHC/Internal/Conc/POSIX.hs
@@ -56,6 +56,7 @@
 import GHC.Internal.Num (Num(..))
 import GHC.Internal.Ptr
 import GHC.Internal.Real (div, fromIntegral)
+import GHC.Internal.STM (TVar, atomically, newTVar, writeTVar)
 import GHC.Internal.Word (Word32, Word64)
 import GHC.Internal.Windows
 
diff --git a/src/GHC/Internal/Conc/Sync.hs b/src/GHC/Internal/Conc/Sync.hs
--- a/src/GHC/Internal/Conc/Sync.hs
+++ b/src/GHC/Internal/Conc/Sync.hs
@@ -76,21 +76,6 @@
         , enableAllocationLimit
         , disableAllocationLimit
 
-        -- * TVars
-        , STM(..)
-        , atomically
-        , retry
-        , orElse
-        , throwSTM
-        , catchSTM
-        , TVar(..)
-        , newTVar
-        , newTVarIO
-        , readTVar
-        , readTVarIO
-        , writeTVar
-        , unsafeIOToSTM
-
         -- * Miscellaneous
         , withMVar
         , modifyMVar_
@@ -608,13 +593,16 @@
         -- NB. keep these in sync with rts/include/rts/Constants.h
      mk_stat 0  = ThreadRunning
      mk_stat 1  = ThreadBlocked BlockedOnMVar
-     mk_stat 2  = ThreadBlocked BlockedOnBlackHole
-     mk_stat 6  = ThreadBlocked BlockedOnSTM
+     mk_stat 2  = ThreadBlocked BlockedOnMVar -- BlockedOnMVarRead
+     mk_stat 3  = ThreadBlocked BlockedOnBlackHole
+     mk_stat 4  = ThreadBlocked BlockedOnException
+     -- 5,6,7: BlockedOn{Read,Write,Delay}
+     mk_stat 8  = ThreadBlocked BlockedOnSTM
+     mk_stat 9  = ThreadBlocked BlockedOnForeignCall
      mk_stat 10 = ThreadBlocked BlockedOnForeignCall
-     mk_stat 11 = ThreadBlocked BlockedOnForeignCall
-     mk_stat 12 = ThreadBlocked BlockedOnException
-     mk_stat 14 = ThreadBlocked BlockedOnMVar -- possibly: BlockedOnMVarRead
-     -- NB. these are hardcoded in rts/PrimOps.cmm
+     -- 11: ThreadMigrating
+     -- 12: BlockedOnDoProc
+     -- 13,14,15: unused
      mk_stat 16 = ThreadFinished
      mk_stat 17 = ThreadDied
      mk_stat _  = ThreadBlocked BlockedOnOther
@@ -664,220 +652,6 @@
    case mkWeakNoFinalizer# t# t s of
       (# s1, w #) -> (# s1, Weak w #)
 
-
------------------------------------------------------------------------------
--- Transactional heap operations
------------------------------------------------------------------------------
-
--- TVars are shared memory locations which support atomic memory
--- transactions.
-
--- |A monad supporting atomic memory transactions.
-newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))
-
-unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
-unSTM (STM a) = a
-
--- | @since base-4.3.0.0
-instance  Functor STM where
-   fmap f x = x >>= (pure . f)
-
--- | @since base-4.8.0.0
-instance Applicative STM where
-  {-# INLINE pure #-}
-  {-# INLINE (*>) #-}
-  {-# INLINE liftA2 #-}
-  pure x = returnSTM x
-  (<*>) = ap
-  liftA2 = liftM2
-  m *> k = thenSTM m k
-
--- | @since base-4.3.0.0
-instance  Monad STM  where
-    {-# INLINE (>>=)  #-}
-    m >>= k     = bindSTM m k
-    (>>) = (*>)
-
--- | @since base-4.17.0.0
-instance Semigroup a => Semigroup (STM a) where
-    (<>) = liftA2 (<>)
-
--- | @since base-4.17.0.0
-instance Monoid a => Monoid (STM a) where
-    mempty = pure mempty
-
-bindSTM :: STM a -> (a -> STM b) -> STM b
-bindSTM (STM m) k = STM ( \s ->
-  case m s of
-    (# new_s, a #) -> unSTM (k a) new_s
-  )
-
-thenSTM :: STM a -> STM b -> STM b
-thenSTM (STM m) k = STM ( \s ->
-  case m s of
-    (# new_s, _ #) -> unSTM k new_s
-  )
-
-returnSTM :: a -> STM a
-returnSTM x = STM (\s -> (# s, x #))
-
--- | Takes the first non-'retry'ing 'STM' action.
---
--- @since base-4.8.0.0
-instance Alternative STM where
-  empty = retry
-  (<|>) = orElse
-
--- | Takes the first non-'retry'ing 'STM' action.
---
--- @since base-4.3.0.0
-instance MonadPlus STM
-
--- | Unsafely performs IO in the STM monad.  Beware: this is a highly
--- dangerous thing to do.
---
---   * The STM implementation will often run transactions multiple
---     times, so you need to be prepared for this if your IO has any
---     side effects.
---
---   * The STM implementation will abort transactions that are known to
---     be invalid and need to be restarted.  This may happen in the middle
---     of `unsafeIOToSTM`, so make sure you don't acquire any resources
---     that need releasing (exception handlers are ignored when aborting
---     the transaction).  That includes doing any IO using Handles, for
---     example.  Getting this wrong will probably lead to random deadlocks.
---
---   * The transaction may have seen an inconsistent view of memory when
---     the IO runs.  Invariants that you expect to be true throughout
---     your program may not be true inside a transaction, due to the
---     way transactions are implemented.  Normally this wouldn't be visible
---     to the programmer, but using `unsafeIOToSTM` can expose it.
---
-unsafeIOToSTM :: IO a -> STM a
-unsafeIOToSTM (IO m) = STM m
-
--- | Perform a series of STM actions atomically.
---
--- Using 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'
--- subverts some of guarantees that STM provides. It makes it possible to
--- run a transaction inside of another transaction, depending on when the
--- thunk is evaluated. If a nested transaction is attempted, an exception
--- is thrown by the runtime. It is possible to safely use 'atomically' inside
--- 'unsafePerformIO' or 'unsafeInterleaveIO', but the typechecker does not
--- rule out programs that may attempt nested transactions, meaning that
--- the programmer must take special care to prevent these.
---
--- However, there are functions for creating transactional variables that
--- can always be safely called in 'unsafePerformIO'. See: 'newTVarIO',
--- 'Control.Concurrent.STM.TChan.newTChanIO',
--- 'Control.Concurrent.STM.TChan.newBroadcastTChanIO',
--- 'Control.Concurrent.STM.TQueue.newTQueueIO',
--- 'Control.Concurrent.STM.TBQueue.newTBQueueIO', and
--- 'Control.Concurrent.STM.TMVar.newTMVarIO'.
---
--- Using 'unsafePerformIO' inside of 'atomically' is also dangerous but for
--- different reasons. See 'unsafeIOToSTM' for more on this.
-
-atomically :: STM a -> IO a
-atomically (STM m) = IO (\s -> (atomically# m) s )
-
--- | Retry execution of the current memory transaction because it has seen
--- values in 'TVar's which mean that it should not continue (e.g. the 'TVar's
--- represent a shared buffer that is now empty).  The implementation may
--- block the thread until one of the 'TVar's that it has read from has been
--- updated. (GHC only)
-retry :: STM a
-retry = STM $ \s# -> retry# s#
-
--- | Compose two alternative STM actions (GHC only).
---
--- If the first action completes without retrying then it forms the result of
--- the 'orElse'. Otherwise, if the first action retries, then the second action
--- is tried in its place. If both actions retry then the 'orElse' as a whole
--- retries.
-orElse :: STM a -> STM a -> STM a
-orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
-
--- | A variant of 'throw' that can only be used within the 'STM' monad.
---
--- Throwing an exception in @STM@ aborts the transaction and propagates the
--- exception. If the exception is caught via 'catchSTM', only the changes
--- enclosed by the catch are rolled back; changes made outside of 'catchSTM'
--- persist.
---
--- If the exception is not caught inside of the 'STM', it is re-thrown by
--- 'atomically', and the entire 'STM' is rolled back.
---
--- Although 'throwSTM' has a type that is an instance of the type of 'throw', the
--- two functions are subtly different:
---
--- > throw e    `seq` x  ===> throw e
--- > throwSTM e `seq` x  ===> x
---
--- The first example will cause the exception @e@ to be raised,
--- whereas the second one won\'t.  In fact, 'throwSTM' will only cause
--- an exception to be raised when it is used within the 'STM' monad.
--- The 'throwSTM' variant should be used in preference to 'throw' to
--- raise an exception within the 'STM' monad because it guarantees
--- ordering with respect to other 'STM' operations, whereas 'throw'
--- does not.
-throwSTM :: Exception e => e -> STM a
-throwSTM e = STM $ raiseIO# (toException e)
-
--- | Exception handling within STM actions.
---
--- @'catchSTM' m f@ catches any exception thrown by @m@ using 'throwSTM',
--- using the function @f@ to handle the exception. If an exception is
--- thrown, any changes made by @m@ are rolled back, but changes prior to
--- @m@ persist.
-catchSTM :: Exception e => STM a -> (e -> STM a) -> STM a
-catchSTM (STM m) handler = STM $ catchSTM# m handler'
-    where
-      handler' e = case fromException e of
-                     Just e' -> unSTM (handler e')
-                     Nothing -> raiseIO# e
-
--- |Shared memory locations that support atomic memory transactions.
-data TVar a = TVar (TVar# RealWorld a)
-
--- | @since base-4.8.0.0
-instance Eq (TVar a) where
-        (TVar tvar1#) == (TVar tvar2#) = isTrue# (sameTVar# tvar1# tvar2#)
-
--- | Create a new 'TVar' holding a value supplied
-newTVar :: a -> STM (TVar a)
-newTVar val = STM $ \s1# ->
-    case newTVar# val s1# of
-         (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
-
--- | @IO@ version of 'newTVar'.  This is useful for creating top-level
--- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using
--- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
--- possible.
-newTVarIO :: a -> IO (TVar a)
-newTVarIO val = IO $ \s1# ->
-    case newTVar# val s1# of
-         (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
-
--- | Return the current value stored in a 'TVar'.
--- This is equivalent to
---
--- >  readTVarIO = atomically . readTVar
---
--- but works much faster, because it doesn't perform a complete
--- transaction, it just reads the current value of the 'TVar'.
-readTVarIO :: TVar a -> IO a
-readTVarIO (TVar tvar#) = IO $ \s# -> readTVarIO# tvar# s#
-
--- |Return the current value stored in a 'TVar'.
-readTVar :: TVar a -> STM a
-readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
-
--- |Write the supplied value into a 'TVar'.
-writeTVar :: TVar a -> a -> STM ()
-writeTVar (TVar tvar#) val = STM $ \s1# ->
-    case writeTVar# tvar# val s1# of
-         s2# -> (# s2#, () #)
 
 -----------------------------------------------------------------------------
 -- MVar utilities
diff --git a/src/GHC/Internal/Conc/Sync.hs-boot b/src/GHC/Internal/Conc/Sync.hs-boot
--- a/src/GHC/Internal/Conc/Sync.hs-boot
+++ b/src/GHC/Internal/Conc/Sync.hs-boot
@@ -17,7 +17,6 @@
 
 module GHC.Internal.Conc.Sync
         ( forkIO,
-          TVar(..),
           ThreadId(..),
           myThreadId,
           showThreadId,
@@ -33,7 +32,6 @@
 forkIO :: IO () -> IO ThreadId
 
 data ThreadId = ThreadId ThreadId#
-data TVar a = TVar (TVar# RealWorld a)
 
 data BlockReason
         = BlockedOnMVar
diff --git a/src/GHC/Internal/Conc/Windows.hs b/src/GHC/Internal/Conc/Windows.hs
--- a/src/GHC/Internal/Conc/Windows.hs
+++ b/src/GHC/Internal/Conc/Windows.hs
@@ -42,12 +42,12 @@
        ) where
 
 import GHC.Internal.Base
-import GHC.Internal.Conc.Sync
 import qualified GHC.Internal.Conc.POSIX as POSIX
 import qualified GHC.Internal.Event.Windows.Thread as WINIO
 import GHC.Internal.Event.Windows.ConsoleEvent
 import GHC.Internal.IO.SubSystem ((<!>))
 import GHC.Internal.Ptr
+import GHC.Internal.STM
 
 -- ----------------------------------------------------------------------------
 -- Thread waiting
diff --git a/src/GHC/Internal/Control/Exception/Base.hs b/src/GHC/Internal/Control/Exception/Base.hs
--- a/src/GHC/Internal/Control/Exception/Base.hs
+++ b/src/GHC/Internal/Control/Exception/Base.hs
@@ -171,8 +171,8 @@
 -- Notice that the usage of 'unsafePerformIO' is safe here.
 
 mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
-mapException f v = unsafePerformIO (catch (evaluate v)
-                                          (\x -> throwIO (f x)))
+mapException f v = unsafePerformIO $ catchNoPropagate (evaluate v) $
+  \(ExceptionWithContext ctx x) -> rethrowIO (ExceptionWithContext ctx (f x))
 
 -----------------------------------------------------------------------------
 -- 'try' and variations.
diff --git a/src/GHC/Internal/Err.hs b/src/GHC/Internal/Err.hs
--- a/src/GHC/Internal/Err.hs
+++ b/src/GHC/Internal/Err.hs
@@ -1,6 +1,7 @@
 {-# LANGUAGE Trustworthy #-}
 {-# LANGUAGE NoImplicitPrelude, MagicHash, ImplicitParams #-}
 {-# LANGUAGE RankNTypes, PolyKinds, DataKinds #-}
+{-# LANGUAGE BangPatterns #-}
 {-# OPTIONS_HADDOCK not-home #-}
 
 -----------------------------------------------------------------------------
@@ -25,6 +26,7 @@
 module GHC.Internal.Err( absentErr, error, errorWithoutStackTrace, undefined ) where
 import GHC.Internal.Types (Char, RuntimeRep)
 import GHC.Internal.Stack.Types
+import GHC.Internal.Magic
 import GHC.Internal.Prim
 import {-# SOURCE #-} GHC.Internal.Exception
   ( errorCallWithCallStackException
@@ -33,7 +35,10 @@
 -- | 'error' stops execution and displays an error message.
 error :: forall (r :: RuntimeRep). forall (a :: TYPE r).
          HasCallStack => [Char] -> a
-error s = raise# (errorCallWithCallStackException s ?callStack)
+error s =
+  -- See Note [Capturing the backtrace in throw] and Note [Hiding precise exception signature in throw]
+  let !se = noinline (errorCallWithCallStackException s ?callStack)
+  in raise# se
           -- Bleh, we should be using 'GHC.Internal.Stack.callStack' instead of
           -- '?callStack' here, but 'GHC.Internal.Stack.callStack' depends on
           -- 'GHC.Internal.Stack.popCallStack', which is partial and depends on
@@ -73,7 +78,10 @@
 -- nor wanted (see #19886). We’d like to use withFrozenCallStack, but that
 -- is not available in this module yet, and making it so is hard. So let’s just
 -- use raise# directly.
-undefined = raise# (errorCallWithCallStackException "Prelude.undefined" ?callStack)
+undefined =
+    -- See Note [Capturing the backtrace in throw] and Note [Hiding precise exception signature in throw]
+    let !se = noinline (errorCallWithCallStackException "Prelude.undefined" ?callStack)
+    in raise# se
 
 -- | Used for compiler-generated error message;
 -- encoding saves bytes of string junk.
diff --git a/src/GHC/Internal/Event/Thread.hs b/src/GHC/Internal/Event/Thread.hs
--- a/src/GHC/Internal/Event/Thread.hs
+++ b/src/GHC/Internal/Event/Thread.hs
@@ -38,11 +38,11 @@
 import GHC.Internal.Foreign.Ptr (Ptr)
 import GHC.Internal.Base
 import GHC.Internal.List (zipWith, zipWith3)
-import GHC.Internal.Conc.Sync (TVar, ThreadId, ThreadStatus(..), atomically, forkIO,
-                      labelThread, modifyMVar_, withMVar, newTVar, sharedCAF,
+import GHC.Internal.STM (TVar, atomically, newTVar, writeTVar, newTVarIO, readTVar, retry, throwSTM, STM)
+import GHC.Internal.Conc.Sync (ThreadId, ThreadStatus(..), forkIO,
+                      labelThread, modifyMVar_, withMVar, sharedCAF,
                       getNumCapabilities, threadCapability, myThreadId, forkOn,
-                      threadStatus, writeTVar, newTVarIO, readTVar, retry,
-                      throwSTM, STM, yield)
+                      threadStatus, yield)
 import GHC.Internal.IO (mask_, uninterruptibleMask_, onException)
 import GHC.Internal.IO.Exception (ioError)
 import GHC.Internal.IOArray (IOArray, newIOArray, readIOArray, writeIOArray,
diff --git a/src/GHC/Internal/Event/Windows.hsc b/src/GHC/Internal/Event/Windows.hsc
--- a/src/GHC/Internal/Event/Windows.hsc
+++ b/src/GHC/Internal/Event/Windows.hsc
@@ -579,7 +579,7 @@
                 ++ " ptr_lpol:" ++ show ptr_lpol
                 ++ " *ptr_lpol:" ++ show cdDataCheck
 
-        startCBResult <- startCB lpol `onException`
+        (startCBResult, startErr) <- startCB lpol `onException`
                         (CbError `fmap` Win32.getLastError) >>= \result -> do
           -- Check to see if the operation was completed on a
           -- non-overlapping handle or was completed immediately.
@@ -617,7 +617,7 @@
                              -- I don't know what the best default here is...
                              | otherwise                                   -> CbPending
                   _                                                        -> result
-          case result' of
+          fmap (\r -> (r, err)) $ case result' of
             CbNone    _ -> error "withOverlappedEx: CbNone shouldn't happen."
             CbIncomplete -> do
                debugIO $ "handling incomplete request synchronously " ++ show (h, lpol)
@@ -684,7 +684,11 @@
                              -- can go into an unbounded alertable wait.
                              delay <- runExpiredTimeouts mgr
                              registerAlertableWait delay
-                        return $ IOFailed Nothing
+                        -- Re-throw the original exception rather than
+                        -- returning IOFailed. This ensures that async
+                        -- exceptions (e.g. Timeout from System.Timeout)
+                        -- propagate correctly to their handlers.
+                        E.throw e
         let runner = do debugIO $ (dbgMsg ":: waiting ") ++ " | "  ++ show lpol
                         res <- readMVar signal `catch` cancel
                         debugIO $ dbgMsg ":: signaled "
@@ -712,13 +716,13 @@
                    debugIO $ dbgMsg $ ":: done bytes: " ++ show bytes
                    case bytes of
                      Just res -> completionCB 0 res
-                     Nothing  -> do err <- FFI.overlappedIOStatus lpol
+                     Nothing  -> do status <- FFI.overlappedIOStatus lpol
+                                    err <- if status == #{const STATUS_PENDING}
+                                             then return startErr
+                                             else FFI.overlappedIOErrCode lpol
                                     numBytes <- FFI.overlappedIONumBytes lpol
-                                    -- TODO: Remap between STATUS_ and ERROR_ instead
-                                    -- of re-interpret here. But for now, don't care.
-                                    let err' = fromIntegral err
-                                    debugIO $ dbgMsg $ ":: done callback: " ++ show err' ++ " - " ++ show numBytes
-                                    completionCB err' (fromIntegral numBytes)
+                                    debugIO $ dbgMsg $ ":: done callback: " ++ show err ++ " - " ++ show numBytes
+                                    completionCB err (fromIntegral numBytes)
               else readMVar signal
           CbError err  -> do
             reqs3 <- removeRequest
@@ -1081,10 +1085,7 @@
                cb <- deRefStablePtr (cdCallback payload)
                reqs <- removeRequest
                debugIO $ "-1.. " ++ show reqs ++ " requests queued."
-               status <- FFI.overlappedIOStatus (lpOverlapped oe)
-               -- TODO: Remap between STATUS_ and ERROR_ instead
-               -- of re-interpret here. But for now, don't care.
-               let status' = fromIntegral status
+               status' <- FFI.overlappedIOErrCode (lpOverlapped oe)
                -- We no longer explicitly free the memory, this is because we
                -- now require the callback to free the memory since the
                -- callback allocated it.  This allows us to simplify memory
diff --git a/src/GHC/Internal/Event/Windows/FFI.hsc b/src/GHC/Internal/Event/Windows/FFI.hsc
--- a/src/GHC/Internal/Event/Windows/FFI.hsc
+++ b/src/GHC/Internal/Event/Windows/FFI.hsc
@@ -46,6 +46,7 @@
     zeroOverlapped,
     pokeOffsetOverlapped,
     overlappedIOStatus,
+    overlappedIOErrCode,
     overlappedIONumBytes,
 
     -- * Cancel pending I/O
@@ -202,10 +203,16 @@
 overlappedIOStatus :: LPOVERLAPPED -> IO NTSTATUS
 overlappedIOStatus lpol = do
   status <- #{peek OVERLAPPED, Internal} lpol
-  -- TODO: Map NTSTATUS to ErrCode?
-  -- See https://github.com/libuv/libuv/blob/b12624c13693c4d29ca84b3556eadc9e9c0936a4/src/win/winsock.c#L153
   return status
 {-# INLINE overlappedIOStatus #-}
+
+foreign import ccall unsafe "winternl.h RtlNtStatusToDosError"
+    c_RtlNtStatusToDosError :: NTSTATUS -> IO ULONG
+
+overlappedIOErrCode :: LPOVERLAPPED -> IO ErrCode
+overlappedIOErrCode lpol = do
+  status <- overlappedIOStatus lpol
+  c_RtlNtStatusToDosError status
 
 overlappedIONumBytes :: LPOVERLAPPED -> IO ULONG_PTR
 overlappedIONumBytes lpol = do
diff --git a/src/GHC/Internal/Event/Windows/Thread.hs b/src/GHC/Internal/Event/Windows/Thread.hs
--- a/src/GHC/Internal/Event/Windows/Thread.hs
+++ b/src/GHC/Internal/Event/Windows/Thread.hs
@@ -7,11 +7,11 @@
     registerDelay,
 ) where
 
-import GHC.Internal.Conc.Sync
 import GHC.Internal.Base
 import GHC.Internal.Event.Windows
 import GHC.Internal.IO
 import GHC.Internal.MVar
+import GHC.Internal.STM
 
 ensureIOManagerIsRunning :: IO ()
 ensureIOManagerIsRunning = wakeupIOManager
@@ -36,4 +36,3 @@
     mgr <- getSystemManager
     _ <- registerTimeout mgr usecs $ atomically $ writeTVar t True
     return t
-
diff --git a/src/GHC/Internal/Exception.hs b/src/GHC/Internal/Exception.hs
--- a/src/GHC/Internal/Exception.hs
+++ b/src/GHC/Internal/Exception.hs
@@ -87,7 +87,7 @@
     -- Note also the absolutely crucial `noinine` in the RHS!
     --   See Note [Hiding precise exception signature in throw]
     let se :: SomeException
-        !se = noinline (unsafePerformIO (toExceptionWithBacktrace e))
+        !se = noinline (unsafePerformIO (withFrozenCallStack $ toExceptionWithBacktrace e))
     in raise# se
 
 -- Note [Capturing the backtrace in throw]
@@ -162,7 +162,12 @@
 -- primops which allow more precise guidance of the demand analyser's heuristic
 -- (e.g. #23847).
 
--- | @since base-4.20.0.0
+-- | Collect a Backtrace and attach it to the 'Exception'.
+--
+-- It is recommended to use 'withFrozenCallStack' when calling this function
+-- in order to avoid leaking implementation details of 'toExceptionWithBacktrace'.
+--
+--  @since base-4.20.0.0
 toExceptionWithBacktrace :: (HasCallStack, Exception e)
                          => e -> IO SomeException
 toExceptionWithBacktrace e
diff --git a/src/GHC/Internal/Exception/Type.hs b/src/GHC/Internal/Exception/Type.hs
--- a/src/GHC/Internal/Exception/Type.hs
+++ b/src/GHC/Internal/Exception/Type.hs
@@ -82,7 +82,7 @@
 
 instance ExceptionAnnotation WhileHandling where
   displayExceptionAnnotation (WhileHandling e) =
-    "While handling " ++ case lines $ displayException e of
+    "While handling " ++ case lines $ displayExceptionWithInfo e of
       [] -> ""
       (l1:ls) ->
         -- Indent lines forward.
@@ -206,7 +206,16 @@
 
 -}
 class (Typeable e, Show e) => Exception e where
-    -- | @toException@ should produce a 'SomeException' with no attached 'ExceptionContext'.
+    -- | 'toException' converts an exception into the existential 'SomeException'
+    -- wrapper type.
+    --
+    -- In doing so, 'toException' should not /add/ an 'ExceptionContext'.
+    --
+    --   - In most cases, the exception does not store its own 'ExceptionContext'.
+    --     The default implementation of 'toException' (which does not store any
+    --     'ExceptionContext') is suitable for these cases.
+    --   - In the rare case that the exception itself stores an 'ExceptionContext',
+    --     this context should be preserved by 'toException'.
     toException   :: e -> SomeException
     fromException :: SomeException -> Maybe e
 
@@ -229,13 +238,11 @@
 -- | @since base-4.8.0.0
 instance Exception Void
 
--- | This drops any attached 'ExceptionContext'.
+-- | NB: this instance preserves the attached 'ExceptionContext'.
 --
 -- @since base-3.0
 instance Exception SomeException where
-    toException (SomeException e) =
-        let ?exceptionContext = emptyExceptionContext
-        in SomeException e
+    toException = id
     fromException = Just
     backtraceDesired (SomeException e) = backtraceDesired e
     displayException (SomeException e) = displayException e
diff --git a/src/GHC/Internal/Heap/InfoTable.hsc b/src/GHC/Internal/Heap/InfoTable.hsc
--- a/src/GHC/Internal/Heap/InfoTable.hsc
+++ b/src/GHC/Internal/Heap/InfoTable.hsc
@@ -47,7 +47,7 @@
   ptrs'   <- (#peek struct StgInfoTable_, layout.payload.ptrs) ptr
   nptrs'  <- (#peek struct StgInfoTable_, layout.payload.nptrs) ptr
   tipe'   <- (#peek struct StgInfoTable_, type) ptr
-  srtlen' <- (#peek struct StgInfoTable_, srt) a0
+  srtlen' <- (#peek struct StgInfoTable_, srt) ptr
   return StgInfoTable
     { entry  = entry'
     , ptrs   = ptrs'
diff --git a/src/GHC/Internal/Heap/InfoTableProf.hsc b/src/GHC/Internal/Heap/InfoTableProf.hsc
--- a/src/GHC/Internal/Heap/InfoTableProf.hsc
+++ b/src/GHC/Internal/Heap/InfoTableProf.hsc
@@ -44,7 +44,7 @@
   ptrs'   <- (#peek struct StgInfoTable_, layout.payload.ptrs) ptr
   nptrs'  <- (#peek struct StgInfoTable_, layout.payload.nptrs) ptr
   tipe'   <- (#peek struct StgInfoTable_, type) ptr
-  srtlen' <- (#peek struct StgInfoTable_, srt) a0
+  srtlen' <- (#peek struct StgInfoTable_, srt) ptr
   return StgInfoTable
     { entry  = entry'
     , ptrs   = ptrs'
diff --git a/src/GHC/Internal/IO/Handle/Internals.hs b/src/GHC/Internal/IO/Handle/Internals.hs
--- a/src/GHC/Internal/IO/Handle/Internals.hs
+++ b/src/GHC/Internal/IO/Handle/Internals.hs
@@ -192,7 +192,7 @@
             throwTo t e
             do_operation fun h act m
         _otherwise ->
-            throwIO e
+            rethrowIO (ExceptionWithContext c e)
 
 -- Note [async]
 -- ~~~~~~~~~~~~
@@ -450,7 +450,7 @@
   (handle_', mb_exc) <- hClose_help handle_
   putMVar m handle_'
   case mb_exc of
-    Just exc -> throwIO exc
+    Just exc -> throwIO (NoBacktrace exc)
     Nothing -> return ()
 
 {-
@@ -884,8 +884,9 @@
 hClose_rethrow :: SomeException -> Handle -> IO ()
 hClose_rethrow e h =
   case fromException e of
-    Just ioe -> ioError (augmentIOError ioe "hClose" h)
-    Nothing  -> throwIO e
+    Just ioe -> rethrowIO $ ExceptionWithContext (someExceptionContext e) $
+                  augmentIOError ioe "hClose" h
+    Nothing  -> throwIO (NoBacktrace e)
 
 hClose' :: Handle -> MVar Handle__ -> IO (Maybe SomeException)
 hClose' h m = withHandle' "hClose" h m $ hClose_help
diff --git a/src/GHC/Internal/IO/Handle/Text.hs b/src/GHC/Internal/IO/Handle/Text.hs
--- a/src/GHC/Internal/IO/Handle/Text.hs
+++ b/src/GHC/Internal/IO/Handle/Text.hs
@@ -50,7 +50,6 @@
 import GHC.Internal.Foreign.C.Types
 import GHC.Internal.Foreign.Storable
 
-import qualified GHC.Internal.Control.Exception as Exception
 import GHC.Internal.System.IO.Error
 import GHC.Internal.Data.Either (Either(..))
 import GHC.Internal.Data.Maybe
@@ -265,13 +264,14 @@
 
 maybeFillReadBuffer :: Handle__ -> CharBuffer -> IO (Maybe CharBuffer)
 maybeFillReadBuffer handle_ buf
-  = catchException
+  = catchNoPropagate
      (do buf' <- getSomeCharacters handle_ buf
          return (Just buf')
      )
-     (\e -> do if isEOFError e
+     (\ec@(ExceptionWithContext _ e) ->
+               if isEOFError e
                   then return Nothing
-                  else ioError e)
+                  else rethrowIO ec)
 
 -- See GHC.Internal.IO.Buffer
 #define CHARBUF_UTF32
@@ -420,7 +420,7 @@
 lazyReadBuffered :: Handle -> Handle__ -> IO (Handle__, [Char])
 lazyReadBuffered h handle_@Handle__{..} = do
    buf <- readIORef haCharBuffer
-   Exception.catch
+   catchNoPropagate
         (do
             buf'@Buffer{..} <- getSomeCharacters handle_ buf
             lazy_rest <- lazyRead h
@@ -431,7 +431,8 @@
             writeIORef haCharBuffer (bufferAdjustL r buf')
             return (handle_, s)
         )
-        (\e -> do (handle_', _) <- hClose_help handle_
+        (\(ExceptionWithContext ctx e) -> do
+                  (handle_', _) <- hClose_help handle_
                   debugIO ("hGetContents caught: " ++ show e)
                   -- We might have a \r cached in CRLF mode.  So we
                   -- need to check for that and return it:
@@ -440,7 +441,8 @@
                                      then "\r"
                                      else ""
                              else
-                                  throw (augmentIOError e "hGetContents" h)
+                                  throw $ NoBacktrace $ ExceptionWithContext ctx $
+                                    augmentIOError e "hGetContents" h
 
                   return (handle_', r)
         )
@@ -495,7 +497,8 @@
       Right s -> return s
       Left e ->
           case fromException e of
-            Just ioe -> throwIO (augmentIOError ioe "hGetContents'" handle)
+            Just ioe -> rethrowIO $ ExceptionWithContext (someExceptionContext e) $
+                          augmentIOError ioe "hGetContents'" handle
             Nothing -> throwIO (NoBacktrace e)
 
 strictRead :: Handle -> Handle__ -> IO (Handle__, Either SomeException String)
@@ -511,12 +514,13 @@
 
 strictReadLoop :: Handle__ -> [CharBuffer] -> CharBuffer -> IO [CharBuffer]
 strictReadLoop handle_ cbufs cbuf0 = do
-    mcbuf <- Exception.catch
+    mcbuf <- catchNoPropagate
         (do r <- readTextDevice handle_ cbuf0
             return (Just r))
-        (\e -> if isEOFError e
+        (\ec@(ExceptionWithContext _ e) ->
+               if isEOFError e
                   then return Nothing
-                  else throw e)
+                  else rethrowIO ec)
     case mcbuf of
       Nothing -> return (cbuf0 : cbufs)
       Just cbuf1 -> strictReadLoop' handle_ cbufs cbuf1
diff --git a/src/GHC/Internal/IO/Handle/Windows.hs b/src/GHC/Internal/IO/Handle/Windows.hs
--- a/src/GHC/Internal/IO/Handle/Windows.hs
+++ b/src/GHC/Internal/IO/Handle/Windows.hs
@@ -26,6 +26,7 @@
 
 import GHC.Internal.Base
 import GHC.Internal.MVar
+import GHC.Internal.Exception.Type (ExceptionWithContext(..))
 import GHC.Internal.IO
 import GHC.Internal.IO.BufferedIO hiding (flushWriteBuffer)
 import GHC.Internal.IO.Encoding
@@ -109,6 +110,11 @@
 addFilePathToIOError fun fp ioe
   = ioe{ ioe_location = fun, ioe_filename = Just fp }
 
+catchAndAnnotate :: FilePath -> String -> IO a -> IO a
+catchAndAnnotate fp s a =
+  catchExceptionNoPropagate a $ \(ExceptionWithContext c e) ->
+    rethrowIO (ExceptionWithContext c (addFilePathToIOError s fp e))
+
 -- | Computation 'openFile' @file mode@ allocates and returns a new, open
 -- handle to manage the file @file@.  It manages input if @mode@
 -- is 'ReadMode', output if @mode@ is 'WriteMode' or 'AppendMode',
@@ -137,9 +143,8 @@
 -- be using 'openBinaryFile'.
 openFile :: FilePath -> IOMode -> IO Handle
 openFile fp im =
-  catchException
-    (openFile' fp im dEFAULT_OPEN_IN_BINARY_MODE True)
-    (\e -> ioError (addFilePathToIOError "openFile" fp e))
+  catchAndAnnotate fp "openFile" $
+    openFile' fp im dEFAULT_OPEN_IN_BINARY_MODE True
 
 -- | Like 'openFile', but opens the file in ordinary blocking mode.
 -- This can be useful for opening a FIFO for writing: if we open in
@@ -149,9 +154,8 @@
 -- @since base-4.4.0.0
 openFileBlocking :: FilePath -> IOMode -> IO Handle
 openFileBlocking fp im =
-  catchException
-    (openFile' fp im dEFAULT_OPEN_IN_BINARY_MODE False)
-    (\e -> ioError (addFilePathToIOError "openFileBlocking" fp e))
+  catchAndAnnotate fp "openFileBlocking" $
+    openFile' fp im dEFAULT_OPEN_IN_BINARY_MODE False
 
 -- | Like 'openFile', but open the file in binary mode.
 -- On Windows, reading a file in text mode (which is the default)
@@ -164,9 +168,8 @@
 
 openBinaryFile :: FilePath -> IOMode -> IO Handle
 openBinaryFile fp m =
-  catchException
-    (openFile' fp m True True)
-    (\e -> ioError (addFilePathToIOError "openBinaryFile" fp e))
+  catchAndAnnotate fp "openBinaryFile" $
+    openFile' fp m True True
 
 openFile' :: String -> IOMode -> Bool -> Bool -> IO Handle
 openFile' filepath iomode binary non_blocking = do
diff --git a/src/GHC/Internal/IO/Windows/Handle.hsc b/src/GHC/Internal/IO/Windows/Handle.hsc
--- a/src/GHC/Internal/IO/Windows/Handle.hsc
+++ b/src/GHC/Internal/IO/Windows/Handle.hsc
@@ -450,9 +450,7 @@
     completionCB err dwBytes
       | err == #{const ERROR_SUCCESS}       = Mgr.ioSuccess $ fromIntegral dwBytes
       | err == #{const ERROR_HANDLE_EOF}    = Mgr.ioSuccess 0
-      | err == #{const STATUS_END_OF_FILE}  = Mgr.ioSuccess 0
       | err == #{const ERROR_BROKEN_PIPE}   = Mgr.ioSuccess 0
-      | err == #{const STATUS_PIPE_BROKEN}  = Mgr.ioSuccess 0
       | err == #{const ERROR_NO_MORE_ITEMS} = Mgr.ioSuccess $ fromIntegral dwBytes
       | err == #{const ERROR_MORE_DATA}     = Mgr.ioSuccess $ fromIntegral dwBytes
       | otherwise                           = Mgr.ioFailed err
@@ -480,9 +478,7 @@
     completionCB err dwBytes
       | err == #{const ERROR_SUCCESS}       = Mgr.ioSuccess $ Just $! fromIntegral dwBytes
       | err == #{const ERROR_HANDLE_EOF}    = Mgr.ioSuccess Nothing
-      | err == #{const STATUS_END_OF_FILE}  = Mgr.ioSuccess Nothing
       | err == #{const ERROR_BROKEN_PIPE}   = Mgr.ioSuccess Nothing
-      | err == #{const STATUS_PIPE_BROKEN}  = Mgr.ioSuccess Nothing
       | err == #{const ERROR_NO_MORE_ITEMS} = Mgr.ioSuccess Nothing
       | err == #{const ERROR_MORE_DATA}     = Mgr.ioSuccess $ Just $! fromIntegral dwBytes
       | otherwise                           = Mgr.ioFailedAny err
diff --git a/src/GHC/Internal/Prim.hs b/src/GHC/Internal/Prim.hs
new file mode 100644
--- /dev/null
+++ b/src/GHC/Internal/Prim.hs
@@ -0,0 +1,11 @@
+{-# LANGUAGE Unsafe #-}
+{-# LANGUAGE NoImplicitPrelude #-}
+
+-- | GHC's primitive types and operations.
+-- Use GHC.Exts from the base package instead of importing this
+-- module directly.
+--
+-- This module has no source-level definitions. All primitive types
+-- and operations are wired-in to GHC. See Note [GHC.Prim] in
+-- primops.txt.pp.
+module GHC.Internal.Prim () where
diff --git a/src/GHC/Internal/STM.hs b/src/GHC/Internal/STM.hs
new file mode 100644
--- /dev/null
+++ b/src/GHC/Internal/STM.hs
@@ -0,0 +1,254 @@
+{-# LANGUAGE NoImplicitPrelude #-}
+{-# LANGUAGE UnboxedTuples #-}
+{-# LANGUAGE MagicHash #-}
+{-# LANGUAGE GADTs #-}
+{-# LANGUAGE RankNTypes #-}
+{-# OPTIONS_HADDOCK not-home #-}
+
+module GHC.Internal.STM
+        (
+          -- * the 'STM' monad
+          STM(..)
+        , atomically
+        , retry
+        , orElse
+        , throwSTM
+        , catchSTM
+        , unsafeIOToSTM
+          -- * TVars
+        , TVar(..)
+        , newTVar
+        , newTVarIO
+        , readTVar
+        , readTVarIO
+        , writeTVar
+        ) where
+
+import GHC.Internal.Base
+import GHC.Internal.Exception (Exception, toExceptionWithBacktrace, fromException, addExceptionContext)
+import GHC.Internal.Exception.Context (ExceptionAnnotation)
+import GHC.Internal.Exception.Type (WhileHandling(..))
+import GHC.Internal.Stack (HasCallStack, withFrozenCallStack)
+
+-- TVars are shared memory locations which support atomic memory
+-- transactions.
+
+-- |A monad supporting atomic memory transactions.
+newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))
+
+unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
+unSTM (STM a) = a
+
+-- | @since base-4.3.0.0
+instance  Functor STM where
+   fmap f x = x >>= (pure . f)
+
+-- | @since base-4.8.0.0
+instance Applicative STM where
+  {-# INLINE pure #-}
+  {-# INLINE (*>) #-}
+  {-# INLINE liftA2 #-}
+  pure x = returnSTM x
+  (<*>) = ap
+  liftA2 = liftM2
+  m *> k = thenSTM m k
+
+-- | @since base-4.3.0.0
+instance  Monad STM  where
+    {-# INLINE (>>=)  #-}
+    m >>= k     = bindSTM m k
+    (>>) = (*>)
+
+-- | @since base-4.17.0.0
+instance Semigroup a => Semigroup (STM a) where
+    (<>) = liftA2 (<>)
+
+-- | @since base-4.17.0.0
+instance Monoid a => Monoid (STM a) where
+    mempty = pure mempty
+
+bindSTM :: STM a -> (a -> STM b) -> STM b
+bindSTM (STM m) k = STM ( \s ->
+  case m s of
+    (# new_s, a #) -> unSTM (k a) new_s
+  )
+
+thenSTM :: STM a -> STM b -> STM b
+thenSTM (STM m) k = STM ( \s ->
+  case m s of
+    (# new_s, _ #) -> unSTM k new_s
+  )
+
+returnSTM :: a -> STM a
+returnSTM x = STM (\s -> (# s, x #))
+
+-- | Takes the first non-'retry'ing 'STM' action.
+--
+-- @since base-4.8.0.0
+instance Alternative STM where
+  empty = retry
+  (<|>) = orElse
+
+-- | Takes the first non-'retry'ing 'STM' action.
+--
+-- @since base-4.3.0.0
+instance MonadPlus STM
+
+-- | Unsafely performs IO in the STM monad.  Beware: this is a highly
+-- dangerous thing to do.
+--
+--   * The STM implementation will often run transactions multiple
+--     times, so you need to be prepared for this if your IO has any
+--     side effects.
+--
+--   * The STM implementation will abort transactions that are known to
+--     be invalid and need to be restarted.  This may happen in the middle
+--     of `unsafeIOToSTM`, so make sure you don't acquire any resources
+--     that need releasing (exception handlers are ignored when aborting
+--     the transaction).  That includes doing any IO using Handles, for
+--     example.  Getting this wrong will probably lead to random deadlocks.
+--
+--   * The transaction may have seen an inconsistent view of memory when
+--     the IO runs.  Invariants that you expect to be true throughout
+--     your program may not be true inside a transaction, due to the
+--     way transactions are implemented.  Normally this wouldn't be visible
+--     to the programmer, but using `unsafeIOToSTM` can expose it.
+--
+unsafeIOToSTM :: IO a -> STM a
+unsafeIOToSTM (IO m) = STM m
+
+-- | Perform a series of STM actions atomically.
+--
+-- Using 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'
+-- subverts some of guarantees that STM provides. It makes it possible to
+-- run a transaction inside of another transaction, depending on when the
+-- thunk is evaluated. If a nested transaction is attempted, an exception
+-- is thrown by the runtime. It is possible to safely use 'atomically' inside
+-- 'unsafePerformIO' or 'unsafeInterleaveIO', but the typechecker does not
+-- rule out programs that may attempt nested transactions, meaning that
+-- the programmer must take special care to prevent these.
+--
+-- However, there are functions for creating transactional variables that
+-- can always be safely called in 'unsafePerformIO'. See: 'newTVarIO',
+-- 'Control.Concurrent.STM.TChan.newTChanIO',
+-- 'Control.Concurrent.STM.TChan.newBroadcastTChanIO',
+-- 'Control.Concurrent.STM.TQueue.newTQueueIO',
+-- 'Control.Concurrent.STM.TBQueue.newTBQueueIO', and
+-- 'Control.Concurrent.STM.TMVar.newTMVarIO'.
+--
+-- Using 'unsafePerformIO' inside of 'atomically' is also dangerous but for
+-- different reasons. See 'unsafeIOToSTM' for more on this.
+
+atomically :: STM a -> IO a
+atomically (STM m) = IO (\s -> (atomically# m) s )
+
+-- | Retry execution of the current memory transaction because it has seen
+-- values in 'TVar's which mean that it should not continue (e.g. the 'TVar's
+-- represent a shared buffer that is now empty).  The implementation may
+-- block the thread until one of the 'TVar's that it has read from has been
+-- updated. (GHC only)
+retry :: STM a
+retry = STM $ \s# -> retry# s#
+
+-- | Compose two alternative STM actions (GHC only).
+--
+-- If the first action completes without retrying then it forms the result of
+-- the 'orElse'. Otherwise, if the first action retries, then the second action
+-- is tried in its place. If both actions retry then the 'orElse' as a whole
+-- retries.
+orElse :: STM a -> STM a -> STM a
+orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
+
+-- | A variant of 'throw' that can only be used within the 'STM' monad.
+--
+-- Throwing an exception in @STM@ aborts the transaction and propagates the
+-- exception. If the exception is caught via 'catchSTM', only the changes
+-- enclosed by the catch are rolled back; changes made outside of 'catchSTM'
+-- persist.
+--
+-- If the exception is not caught inside of the 'STM', it is re-thrown by
+-- 'atomically', and the entire 'STM' is rolled back.
+--
+-- Although 'throwSTM' has a type that is an instance of the type of 'throw', the
+-- two functions are subtly different:
+--
+-- > throw e    `seq` x  ===> throw e
+-- > throwSTM e `seq` x  ===> x
+--
+-- The first example will cause the exception @e@ to be raised,
+-- whereas the second one won\'t.  In fact, 'throwSTM' will only cause
+-- an exception to be raised when it is used within the 'STM' monad.
+-- The 'throwSTM' variant should be used in preference to 'throw' to
+-- raise an exception within the 'STM' monad because it guarantees
+-- ordering with respect to other 'STM' operations, whereas 'throw'
+-- does not.
+throwSTM :: (HasCallStack, Exception e) => e -> STM a
+throwSTM e = do
+    -- N.B. Typically use of unsafeIOToSTM is very much frowned upon as this
+    -- is an easy way to end up with nested transactions. However, we can be
+    -- certain that toExceptionWithBacktrace will not initiate a transaction.
+    se <- unsafeIOToSTM (withFrozenCallStack $ toExceptionWithBacktrace e)
+    STM $ raiseIO# se
+
+-- | Exception handling within STM actions.
+--
+-- @'catchSTM' m f@ catches any exception thrown by @m@ using 'throwSTM',
+-- using the function @f@ to handle the exception. If an exception is
+-- thrown, any changes made by @m@ are rolled back, but changes prior to
+-- @m@ persist.
+catchSTM :: Exception e => STM a -> (e -> STM a) -> STM a
+catchSTM (STM m) handler = STM $ catchSTM# m handler'
+    where
+      handler' e = case fromException e of
+                     Just e' -> unSTM (annotateSTM (WhileHandling e) (handler e'))
+                     Nothing -> raiseIO# e
+
+-- | Execute an 'STM' action, adding the given 'ExceptionContext'
+-- to any thrown synchronous exceptions.
+annotateSTM :: forall e a. ExceptionAnnotation e => e -> STM a -> STM a
+annotateSTM ann (STM io) = STM (catchSTM# io handler) -- not catch#, see #27657
+  where
+    handler se = raiseIO# (addExceptionContext ann se)
+
+-- |Shared memory locations that support atomic memory transactions.
+data TVar a = TVar (TVar# RealWorld a)
+
+-- | @since base-4.8.0.0
+instance Eq (TVar a) where
+        (TVar tvar1#) == (TVar tvar2#) = isTrue# (sameTVar# tvar1# tvar2#)
+
+-- | Create a new 'TVar' holding a value supplied
+newTVar :: a -> STM (TVar a)
+newTVar val = STM $ \s1# ->
+    case newTVar# val s1# of
+         (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
+
+-- | @IO@ version of 'newTVar'.  This is useful for creating top-level
+-- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using
+-- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
+-- possible.
+newTVarIO :: a -> IO (TVar a)
+newTVarIO val = IO $ \s1# ->
+    case newTVar# val s1# of
+         (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
+
+-- | Return the current value stored in a 'TVar'.
+-- This is equivalent to
+--
+-- >  readTVarIO = atomically . readTVar
+--
+-- but works much faster, because it doesn't perform a complete
+-- transaction, it just reads the current value of the 'TVar'.
+readTVarIO :: TVar a -> IO a
+readTVarIO (TVar tvar#) = IO $ \s# -> readTVarIO# tvar# s#
+
+-- |Return the current value stored in a 'TVar'.
+readTVar :: TVar a -> STM a
+readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
+
+-- |Write the supplied value into a 'TVar'.
+writeTVar :: TVar a -> a -> STM ()
+writeTVar (TVar tvar#) val = STM $ \s1# ->
+    case writeTVar# tvar# val s1# of
+         s2# -> (# s2#, () #)
+
diff --git a/src/GHC/Internal/Stack/Annotation.hs b/src/GHC/Internal/Stack/Annotation.hs
--- a/src/GHC/Internal/Stack/Annotation.hs
+++ b/src/GHC/Internal/Stack/Annotation.hs
@@ -4,6 +4,7 @@
 
 import GHC.Internal.Base
 import GHC.Internal.Data.Typeable
+import GHC.Internal.Stack (SrcLoc, prettySrcLoc)
 
 -- ----------------------------------------------------------------------------
 -- StackAnnotation
@@ -13,8 +14,38 @@
 -- as the payload of 'AnnFrame' stack frames.
 --
 class StackAnnotation a where
+  -- | Display a human readable string for the 'StackAnnotation'.
+  --
+  -- This is supposed to be the long version of 'displayStackAnnotationShort'
+  -- and may contain a source location.
+  --
+  -- If not provided, 'displayStackAnnotation' is derived from 'stackAnnotationSourceLocation'
+  -- and 'displayStackAnnotationShort'.
   displayStackAnnotation :: a -> String
 
+  -- | Get the 'SrcLoc' of the given 'StackAnnotation'.
+  --
+  -- This is optional, 'SrcLoc' are not strictly required for 'StackAnnotation', but
+  -- it is still heavily encouarged to provide a 'SrcLoc' for better IPE backtraces.
+  stackAnnotationSourceLocation :: a -> Maybe SrcLoc
+
+  -- | The description of the StackAnnotation without any metadata such as source locations.
+  --
+  -- Pefer implementing 'displayStackAnnotationShort' over 'displayStackAnnotation'.
+  displayStackAnnotationShort :: a -> String
+
+  {-# MINIMAL displayStackAnnotation | displayStackAnnotationShort #-}
+
+  displayStackAnnotation ann =
+    displayStackAnnotationShort ann
+      ++ case stackAnnotationSourceLocation ann of
+          Nothing -> ""
+          Just srcLoc -> ", called at " ++ prettySrcLoc srcLoc
+
+  stackAnnotationSourceLocation _ann = Nothing
+
+  displayStackAnnotationShort = displayStackAnnotation
+
 -- ----------------------------------------------------------------------------
 -- Annotations
 -- ----------------------------------------------------------------------------
@@ -28,4 +59,11 @@
   SomeStackAnnotation :: forall a. (Typeable a, StackAnnotation a) => a -> SomeStackAnnotation
 
 instance StackAnnotation SomeStackAnnotation where
-  displayStackAnnotation (SomeStackAnnotation a) = displayStackAnnotation a
+  displayStackAnnotation (SomeStackAnnotation a) =
+    displayStackAnnotation a
+
+  stackAnnotationSourceLocation (SomeStackAnnotation a) =
+    stackAnnotationSourceLocation a
+
+  displayStackAnnotationShort (SomeStackAnnotation a) =
+    displayStackAnnotationShort a
diff --git a/src/GHC/Internal/Stack/Decode.hs b/src/GHC/Internal/Stack/Decode.hs
--- a/src/GHC/Internal/Stack/Decode.hs
+++ b/src/GHC/Internal/Stack/Decode.hs
@@ -11,6 +11,7 @@
 {-# LANGUAGE TypeFamilies #-}
 {-# LANGUAGE TypeInType #-}
 {-# LANGUAGE UnboxedTuples #-}
+{-# LANGUAGE UnboxedSums #-}
 {-# LANGUAGE UnliftedFFITypes #-}
 
 module GHC.Internal.Stack.Decode (
@@ -214,21 +215,19 @@
 stackHead :: StackSnapshot# -> StackFrameLocation
 stackHead s# = (StackSnapshot s#, 0) -- GHC stacks are never empty
 
--- | Advance to the next stack frame (if any)
---
--- The last `Int#` in the result tuple is meant to be treated as bool
--- (has_next).
+-- | Advance to the next stack frame (if any).
 foreign import prim "advanceStackFrameLocationzh"
   advanceStackFrameLocation# ::
-    StackSnapshot# -> Word# -> (# StackSnapshot#, Word#, Int# #)
+    StackSnapshot# -> Word# -> (# (# #) | (# StackSnapshot#, Word# #) #)
 
 -- | Advance to the next stack frame (if any)
 advanceStackFrameLocation :: StackFrameLocation -> Maybe StackFrameLocation
 advanceStackFrameLocation ((StackSnapshot stackSnapshot#), index) =
-  let !(# s', i', hasNext #) = advanceStackFrameLocation# stackSnapshot# (wordOffsetToWord# index)
-   in if I# hasNext > 0
-        then Just (StackSnapshot s', primWordToWordOffset i')
-        else Nothing
+  case advanceStackFrameLocation# stackSnapshot# (wordOffsetToWord# index) of
+    (# (# #) | #) ->
+      Nothing
+    (# | (# s', i' #) #) ->
+      Just (StackSnapshot s', primWordToWordOffset i')
   where
     primWordToWordOffset :: Word# -> WordOffset
     primWordToWordOffset w# = fromIntegral (W# w#)
@@ -269,7 +268,7 @@
     cWordArrayToList ptr size = mapM (peekElemOff ptr) [0 .. (size - 1)]
 
     usedBitmapWords :: Int -> Int
-    usedBitmapWords 0 = error "Invalid large bitmap size 0."
+    usedBitmapWords 0 = 0
     usedBitmapWords size = (size `div` fromIntegral wORD_SIZE_IN_BITS) + 1
 
     bitmapWordsPointerness :: Word -> [Word] -> [Pointerness]
diff --git a/src/GHC/Internal/Stats.hsc b/src/GHC/Internal/Stats.hsc
--- a/src/GHC/Internal/Stats.hsc
+++ b/src/GHC/Internal/Stats.hsc
@@ -111,6 +111,8 @@
   , gc_cpu_ns :: RtsTime
     -- | Total elapsed time used by the GC
   , gc_elapsed_ns :: RtsTime
+    -- | Total elapsed time used during GC synchronization
+  , gc_sync_elapsed_ns :: RtsTime
     -- | Total CPU time (at the previous GC)
   , cpu_ns :: RtsTime
     -- | Total elapsed time (at the previous GC)
@@ -234,6 +236,7 @@
     mutator_elapsed_ns <- (# peek RTSStats, mutator_elapsed_ns) p
     gc_cpu_ns <- (# peek RTSStats, gc_cpu_ns) p
     gc_elapsed_ns <- (# peek RTSStats, gc_elapsed_ns) p
+    gc_sync_elapsed_ns <- (# peek RTSStats, gc_sync_elapsed_ns) p
     cpu_ns <- (# peek RTSStats, cpu_ns) p
     elapsed_ns <- (# peek RTSStats, elapsed_ns) p
     nonmoving_gc_sync_cpu_ns <- (# peek RTSStats, nonmoving_gc_sync_cpu_ns) p
diff --git a/src/GHC/Internal/System/Environment/ExecutablePath.hsc b/src/GHC/Internal/System/Environment/ExecutablePath.hsc
--- a/src/GHC/Internal/System/Environment/ExecutablePath.hsc
+++ b/src/GHC/Internal/System/Environment/ExecutablePath.hsc
@@ -41,7 +41,7 @@
 import GHC.Internal.IO (FilePath)
 import GHC.Internal.Real
 #if defined(darwin_HOST_OS)
-import GHC.Internal.Control.Exception (catch, throw)
+import GHC.Internal.Control.Exception (catchJust)
 import GHC.Internal.Word
 import GHC.Internal.Foreign.C.Types
 import GHC.Internal.Foreign.C.Error
@@ -60,7 +60,7 @@
 import GHC.Internal.Foreign.Marshal.Array
 import GHC.Internal.System.Posix.Internals
 #elif defined(solaris2_HOST_OS)
-import GHC.Internal.Control.Exception (catch, throw)
+import GHC.Internal.Control.Exception (catchJust)
 import GHC.Internal.Data.Functor
 import GHC.Internal.Foreign.C.Types
 import GHC.Internal.Foreign.C.Error
@@ -69,7 +69,7 @@
 import GHC.Internal.System.IO.Error (isDoesNotExistError)
 import GHC.Internal.System.Posix.Internals
 #elif defined(freebsd_HOST_OS) || defined(netbsd_HOST_OS)
-import GHC.Internal.Control.Exception (catch, throw)
+import GHC.Internal.Control.Exception (catchJust)
 import GHC.Internal.Data.Functor
 import GHC.Internal.Foreign.C.Types
 import GHC.Internal.Foreign.C.Error
@@ -193,10 +193,10 @@
 getExecutablePath = _NSGetExecutablePath >>= realpath
 
 -- realpath(3) fails with ENOENT file does not exist (e.g. was deleted)
-executablePath = Just (fmap Just getExecutablePath `catch` f)
+executablePath = Just (catchJust f (fmap Just getExecutablePath) (\_ -> pure Nothing))
   where
-  f e | isDoesNotExistError e = pure Nothing
-      | otherwise             = throw e
+  f e | isDoesNotExistError e = Just ()
+      | otherwise             = Nothing
 
 --------------------------------------------------------------------------------
 -- Linux / Solaris / Hurd
@@ -232,12 +232,12 @@
 #  elif defined(solaris2_HOST_OS)
 getExecutablePath = readSymbolicLink "/proc/self/path/a.out"
 
-executablePath = Just ((Just <$> getExecutablePath) `catch` f)
+executablePath = Just (catchJust f (Just <$> getExecutablePath) (\_ -> pure Nothing))
   where
     -- readlink(2) fails with ENOENT when the executable has been deleted,
     -- even though the symlink itself still exists according to readdir(3).
-    f e | isDoesNotExistError e = pure Nothing
-        | otherwise             = throw e
+    f e | isDoesNotExistError e = Just ()
+        | otherwise             = Nothing
 
 #endif
 
@@ -287,15 +287,15 @@
       ]
 #  endif
 
-executablePath = Just (fmap Just getExecutablePath `catch` f)
+executablePath = Just (catchJust f (fmap Just getExecutablePath) (\_ -> pure Nothing))
   where
   -- The sysctl fails with errno ENOENT when executable has been deleted;
   -- see https://gitlab.haskell.org/ghc/ghc/-/issues/12377#note_321346.
-  f e | isDoesNotExistError e = pure Nothing
+  f e | isDoesNotExistError e = Just ()
 
   -- As far as I know, ENOENT is the only kind of failure that should be
   -- expected and handled.  Re-throw other errors.
-      | otherwise             = throw e
+      | otherwise             = Nothing
 
 
 --------------------------------------------------------------------------------
diff --git a/src/GHC/Internal/System/IO/Error.hs b/src/GHC/Internal/System/IO/Error.hs
--- a/src/GHC/Internal/System/IO/Error.hs
+++ b/src/GHC/Internal/System/IO/Error.hs
@@ -319,9 +319,10 @@
 ioeSetFileName    ioe filename = ioe{ ioe_filename = Just filename }
 
 -- | Catch any 'IOError' that occurs in the computation and throw a
--- modified version.
+-- modified version, preserving the original 'ExceptionContext'.
 modifyIOError :: (IOError -> IOError) -> IO a -> IO a
-modifyIOError f io = catch io (\e -> throwIO (NoBacktrace $ f e))
+modifyIOError f io = catchNoPropagate io $ \(ExceptionWithContext ctx e) ->
+  rethrowIO (ExceptionWithContext ctx (f e))
 
 -- -----------------------------------------------------------------------------
 -- annotating an IOError
diff --git a/src/GHC/Internal/Types.hs b/src/GHC/Internal/Types.hs
--- a/src/GHC/Internal/Types.hs
+++ b/src/GHC/Internal/Types.hs
@@ -35,6 +35,7 @@
         SPEC(..),
         Symbol,
         Any,
+        UnusedType,
 
         -- * Type equality
         type (~), type (~~), Coercible,
@@ -283,48 +284,53 @@
 *                                                                      *
 ********************************************************************* -}
 
--- | The type constructor @Any :: forall k. k@ is a type to which you can unsafely coerce any type, and back.
+-- | The type constructor @Any :: forall k. k@ allows creating an arbitrary type
+-- of the given kind.
 --
--- For @unsafeCoerce@ this means for all lifted types @t@ that
--- @unsafeCoerce (unsafeCoerce x :: Any) :: t@ is equivalent to @x@ and safe.
+-- It can be used to create a placeholder type when you only have a kind in hand.
 --
--- The same is true for *all* types when using
--- @
---   unsafeCoerce# :: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep)
---                   (a :: TYPE r1) (b :: TYPE r2).
---                   a -> b
--- @
--- but /only/ if you instantiate @r1@ and @r2@ to the /same/ runtime representation.
--- For example using @(unsafeCoerce# :: forall (a :: TYPE IntRep) (b :: TYPE IntRep). a -> b) x@
--- is fine, but @(unsafeCoerce# :: forall (a :: TYPE IntRep) (b :: TYPE FloatRep). a -> b)@
--- will likely cause seg-faults or worse.
--- For this resason, users should always prefer unsafeCoerce over unsafeCoerce# when possible.
+-- You can use 'unsafeCoerce#' to unsafely coerce a value from @ty :: k@ to @Any \@k@
+-- and back. As per the documentation of 'unsafeCoerce#', this is only sound if both
+-- sides have the __exact same__runtime representation. Some examples:
 --
--- Here are some more examples:
 -- @
---    bad_a1 :: Any @(TYPE 'IntRep)
---    bad_a1 = unsafeCoerce# True
---
---    bad_a2 :: Any @(TYPE ('BoxedRep 'UnliftedRep))
---    bad_a2 = unsafeCoerce# True
+--    unsafeCoerce# True :: (Any :: Type)                -- OK
+--    unsafeCoerce# (1# :: Int#) :: (Any :: TYPE IntRep) -- OK
+--    unsafeCoerce# True :: (Any :: Type IntRep)         -- INVALID
+--    unsafeCoerce  True :: (Any :: UnliftedType)        -- INVALID
+--    unsafeCoerce  (ba :: ByteArray#) :: (Any :: Type)  -- INVALID
 -- @
--- Here @bad_a1@ is bad because we started with @True :: (Bool :: Type)@, represented by a boxed heap pointer,
--- and coerced it to @a1 :: Any @(TYPE 'IntRep)@, whose representation is a non-pointer integer.
--- That's why we had to use `unsafeCoerce#`; it is really unsafe because it can change representations.
--- Similarly @bad_a2@ is bad because although both @True@ and @bad_a2@ are represented by a heap pointer,
--- @True@ is lifted but @bad_a2@ is not; bugs here may be rather subtle.
 --
--- If you must use unsafeCoerce# to cast to `Any`, type annotations are recommended
--- to make sure that @Any@ has the correct kind. As casting between different runtimereps is
--- unsound. For example to cast a @ByteArray#@ to @Any@ you might use:
--- @
---    unsafeCoerce# b :: (Any :: TYPE ('BoxedRep 'Unlifted))
--- @
+-- To avoid accidentally unsafe-coercing between different representations,
+-- it is recommended to:
+--  - use explicit type annotations or type applications at every use-site
+--    of 'unsafeCoerce#'
+--  - use representation-monomorphic variants such as 'unsafeCoerce' or
+--    'unsafeCoerceUnlifted'.
+--
+-- In particular, this also implies it is safe to round-trip unsafe-coercion via 'Any',
+-- as long as the kinds line up e.g. @unsafeCoerce (unsafeCoerce (val :: a) :: 'Any') :: a@
+-- is safe in that way.
 type family Any :: k where { }
--- See Note [Any types] in GHC.Builtin.Types. Also, for a bit of history on Any see
+-- See Note [The types Any and UnusedType] in GHC.Builtin.Types. Also, for a bit of history on Any see
 -- #10886. Note that this must be a *closed* type family: we need to ensure
 -- that this can't reduce to a `data` type for the results discussed in
--- Note [Any types].
+-- Note [The types Any and UnusedType].
+--
+
+-- | @UnusedType \@k "foo"@ denotes an arbitrary type of kind
+-- @k@ and is pretty-printed as @foo@ .
+--
+-- This type is used internally by GHC to fill in otherwise
+-- unconstrained type variables, such as @a@ in @length \@a []@.
+-- It is exported purely for documentation purposes.
+--
+-- You shouldn't ever see this type in the compiler's output if
+-- you don't specifically ask for it, for instance when viewing
+-- core, since the compiler will try hard to output a given
+-- @'UnusedType' "m_0"@ simply as @m_0@.
+type family UnusedType :: Symbol -> k where { }
+-- See Note [The types Any and UnusedType] in GHC.Builtin.Types.
 
 {- *********************************************************************
 *                                                                      *
