- Use _SEH2_YIELD when returning from an exception instead of returning outside the...
[reactos.git] / reactos / ntoskrnl / ke / wait.c
index 99dce85..2e9c1c8 100644 (file)
 /*
- * COPYRIGHT:       See COPYING in the top level directory
  * PROJECT:         ReactOS Kernel
+ * LICENSE:         GPL - See COPYING in the top level directory
  * FILE:            ntoskrnl/ke/wait.c
  * PURPOSE:         Manages waiting for Dispatcher Objects
- * PROGRAMMERS:     Alex Ionescu (alex@relsoft.net)
+ * PROGRAMMERS:     Alex Ionescu (alex.ionescu@reactos.org)
  *                  Gunnar Dalsnes
  */
 
 /* INCLUDES ******************************************************************/
 
 #include <ntoskrnl.h>
-
 #define NDEBUG
-#include <internal/debug.h>
+#include <debug.h>
 
-/* GLOBALS ******************************************************************/
+/* PRIVATE FUNCTIONS *********************************************************/
 
-KSPIN_LOCK DispatcherDatabaseLock;
+VOID
+FASTCALL
+KiWaitTest(IN PVOID ObjectPointer,
+           IN KPRIORITY Increment)
+{
+    PLIST_ENTRY WaitEntry, WaitList;
+    PKWAIT_BLOCK WaitBlock;
+    PKTHREAD WaitThread;
+    PKMUTANT FirstObject = ObjectPointer;
+    NTSTATUS WaitStatus;
 
-/* PRIVATE FUNCTIONS *********************************************************/
+    /* Loop the Wait Entries */
+    WaitList = &FirstObject->Header.WaitListHead;
+    WaitEntry = WaitList->Flink;
+    while ((FirstObject->Header.SignalState > 0) && (WaitEntry != WaitList))
+    {
+        /* Get the current wait block */
+        WaitBlock = CONTAINING_RECORD(WaitEntry, KWAIT_BLOCK, WaitListEntry);
+        WaitThread = WaitBlock->Thread;
+        WaitStatus = STATUS_KERNEL_APC;
 
-/*
- * Rules for checking alertability:
- *  - For Alertable waits ONLY:
- *      * We don't wait and return STATUS_ALERTED if the thread is alerted
- *        in EITHER the specified wait mode OR in Kernel Mode.
- *  - For BOTH Alertable AND Non-Alertable waits:
- *      * We don't want and return STATUS_USER_APC if the User Mode APC list
- *        is not empty AND the wait mode is User Mode.
- */
-#define KiCheckAlertability()                                               \
-    if (Alertable)                                                          \
-    {                                                                       \
-        if (CurrentThread->Alerted[(int)WaitMode])                          \
-        {                                                                   \
-            CurrentThread->Alerted[(int)WaitMode] = FALSE;                  \
-            WaitStatus = STATUS_ALERTED;                                    \
-            break;                                                          \
-        }                                                                   \
-        else if ((WaitMode != KernelMode) &&                                \
-                (!IsListEmpty(&CurrentThread->ApcState.ApcListHead[UserMode])))\
-        {                                                                   \
-            CurrentThread->ApcState.UserApcPending = TRUE;                  \
-            WaitStatus = STATUS_USER_APC;                                   \
-            break;                                                          \
-        }                                                                   \
-        else if (CurrentThread->Alerted[KernelMode])                        \
-        {                                                                   \
-            CurrentThread->Alerted[KernelMode] = FALSE;                     \
-            WaitStatus = STATUS_ALERTED;                                    \
-            break;                                                          \
-        }                                                                   \
-    }                                                                       \
-    else if ((WaitMode != KernelMode) &&                                    \
-             (CurrentThread->ApcState.UserApcPending))                      \
-    {                                                                       \
-        WaitStatus = STATUS_USER_APC;                                       \
-        break;                                                              \
-    }                                                                       \
+        /* Check the current Wait Mode */
+        if (WaitBlock->WaitType == WaitAny)
+        {
+            /* Easy case, satisfy only this wait */
+            WaitStatus = (NTSTATUS)WaitBlock->WaitKey;
+            KiSatisfyObjectWait(FirstObject, WaitThread);
+        }
 
-/* PUBLIC FUNCTIONS **********************************************************/
+        /* Now do the rest of the unwait */
+        KiUnwaitThread(WaitThread, WaitStatus, Increment);
+        WaitEntry = WaitList->Flink;
+    }
+}
 
 VOID
 FASTCALL
-KiWaitSatisfyAll(PKWAIT_BLOCK FirstBlock)
+KiUnlinkThread(IN PKTHREAD Thread,
+               IN NTSTATUS WaitStatus)
 {
-    PKWAIT_BLOCK WaitBlock = FirstBlock;
-    PKTHREAD WaitThread = WaitBlock->Thread;
+    PKWAIT_BLOCK WaitBlock;
+    PKTIMER Timer;
+
+    /* Update wait status */
+    Thread->WaitStatus |= WaitStatus;
 
-    /* Loop through all the Wait Blocks, and wake each Object */
+    /* Remove the Wait Blocks from the list */
+    WaitBlock = Thread->WaitBlockList;
     do
     {
-        /* Make sure it hasn't timed out */
-        if (WaitBlock->WaitKey != STATUS_TIMEOUT)
-        {
-            /* Wake the Object */
-            KiSatisfyObjectWait((PKMUTANT)WaitBlock->Object, WaitThread);
-        }
+        /* Remove it */
+        RemoveEntryList(&WaitBlock->WaitListEntry);
 
-        /* Move to the next block */
+        /* Go to the next one */
         WaitBlock = WaitBlock->NextWaitBlock;
-    }
-    while (WaitBlock != FirstBlock);
+    } while (WaitBlock != Thread->WaitBlockList);
+
+    /* Remove the thread from the wait list! */
+    if (Thread->WaitListEntry.Flink) RemoveEntryList(&Thread->WaitListEntry);
+
+    /* Check if there's a Thread Timer */
+    Timer = &Thread->Timer;
+    if (Timer->Header.Inserted) KxRemoveTreeTimer(Timer);
+
+    /* Increment the Queue's active threads */
+    if (Thread->Queue) Thread->Queue->CurrentCount++;
 }
 
