2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/include/ke_x.h
5 * PURPOSE: Internal Inlined Functions for the Kernel
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
10 // Thread Dispatcher Header DebugActive Mask
12 #define DR_MASK(x) 1 << x
13 #define DR_ACTIVE_MASK 0x10
14 #define DR_REG_MASK 0x4F
18 // Sanitizes a selector
22 Ke386SanitizeSeg(IN ULONG Cs
,
23 IN KPROCESSOR_MODE Mode
)
26 // Check if we're in kernel-mode, and force CPL 0 if so.
27 // Otherwise, force CPL 3.
29 return ((Mode
== KernelMode
) ?
30 (Cs
& (0xFFFF & ~RPL_MASK
)) :
31 (RPL_MASK
| (Cs
& 0xFFFF)));
39 Ke386SanitizeFlags(IN ULONG Eflags
,
40 IN KPROCESSOR_MODE Mode
)
43 // Check if we're in kernel-mode, and sanitize EFLAGS if so.
44 // Otherwise, also force interrupt mask on.
46 return ((Mode
== KernelMode
) ?
47 (Eflags
& (EFLAGS_USER_SANITIZE
| EFLAGS_INTERRUPT_MASK
)) :
48 (EFLAGS_INTERRUPT_MASK
| (Eflags
& EFLAGS_USER_SANITIZE
)));
52 // Gets a DR register from a CONTEXT structure
56 KiDrFromContext(IN ULONG Dr
,
59 return *(PVOID
*)((ULONG_PTR
)Context
+ KiDebugRegisterContextOffsets
[Dr
]);
63 // Gets a DR register from a KTRAP_FRAME structure
67 KiDrFromTrapFrame(IN ULONG Dr
,
68 IN PKTRAP_FRAME TrapFrame
)
70 return (PVOID
*)((ULONG_PTR
)TrapFrame
+ KiDebugRegisterTrapOffsets
[Dr
]);
78 Ke386SanitizeDr(IN PVOID DrAddress
,
79 IN KPROCESSOR_MODE Mode
)
82 // Check if we're in kernel-mode, and return the address directly if so.
83 // Otherwise, make sure it's not inside the kernel-mode address space.
84 // If it is, then clear the address.
86 return ((Mode
== KernelMode
) ? DrAddress
:
87 (DrAddress
<= MM_HIGHEST_USER_ADDRESS
) ? DrAddress
: 0);
94 KeGetCurrentThread(VOID
)
97 /* Return the current thread */
98 return ((PKIPCR
)KeGetPcr())->PrcbData
.CurrentThread
;
99 #elif defined (_M_AMD64)
100 return (PRKTHREAD
)__readgsqword(FIELD_OFFSET(KIPCR
, Prcb
.CurrentThread
));
102 PKPRCB Prcb
= KeGetCurrentPrcb();
103 return Prcb
->CurrentThread
;
109 KeGetPreviousMode(VOID
)
111 /* Return the current mode */
112 return KeGetCurrentThread()->PreviousMode
;
118 KeFlushProcessTb(VOID
)
120 /* Flush the TLB by resetting CR3 */
122 __asm__("sync\n\tisync\n\t");
125 // We need to implement this!
127 ASSERTMSG("Need ARM flush routine\n", FALSE
);
129 __writecr3(__readcr3());
134 // Enters a Guarded Region
136 #define KeEnterGuardedRegion() \
138 PKTHREAD _Thread = KeGetCurrentThread(); \
140 /* Sanity checks */ \
141 ASSERT(KeGetCurrentIrql() <= APC_LEVEL); \
142 ASSERT(_Thread == KeGetCurrentThread()); \
143 ASSERT((_Thread->SpecialApcDisable <= 0) && \
144 (_Thread->SpecialApcDisable != -32768)); \
146 /* Disable Special APCs */ \
147 _Thread->SpecialApcDisable--; \
151 // Leaves a Guarded Region
153 #define KeLeaveGuardedRegion() \
155 PKTHREAD _Thread = KeGetCurrentThread(); \
157 /* Sanity checks */ \
158 ASSERT(KeGetCurrentIrql() <= APC_LEVEL); \
159 ASSERT(_Thread == KeGetCurrentThread()); \
160 ASSERT(_Thread->SpecialApcDisable < 0); \
162 /* Leave region and check if APCs are OK now */ \
163 if (!(++_Thread->SpecialApcDisable)) \
165 /* Check for Kernel APCs on the list */ \
166 if (!IsListEmpty(&_Thread->ApcState. \
167 ApcListHead[KernelMode])) \
169 /* Check for APC Delivery */ \
170 KiCheckForKernelApcDelivery(); \
176 // TODO: Guarded Mutex Routines
180 // Enters a Critical Region
182 #define KeEnterCriticalRegion() \
184 PKTHREAD _Thread = KeGetCurrentThread(); \
186 /* Sanity checks */ \
187 ASSERT(_Thread == KeGetCurrentThread()); \
188 ASSERT((_Thread->KernelApcDisable <= 0) && \
189 (_Thread->KernelApcDisable != -32768)); \
191 /* Disable Kernel APCs */ \
192 _Thread->KernelApcDisable--; \
196 // Leaves a Critical Region
198 #define KeLeaveCriticalRegion() \
200 PKTHREAD _Thread = KeGetCurrentThread(); \
202 /* Sanity checks */ \
203 ASSERT(_Thread == KeGetCurrentThread()); \
204 ASSERT(_Thread->KernelApcDisable < 0); \
206 /* Enable Kernel APCs */ \
207 _Thread->KernelApcDisable++; \
209 /* Check if Kernel APCs are now enabled */ \
210 if (!(_Thread->KernelApcDisable)) \
212 /* Check if we need to request an APC Delivery */ \
213 if (!(IsListEmpty(&_Thread->ApcState.ApcListHead[KernelMode])) && \
214 !(_Thread->SpecialApcDisable)) \
216 /* Check for the right environment */ \
217 KiCheckForKernelApcDelivery(); \
224 // Spinlock Acquire at IRQL >= DISPATCH_LEVEL
228 KxAcquireSpinLock(IN PKSPIN_LOCK SpinLock
)
230 /* On UP builds, spinlocks don't exist at IRQL >= DISPATCH */
231 UNREFERENCED_PARAMETER(SpinLock
);
235 // Spinlock Release at IRQL >= DISPATCH_LEVEL
239 KxReleaseSpinLock(IN PKSPIN_LOCK SpinLock
)
241 /* On UP builds, spinlocks don't exist at IRQL >= DISPATCH */
242 UNREFERENCED_PARAMETER(SpinLock
);
246 // This routine protects against multiple CPU acquires, it's meaningless on UP.
250 KiAcquireDispatcherObject(IN DISPATCHER_HEADER
* Object
)
252 UNREFERENCED_PARAMETER(Object
);
256 // This routine protects against multiple CPU acquires, it's meaningless on UP.
260 KiReleaseDispatcherObject(IN DISPATCHER_HEADER
* Object
)
262 UNREFERENCED_PARAMETER(Object
);
267 KiAcquireDispatcherLock(VOID
)
269 /* Raise to DPC level */
270 return KeRaiseIrqlToDpcLevel();
275 KiReleaseDispatcherLock(IN KIRQL OldIrql
)
277 /* Just exit the dispatcher */
278 KiExitDispatcher(OldIrql
);
283 KiAcquireDispatcherLockAtDpcLevel(VOID
)
285 /* This is a no-op at DPC Level for UP systems */
291 KiReleaseDispatcherLockFromDpcLevel(VOID
)
293 /* This is a no-op at DPC Level for UP systems */
298 // This routine makes the thread deferred ready on the boot CPU.
302 KiInsertDeferredReadyList(IN PKTHREAD Thread
)
304 /* Set the thread to deferred state and boot CPU */
305 Thread
->State
= DeferredReady
;
306 Thread
->DeferredProcessor
= 0;
308 /* Make the thread ready immediately */
309 KiDeferredReadyThread(Thread
);
314 KiRescheduleThread(IN BOOLEAN NewThread
,
317 /* This is meaningless on UP systems */
318 UNREFERENCED_PARAMETER(NewThread
);
319 UNREFERENCED_PARAMETER(Cpu
);
323 // This routine protects against multiple CPU acquires, it's meaningless on UP.
327 KiSetThreadSwapBusy(IN PKTHREAD Thread
)
329 UNREFERENCED_PARAMETER(Thread
);
333 // This routine protects against multiple CPU acquires, it's meaningless on UP.
337 KiAcquirePrcbLock(IN PKPRCB Prcb
)
339 UNREFERENCED_PARAMETER(Prcb
);
343 // This routine protects against multiple CPU acquires, it's meaningless on UP.
347 KiReleasePrcbLock(IN PKPRCB Prcb
)
349 UNREFERENCED_PARAMETER(Prcb
);
353 // This routine protects against multiple CPU acquires, it's meaningless on UP.
357 KiAcquireThreadLock(IN PKTHREAD Thread
)
359 UNREFERENCED_PARAMETER(Thread
);
363 // This routine protects against multiple CPU acquires, it's meaningless on UP.
367 KiReleaseThreadLock(IN PKTHREAD Thread
)
369 UNREFERENCED_PARAMETER(Thread
);
373 // This routine protects against multiple CPU acquires, it's meaningless on UP.
377 KiTryThreadLock(IN PKTHREAD Thread
)
379 UNREFERENCED_PARAMETER(Thread
);
385 KiCheckDeferredReadyList(IN PKPRCB Prcb
)
387 /* There are no deferred ready lists on UP systems */
388 UNREFERENCED_PARAMETER(Prcb
);
393 KiRundownThread(IN PKTHREAD Thread
)
396 /* Check if this is the NPX Thread */
397 if (KeGetCurrentPrcb()->NpxThread
== Thread
)
400 KeGetCurrentPrcb()->NpxThread
= NULL
;
408 KiRequestApcInterrupt(IN BOOLEAN NeedApc
,
411 /* We deliver instantly on UP */
412 UNREFERENCED_PARAMETER(NeedApc
);
413 UNREFERENCED_PARAMETER(Processor
);
418 KiAcquireTimerLock(IN ULONG Hand
)
420 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
422 /* Nothing to do on UP */
423 UNREFERENCED_PARAMETER(Hand
);
429 KiReleaseTimerLock(IN PKSPIN_LOCK_QUEUE LockQueue
)
431 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
433 /* Nothing to do on UP */
434 UNREFERENCED_PARAMETER(LockQueue
);
440 // Spinlock Acquisition at IRQL >= DISPATCH_LEVEL
444 KxAcquireSpinLock(IN PKSPIN_LOCK SpinLock
)
448 /* Try to acquire it */
449 if (InterlockedBitTestAndSet((PLONG
)SpinLock
, 0))
451 /* Value changed... wait until it's locked */
452 while (*(volatile KSPIN_LOCK
*)SpinLock
== 1)
455 /* On debug builds, we use a much slower but useful routine */
456 //Kii386SpinOnSpinLock(SpinLock, 5);
458 /* FIXME: Do normal yield for now */
461 /* Otherwise, just yield and keep looping */
469 /* On debug builds, we OR in the KTHREAD */
470 *SpinLock
= (KSPIN_LOCK
)KeGetCurrentThread() | 1;
472 /* All is well, break out */
479 // Spinlock Release at IRQL >= DISPATCH_LEVEL
483 KxReleaseSpinLock(IN PKSPIN_LOCK SpinLock
)
486 /* Make sure that the threads match */
487 if (((KSPIN_LOCK
)KeGetCurrentThread() | 1) != *SpinLock
)
489 /* They don't, bugcheck */
490 KeBugCheckEx(SPIN_LOCK_NOT_OWNED
, (ULONG_PTR
)SpinLock
, 0, 0, 0);
494 InterlockedAnd((PLONG
)SpinLock
, 0);
499 KiAcquireDispatcherObject(IN DISPATCHER_HEADER
* Object
)
503 /* Make sure we're at a safe level to touch the lock */
504 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
506 /* Start acquire loop */
509 /* Loop until the other CPU releases it */
512 /* Check if it got released */
513 OldValue
= Object
->Lock
;
514 if ((OldValue
& KOBJECT_LOCK_BIT
) == 0) break;
516 /* Let the CPU know that this is a loop */
520 /* Try acquiring the lock now */
521 } while (InterlockedCompareExchange(&Object
->Lock
,
522 OldValue
| KOBJECT_LOCK_BIT
,
523 OldValue
) != OldValue
);
528 KiReleaseDispatcherObject(IN DISPATCHER_HEADER
* Object
)
530 /* Make sure we're at a safe level to touch the lock */
531 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
534 InterlockedAnd(&Object
->Lock
, ~KOBJECT_LOCK_BIT
);
539 KiAcquireDispatcherLock(VOID
)
541 /* Raise to synchronization level and acquire the dispatcher lock */
542 return KeAcquireQueuedSpinLockRaiseToSynch(LockQueueDispatcherLock
);
547 KiReleaseDispatcherLock(IN KIRQL OldIrql
)
549 /* First release the lock */
550 KeReleaseQueuedSpinLockFromDpcLevel(&KeGetCurrentPrcb()->
551 LockQueue
[LockQueueDispatcherLock
]);
553 /* Then exit the dispatcher */
554 KiExitDispatcher(OldIrql
);
559 KiAcquireDispatcherLockAtDpcLevel(VOID
)
561 /* Acquire the dispatcher lock */
562 KeAcquireQueuedSpinLockAtDpcLevel(LockQueueDispatcherLock
);
567 KiReleaseDispatcherLockFromDpcLevel(VOID
)
569 /* Release the dispatcher lock */
570 KeReleaseQueuedSpinLockFromDpcLevel(LockQueueDispatcherLock
);
574 // This routine inserts a thread into the deferred ready list of the given CPU
578 KiInsertDeferredReadyList(IN PKTHREAD Thread
)
580 PKPRCB Prcb
= KeGetCurrentPrcb();
582 /* Set the thread to deferred state and CPU */
583 Thread
->State
= DeferredReady
;
584 Thread
->DeferredProcessor
= Prcb
->Number
;
586 /* Add it on the list */
587 PushEntryList(&Prcb
->DeferredReadyListHead
, &Thread
->SwapListEntry
);
592 KiRescheduleThread(IN BOOLEAN NewThread
,
595 /* Check if a new thread needs to be scheduled on a different CPU */
596 if ((NewThread
) && !(KeGetPcr()->Number
== Cpu
))
598 /* Send an IPI to request delivery */
599 KiIpiSendRequest(AFFINITY_MASK(Cpu
), IPI_DPC
);
604 // This routine sets the current thread in a swap busy state, which ensure that
605 // nobody else tries to swap it concurrently.
609 KiSetThreadSwapBusy(IN PKTHREAD Thread
)
611 /* Make sure nobody already set it */
612 ASSERT(Thread
->SwapBusy
== FALSE
);
614 /* Set it ourselves */
615 Thread
->SwapBusy
= TRUE
;
619 // This routine acquires the PRCB lock so that only one caller can touch
620 // volatile PRCB data.
622 // Since this is a simple optimized spin-lock, it must be be only acquired
623 // at dispatcher level or higher!
627 KiAcquirePrcbLock(IN PKPRCB Prcb
)
629 /* Make sure we're at a safe level to touch the PRCB lock */
630 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
632 /* Start acquire loop */
635 /* Acquire the lock and break out if we acquired it first */
636 if (!InterlockedExchange((PLONG
)&Prcb
->PrcbLock
, 1)) break;
638 /* Loop until the other CPU releases it */
641 /* Let the CPU know that this is a loop */
643 } while (Prcb
->PrcbLock
);
648 // This routine releases the PRCB lock so that other callers can touch
649 // volatile PRCB data.
651 // Since this is a simple optimized spin-lock, it must be be only acquired
652 // at dispatcher level or higher!
656 KiReleasePrcbLock(IN PKPRCB Prcb
)
658 /* Make sure it's acquired! */
659 ASSERT(Prcb
->PrcbLock
!= 0);
662 InterlockedAnd((PLONG
)&Prcb
->PrcbLock
, 0);
666 // This routine acquires the thread lock so that only one caller can touch
667 // volatile thread data.
669 // Since this is a simple optimized spin-lock, it must be be only acquired
670 // at dispatcher level or higher!
674 KiAcquireThreadLock(IN PKTHREAD Thread
)
676 /* Make sure we're at a safe level to touch the thread lock */
677 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
679 /* Start acquire loop */
682 /* Acquire the lock and break out if we acquired it first */
683 if (!InterlockedExchange((PLONG
)&Thread
->ThreadLock
, 1)) break;
685 /* Loop until the other CPU releases it */
688 /* Let the CPU know that this is a loop */
690 } while (Thread
->ThreadLock
);
695 // This routine releases the thread lock so that other callers can touch
696 // volatile thread data.
698 // Since this is a simple optimized spin-lock, it must be be only acquired
699 // at dispatcher level or higher!
703 KiReleaseThreadLock(IN PKTHREAD Thread
)
706 InterlockedAnd((PLONG
)&Thread
->ThreadLock
, 0);
711 KiTryThreadLock(IN PKTHREAD Thread
)
715 /* If the lock isn't acquired, return false */
716 if (!Thread
->ThreadLock
) return FALSE
;
718 /* Otherwise, try to acquire it and check the result */
720 Value
= InterlockedExchange((PLONG
)&Thread
->ThreadLock
, Value
);
722 /* Return the lock state */
723 return (Value
== TRUE
);
728 KiCheckDeferredReadyList(IN PKPRCB Prcb
)
730 /* Scan the deferred ready lists if required */
731 if (Prcb
->DeferredReadyListHead
.Next
) KiProcessDeferredReadyList(Prcb
);
736 KiRundownThread(IN PKTHREAD Thread
)
738 #if defined(_M_IX86) || defined(_M_AMD64)
740 ASSERTMSG("Not yet implemented\n", FALSE
);
746 KiRequestApcInterrupt(IN BOOLEAN NeedApc
,
749 /* Check if we need to request APC delivery */
752 /* Check if it's on another CPU */
753 if (KeGetPcr()->Number
!= Processor
)
755 /* Send an IPI to request delivery */
756 KiIpiSendRequest(AFFINITY_MASK(Processor
), IPI_APC
);
760 /* Request a software interrupt */
761 HalRequestSoftwareInterrupt(APC_LEVEL
);
768 KiAcquireTimerLock(IN ULONG Hand
)
770 PKSPIN_LOCK_QUEUE LockQueue
;
772 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
774 /* Get the lock index */
775 LockIndex
= Hand
>> LOCK_QUEUE_TIMER_LOCK_SHIFT
;
776 LockIndex
&= (LOCK_QUEUE_TIMER_TABLE_LOCKS
- 1);
778 /* Now get the lock */
779 LockQueue
= &KeGetCurrentPrcb()->LockQueue
[LockQueueTimerTableLock
+ LockIndex
];
781 /* Acquire it and return */
782 KeAcquireQueuedSpinLockAtDpcLevel(LockQueue
);
788 KiReleaseTimerLock(IN PKSPIN_LOCK_QUEUE LockQueue
)
790 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
792 /* Release the lock */
793 KeReleaseQueuedSpinLockFromDpcLevel(LockQueue
);
800 KiAcquireApcLock(IN PKTHREAD Thread
,
801 IN PKLOCK_QUEUE_HANDLE Handle
)
803 /* Acquire the lock and raise to synchronization level */
804 KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread
->ApcQueueLock
, Handle
);
809 KiAcquireApcLockAtDpcLevel(IN PKTHREAD Thread
,
810 IN PKLOCK_QUEUE_HANDLE Handle
)
812 /* Acquire the lock */
813 KeAcquireInStackQueuedSpinLockAtDpcLevel(&Thread
->ApcQueueLock
, Handle
);
818 KiAcquireApcLockAtApcLevel(IN PKTHREAD Thread
,
819 IN PKLOCK_QUEUE_HANDLE Handle
)
821 /* Acquire the lock */
822 KeAcquireInStackQueuedSpinLock(&Thread
->ApcQueueLock
, Handle
);
827 KiReleaseApcLock(IN PKLOCK_QUEUE_HANDLE Handle
)
829 /* Release the lock */
830 KeReleaseInStackQueuedSpinLock(Handle
);
835 KiReleaseApcLockFromDpcLevel(IN PKLOCK_QUEUE_HANDLE Handle
)
837 /* Release the lock */
838 KeReleaseInStackQueuedSpinLockFromDpcLevel(Handle
);
843 KiAcquireProcessLock(IN PKPROCESS Process
,
844 IN PKLOCK_QUEUE_HANDLE Handle
)
846 /* Acquire the lock and raise to synchronization level */
847 KeAcquireInStackQueuedSpinLockRaiseToSynch(&Process
->ProcessLock
, Handle
);
852 KiReleaseProcessLock(IN PKLOCK_QUEUE_HANDLE Handle
)
854 /* Release the lock */
855 KeReleaseInStackQueuedSpinLock(Handle
);
860 KiReleaseProcessLockFromDpcLevel(IN PKLOCK_QUEUE_HANDLE Handle
)
862 /* Release the lock */
863 KeReleaseInStackQueuedSpinLockFromDpcLevel(Handle
);
868 KiAcquireDeviceQueueLock(IN PKDEVICE_QUEUE DeviceQueue
,
869 IN PKLOCK_QUEUE_HANDLE DeviceLock
)
871 /* Check if we were called from a threaded DPC */
872 if (KeGetCurrentPrcb()->DpcThreadActive
)
874 /* Lock the Queue, we're not at DPC level */
875 KeAcquireInStackQueuedSpinLock(&DeviceQueue
->Lock
, DeviceLock
);
879 /* We must be at DPC level, acquire the lock safely */
880 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL
);
881 KeAcquireInStackQueuedSpinLockAtDpcLevel(&DeviceQueue
->Lock
,
888 KiReleaseDeviceQueueLock(IN PKLOCK_QUEUE_HANDLE DeviceLock
)
890 /* Check if we were called from a threaded DPC */
891 if (KeGetCurrentPrcb()->DpcThreadActive
)
893 /* Unlock the Queue, we're not at DPC level */
894 KeReleaseInStackQueuedSpinLock(DeviceLock
);
898 /* We must be at DPC level, release the lock safely */
899 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL
);
900 KeReleaseInStackQueuedSpinLockFromDpcLevel(DeviceLock
);
905 // Satisfies the wait of any dispatcher object
907 #define KiSatisfyObjectWait(Object, Thread) \
909 /* Special case for Mutants */ \
910 if ((Object)->Header.Type == MutantObject) \
912 /* Decrease the Signal State */ \
913 (Object)->Header.SignalState--; \
915 /* Check if it's now non-signaled */ \
916 if (!(Object)->Header.SignalState) \
918 /* Set the Owner Thread */ \
919 (Object)->OwnerThread = Thread; \
921 /* Disable APCs if needed */ \
922 Thread->KernelApcDisable = Thread->KernelApcDisable - \
923 (Object)->ApcDisable; \
925 /* Check if it's abandoned */ \
926 if ((Object)->Abandoned) \
929 (Object)->Abandoned = FALSE; \
931 /* Return Status */ \
932 Thread->WaitStatus = STATUS_ABANDONED; \
935 /* Insert it into the Mutant List */ \
936 InsertHeadList(Thread->MutantListHead.Blink, \
937 &(Object)->MutantListEntry); \
940 else if (((Object)->Header.Type & TIMER_OR_EVENT_TYPE) == \
941 EventSynchronizationObject) \
943 /* Synchronization Timers and Events just get un-signaled */ \
944 (Object)->Header.SignalState = 0; \
946 else if ((Object)->Header.Type == SemaphoreObject) \
948 /* These ones can have multiple states, so we only decrease it */ \
949 (Object)->Header.SignalState--; \
954 // Satisfies the wait of a mutant dispatcher object
956 #define KiSatisfyMutantWait(Object, Thread) \
958 /* Decrease the Signal State */ \
959 (Object)->Header.SignalState--; \
961 /* Check if it's now non-signaled */ \
962 if (!(Object)->Header.SignalState) \
964 /* Set the Owner Thread */ \
965 (Object)->OwnerThread = Thread; \
967 /* Disable APCs if needed */ \
968 Thread->KernelApcDisable = Thread->KernelApcDisable - \
969 (Object)->ApcDisable; \
971 /* Check if it's abandoned */ \
972 if ((Object)->Abandoned) \
975 (Object)->Abandoned = FALSE; \
977 /* Return Status */ \
978 Thread->WaitStatus = STATUS_ABANDONED; \
981 /* Insert it into the Mutant List */ \
982 InsertHeadList(Thread->MutantListHead.Blink, \
983 &(Object)->MutantListEntry); \
988 // Satisfies the wait of any nonmutant dispatcher object
990 #define KiSatisfyNonMutantWait(Object) \
992 if (((Object)->Header.Type & TIMER_OR_EVENT_TYPE) == \
993 EventSynchronizationObject) \
995 /* Synchronization Timers and Events just get un-signaled */ \
996 (Object)->Header.SignalState = 0; \
998 else if ((Object)->Header.Type == SemaphoreObject) \
1000 /* These ones can have multiple states, so we only decrease it */ \
1001 (Object)->Header.SignalState--; \
1006 // Recalculates the due time
1010 KiRecalculateDueTime(IN PLARGE_INTEGER OriginalDueTime
,
1011 IN PLARGE_INTEGER DueTime
,
1012 IN OUT PLARGE_INTEGER NewDueTime
)
1014 /* Don't do anything for absolute waits */
1015 if (OriginalDueTime
->QuadPart
>= 0) return OriginalDueTime
;
1017 /* Otherwise, query the interrupt time and recalculate */
1018 NewDueTime
->QuadPart
= KeQueryInterruptTime();
1019 NewDueTime
->QuadPart
-= DueTime
->QuadPart
;
1024 // Determines whether a thread should be added to the wait list
1028 KiCheckThreadStackSwap(IN PKTHREAD Thread
,
1029 IN KPROCESSOR_MODE WaitMode
)
1031 /* Check the required conditions */
1032 if ((WaitMode
!= KernelMode
) &&
1033 (Thread
->EnableStackSwap
) &&
1034 (Thread
->Priority
>= (LOW_REALTIME_PRIORITY
+ 9)))
1036 /* We are go for swap */
1041 /* Don't swap the thread */
1047 // Adds a thread to the wait list
1049 #define KiAddThreadToWaitList(Thread, Swappable) \
1051 /* Make sure it's swappable */ \
1054 /* Insert it into the PRCB's List */ \
1055 InsertTailList(&KeGetCurrentPrcb()->WaitListHead, \
1056 &Thread->WaitListEntry); \
1061 // Checks if a wait in progress should be interrupted by APCs or an alertable
1066 KiCheckAlertability(IN PKTHREAD Thread
,
1067 IN BOOLEAN Alertable
,
1068 IN KPROCESSOR_MODE WaitMode
)
1070 /* Check if the wait is alertable */
1073 /* It is, first check if the thread is alerted in this mode */
1074 if (Thread
->Alerted
[WaitMode
])
1076 /* It is, so bail out of the wait */
1077 Thread
->Alerted
[WaitMode
] = FALSE
;
1078 return STATUS_ALERTED
;
1080 else if ((WaitMode
!= KernelMode
) &&
1081 (!IsListEmpty(&Thread
->ApcState
.ApcListHead
[UserMode
])))
1083 /* It's isn't, but this is a user wait with queued user APCs */
1084 Thread
->ApcState
.UserApcPending
= TRUE
;
1085 return STATUS_USER_APC
;
1087 else if (Thread
->Alerted
[KernelMode
])
1089 /* It isn't that either, but we're alered in kernel mode */
1090 Thread
->Alerted
[KernelMode
] = FALSE
;
1091 return STATUS_ALERTED
;
1094 else if ((WaitMode
!= KernelMode
) && (Thread
->ApcState
.UserApcPending
))
1096 /* Not alertable, but this is a user wait with pending user APCs */
1097 return STATUS_USER_APC
;
1100 /* Otherwise, we're fine */
1101 return STATUS_WAIT_0
;
1105 // Called by Wait and Queue code to insert a timer for dispatching.
1106 // Also called by KeSetTimerEx to insert a timer from the caller.
1110 KxInsertTimer(IN PKTIMER Timer
,
1113 PKSPIN_LOCK_QUEUE LockQueue
;
1115 /* Acquire the lock and release the dispatcher lock */
1116 LockQueue
= KiAcquireTimerLock(Hand
);
1117 KiReleaseDispatcherLockFromDpcLevel();
1119 /* Try to insert the timer */
1120 if (KiInsertTimerTable(Timer
, Hand
))
1123 KiCompleteTimer(Timer
, LockQueue
);
1127 /* Do nothing, just release the lock */
1128 KiReleaseTimerLock(LockQueue
);
1133 // Called from Unlink and Queue Insert Code.
1134 // Also called by timer code when canceling an inserted timer.
1135 // Removes a timer from it's tree.
1139 KxRemoveTreeTimer(IN PKTIMER Timer
)
1141 ULONG Hand
= Timer
->Header
.Hand
;
1142 PKSPIN_LOCK_QUEUE LockQueue
;
1143 PKTIMER_TABLE_ENTRY TimerEntry
;
1145 /* Acquire timer lock */
1146 LockQueue
= KiAcquireTimerLock(Hand
);
1148 /* Set the timer as non-inserted */
1149 Timer
->Header
.Inserted
= FALSE
;
1151 /* Remove it from the timer list */
1152 if (RemoveEntryList(&Timer
->TimerListEntry
))
1154 /* Get the entry and check if it's empty */
1155 TimerEntry
= &KiTimerTableListHead
[Hand
];
1156 if (IsListEmpty(&TimerEntry
->Entry
))
1158 /* Clear the time then */
1159 TimerEntry
->Time
.HighPart
= 0xFFFFFFFF;
1163 /* Release the timer lock */
1164 KiReleaseTimerLock(LockQueue
);
1169 KxSetTimerForThreadWait(IN PKTIMER Timer
,
1170 IN LARGE_INTEGER Interval
,
1174 LARGE_INTEGER InterruptTime
, SystemTime
, TimeDifference
;
1176 /* Check the timer's interval to see if it's absolute */
1177 Timer
->Header
.Absolute
= FALSE
;
1178 if (Interval
.HighPart
>= 0)
1180 /* Get the system time and calculate the relative time */
1181 KeQuerySystemTime(&SystemTime
);
1182 TimeDifference
.QuadPart
= SystemTime
.QuadPart
- Interval
.QuadPart
;
1183 Timer
->Header
.Absolute
= TRUE
;
1185 /* Check if we've already expired */
1186 if (TimeDifference
.HighPart
>= 0)
1188 /* Reset everything */
1189 Timer
->DueTime
.QuadPart
= 0;
1191 Timer
->Header
.Hand
= 0;
1196 /* Update the interval */
1197 Interval
= TimeDifference
;
1201 /* Calculate the due time */
1202 InterruptTime
.QuadPart
= KeQueryInterruptTime();
1203 DueTime
= InterruptTime
.QuadPart
- Interval
.QuadPart
;
1204 Timer
->DueTime
.QuadPart
= DueTime
;
1206 /* Calculate the timer handle */
1207 *Hand
= KiComputeTimerTableIndex(DueTime
);
1208 Timer
->Header
.Hand
= (UCHAR
)*Hand
;
1211 #define KxDelayThreadWait() \
1213 /* Setup the Wait Block */ \
1214 Thread->WaitBlockList = TimerBlock; \
1216 /* Setup the timer */ \
1217 KxSetTimerForThreadWait(Timer, *Interval, &Hand); \
1219 /* Save the due time for the caller */ \
1220 DueTime.QuadPart = Timer->DueTime.QuadPart; \
1222 /* Link the timer to this Wait Block */ \
1223 TimerBlock->NextWaitBlock = TimerBlock; \
1224 Timer->Header.WaitListHead.Flink = &TimerBlock->WaitListEntry; \
1225 Timer->Header.WaitListHead.Blink = &TimerBlock->WaitListEntry; \
1227 /* Clear wait status */ \
1228 Thread->WaitStatus = STATUS_SUCCESS; \
1230 /* Setup wait fields */ \
1231 Thread->Alertable = Alertable; \
1232 Thread->WaitReason = DelayExecution; \
1233 Thread->WaitMode = WaitMode; \
1235 /* Check if we can swap the thread's stack */ \
1236 Thread->WaitListEntry.Flink = NULL; \
1237 Swappable = KiCheckThreadStackSwap(Thread, WaitMode); \
1239 /* Set the wait time */ \
1240 Thread->WaitTime = KeTickCount.LowPart;
1242 #define KxMultiThreadWait() \
1243 /* Link wait block array to the thread */ \
1244 Thread->WaitBlockList = WaitBlockArray; \
1246 /* Reset the index */ \
1249 /* Loop wait blocks */ \
1252 /* Fill out the wait block */ \
1253 WaitBlock = &WaitBlockArray[Index]; \
1254 WaitBlock->Object = Object[Index]; \
1255 WaitBlock->WaitKey = (USHORT)Index; \
1256 WaitBlock->WaitType = WaitType; \
1257 WaitBlock->Thread = Thread; \
1259 /* Link to next block */ \
1260 WaitBlock->NextWaitBlock = &WaitBlockArray[Index + 1]; \
1262 } while (Index < Count); \
1264 /* Link the last block */ \
1265 WaitBlock->NextWaitBlock = WaitBlockArray; \
1267 /* Set default wait status */ \
1268 Thread->WaitStatus = STATUS_WAIT_0; \
1270 /* Check if we have a timer */ \
1273 /* Link to the block */ \
1274 TimerBlock->NextWaitBlock = WaitBlockArray; \
1276 /* Setup the timer */ \
1277 KxSetTimerForThreadWait(Timer, *Timeout, &Hand); \
1279 /* Save the due time for the caller */ \
1280 DueTime.QuadPart = Timer->DueTime.QuadPart; \
1282 /* Initialize the list */ \
1283 InitializeListHead(&Timer->Header.WaitListHead); \
1286 /* Set wait settings */ \
1287 Thread->Alertable = Alertable; \
1288 Thread->WaitMode = WaitMode; \
1289 Thread->WaitReason = WaitReason; \
1291 /* Check if we can swap the thread's stack */ \
1292 Thread->WaitListEntry.Flink = NULL; \
1293 Swappable = KiCheckThreadStackSwap(Thread, WaitMode); \
1295 /* Set the wait time */ \
1296 Thread->WaitTime = KeTickCount.LowPart;
1298 #define KxSingleThreadWait() \
1299 /* Setup the Wait Block */ \
1300 Thread->WaitBlockList = WaitBlock; \
1301 WaitBlock->WaitKey = STATUS_SUCCESS; \
1302 WaitBlock->Object = Object; \
1303 WaitBlock->WaitType = WaitAny; \
1305 /* Clear wait status */ \
1306 Thread->WaitStatus = STATUS_SUCCESS; \
1308 /* Check if we have a timer */ \
1311 /* Setup the timer */ \
1312 KxSetTimerForThreadWait(Timer, *Timeout, &Hand); \
1314 /* Save the due time for the caller */ \
1315 DueTime.QuadPart = Timer->DueTime.QuadPart; \
1317 /* Pointer to timer block */ \
1318 WaitBlock->NextWaitBlock = TimerBlock; \
1319 TimerBlock->NextWaitBlock = WaitBlock; \
1321 /* Link the timer to this Wait Block */ \
1322 Timer->Header.WaitListHead.Flink = &TimerBlock->WaitListEntry; \
1323 Timer->Header.WaitListHead.Blink = &TimerBlock->WaitListEntry; \
1327 /* No timer block, just ourselves */ \
1328 WaitBlock->NextWaitBlock = WaitBlock; \
1331 /* Set wait settings */ \
1332 Thread->Alertable = Alertable; \
1333 Thread->WaitMode = WaitMode; \
1334 Thread->WaitReason = WaitReason; \
1336 /* Check if we can swap the thread's stack */ \
1337 Thread->WaitListEntry.Flink = NULL; \
1338 Swappable = KiCheckThreadStackSwap(Thread, WaitMode); \
1340 /* Set the wait time */ \
1341 Thread->WaitTime = KeTickCount.LowPart;
1343 #define KxQueueThreadWait() \
1344 /* Setup the Wait Block */ \
1345 Thread->WaitBlockList = WaitBlock; \
1346 WaitBlock->WaitKey = STATUS_SUCCESS; \
1347 WaitBlock->Object = Queue; \
1348 WaitBlock->WaitType = WaitAny; \
1349 WaitBlock->Thread = Thread; \
1351 /* Clear wait status */ \
1352 Thread->WaitStatus = STATUS_SUCCESS; \
1354 /* Check if we have a timer */ \
1357 /* Setup the timer */ \
1358 KxSetTimerForThreadWait(Timer, *Timeout, &Hand); \
1360 /* Save the due time for the caller */ \
1361 DueTime.QuadPart = Timer->DueTime.QuadPart; \
1363 /* Pointer to timer block */ \
1364 WaitBlock->NextWaitBlock = TimerBlock; \
1365 TimerBlock->NextWaitBlock = WaitBlock; \
1367 /* Link the timer to this Wait Block */ \
1368 Timer->Header.WaitListHead.Flink = &TimerBlock->WaitListEntry; \
1369 Timer->Header.WaitListHead.Blink = &TimerBlock->WaitListEntry; \
1373 /* No timer block, just ourselves */ \
1374 WaitBlock->NextWaitBlock = WaitBlock; \
1377 /* Set wait settings */ \
1378 Thread->Alertable = FALSE; \
1379 Thread->WaitMode = WaitMode; \
1380 Thread->WaitReason = WrQueue; \
1382 /* Check if we can swap the thread's stack */ \
1383 Thread->WaitListEntry.Flink = NULL; \
1384 Swappable = KiCheckThreadStackSwap(Thread, WaitMode); \
1386 /* Set the wait time */ \
1387 Thread->WaitTime = KeTickCount.LowPart;
1394 KxUnwaitThread(IN DISPATCHER_HEADER
*Object
,
1395 IN KPRIORITY Increment
)
1397 PLIST_ENTRY WaitEntry
, WaitList
;
1398 PKWAIT_BLOCK WaitBlock
;
1399 PKTHREAD WaitThread
;
1402 /* Loop the Wait Entries */
1403 WaitList
= &Object
->WaitListHead
;
1404 ASSERT(IsListEmpty(&Object
->WaitListHead
) == FALSE
);
1405 WaitEntry
= WaitList
->Flink
;
1408 /* Get the current wait block */
1409 WaitBlock
= CONTAINING_RECORD(WaitEntry
, KWAIT_BLOCK
, WaitListEntry
);
1411 /* Get the waiting thread */
1412 WaitThread
= WaitBlock
->Thread
;
1414 /* Check the current Wait Mode */
1415 if (WaitBlock
->WaitType
== WaitAny
)
1417 /* Use the actual wait key */
1418 WaitKey
= WaitBlock
->WaitKey
;
1422 /* Otherwise, use STATUS_KERNEL_APC */
1423 WaitKey
= STATUS_KERNEL_APC
;
1426 /* Unwait the thread */
1427 KiUnwaitThread(WaitThread
, WaitKey
, Increment
);
1430 WaitEntry
= WaitList
->Flink
;
1431 } while (WaitEntry
!= WaitList
);
1435 // Unwaits a Thread waiting on an event
1439 KxUnwaitThreadForEvent(IN PKEVENT Event
,
1440 IN KPRIORITY Increment
)
1442 PLIST_ENTRY WaitEntry
, WaitList
;
1443 PKWAIT_BLOCK WaitBlock
;
1444 PKTHREAD WaitThread
;
1446 /* Loop the Wait Entries */
1447 WaitList
= &Event
->Header
.WaitListHead
;
1448 ASSERT(IsListEmpty(&Event
->Header
.WaitListHead
) == FALSE
);
1449 WaitEntry
= WaitList
->Flink
;
1452 /* Get the current wait block */
1453 WaitBlock
= CONTAINING_RECORD(WaitEntry
, KWAIT_BLOCK
, WaitListEntry
);
1455 /* Get the waiting thread */
1456 WaitThread
= WaitBlock
->Thread
;
1458 /* Check the current Wait Mode */
1459 if (WaitBlock
->WaitType
== WaitAny
)
1462 Event
->Header
.SignalState
= 0;
1464 /* Un-signal the event and unwait the thread */
1465 KiUnwaitThread(WaitThread
, WaitBlock
->WaitKey
, Increment
);
1469 /* Unwait the thread with STATUS_KERNEL_APC */
1470 KiUnwaitThread(WaitThread
, STATUS_KERNEL_APC
, Increment
);
1473 WaitEntry
= WaitList
->Flink
;
1474 } while (WaitEntry
!= WaitList
);
1478 // This routine queues a thread that is ready on the PRCB's ready lists.
1479 // If this thread cannot currently run on this CPU, then the thread is
1480 // added to the deferred ready list instead.
1482 // This routine must be entered with the PRCB lock held and it will exit
1483 // with the PRCB lock released!
1487 KxQueueReadyThread(IN PKTHREAD Thread
,
1494 ASSERT(Prcb
== KeGetCurrentPrcb());
1495 ASSERT(Thread
->State
== Running
);
1496 ASSERT(Thread
->NextProcessor
== Prcb
->Number
);
1498 /* Check if this thread is allowed to run in this CPU */
1500 if ((Thread
->Affinity
) & (Prcb
->SetMember
))
1505 /* Set thread ready for execution */
1506 Thread
->State
= Ready
;
1508 /* Save current priority and if someone had pre-empted it */
1509 Priority
= Thread
->Priority
;
1510 Preempted
= Thread
->Preempted
;
1512 /* We're not pre-empting now, and set the wait time */
1513 Thread
->Preempted
= FALSE
;
1514 Thread
->WaitTime
= KeTickCount
.LowPart
;
1517 ASSERT((Priority
>= 0) && (Priority
<= HIGH_PRIORITY
));
1519 /* Insert this thread in the appropriate order */
1520 Preempted
? InsertHeadList(&Prcb
->DispatcherReadyListHead
[Priority
],
1521 &Thread
->WaitListEntry
) :
1522 InsertTailList(&Prcb
->DispatcherReadyListHead
[Priority
],
1523 &Thread
->WaitListEntry
);
1525 /* Update the ready summary */
1526 Prcb
->ReadySummary
|= PRIORITY_MASK(Priority
);
1529 ASSERT(Priority
== Thread
->Priority
);
1531 /* Release the PRCB lock */
1532 KiReleasePrcbLock(Prcb
);
1536 /* Otherwise, prepare this thread to be deferred */
1537 Thread
->State
= DeferredReady
;
1538 Thread
->DeferredProcessor
= Prcb
->Number
;
1540 /* Release the lock and defer scheduling */
1541 KiReleasePrcbLock(Prcb
);
1542 KiDeferredReadyThread(Thread
);
1547 // This routine scans for an appropriate ready thread to select at the
1548 // given priority and for the given CPU.
1552 KiSelectReadyThread(IN KPRIORITY Priority
,
1555 ULONG PrioritySet
, HighPriority
;
1556 PLIST_ENTRY ListEntry
;
1557 PKTHREAD Thread
= NULL
;
1559 /* Save the current mask and get the priority set for the CPU */
1560 PrioritySet
= Prcb
->ReadySummary
>> Priority
;
1561 if (!PrioritySet
) goto Quickie
;
1563 /* Get the highest priority possible */
1564 BitScanReverse((PULONG
)&HighPriority
, PrioritySet
);
1565 ASSERT((PrioritySet
& PRIORITY_MASK(HighPriority
)) != 0);
1566 HighPriority
+= Priority
;
1568 /* Make sure the list isn't empty at the highest priority */
1569 ASSERT(IsListEmpty(&Prcb
->DispatcherReadyListHead
[HighPriority
]) == FALSE
);
1571 /* Get the first thread on the list */
1572 ListEntry
= Prcb
->DispatcherReadyListHead
[HighPriority
].Flink
;
1573 Thread
= CONTAINING_RECORD(ListEntry
, KTHREAD
, WaitListEntry
);
1575 /* Make sure this thread is here for a reason */
1576 ASSERT(HighPriority
== Thread
->Priority
);
1577 ASSERT(Thread
->Affinity
& AFFINITY_MASK(Prcb
->Number
));
1578 ASSERT(Thread
->NextProcessor
== Prcb
->Number
);
1580 /* Remove it from the list */
1581 if (RemoveEntryList(&Thread
->WaitListEntry
))
1583 /* The list is empty now, reset the ready summary */
1584 Prcb
->ReadySummary
^= PRIORITY_MASK(HighPriority
);
1587 /* Sanity check and return the thread */
1589 ASSERT((Thread
== NULL
) ||
1590 (Thread
->BasePriority
== 0) ||
1591 (Thread
->Priority
!= 0));
1596 // This routine computes the new priority for a thread. It is only valid for
1597 // threads with priorities in the dynamic priority range.
1601 KiComputeNewPriority(IN PKTHREAD Thread
,
1602 IN SCHAR Adjustment
)
1606 /* Priority sanity checks */
1607 ASSERT((Thread
->PriorityDecrement
>= 0) &&
1608 (Thread
->PriorityDecrement
<= Thread
->Priority
));
1609 ASSERT((Thread
->Priority
< LOW_REALTIME_PRIORITY
) ?
1610 TRUE
: (Thread
->PriorityDecrement
== 0));
1612 /* Get the current priority */
1613 Priority
= Thread
->Priority
;
1614 if (Priority
< LOW_REALTIME_PRIORITY
)
1616 /* Decrease priority by the priority decrement */
1617 Priority
-= (Thread
->PriorityDecrement
+ Adjustment
);
1619 /* Don't go out of bounds */
1620 if (Priority
< Thread
->BasePriority
) Priority
= Thread
->BasePriority
;
1622 /* Reset the priority decrement */
1623 Thread
->PriorityDecrement
= 0;
1627 ASSERT((Thread
->BasePriority
== 0) || (Priority
!= 0));
1629 /* Return the new priority */