-/*
- * @implemented
- *
- * FUNCTION: Puts the current thread into an alertable or nonalertable
- * wait state for a given internal
- * ARGUMENTS:
- *          WaitMode = Processor mode in which the caller is waiting
- *          Altertable = Specifies if the wait is alertable
- *          Interval = Specifies the interval to wait
- * RETURNS: Status
- */
-NTSTATUS
-STDCALL
-KeDelayExecutionThread(KPROCESSOR_MODE WaitMode,
-                       BOOLEAN Alertable,
-                       PLARGE_INTEGER Interval)
+/* Must be called with the dispatcher lock held */
+VOID
+FASTCALL
+KiUnwaitThread(IN PKTHREAD Thread,
+               IN NTSTATUS WaitStatus,
+               IN KPRIORITY Increment)
 {
-    PKWAIT_BLOCK TimerWaitBlock;
-    PKTIMER ThreadTimer;
-    PKTHREAD CurrentThread = KeGetCurrentThread();
-    NTSTATUS WaitStatus = STATUS_SUCCESS;
-    DPRINT("Entering KeDelayExecutionThread\n");
+    /* Unlink the thread */
+    KiUnlinkThread(Thread, WaitStatus);
 
-    /* Check if the lock is already held */
-    if (CurrentThread->WaitNext)
-    {
-        /* Lock is held, disable Wait Next */
-        DPRINT("Lock is held\n");
-        CurrentThread->WaitNext = FALSE;
-    }
-    else
+    /* Tell the scheduler do to the increment when it readies the thread */
+    ASSERT(Increment >= 0);
+    Thread->AdjustIncrement = (SCHAR)Increment;
+    Thread->AdjustReason = AdjustUnwait;
+
+    /* Reschedule the Thread */
+    KiReadyThread(Thread);
+}
+
+VOID
+FASTCALL
+KiAcquireFastMutex(IN PFAST_MUTEX FastMutex)
+{
+    /* Increase contention count */
+    FastMutex->Contention++;
+
+    /* Wait for the event */
+    KeWaitForSingleObject(&FastMutex->Gate,
+                          WrMutex,
+                          KernelMode,
+                          FALSE,
+                          NULL);
+}
+
+VOID
+FASTCALL
+KiAcquireGuardedMutex(IN OUT PKGUARDED_MUTEX GuardedMutex)
+{
+    ULONG BitsToRemove, BitsToAdd;
+    LONG OldValue, NewValue;
+
+    /* We depend on these bits being just right */
+    C_ASSERT((GM_LOCK_WAITER_WOKEN * 2) == GM_LOCK_WAITER_INC);
+    
+    /* Increase the contention count */
+    GuardedMutex->Contention++;
+    
+    /* Start by unlocking the Guarded Mutex */
+    BitsToRemove = GM_LOCK_BIT;
+    BitsToAdd = GM_LOCK_WAITER_INC;
+    
+    /* Start change loop */
+    for (;;)
     {
-        /* Lock not held, acquire it */
-        DPRINT("Lock is not held, acquiring\n");
-        CurrentThread->WaitIrql = KeAcquireDispatcherDatabaseLock();
+        /* Loop sanity checks */
+        ASSERT((BitsToRemove == GM_LOCK_BIT) ||
+               (BitsToRemove == (GM_LOCK_BIT | GM_LOCK_WAITER_WOKEN)));
+        ASSERT((BitsToAdd == GM_LOCK_WAITER_INC) ||
+               (BitsToAdd == GM_LOCK_WAITER_WOKEN));
+        
+        /* Get the Count Bits */
+        OldValue = GuardedMutex->Count;
+        
+        /* Start internal bit change loop */
+        for (;;)
+        {
+            /* Check if the Guarded Mutex is locked */
+            if (OldValue & GM_LOCK_BIT)
+            {
+                /* Sanity check */
+                ASSERT((BitsToRemove == GM_LOCK_BIT) ||
+                       ((OldValue & GM_LOCK_WAITER_WOKEN) != 0));
+                
+                /* Unlock it by removing the Lock Bit */
+                NewValue = OldValue ^ BitsToRemove;
+                NewValue = InterlockedCompareExchange(&GuardedMutex->Count,
+                                                      NewValue,
+                                                      OldValue);
+                if (NewValue == OldValue) return;
+            }
+            else
+            {
+                /* The Guarded Mutex isn't locked, so simply set the bits */
+                NewValue = OldValue + BitsToAdd;
+                NewValue = InterlockedCompareExchange(&GuardedMutex->Count,
+                                                      NewValue,
+                                                      OldValue);
+                if (NewValue == OldValue) break;
+            }
+            
+            /* Old value changed, loop again */
+            OldValue = NewValue;
+        }
+        
+        /* Now we have to wait for it */
+        KeWaitForGate(&GuardedMutex->Gate, WrGuardedMutex, KernelMode);
+        ASSERT((GuardedMutex->Count & GM_LOCK_WAITER_WOKEN) != 0);
+        
+        /* Ok, the wait is done, so set the new bits */
+        BitsToRemove = GM_LOCK_BIT | GM_LOCK_WAITER_WOKEN;
+        BitsToAdd = GM_LOCK_WAITER_WOKEN;
     }
+}
 
-    /* Use built-in Wait block */
-    TimerWaitBlock = &CurrentThread->WaitBlock[TIMER_WAIT_BLOCK];
+//
+// This routine exits the dispatcher after a compatible operation and
+// swaps the context to the next scheduled thread on the current CPU if
+// one is available.
+//
+// It does NOT attempt to scan for a new thread to schedule.
+//
+VOID
+FASTCALL
+KiExitDispatcher(IN KIRQL OldIrql)
+{
+    PKPRCB Prcb = KeGetCurrentPrcb();
+    PKTHREAD Thread, NextThread;
+    BOOLEAN PendingApc;
 
-    /* Start Wait Loop */
-    do
+    /* Make sure we're at synchronization level */
+    ASSERT(KeGetCurrentIrql() == SYNCH_LEVEL);
+
+    /* Check if we have deferred threads */
+    KiCheckDeferredReadyList(Prcb);
+
+    /* Check if we were called at dispatcher level or higher */
+    if (OldIrql >= DISPATCH_LEVEL)
     {
-        /* Check if a kernel APC is pending and we were below APC_LEVEL */
-        if ((CurrentThread->ApcState.KernelApcPending) &&
-            (CurrentThread->WaitIrql < APC_LEVEL))
+        /* Check if we have a thread to schedule, and that no DPC is active */
+        if ((Prcb->NextThread) && !(Prcb->DpcRoutineActive))
         {
-            /* Unlock the dispatcher */
-            KeReleaseDispatcherDatabaseLock(CurrentThread->WaitIrql);
-            goto SkipWait;
+            /* Request DPC interrupt */
+            HalRequestSoftwareInterrupt(DISPATCH_LEVEL);
         }
 
-        /* Check if we can do an alertable wait, if requested */
-        KiCheckAlertability();
+        /* Lower IRQL and exit */
+        goto Quickie;
+    }
 
-        /* Set status */
-        CurrentThread->WaitStatus = STATUS_WAIT_0;
+    /* Make sure there's a new thread scheduled */
+    if (!Prcb->NextThread) goto Quickie;
 
-        /* Set Timer */
-        ThreadTimer = &CurrentThread->Timer;
+    /* Lock the PRCB */
+    KiAcquirePrcbLock(Prcb);
 
-        /* Setup the Wait Block */
-        CurrentThread->WaitBlockList = TimerWaitBlock;
-        TimerWaitBlock->NextWaitBlock = TimerWaitBlock;
+    /* Get the next and current threads now */
+    NextThread = Prcb->NextThread;
+    Thread = Prcb->CurrentThread;
 
-        /* Link the timer to this Wait Block */
-        ThreadTimer->Header.WaitListHead.Flink = &TimerWaitBlock->WaitListEntry;
-        ThreadTimer->Header.WaitListHead.Blink = &TimerWaitBlock->WaitListEntry;
+    /* Set current thread's swap busy to true */
+    KiSetThreadSwapBusy(Thread);
 
-        /* Insert the Timer into the Timer Lists and enable it */
-        if (!KiInsertTimer(ThreadTimer, *Interval))
+    /* Switch threads in PRCB */
+    Prcb->NextThread = NULL;
+    Prcb->CurrentThread = NextThread;
+
+    /* Set thread to running */
+    NextThread->State = Running;
+
+    /* Queue it on the ready lists */
+    KxQueueReadyThread(Thread, Prcb);
+
+    /* Set wait IRQL */
+    Thread->WaitIrql = OldIrql;
+
+    /* Swap threads and check if APCs were pending */
+    PendingApc = KiSwapContext(Thread, NextThread);
+    if (PendingApc)
+    {
+        /* Lower only to APC */
+        KeLowerIrql(APC_LEVEL);
+
+        /* Deliver APCs */
+        KiDeliverApc(KernelMode, NULL, NULL);
+        ASSERT(OldIrql == PASSIVE_LEVEL);
+    }
+
+    /* Lower IRQl back */
+Quickie:
+    KeLowerIrql(OldIrql);
+}
+
+/* PUBLIC FUNCTIONS **********************************************************/
+
+/*
+ * @implemented
+ */
+NTSTATUS
+NTAPI
+KeDelayExecutionThread(IN KPROCESSOR_MODE WaitMode,
+                       IN BOOLEAN Alertable,
+                       IN PLARGE_INTEGER Interval OPTIONAL)
+{
+    PKTIMER Timer;
+    PKWAIT_BLOCK TimerBlock;
+    PKTHREAD Thread = KeGetCurrentThread();
+    NTSTATUS WaitStatus;
+    BOOLEAN Swappable;
+    PLARGE_INTEGER OriginalDueTime;
+    LARGE_INTEGER DueTime, NewDueTime, InterruptTime;
+    ULONG Hand = 0;
+
+    /* If this is a user-mode wait of 0 seconds, yield execution */
+    if (!(Interval->QuadPart) && (WaitMode != KernelMode))
+    {
+        /* Make sure the wait isn't alertable or interrupting an APC */
+        if (!(Alertable) && !(Thread->ApcState.UserApcPending))
         {
-            /* FIXME: The timer already expired, we should find a new ready thread */
-            WaitStatus = STATUS_SUCCESS;
-            break;
+            /* Yield execution */
+            NtYieldExecution();
         }
+    }
+
+    /* Setup the original time and timer/wait blocks */
+    OriginalDueTime = Interval;
+    Timer = &Thread->Timer;
+    TimerBlock = &Thread->WaitBlock[TIMER_WAIT_BLOCK];
+
+    /* Check if the lock is already held */
+    if (!Thread->WaitNext) goto WaitStart;
 
-        /* Handle Kernel Queues */
-        if (CurrentThread->Queue)
+    /*  Otherwise, we already have the lock, so initialize the wait */
+    Thread->WaitNext = FALSE;
+    KxDelayThreadWait();
+
+    /* Start wait loop */
+    for (;;)
+    {
+        /* Disable pre-emption */
+        Thread->Preempted = FALSE;
+
+        /* Check if a kernel APC is pending and we're below APC_LEVEL */
+        if ((Thread->ApcState.KernelApcPending) && !(Thread->SpecialApcDisable) &&
+            (Thread->WaitIrql < APC_LEVEL))
         {
-            DPRINT("Waking Queue\n");
-            KiWakeQueue(CurrentThread->Queue);
+            /* Unlock the dispatcher */
+            KiReleaseDispatcherLock(Thread->WaitIrql);
         }
+        else
+        {
+            /* Check if we have to bail out due to an alerted state */
+            WaitStatus = KiCheckAlertability(Thread, Alertable, WaitMode);
+            if (WaitStatus != STATUS_WAIT_0) break;
 
-        /* Setup the wait information */
-        CurrentThread->Alertable = Alertable;
-        CurrentThread->WaitMode = WaitMode;
-        CurrentThread->WaitReason = DelayExecution;
-        CurrentThread->WaitTime = ((PLARGE_INTEGER)&KeTickCount)->LowPart;
-        CurrentThread->State = Waiting;
+            /* Check if the timer expired */
+            InterruptTime.QuadPart = KeQueryInterruptTime();
+            if ((ULONGLONG)InterruptTime.QuadPart >= Timer->DueTime.QuadPart)
+            {
+                /* It did, so we don't need to wait */
+                goto NoWait;
+            }
 
-        /* Find a new thread to run */
-        DPRINT("Swapping threads\n");
-        WaitStatus = KiSwapThread();
+            /* It didn't, so activate it */
+            Timer->Header.Inserted = TRUE;
 
-        /* Check if we were executing an APC or if we timed out */
-        if (WaitStatus != STATUS_KERNEL_APC)
-        {
-            /* This is a good thing */
-            if (WaitStatus == STATUS_TIMEOUT) WaitStatus = STATUS_SUCCESS;
+            /* Handle Kernel Queues */
+            if (Thread->Queue) KiActivateWaiterQueue(Thread->Queue);
 
-            /* Return Status */
-            return WaitStatus;
-        }
+            /* Setup the wait information */
+            Thread->State = Waiting;
+
+            /* Add the thread to the wait list */
+            KiAddThreadToWaitList(Thread, Swappable);
 
-        /* FIXME: Fixup interval */
+            /* Insert the timer and swap the thread */
+            ASSERT(Thread->WaitIrql <= DISPATCH_LEVEL);
+            KiSetThreadSwapBusy(Thread);
+            KxInsertTimer(Timer, Hand);
+            WaitStatus = KiSwapThread(Thread, KeGetCurrentPrcb());
 
-        /* Acquire again the lock */
-SkipWait:
-        DPRINT("Looping again\n");
-        CurrentThread->WaitIrql = KeAcquireDispatcherDatabaseLock();
+            /* Check if were swapped ok */
+            if (WaitStatus != STATUS_KERNEL_APC)
+            {
+                /* This is a good thing */
+                if (WaitStatus == STATUS_TIMEOUT) WaitStatus = STATUS_SUCCESS;
+
+                /* Return Status */
+                return WaitStatus;
+            }
+
+            /* Recalculate due times */
+            Interval = KiRecalculateDueTime(OriginalDueTime,
+                                            &DueTime,
+                                            &NewDueTime);
+        }
+
+WaitStart:
+        /* Setup a new wait */
+        Thread->WaitIrql = KeRaiseIrqlToSynchLevel();
+        KxDelayThreadWait();
+        KiAcquireDispatcherLockAtDpcLevel();
     }
-    while (TRUE);
 
-    /* Release the Lock, we are done */
-    DPRINT("Returning from KeDelayExecutionThread(), %x. Status: %d\n",
-            KeGetCurrentThread(), Status);
-    KeReleaseDispatcherDatabaseLock(CurrentThread->WaitIrql);
+    /* We're done! */
+    KiReleaseDispatcherLock(Thread->WaitIrql);
     return WaitStatus;
+
+NoWait:
+    /* There was nothing to wait for. Did we have a wait interval? */
+    if (!Interval->QuadPart)
+    {
+        /* Unlock the dispatcher and do a yield */
+        KiReleaseDispatcherLock(Thread->WaitIrql);
+        return NtYieldExecution();
+    }
+
+    /* Unlock the dispatcher and adjust the quantum for a no-wait */
+    KiReleaseDispatcherLockFromDpcLevel();
+    KiAdjustQuantumThread(Thread);
+    return STATUS_SUCCESS;
 }
 
 /*
  * @implemented
- *
- * FUNCTION: Puts the current thread into a wait state until the
- * given dispatcher object is set to signalled
- * ARGUMENTS:
- *         Object = Object to wait on
- *         WaitReason = Reason for the wait (debugging aid)
- *         WaitMode = Can be KernelMode or UserMode, if UserMode then
- *                    user-mode APCs can be delivered and the thread's
- *                    stack can be paged out
- *         Altertable = Specifies if the wait is a alertable
- *         Timeout = Optional timeout value
- * RETURNS: Status
  */
 NTSTATUS
-STDCALL
-KeWaitForSingleObject(PVOID Object,
-                      KWAIT_REASON WaitReason,
-                      KPROCESSOR_MODE WaitMode,
-                      BOOLEAN Alertable,
-                      PLARGE_INTEGER Timeout)
+NTAPI
+KeWaitForSingleObject(IN PVOID Object,
+                      IN KWAIT_REASON WaitReason,
+                      IN KPROCESSOR_MODE WaitMode,
+                      IN BOOLEAN Alertable,
+                      IN PLARGE_INTEGER Timeout OPTIONAL)
 {
-    PKMUTANT CurrentObject;
-    PKWAIT_BLOCK WaitBlock;
-    PKWAIT_BLOCK TimerWaitBlock;
-    PKTIMER ThreadTimer;
-    PKTHREAD CurrentThread = KeGetCurrentThread();
-    NTSTATUS WaitStatus = STATUS_SUCCESS;
-    DPRINT("Entering KeWaitForSingleObject\n");
+    PKTHREAD Thread = KeGetCurrentThread();
+    PKMUTANT CurrentObject = (PKMUTANT)Object;
+    PKWAIT_BLOCK WaitBlock = &Thread->WaitBlock[0];
+    PKWAIT_BLOCK TimerBlock = &Thread->WaitBlock[TIMER_WAIT_BLOCK];
+    PKTIMER Timer = &Thread->Timer;
+    NTSTATUS WaitStatus;
+    BOOLEAN Swappable;
+    LARGE_INTEGER DueTime, NewDueTime, InterruptTime;
+    PLARGE_INTEGER OriginalDueTime = Timeout;
+    ULONG Hand = 0;
 
     /* Check if the lock is already held */
-    if (CurrentThread->WaitNext)
-    {
-        /* Lock is held, disable Wait Next */
-        DPRINT("Lock is held\n");
-        CurrentThread->WaitNext = FALSE;
-    }
-    else
-    {
-        /* Lock not held, acquire it */
-        DPRINT("Lock is not held, acquiring\n");
-        CurrentThread->WaitIrql = KeAcquireDispatcherDatabaseLock();
-    }
+    if (!Thread->WaitNext) goto WaitStart;
 
-    /* Start the actual Loop */
-    do
+    /*  Otherwise, we already have the lock, so initialize the wait */
+    Thread->WaitNext = FALSE;
+    KxSingleThreadWait();
+
+    /* Start wait loop */
+    for (;;)
     {
-        /* Check if a kernel APC is pending and we were below APC_LEVEL */
-        if ((CurrentThread->ApcState.KernelApcPending) &&
-            (CurrentThread->WaitIrql < APC_LEVEL))
+        /* Disable pre-emption */
+        Thread->Preempted = FALSE;
+
+        /* Check if a kernel APC is pending and we're below APC_LEVEL */
+        if ((Thread->ApcState.KernelApcPending) && !(Thread->SpecialApcDisable) &&
+            (Thread->WaitIrql < APC_LEVEL))
         {
             /* Unlock the dispatcher */
-            KeReleaseDispatcherDatabaseLock(CurrentThread->WaitIrql);
-            goto SkipWait;
+            KiReleaseDispatcherLock(Thread->WaitIrql);
         }
-
-        /* Set default status */
-        CurrentThread->WaitStatus = STATUS_WAIT_0;
-
-        /* Append wait block to the KTHREAD wait block list */
-        CurrentThread->WaitBlockList = WaitBlock = &CurrentThread->WaitBlock[0];
-
-        /* Get the Current Object */
-        CurrentObject = (PKMUTANT)Object;
-
-        /* Check if it's a mutant */
-        if (CurrentObject->Header.Type == MutantObject)
+        else
         {
-            /* Check its signal state or if we own it */
-            if ((CurrentObject->Header.SignalState > 0) ||
-                (CurrentThread == CurrentObject->OwnerThread))
+            /* Sanity check */
+            ASSERT(CurrentObject->Header.Type != QueueObject);
+
+            /* Check if it's a mutant */
+            if (CurrentObject->Header.Type == MutantObject)
             {
-                /* Just unwait this guy and exit */
-                if (CurrentObject->Header.SignalState != (LONG)MINLONG)
+                /* Check its signal state or if we own it */
+                if ((CurrentObject->Header.SignalState > 0) ||
+                    (Thread == CurrentObject->OwnerThread))
                 {
-                    /* It has a normal signal state, so unwait it and return */
-                    KiSatisfyMutantWait(CurrentObject, CurrentThread);
-                    WaitStatus = CurrentThread->WaitStatus;
-                    goto DontWait;
-                }
-                else
-                {
-                    /* According to wasm.ru, we must raise this exception (tested and true) */
-                    KeReleaseDispatcherDatabaseLock(CurrentThread->WaitIrql);
-                    ExRaiseStatus(STATUS_MUTANT_LIMIT_EXCEEDED);
+                    /* Just unwait this guy and exit */
+                    if (CurrentObject->Header.SignalState != (LONG)MINLONG)
+                    {
+                        /* It has a normal signal state. Unwait and return */
+                        KiSatisfyMutantWait(CurrentObject, Thread);
+                        WaitStatus = Thread->WaitStatus;
+                        goto DontWait;
+                    }
+                    else
+                    {
+                        /* Raise an exception */
+                        KiReleaseDispatcherLock(Thread->WaitIrql);
+                        ExRaiseStatus(STATUS_MUTANT_LIMIT_EXCEEDED);
+                   }
                 }
             }
-        }
-        else if (CurrentObject->Header.SignalState > 0)
-        {
-            /* Another satisfied object */
-            KiSatisfyNonMutantWait(CurrentObject, CurrentThread);
-            WaitStatus = STATUS_WAIT_0;
-            goto DontWait;
-        }
-
-        /* Set up the Wait Block */
-        WaitBlock->Object = CurrentObject;
-        WaitBlock->Thread = CurrentThread;
-        WaitBlock->WaitKey = (USHORT)(STATUS_SUCCESS);
-        WaitBlock->WaitType = WaitAny;
-        WaitBlock->NextWaitBlock = WaitBlock;
-
-        /* Make sure we can satisfy the Alertable request */
-        KiCheckAlertability();
-
-        /* Enable the Timeout Timer if there was any specified */
-        if (Timeout)
-        {
-            /* Fail if the timeout interval is actually 0 */
-            if (!Timeout->QuadPart)
+            else if (CurrentObject->Header.SignalState > 0)
             {
-                /* Return a timeout */
-                WaitStatus = STATUS_TIMEOUT;
+                /* Another satisfied object */
+                KiSatisfyNonMutantWait(CurrentObject);
+                WaitStatus = STATUS_WAIT_0;
                 goto DontWait;
             }
 
-            /* Point to Timer Wait Block and Thread Timer */
-            TimerWaitBlock = &CurrentThread->WaitBlock[TIMER_WAIT_BLOCK];
-            ThreadTimer = &CurrentThread->Timer;
+            /* Make sure we can satisfy the Alertable request */
+            WaitStatus = KiCheckAlertability(Thread, Alertable, WaitMode);
+            if (WaitStatus != STATUS_WAIT_0) break;
 
-            /* Connect the Timer Wait Block */
-            WaitBlock->NextWaitBlock = TimerWaitBlock;
+            /* Enable the Timeout Timer if there was any specified */
+            if (Timeout)
+            {
+                /* Check if the timer expired */
+                InterruptTime.QuadPart = KeQueryInterruptTime();
+                if ((ULONGLONG)InterruptTime.QuadPart >=
+                    Timer->DueTime.QuadPart)
+                {
+                    /* It did, so we don't need to wait */
+                    WaitStatus = STATUS_TIMEOUT;
+                    goto DontWait;
+                }
 
-            /* Set up the Timer Wait Block */
-            TimerWaitBlock->NextWaitBlock = WaitBlock;
+                /* It didn't, so activate it */
+                Timer->Header.Inserted = TRUE;
+            }
 
-            /* Link the timer to this Wait Block */
-            ThreadTimer->Header.WaitListHead.Flink = &TimerWaitBlock->WaitListEntry;
-            ThreadTimer->Header.WaitListHead.Blink = &TimerWaitBlock->WaitListEntry;
+            /* Link the Object to this Wait Block */
+            InsertTailList(&CurrentObject->Header.WaitListHead,
+                           &WaitBlock->WaitListEntry);
 
-            /* Insert the Timer into the Timer Lists and enable it */
-            if (!KiInsertTimer(ThreadTimer, *Timeout))
-            {
-                /* Return a timeout if we couldn't insert the timer */
-                WaitStatus = STATUS_TIMEOUT;
-                goto DontWait;
-            }
-        }
+            /* Handle Kernel Queues */
+            if (Thread->Queue) KiActivateWaiterQueue(Thread->Queue);
 
-        /* Link the Object to this Wait Block */
-        InsertTailList(&CurrentObject->Header.WaitListHead,
-                       &WaitBlock->WaitListEntry);
+            /* Setup the wait information */
+            Thread->State = Waiting;
 
-        /* Handle Kernel Queues */
-        if (CurrentThread->Queue)
-        {
-            DPRINT("Waking Queue\n");
-            KiWakeQueue(CurrentThread->Queue);
-        }
+            /* Add the thread to the wait list */
+            KiAddThreadToWaitList(Thread, Swappable);
 
-        /* Setup the wait information */
-        CurrentThread->Alertable = Alertable;
-        CurrentThread->WaitMode = WaitMode;
-        CurrentThread->WaitReason = WaitReason;
-        CurrentThread->WaitTime = ((PLARGE_INTEGER)&KeTickCount)->LowPart;
-        CurrentThread->State = Waiting;
+            /* Activate thread swap */
+            ASSERT(Thread->WaitIrql <= DISPATCH_LEVEL);
+            KiSetThreadSwapBusy(Thread);
 
-        /* Find a new thread to run */
-        DPRINT("Swapping threads\n");
-        WaitStatus = KiSwapThread();
+            /* Check if we have a timer */
+            if (Timeout)
+            {
+                /* Insert it */
+                KxInsertTimer(Timer, Hand);
+            }
+            else
+            {
+                /* Otherwise, unlock the dispatcher */
+                KiReleaseDispatcherLockFromDpcLevel();
+            }
 
-        /* Check if we were executing an APC */
-        if (WaitStatus != STATUS_KERNEL_APC)
-        {
-            /* Return Status */
-            return WaitStatus;
-        }
+            /* Do the actual swap */
+            WaitStatus = KiSwapThread(Thread, KeGetCurrentPrcb());
 
-        /* Check if we had a timeout */
-        if (Timeout)
-        {
-             /* FIXME: Fixup interval */
-        }
+            /* Check if we were executing an APC */
+            if (WaitStatus != STATUS_KERNEL_APC) return WaitStatus;
 
-        /* Acquire again the lock */
-SkipWait:
-        DPRINT("Looping again\n");
-        CurrentThread->WaitIrql = KeAcquireDispatcherDatabaseLock();
+            /* Check if we had a timeout */
+            if (Timeout)
+            {
+                /* Recalculate due times */
+                Timeout = KiRecalculateDueTime(OriginalDueTime,
+                                               &DueTime,
+                                               &NewDueTime);
+            }
+        }
+WaitStart:
+        /* Setup a new wait */
+        Thread->WaitIrql = KeRaiseIrqlToSynchLevel();
+        KxSingleThreadWait();
+        KiAcquireDispatcherLockAtDpcLevel();
     }
-    while (TRUE);
 
-    /* Release the Lock, we are done */
-    DPRINT("Returning from KeWaitForMultipleObjects(), %x. Status: %d\n",
-            KeGetCurrentThread(), WaitStatus);
-    KeReleaseDispatcherDatabaseLock(CurrentThread->WaitIrql);
+    /* Wait complete */
+    KiReleaseDispatcherLock(Thread->WaitIrql);
     return WaitStatus;
 
 DontWait:
-    /* Adjust the Quantum */
-    KiAdjustQuantumThread(CurrentThread);
+    /* Release dispatcher lock but maintain high IRQL */
+    KiReleaseDispatcherLockFromDpcLevel();
 
-    /* Release & Return */
-    DPRINT("Quick-return from KeWaitForMultipleObjects(), %x. Status: %d\n.",
-            KeGetCurrentThread(), WaitStatus);
-    KeReleaseDispatcherDatabaseLock(CurrentThread->WaitIrql);
+    /* Adjust the Quantum and return the wait status */
+    KiAdjustQuantumThread(Thread);
     return WaitStatus;
 }
 
@@ -409,447 +562,320 @@ DontWait:
  * @implemented
  */
 NTSTATUS
-STDCALL
-KeWaitForMultipleObjects(ULONG Count,
-                         PVOID Object[],
-                         WAIT_TYPE WaitType,
-                         KWAIT_REASON WaitReason,
-                         KPROCESSOR_MODE WaitMode,
-                         BOOLEAN Alertable,
-                         PLARGE_INTEGER Timeout,
-                         PKWAIT_BLOCK WaitBlockArray)
+NTAPI
+KeWaitForMultipleObjects(IN ULONG Count,
+                         IN PVOID Object[],
+                         IN WAIT_TYPE WaitType,
+                         IN KWAIT_REASON WaitReason,
+                         IN KPROCESSOR_MODE WaitMode,
+                         IN BOOLEAN Alertable,
+                         IN PLARGE_INTEGER Timeout OPTIONAL,
+                         OUT PKWAIT_BLOCK WaitBlockArray OPTIONAL)
 {
     PKMUTANT CurrentObject;
     PKWAIT_BLOCK WaitBlock;
-    PKWAIT_BLOCK TimerWaitBlock;
-    PKTIMER ThreadTimer;
-    PKTHREAD CurrentThread = KeGetCurrentThread();
-    ULONG AllObjectsSignaled;
-    ULONG WaitIndex;
+    PKTHREAD Thread = KeGetCurrentThread();
+    PKWAIT_BLOCK TimerBlock = &Thread->WaitBlock[TIMER_WAIT_BLOCK];
+    PKTIMER Timer = &Thread->Timer;
     NTSTATUS WaitStatus = STATUS_SUCCESS;
-    DPRINT("Entering KeWaitForMultipleObjects(Count %lu Object[] %p) "
-           "PsGetCurrentThread() %x, Timeout %x\n",
-           Count, Object, PsGetCurrentThread(), Timeout);
-
-    /* Set the Current Thread */
-    CurrentThread = KeGetCurrentThread();
+    BOOLEAN Swappable;
+    PLARGE_INTEGER OriginalDueTime = Timeout;
+    LARGE_INTEGER DueTime, NewDueTime, InterruptTime;
+    ULONG Index, Hand = 0;
 
-    /* Check if the lock is already held */
-    if (CurrentThread->WaitNext)
-    {
-        /* Lock is held, disable Wait Next */
-        DPRINT("Lock is held\n");
-        CurrentThread->WaitNext = FALSE;
-    }
-    else
-    {
-        /* Lock not held, acquire it */
-        DPRINT("Lock is not held, acquiring\n");
-        CurrentThread->WaitIrql = KeAcquireDispatcherDatabaseLock();
-    }
-
-    /* Make sure the Wait Count is valid for the Thread and Maximum Wait Objects */
+    /* Make sure the Wait Count is valid */
     if (!WaitBlockArray)
     {
         /* Check in regards to the Thread Object Limit */
-        if (Count > THREAD_WAIT_OBJECTS) KEBUGCHECK(MAXIMUM_WAIT_OBJECTS_EXCEEDED);
+        if (Count > THREAD_WAIT_OBJECTS)
+        {
+            /* Bugcheck */
+            KeBugCheck(MAXIMUM_WAIT_OBJECTS_EXCEEDED);
+        }
 
         /* Use the Thread's Wait Block */
-        WaitBlockArray = &CurrentThread->WaitBlock[0];
+        WaitBlockArray = &Thread->WaitBlock[0];
     }
     else
     {
-        /* Using our own Block Array. Check in regards to System Object Limit */
-        if (Count > MAXIMUM_WAIT_OBJECTS) KEBUGCHECK(MAXIMUM_WAIT_OBJECTS_EXCEEDED);
+        /* Using our own Block Array, so check with the System Object Limit */
+        if (Count > MAXIMUM_WAIT_OBJECTS)
+        {
+            /* Bugcheck */
+            KeBugCheck(MAXIMUM_WAIT_OBJECTS_EXCEEDED);
+        }
     }
 
-    /* Start the actual Loop */
-    do
+    /* Sanity check */
+    ASSERT(Count != 0);
+
+    /* Check if the lock is already held */
+    if (!Thread->WaitNext) goto WaitStart;
+
+    /*  Otherwise, we already have the lock, so initialize the wait */
+    Thread->WaitNext = FALSE;
+    /*  Note that KxMultiThreadWait is a macro, defined in ke_x.h, that  */
+    /*  uses  (and modifies some of) the following local                 */
+    /*  variables:                                                       */
+    /*  Thread, Index, WaitBlock, Timer, Timeout, Hand and Swappable.    */
+    /*  If it looks like this code doesn't actually wait for any objects */
+    /*  at all, it's because the setup is done by that macro.            */
+    KxMultiThreadWait();
+
+    /* Start wait loop */
+    for (;;)
     {
-        /* Check if a kernel APC is pending and we were below APC_LEVEL */
-        if ((CurrentThread->ApcState.KernelApcPending) &&
-            (CurrentThread->WaitIrql < APC_LEVEL))
+        /* Disable pre-emption */
+        Thread->Preempted = FALSE;
+
+        /* Check if a kernel APC is pending and we're below APC_LEVEL */
+        if ((Thread->ApcState.KernelApcPending) && !(Thread->SpecialApcDisable) &&
+            (Thread->WaitIrql < APC_LEVEL))
         {
             /* Unlock the dispatcher */
-            KeReleaseDispatcherDatabaseLock(CurrentThread->WaitIrql);
-            goto SkipWait;
+            KiReleaseDispatcherLock(Thread->WaitIrql);
         }
-
-        /* Append wait block to the KTHREAD wait block list */
-        CurrentThread->WaitBlockList = WaitBlock = WaitBlockArray;
-
-        /* Set default wait status */
-        CurrentThread->WaitStatus = STATUS_WAIT_0;
-
-        /* Check if the wait is (already) satisfied */
-        AllObjectsSignaled = TRUE;
-
-        /* First, we'll try to satisfy the wait directly */
-        for (WaitIndex = 0; WaitIndex < Count; WaitIndex++)
+        else
         {
-            /* Get the Current Object */
-            CurrentObject = (PKMUTANT)Object[WaitIndex];
-
-            /* Check the type of wait */
+            /* Check what kind of wait this is */
+            Index = 0;
             if (WaitType == WaitAny)
             {
-                /* Check if the Object is a mutant */
-                if (CurrentObject->Header.Type == MutantObject)
+                /* Loop blocks */
+                do
                 {
-                    /* Check if it's signaled */
-                    if ((CurrentObject->Header.SignalState > 0) ||
-                        (CurrentThread == CurrentObject->OwnerThread))
+                    /* Get the Current Object */
+                    CurrentObject = (PKMUTANT)Object[Index];
+                    ASSERT(CurrentObject->Header.Type != QueueObject);
+
+                    /* Check if the Object is a mutant */
+                    if (CurrentObject->Header.Type == MutantObject)
                     {
-                        /* This is a Wait Any, so just unwait this and exit */
-                        if (CurrentObject->Header.SignalState != (LONG)MINLONG)
-                        {
-                            /* Normal signal state, so unwait it and return */
-                            KiSatisfyMutantWait(CurrentObject, CurrentThread);
-                            WaitStatus = CurrentThread->WaitStatus | WaitIndex;
-                            goto DontWait;
-                        }
-                        else
+                        /* Check if it's signaled */
+                        if ((CurrentObject->Header.SignalState > 0) ||
+                            (Thread == CurrentObject->OwnerThread))
                         {
-                            /* According to wasm.ru, we must raise this exception (tested and true) */
-                            KeReleaseDispatcherDatabaseLock(CurrentThread->WaitIrql);
-                            ExRaiseStatus(STATUS_MUTANT_LIMIT_EXCEEDED);
+                            /* This is a Wait Any, so unwait this and exit */
+                            if (CurrentObject->Header.SignalState !=
+                                (LONG)MINLONG)
+                            {
+                                /* Normal signal state, unwait it and return */
+                                KiSatisfyMutantWait(CurrentObject, Thread);
+                                WaitStatus = Thread->WaitStatus | Index;
+                                goto DontWait;
+                            }
+                            else
+                            {
+                                /* Raise an exception (see wasm.ru) */
+                                KiReleaseDispatcherLock(Thread->WaitIrql);
+                                ExRaiseStatus(STATUS_MUTANT_LIMIT_EXCEEDED);
+                            }
                         }
                     }
-                }
-                else if (CurrentObject->Header.SignalState > 0)
-                {
-                    /* Another signaled object, unwait and return */
-                    KiSatisfyNonMutantWait(CurrentObject, CurrentThread);
-                    WaitStatus = WaitIndex;
-                    goto DontWait;
-                }
+                    else if (CurrentObject->Header.SignalState > 0)
+                    {
+                        /* Another signaled object, unwait and return */
+                        KiSatisfyNonMutantWait(CurrentObject);
+                        WaitStatus = Index;
+                        goto DontWait;
+                    }
+
+                    /* Go to the next block */
+                    Index++;
+                } while (Index < Count);
             }
             else
             {
-                /* Check if we're dealing with a mutant again */
-                if (CurrentObject->Header.Type == MutantObject)
+                /* Loop blocks */
+                do
                 {
-                    /* Check if it has an invalid count */
-                    if ((CurrentThread == CurrentObject->OwnerThread) &&
-                        (CurrentObject->Header.SignalState == MINLONG))
+                    /* Get the Current Object */
+                    CurrentObject = (PKMUTANT)Object[Index];
+                    ASSERT(CurrentObject->Header.Type != QueueObject);
+
+                    /* Check if we're dealing with a mutant again */
+                    if (CurrentObject->Header.Type == MutantObject)
                     {
-                        /* Raise an exception */
-                        KeReleaseDispatcherDatabaseLock(CurrentThread->WaitIrql);
-                        ExRaiseStatus(STATUS_MUTANT_LIMIT_EXCEEDED);
+                        /* Check if it has an invalid count */
+                        if ((Thread == CurrentObject->OwnerThread) &&
+                            (CurrentObject->Header.SignalState == (LONG)MINLONG))
+                        {
+                            /* Raise an exception */
+                            KiReleaseDispatcherLock(Thread->WaitIrql);
+                            ExRaiseStatus(STATUS_MUTANT_LIMIT_EXCEEDED);
+                        }
+                        else if ((CurrentObject->Header.SignalState <= 0) &&
+                                 (Thread != CurrentObject->OwnerThread))
+                        {
+                            /* We don't own it, can't satisfy the wait */
+                            break;
+                        }
                     }
-                    else if ((CurrentObject->Header.SignalState <= 0) &&
-                             (CurrentThread != CurrentObject->OwnerThread))
+                    else if (CurrentObject->Header.SignalState <= 0)
                     {
-                        /* We don't own it, can't satisfy the wait */
-                        AllObjectsSignaled = FALSE;
+                        /* Not signaled, can't satisfy */
+                        break;
                     }
-                }
-                else if (CurrentObject->Header.SignalState <= 0)
-                {
-                    /* Not signaled, can't satisfy */
-                    AllObjectsSignaled = FALSE;
-                }
-            }
-
-            /* Set up a Wait Block for this Object */
-            WaitBlock->Object = CurrentObject;
-            WaitBlock->Thread = CurrentThread;
-            WaitBlock->WaitKey = (USHORT)WaitIndex;
-            WaitBlock->WaitType = (USHORT)WaitType;
-            WaitBlock->NextWaitBlock = WaitBlock + 1;
 
-            /* Move to the next Wait Block */
-            WaitBlock = WaitBlock->NextWaitBlock;
-        }
+                    /* Go to the next block */
+                    Index++;
+                } while (Index < Count);
 
-        /* Return to the Root Wait Block */
-        WaitBlock--;
-        WaitBlock->NextWaitBlock = WaitBlockArray;
+                /* Check if we've went through all the objects */
+                if (Index == Count)
+                {
+                    /* Loop wait blocks */
+                    WaitBlock = WaitBlockArray;
+                    do
+                    {
+                        /* Get the object and satisfy it */
+                        CurrentObject = (PKMUTANT)WaitBlock->Object;
+                        KiSatisfyObjectWait(CurrentObject, Thread);
 
-        /* Check if this is a Wait All and all the objects are signaled */
-        if ((WaitType == WaitAll) && (AllObjectsSignaled))
-        {
-            /* Return to the Root Wait Block */
-            WaitBlock = CurrentThread->WaitBlockList;
+                        /* Go to the next block */
+                        WaitBlock = WaitBlock->NextWaitBlock;
+                    } while(WaitBlock != WaitBlockArray);
 
-            /* Satisfy their Waits and return to the caller */
-            KiWaitSatisfyAll(WaitBlock);
-            WaitStatus = CurrentThread->WaitStatus;
-            goto DontWait;
-        }
+                    /* Set the wait status and get out */
+                    WaitStatus = Thread->WaitStatus;
+                    goto DontWait;
+                }
+            }
 
-        /* Make sure we can satisfy the Alertable request */
-        KiCheckAlertability();
+            /* Make sure we can satisfy the Alertable request */
+            WaitStatus = KiCheckAlertability(Thread, Alertable, WaitMode);
+            if (WaitStatus != STATUS_WAIT_0) break;
 
-        /* Enable the Timeout Timer if there was any specified */
-        if (Timeout)
-        {
-            /* Make sure the timeout interval isn't actually 0 */
-            if (!Timeout->QuadPart)
+            /* Enable the Timeout Timer if there was any specified */
+            if (Timeout)
             {
-                /* Return a timeout */
-                WaitStatus = STATUS_TIMEOUT;
-                goto DontWait;
-            }
+                /* Check if the timer expired */
+                InterruptTime.QuadPart = KeQueryInterruptTime();
+                if ((ULONGLONG)InterruptTime.QuadPart >=
+                    Timer->DueTime.QuadPart)
+                {
+                    /* It did, so we don't need to wait */
+                    WaitStatus = STATUS_TIMEOUT;
+                    goto DontWait;
+                }
 
-            /* Point to Timer Wait Block and Thread Timer */
-            TimerWaitBlock = &CurrentThread->WaitBlock[TIMER_WAIT_BLOCK];
-            ThreadTimer = &CurrentThread->Timer;
+                /* It didn't, so activate it */
+                Timer->Header.Inserted = TRUE;
 
-            /* Connect the Timer Wait Block */
-            WaitBlock->NextWaitBlock = TimerWaitBlock;
+                /* Link the wait blocks */
+                WaitBlock->NextWaitBlock = TimerBlock;
+            }
 
-            /* Set up the Timer Wait Block */
-            TimerWaitBlock->NextWaitBlock = WaitBlockArray;
+            /* Insert into Object's Wait List*/
+            WaitBlock = WaitBlockArray;
+            do
+            {
+                /* Get the Current Object */
+                CurrentObject = WaitBlock->Object;
 
-            /* Initialize the list head */
-            InitializeListHead(&ThreadTimer->Header.WaitListHead);
+                /* Link the Object to this Wait Block */
+                InsertTailList(&CurrentObject->Header.WaitListHead,
+                               &WaitBlock->WaitListEntry);
 
-            /* Insert the Timer into the Timer Lists and enable it */
-            if (!KiInsertTimer(ThreadTimer, *Timeout))
-            {
-                /* Return a timeout if we couldn't insert the timer */
-                WaitStatus = STATUS_TIMEOUT;
-                goto DontWait;
-            }
-        }
+                /* Move to the next Wait Block */
+                WaitBlock = WaitBlock->NextWaitBlock;
+            } while (WaitBlock != WaitBlockArray);
 
-        /* Insert into Object's Wait List*/
-        WaitBlock = CurrentThread->WaitBlockList;
-        do
-        {
-            /* Get the Current Object */
-            CurrentObject = WaitBlock->Object;
+            /* Handle Kernel Queues */
+            if (Thread->Queue) KiActivateWaiterQueue(Thread->Queue);
 
-            /* Link the Object to this Wait Block */
-            InsertTailList(&CurrentObject->Header.WaitListHead,
-                           &WaitBlock->WaitListEntry);
+            /* Setup the wait information */
+            Thread->State = Waiting;
 
-            /* Move to the next Wait Block */
-            WaitBlock = WaitBlock->NextWaitBlock;
-        }
-        while (WaitBlock != WaitBlockArray);
+            /* Add the thread to the wait list */
+            KiAddThreadToWaitList(Thread, Swappable);
 
-        /* Handle Kernel Queues */
-        if (CurrentThread->Queue)
-        {
-            DPRINT("Waking Queue\n");
-            KiWakeQueue(CurrentThread->Queue);
-        }
+            /* Activate thread swap */
+            ASSERT(Thread->WaitIrql <= DISPATCH_LEVEL);
+            KiSetThreadSwapBusy(Thread);
 
-        /* Setup the wait information */
-        CurrentThread->Alertable = Alertable;
-        CurrentThread->WaitMode = WaitMode;
-        CurrentThread->WaitReason = WaitReason;
-        CurrentThread->WaitTime = ((PLARGE_INTEGER)&KeTickCount)->LowPart;
-        CurrentThread->State = Waiting;
+            /* Check if we have a timer */
+            if (Timeout)
+            {
+                /* Insert it */
+                KxInsertTimer(Timer, Hand);
+            }
+            else
+            {
+                /* Otherwise, unlock the dispatcher */
+                KiReleaseDispatcherLockFromDpcLevel();
+            }
 
-        /* Find a new thread to run */
-        DPRINT("Swapping threads\n");
-        WaitStatus = KiSwapThread();
+            /* Swap the thread */
+            WaitStatus = KiSwapThread(Thread, KeGetCurrentPrcb());
 
-        /* Check if we were executing an APC */
-        DPRINT("Thread is back\n");
-        if (WaitStatus != STATUS_KERNEL_APC)
-        {
-            /* Return Status */
-            return WaitStatus;
-        }
+            /* Check if we were executing an APC */
+            if (WaitStatus != STATUS_KERNEL_APC) return WaitStatus;
 
-        /* Check if we had a timeout */
-        if (Timeout)
-        {
-             /* FIXME: Fixup interval */
+            /* Check if we had a timeout */
+            if (Timeout)
+            {
+                /* Recalculate due times */
+                Timeout = KiRecalculateDueTime(OriginalDueTime,
+                                               &DueTime,
+                                               &NewDueTime);
+            }
         }
 
-        /* Acquire again the lock */
-SkipWait:
-        DPRINT("Looping again\n");
-        CurrentThread->WaitIrql = KeAcquireDispatcherDatabaseLock();
+WaitStart:
+        /* Setup a new wait */
+        Thread->WaitIrql = KeRaiseIrqlToSynchLevel();
+        KxMultiThreadWait();
+        KiAcquireDispatcherLockAtDpcLevel();
     }
-    while (TRUE);
 
-    /* Release the Lock, we are done */
-    DPRINT("Returning, %x. Status: %d\n",  KeGetCurrentThread(), WaitStatus);
-    KeReleaseDispatcherDatabaseLock(CurrentThread->WaitIrql);
+    /* We are done */
+    KiReleaseDispatcherLock(Thread->WaitIrql);
     return WaitStatus;
 
 DontWait:
-    /* Adjust the Quantum */
-    KiAdjustQuantumThread(CurrentThread);
+    /* Release dispatcher lock but maintain high IRQL */
+    KiReleaseDispatcherLockFromDpcLevel();
 
-    /* Release & Return */
-    DPRINT("Returning, %x. Status: %d\n. We did not wait.",
-             KeGetCurrentThread(), WaitStatus);
-    KeReleaseDispatcherDatabaseLock(CurrentThread->WaitIrql);
+    /* Adjust the Quantum and return the wait status */
+    KiAdjustQuantumThread(Thread);
     return WaitStatus;
 }
 
-VOID
-FASTCALL
-KiWaitTest(PVOID ObjectPointer,
-           KPRIORITY Increment)
+NTSTATUS
+NTAPI
+NtDelayExecution(IN BOOLEAN Alertable,
+                 IN PLARGE_INTEGER DelayInterval)
 {
-    PLIST_ENTRY WaitEntry;
-    PLIST_ENTRY WaitList;
-    PKWAIT_BLOCK CurrentWaitBlock;
-    PKWAIT_BLOCK NextWaitBlock;
-    PKTHREAD WaitThread;
-    PKMUTANT FirstObject = ObjectPointer, Object;
+    KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
+    LARGE_INTEGER SafeInterval;
+    NTSTATUS Status;
 
-    /* Loop the Wait Entries */
-    DPRINT("KiWaitTest for Object: %x\n", FirstObject);
-    WaitList = &FirstObject->Header.WaitListHead;
-    WaitEntry = WaitList->Flink;
-    while ((FirstObject->Header.SignalState > 0) && (WaitEntry != WaitList))
+    /* Check the previous mode */
+    if (PreviousMode != KernelMode)
     {
-        /* Get the current wait block */
-        CurrentWaitBlock = CONTAINING_RECORD(WaitEntry,
-                                             KWAIT_BLOCK,
-                                             WaitListEntry);
-        WaitThread = CurrentWaitBlock->Thread;
-
-        /* Check the current Wait Mode */
-        if (CurrentWaitBlock->WaitType == WaitAny)
+        /* Enter SEH for probing */
+        _SEH2_TRY
         {
-            /* Easy case, satisfy only this wait */
-            DPRINT("Satisfiying a Wait any\n");
-            WaitEntry = WaitEntry->Blink;
-            KiSatisfyObjectWait(FirstObject, WaitThread);
+            /* Probe and capture the time out */
+            SafeInterval = ProbeForReadLargeInteger(DelayInterval);
+            DelayInterval = &SafeInterval;
         }
-        else
+        _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
         {
-            /* Everything must be satisfied */
-            DPRINT("Checking for a Wait All\n");
-            NextWaitBlock = CurrentWaitBlock->NextWaitBlock;
-
-            /* Loop first to make sure they are valid */
-            while (NextWaitBlock != CurrentWaitBlock)
-            {
-                /* Check if the object is signaled */
-                Object = NextWaitBlock->Object;
-                DPRINT("Checking: %p %d\n",
-                        Object, Object->Header.SignalState);
-                if (NextWaitBlock->WaitKey != STATUS_TIMEOUT)
-                {
-                    /* Check if this is a mutant */
-                    if ((Object->Header.Type == MutantObject) &&
-                        (Object->Header.SignalState <= 0) &&
-                        (WaitThread == Object->OwnerThread))
-                    {
-                        /* It's a signaled mutant */
-                    }
-                    else if (Object->Header.SignalState <= 0)
-                    {
-                        /* Skip the unwaiting */
-                        goto SkipUnwait;
-                    }
-                }
-
-                /* Go to the next Wait block */
-                NextWaitBlock = NextWaitBlock->NextWaitBlock;
-            }
-
-            /* All the objects are signaled, we can satisfy */
-            DPRINT("Satisfiying a Wait All\n");
-            WaitEntry = WaitEntry->Blink;
-            KiWaitSatisfyAll(CurrentWaitBlock);
+            /* Return the exception code */
+            _SEH2_YIELD(return _SEH2_GetExceptionCode());
         }
+        _SEH2_END;
+   }
 
-        /* All waits satisfied, unwait the thread */
-        DPRINT("Unwaiting the Thread\n");
-        KiAbortWaitThread(WaitThread, CurrentWaitBlock->WaitKey, Increment);
-
-SkipUnwait:
-        /* Next entry */
-        WaitEntry = WaitEntry->Flink;
-    }
-
-    DPRINT("Done\n");
-}
+   /* Call the Kernel Function */
+   Status = KeDelayExecutionThread(PreviousMode,
+                                   Alertable,
+                                   DelayInterval);
 
-/* Must be called with the dispatcher lock held */
-VOID
-FASTCALL
-KiAbortWaitThread(PKTHREAD Thread,
-                  NTSTATUS WaitStatus,
-                  KPRIORITY Increment)
-{
-    PKWAIT_BLOCK WaitBlock;
-
-    /* If we are blocked, we must be waiting on something also */
-    DPRINT("KiAbortWaitThread: %x, Status: %x, %x \n",
-            Thread, WaitStatus, Thread->WaitBlockList);
-
-    /* Remove the Wait Blocks from the list */
-    DPRINT("Removing waits\n");
-    WaitBlock = Thread->WaitBlockList;
-    do
-    {
-        /* Remove it */
-        DPRINT("Removing Waitblock: %x, %x\n",
-                WaitBlock, WaitBlock->NextWaitBlock);
-        RemoveEntryList(&WaitBlock->WaitListEntry);
-
-        /* Go to the next one */
-        WaitBlock = WaitBlock->NextWaitBlock;
-    } while (WaitBlock != Thread->WaitBlockList);
-
-    /* Check if there's a Thread Timer */
-    if (Thread->Timer.Header.Inserted)
-    {
-        /* Cancel the Thread Timer with the no-lock fastpath */
-        DPRINT("Removing the Thread's Timer\n");
-        Thread->Timer.Header.Inserted = FALSE;
-        RemoveEntryList(&Thread->Timer.TimerListEntry);
-    }
-
-    /* Increment the Queue's active threads */
-    if (Thread->Queue)
-    {
-        DPRINT("Incrementing Queue's active threads\n");
-        Thread->Queue->CurrentCount++;
-    }
-
-    /* Reschedule the Thread */
-    DPRINT("Unblocking the Thread\n");
-    KiUnblockThread(Thread, &WaitStatus, 0);
-}
-
-VOID
-FASTCALL
-KiAcquireFastMutex(IN PFAST_MUTEX FastMutex)
-{
-    /* Increase contention count */
-    FastMutex->Contention++;
-
-    /* Wait for the event */
-    KeWaitForSingleObject(&FastMutex->Gate,
-                          WrMutex,
-                          KernelMode,
-                          FALSE,
-                          NULL);
-}
-
-VOID
-FASTCALL
-KiExitDispatcher(KIRQL OldIrql)
-{
-    /* If it's the idle thread, dispatch */
-    if (!(KeIsExecutingDpc()) &&
-        (OldIrql < DISPATCH_LEVEL) &&
-        (KeGetCurrentThread()) &&
-        (KeGetCurrentThread() == KeGetCurrentPrcb()->IdleThread))
-    {
-        KiDispatchThreadNoLock(Ready);
-    }
-    else
-    {
-        KeReleaseDispatcherDatabaseLockFromDpcLevel();    
-    }
-
-    /* Lower irql back */
-    KeLowerIrql(OldIrql);
+   /* Return Status */
+   return Status;
 }
 
 /* EOF */