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
17 // Sanitizes a selector
21 Ke386SanitizeSeg(IN ULONG Cs
,
22 IN KPROCESSOR_MODE Mode
)
25 // Check if we're in kernel-mode, and force CPL 0 if so.
26 // Otherwise, force CPL 3.
28 return ((Mode
== KernelMode
) ?
29 (Cs
& (0xFFFF & ~RPL_MASK
)) :
30 (RPL_MASK
| (Cs
& 0xFFFF)));
38 Ke386SanitizeFlags(IN ULONG Eflags
,
39 IN KPROCESSOR_MODE Mode
)
42 // Check if we're in kernel-mode, and sanitize EFLAGS if so.
43 // Otherwise, also force interrupt mask on.
45 return ((Mode
== KernelMode
) ?
46 (Eflags
& (EFLAGS_USER_SANITIZE
| EFLAGS_INTERRUPT_MASK
)) :
47 (EFLAGS_INTERRUPT_MASK
| (Eflags
& EFLAGS_USER_SANITIZE
)));
51 // Gets a DR register from a CONTEXT structure
55 KiDrFromContext(IN ULONG Dr
,
58 return *(PVOID
*)((ULONG_PTR
)Context
+ KiDebugRegisterContextOffsets
[Dr
]);
62 // Gets a DR register from a KTRAP_FRAME structure
66 KiDrFromTrapFrame(IN ULONG Dr
,
67 IN PKTRAP_FRAME TrapFrame
)
69 return (PVOID
*)((ULONG_PTR
)TrapFrame
+ KiDebugRegisterTrapOffsets
[Dr
]);
77 Ke386SanitizeDr(IN PVOID DrAddress
,
78 IN KPROCESSOR_MODE Mode
)
81 // Check if we're in kernel-mode, and return the address directly if so.
82 // Otherwise, make sure it's not inside the kernel-mode address space.
83 // If it is, then clear the address.
85 return ((Mode
== KernelMode
) ? DrAddress
:
86 (DrAddress
<= MM_HIGHEST_USER_ADDRESS
) ? DrAddress
: 0);
90 // Enters a Guarded Region
92 #define KeEnterGuardedRegion() \
94 PKTHREAD _Thread = KeGetCurrentThread(); \
97 ASSERT_IRQL_LESS_OR_EQUAL(APC_LEVEL); \
98 ASSERT(_Thread == KeGetCurrentThread()); \
99 ASSERT((_Thread->SpecialApcDisable <= 0) && \
100 (_Thread->SpecialApcDisable != -32768)); \
102 /* Disable Special APCs */ \
103 _Thread->SpecialApcDisable--; \
107 // Leaves a Guarded Region
109 #define KeLeaveGuardedRegion() \
111 PKTHREAD _Thread = KeGetCurrentThread(); \
113 /* Sanity checks */ \
114 ASSERT_IRQL_LESS_OR_EQUAL(APC_LEVEL); \
115 ASSERT(_Thread == KeGetCurrentThread()); \
116 ASSERT(_Thread->SpecialApcDisable < 0); \
118 /* Leave region and check if APCs are OK now */ \
119 if (!(++_Thread->SpecialApcDisable)) \
121 /* Check for Kernel APCs on the list */ \
122 if (!IsListEmpty(&_Thread->ApcState. \
123 ApcListHead[KernelMode])) \
125 /* Check for APC Delivery */ \
126 KiCheckForKernelApcDelivery(); \
132 // TODO: Guarded Mutex Routines
136 // Enters a Critical Region
138 #define KeEnterCriticalRegion() \
140 PKTHREAD _Thread = KeGetCurrentThread(); \
142 /* Sanity checks */ \
143 ASSERT(_Thread == KeGetCurrentThread()); \
144 ASSERT((_Thread->KernelApcDisable <= 0) && \
145 (_Thread->KernelApcDisable != -32768)); \
147 /* Disable Kernel APCs */ \
148 _Thread->KernelApcDisable--; \
152 // Leaves a Critical Region
154 #define KeLeaveCriticalRegion() \
156 PKTHREAD _Thread = KeGetCurrentThread(); \
158 /* Sanity checks */ \
159 ASSERT(_Thread == KeGetCurrentThread()); \
160 ASSERT(_Thread->KernelApcDisable < 0); \
162 /* Enable Kernel APCs */ \
163 _Thread->KernelApcDisable++; \
165 /* Check if Kernel APCs are now enabled */ \
166 if (!(_Thread->KernelApcDisable)) \
168 /* Check if we need to request an APC Delivery */ \
169 if (!(IsListEmpty(&_Thread->ApcState.ApcListHead[KernelMode])) && \
170 !(_Thread->SpecialApcDisable)) \
172 /* Check for the right environment */ \
173 KiCheckForKernelApcDelivery(); \
179 // Satisfies the wait of any dispatcher object
181 #define KiSatisfyObjectWait(Object, Thread) \
183 /* Special case for Mutants */ \
184 if ((Object)->Header.Type == MutantObject) \
186 /* Decrease the Signal State */ \
187 (Object)->Header.SignalState--; \
189 /* Check if it's now non-signaled */ \
190 if (!(Object)->Header.SignalState) \
192 /* Set the Owner Thread */ \
193 (Object)->OwnerThread = Thread; \
195 /* Disable APCs if needed */ \
196 Thread->KernelApcDisable -= (Object)->ApcDisable; \
198 /* Check if it's abandoned */ \
199 if ((Object)->Abandoned) \
202 (Object)->Abandoned = FALSE; \
204 /* Return Status */ \
205 Thread->WaitStatus = STATUS_ABANDONED; \
208 /* Insert it into the Mutant List */ \
209 InsertHeadList(Thread->MutantListHead.Blink, \
210 &(Object)->MutantListEntry); \
213 else if (((Object)->Header.Type & TIMER_OR_EVENT_TYPE) == \
214 EventSynchronizationObject) \
216 /* Synchronization Timers and Events just get un-signaled */ \
217 (Object)->Header.SignalState = 0; \
219 else if ((Object)->Header.Type == SemaphoreObject) \
221 /* These ones can have multiple states, so we only decrease it */ \
222 (Object)->Header.SignalState--; \
227 // Satisfies the wait of a mutant dispatcher object
229 #define KiSatisfyMutantWait(Object, Thread) \
231 /* Decrease the Signal State */ \
232 (Object)->Header.SignalState--; \
234 /* Check if it's now non-signaled */ \
235 if (!(Object)->Header.SignalState) \
237 /* Set the Owner Thread */ \
238 (Object)->OwnerThread = Thread; \
240 /* Disable APCs if needed */ \
241 Thread->KernelApcDisable -= (Object)->ApcDisable; \
243 /* Check if it's abandoned */ \
244 if ((Object)->Abandoned) \
247 (Object)->Abandoned = FALSE; \
249 /* Return Status */ \
250 Thread->WaitStatus = STATUS_ABANDONED; \
253 /* Insert it into the Mutant List */ \
254 InsertHeadList(Thread->MutantListHead.Blink, \
255 &(Object)->MutantListEntry); \
260 // Satisfies the wait of any nonmutant dispatcher object
262 #define KiSatisfyNonMutantWait(Object, Thread) \
264 if (((Object)->Header.Type & TIMER_OR_EVENT_TYPE) == \
265 EventSynchronizationObject) \
267 /* Synchronization Timers and Events just get un-signaled */ \
268 (Object)->Header.SignalState = 0; \
270 else if ((Object)->Header.Type == SemaphoreObject) \
272 /* These ones can have multiple states, so we only decrease it */ \
273 (Object)->Header.SignalState--; \
278 // Recalculates the due time
282 KiRecalculateDueTime(IN PLARGE_INTEGER OriginalDueTime
,
283 IN PLARGE_INTEGER DueTime
,
284 IN OUT PLARGE_INTEGER NewDueTime
)
286 /* Don't do anything for absolute waits */
287 if (OriginalDueTime
->QuadPart
>= 0) return OriginalDueTime
;
289 /* Otherwise, query the interrupt time and recalculate */
290 NewDueTime
->QuadPart
= KeQueryInterruptTime();
291 NewDueTime
->QuadPart
-= DueTime
->QuadPart
;
296 // Determines wether a thread should be added to the wait list
300 KiCheckThreadStackSwap(IN PKTHREAD Thread
,
301 IN KPROCESSOR_MODE WaitMode
)
303 /* Check the required conditions */
304 if ((WaitMode
!= KernelMode
) &&
305 (Thread
->EnableStackSwap
) &&
306 (Thread
->Priority
>= (LOW_REALTIME_PRIORITY
+ 9)))
308 /* We are go for swap */
313 /* Don't swap the thread */
319 // Adds a thread to the wait list
321 #define KiAddThreadToWaitList(Thread, Swappable) \
323 /* Make sure it's swappable */ \
326 /* Insert it into the PRCB's List */ \
327 InsertTailList(&KeGetCurrentPrcb()->WaitListHead, \
328 &Thread->WaitListEntry); \
333 // Checks if a wait in progress should be interrupted by APCs or an alertable
338 KiCheckAlertability(IN PKTHREAD Thread
,
339 IN BOOLEAN Alertable
,
340 IN KPROCESSOR_MODE WaitMode
)
342 /* Check if the wait is alertable */
345 /* It is, first check if the thread is alerted in this mode */
346 if (Thread
->Alerted
[WaitMode
])
348 /* It is, so bail out of the wait */
349 Thread
->Alerted
[WaitMode
] = FALSE
;
350 return STATUS_ALERTED
;
352 else if ((WaitMode
!= KernelMode
) &&
353 (!IsListEmpty(&Thread
->ApcState
.ApcListHead
[UserMode
])))
355 /* It's isn't, but this is a user wait with queued user APCs */
356 Thread
->ApcState
.UserApcPending
= TRUE
;
357 return STATUS_USER_APC
;
359 else if (Thread
->Alerted
[KernelMode
])
361 /* It isn't that either, but we're alered in kernel mode */
362 Thread
->Alerted
[KernelMode
] = FALSE
;
363 return STATUS_ALERTED
;
366 else if ((WaitMode
!= KernelMode
) && (Thread
->ApcState
.UserApcPending
))
368 /* Not alertable, but this is a user wait with pending user APCs */
369 return STATUS_USER_APC
;
372 /* Otherwise, we're fine */
373 return STATUS_WAIT_0
;
378 KxDelayThreadWait(IN PKTHREAD Thread
,
379 IN BOOLEAN Alertable
,
380 IN KPROCESSOR_MODE WaitMode
)
383 PKWAIT_BLOCK TimerBlock
= &Thread
->WaitBlock
[TIMER_WAIT_BLOCK
];
385 /* Setup the Wait Block */
386 Thread
->WaitBlockList
= TimerBlock
;
387 TimerBlock
->NextWaitBlock
= TimerBlock
;
389 /* Link the timer to this Wait Block */
390 Thread
->Timer
.Header
.WaitListHead
.Flink
= &TimerBlock
->WaitListEntry
;
391 Thread
->Timer
.Header
.WaitListHead
.Blink
= &TimerBlock
->WaitListEntry
;
393 /* Clear wait status */
394 Thread
->WaitStatus
= STATUS_WAIT_0
;
396 /* Setup wait fields */
397 Thread
->Alertable
= Alertable
;
398 Thread
->WaitReason
= DelayExecution
;
399 Thread
->WaitMode
= WaitMode
;
401 /* Check if we can swap the thread's stack */
402 Thread
->WaitListEntry
.Flink
= NULL
;
403 Swappable
= KiCheckThreadStackSwap(Thread
, WaitMode
);
405 /* Set the wait time */
406 Thread
->WaitTime
= ((PLARGE_INTEGER
)&KeTickCount
)->LowPart
;
412 KxMultiThreadWait(IN PKTHREAD Thread
,
413 IN PKWAIT_BLOCK WaitBlock
,
414 IN BOOLEAN Alertable
,
415 IN KWAIT_REASON WaitReason
,
416 IN KPROCESSOR_MODE WaitMode
)
419 PKTIMER ThreadTimer
= &Thread
->Timer
;
421 /* Set default wait status */
422 Thread
->WaitStatus
= STATUS_WAIT_0
;
424 /* Link wait block array to the thread */
425 Thread
->WaitBlockList
= WaitBlock
;
427 /* Initialize the timer list */
428 InitializeListHead(&ThreadTimer
->Header
.WaitListHead
);
430 /* Set wait settings */
431 Thread
->Alertable
= Alertable
;
432 Thread
->WaitMode
= WaitMode
;
433 Thread
->WaitReason
= WaitReason
;
435 /* Check if we can swap the thread's stack */
436 Thread
->WaitListEntry
.Flink
= NULL
;
437 Swappable
= KiCheckThreadStackSwap(Thread
, WaitMode
);
439 /* Set the wait time */
440 Thread
->WaitTime
= ((PLARGE_INTEGER
)&KeTickCount
)->LowPart
;
446 KxSingleThreadWait(IN PKTHREAD Thread
,
447 IN PKWAIT_BLOCK WaitBlock
,
449 IN PLARGE_INTEGER Timeout
,
450 IN BOOLEAN Alertable
,
451 IN KWAIT_REASON WaitReason
,
452 IN KPROCESSOR_MODE WaitMode
)
455 PKWAIT_BLOCK TimerBlock
= &Thread
->WaitBlock
[TIMER_WAIT_BLOCK
];
457 /* Setup the Wait Block */
458 Thread
->WaitBlockList
= WaitBlock
;
459 WaitBlock
->WaitKey
= STATUS_WAIT_0
;
460 WaitBlock
->Object
= Object
;
461 WaitBlock
->WaitType
= WaitAny
;
463 /* Clear wait status */
464 Thread
->WaitStatus
= STATUS_WAIT_0
;
466 /* Check if we have a timer */
469 /* Pointer to timer block */
470 WaitBlock
->NextWaitBlock
= TimerBlock
;
471 TimerBlock
->NextWaitBlock
= WaitBlock
;
473 /* Link the timer to this Wait Block */
474 Thread
->Timer
.Header
.WaitListHead
.Flink
= &TimerBlock
->WaitListEntry
;
475 Thread
->Timer
.Header
.WaitListHead
.Blink
= &TimerBlock
->WaitListEntry
;
479 /* No timer block, just ourselves */
480 WaitBlock
->NextWaitBlock
= WaitBlock
;
483 /* Setup wait fields */
484 Thread
->Alertable
= Alertable
;
485 Thread
->WaitReason
= WaitReason
;
486 Thread
->WaitMode
= WaitMode
;
488 /* Check if we can swap the thread's stack */
489 Thread
->WaitListEntry
.Flink
= NULL
;
490 Swappable
= KiCheckThreadStackSwap(Thread
, WaitMode
);
492 /* Set the wait time */
493 Thread
->WaitTime
= ((PLARGE_INTEGER
)&KeTickCount
)->LowPart
;
502 KxUnwaitThread(IN DISPATCHER_HEADER
*Object
,
503 IN KPRIORITY Increment
)
505 PLIST_ENTRY WaitEntry
, WaitList
;
506 PKWAIT_BLOCK CurrentWaitBlock
;
510 /* Loop the Wait Entries */
511 WaitList
= &Object
->WaitListHead
;
512 WaitEntry
= WaitList
->Flink
;
515 /* Get the current wait block */
516 CurrentWaitBlock
= CONTAINING_RECORD(WaitEntry
,
520 /* Get the waiting thread */
521 WaitThread
= CurrentWaitBlock
->Thread
;
523 /* Check the current Wait Mode */
524 if (CurrentWaitBlock
->WaitType
== WaitAny
)
526 /* Use the actual wait key */
527 WaitKey
= CurrentWaitBlock
->WaitKey
;
531 /* Otherwise, use STATUS_KERNEL_APC */
532 WaitKey
= STATUS_KERNEL_APC
;
535 /* Unwait the thread */
536 KiUnwaitThread(WaitThread
, WaitKey
, Increment
);
539 WaitEntry
= WaitList
->Flink
;
540 } while (WaitEntry
!= WaitList
);
544 // Unwaits a Thread waiting on an event
548 KxUnwaitThreadForEvent(IN PKEVENT Event
,
549 IN KPRIORITY Increment
)
551 PLIST_ENTRY WaitEntry
, WaitList
;
552 PKWAIT_BLOCK CurrentWaitBlock
;
555 /* Loop the Wait Entries */
556 WaitList
= &Event
->Header
.WaitListHead
;
557 WaitEntry
= WaitList
->Flink
;
560 /* Get the current wait block */
561 CurrentWaitBlock
= CONTAINING_RECORD(WaitEntry
,
565 /* Get the waiting thread */
566 WaitThread
= CurrentWaitBlock
->Thread
;
568 /* Check the current Wait Mode */
569 if (CurrentWaitBlock
->WaitType
== WaitAny
)
572 Event
->Header
.SignalState
= 0;
574 /* Un-signal the event and unwait the thread */
575 KiUnwaitThread(WaitThread
, CurrentWaitBlock
->WaitKey
, Increment
);
580 /* Unwait the thread with STATUS_KERNEL_APC */
581 KiUnwaitThread(WaitThread
, STATUS_KERNEL_APC
, Increment
);
585 WaitEntry
= WaitList
->Flink
;
586 } while (WaitEntry
!= WaitList
);
591 // Spinlock Acquire at IRQL >= DISPATCH_LEVEL
595 KxAcquireSpinLock(IN PKSPIN_LOCK SpinLock
)
597 /* On UP builds, spinlocks don't exist at IRQL >= DISPATCH */
598 UNREFERENCED_PARAMETER(SpinLock
);
602 // Spinlock Release at IRQL >= DISPATCH_LEVEL
606 KxReleaseSpinLock(IN PKSPIN_LOCK SpinLock
)
608 /* On UP builds, spinlocks don't exist at IRQL >= DISPATCH */
609 UNREFERENCED_PARAMETER(SpinLock
);
613 // This routine protects against multiple CPU acquires, it's meaningless on UP.
617 KiAcquireDispatcherObject(IN DISPATCHER_HEADER
* Object
)
619 UNREFERENCED_PARAMETER(Object
);
623 // This routine protects against multiple CPU acquires, it's meaningless on UP.
627 KiReleaseDispatcherObject(IN DISPATCHER_HEADER
* Object
)
629 UNREFERENCED_PARAMETER(Object
);
634 KiAcquireDispatcherLock(VOID
)
636 /* Raise to DPC level */
637 return KeRaiseIrqlToDpcLevel();
642 KiReleaseDispatcherLock(IN KIRQL OldIrql
)
644 /* Just exit the dispatcher */
645 KiExitDispatcher(OldIrql
);
650 KiAcquireDispatcherLockAtDpcLevel(VOID
)
652 /* This is a no-op at DPC Level for UP systems */
658 KiReleaseDispatcherLockFromDpcLevel(VOID
)
660 /* This is a no-op at DPC Level for UP systems */
665 // This routine makes the thread deferred ready on the boot CPU.
669 KiInsertDeferredReadyList(IN PKTHREAD Thread
)
671 /* Set the thread to deferred state and boot CPU */
672 Thread
->State
= DeferredReady
;
673 Thread
->DeferredProcessor
= 0;
675 /* Make the thread ready immediately */
676 KiDeferredReadyThread(Thread
);
681 KiRescheduleThread(IN BOOLEAN NewThread
,
684 /* This is meaningless on UP systems */
685 UNREFERENCED_PARAMETER(NewThread
);
686 UNREFERENCED_PARAMETER(Cpu
);
690 // This routine protects against multiple CPU acquires, it's meaningless on UP.
694 KiSetThreadSwapBusy(IN PKTHREAD Thread
)
696 UNREFERENCED_PARAMETER(Thread
);
700 // This routine protects against multiple CPU acquires, it's meaningless on UP.
704 KiAcquirePrcbLock(IN PKPRCB Prcb
)
706 UNREFERENCED_PARAMETER(Prcb
);
710 // This routine protects against multiple CPU acquires, it's meaningless on UP.
714 KiReleasePrcbLock(IN PKPRCB Prcb
)
716 UNREFERENCED_PARAMETER(Prcb
);
720 // This routine protects against multiple CPU acquires, it's meaningless on UP.
724 KiAcquireThreadLock(IN PKTHREAD Thread
)
726 UNREFERENCED_PARAMETER(Thread
);
730 // This routine protects against multiple CPU acquires, it's meaningless on UP.
734 KiReleaseThreadLock(IN PKTHREAD Thread
)
736 UNREFERENCED_PARAMETER(Thread
);
740 // This routine protects against multiple CPU acquires, it's meaningless on UP.
744 KiTryThreadLock(IN PKTHREAD Thread
)
746 UNREFERENCED_PARAMETER(Thread
);
752 KiCheckDeferredReadyList(IN PKPRCB Prcb
)
754 /* There are no deferred ready lists on UP systems */
755 UNREFERENCED_PARAMETER(Prcb
);
760 KiRundownThread(IN PKTHREAD Thread
)
762 /* Check if this is the NPX Thread */
763 if (KeGetCurrentPrcb()->NpxThread
== Thread
)
766 KeGetCurrentPrcb()->NpxThread
= NULL
;
773 KiRequestApcInterrupt(IN BOOLEAN NeedApc
,
776 /* We deliver instantly on UP */
777 UNREFERENCED_PARAMETER(NeedApc
);
778 UNREFERENCED_PARAMETER(Processor
);
784 // Spinlock Acquisition at IRQL >= DISPATCH_LEVEL
788 KxAcquireSpinLock(IN PKSPIN_LOCK SpinLock
)
792 /* Try to acquire it */
793 if (InterlockedBitTestAndSet((PLONG
)SpinLock
, 0))
795 /* Value changed... wait until it's locked */
796 while (*(volatile KSPIN_LOCK
*)SpinLock
== 1)
799 /* On debug builds, we use a much slower but useful routine */
800 Kii386SpinOnSpinLock(SpinLock
, 5);
802 /* Otherwise, just yield and keep looping */
810 /* On debug builds, we OR in the KTHREAD */
811 *SpinLock
= KeGetCurrentThread() | 1;
813 /* All is well, break out */
820 // Spinlock Release at IRQL >= DISPATCH_LEVEL
824 KxReleaseSpinLock(IN PKSPIN_LOCK SpinLock
)
827 /* Make sure that the threads match */
828 if ((KeGetCurrentThread() | 1) != *SpinLock
)
830 /* They don't, bugcheck */
831 KeBugCheckEx(SPIN_LOCK_NOT_OWNED
, SpinLock
, 0, 0, 0);
835 InterlockedAnd(SpinLock
, 0);
840 KiAcquireDispatcherObject(IN DISPATCHER_HEADER
* Object
)
842 LONG OldValue
, NewValue
;
844 /* Make sure we're at a safe level to touch the lock */
845 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
847 /* Start acquire loop */
850 /* Loop until the other CPU releases it */
851 while ((UCHAR
)Object
->Lock
& KOBJECT_LOCK_BIT
)
853 /* Let the CPU know that this is a loop */
857 /* Try acquiring the lock now */
858 NewValue
= InterlockedCompareExchange(&Object
->Lock
,
859 OldValue
| KOBJECT_LOCK_BIT
,
861 } while (NewValue
!= OldValue
);
866 KiReleaseDispatcherObject(IN DISPATCHER_HEADER
* Object
)
868 /* Make sure we're at a safe level to touch the lock */
869 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
872 InterlockedAnd(&Object
->Lock
, ~KOBJECT_LOCK_BIT
);
877 KiAcquireDispatcherLock(VOID
)
879 /* Raise to synchronization level and acquire the dispatcher lock */
880 return KeAcquireQueuedSpinLockRaiseToSynch(LockQueueDispatcherLock
);
885 KiReleaseDispatcherLock(IN KIRQL OldIrql
)
887 /* First release the lock */
888 KeReleaseQueuedSpinLockFromDpcLevel(&KeGetCurrentPrcb()->
889 LockQueue
[LockQueueDispatcherLock
]);
891 /* Then exit the dispatcher */
892 KiExitDispatcher(OldIrql
);
896 // This routine inserts a thread into the deferred ready list of the given CPU
900 KiInsertDeferredReadyList(IN PKTHREAD Thread
)
902 PKPRCB Prcb
= KeGetCurrentPrcb();
904 /* Set the thread to deferred state and CPU */
905 Thread
->State
= DeferredReady
;
906 Thread
->DeferredProcessor
= Prcb
->Number
;
908 /* Add it on the list */
909 PushEntryList(&Prcb
->DeferredReadyListHead
, &Thread
->SwapListEntry
);
914 KiRescheduleThread(IN BOOLEAN NewThread
,
917 /* Check if a new thread needs to be scheduled on a different CPU */
918 if ((NewThread
) && !(KeGetPcr()->Number
== Cpu
))
920 /* Send an IPI to request delivery */
921 KiIpiSendRequest(AFFINITY_MASK(Cpu
), IPI_DPC
);
926 // This routine sets the current thread in a swap busy state, which ensure that
927 // nobody else tries to swap it concurrently.
931 KiSetThreadSwapBusy(IN PKTHREAD Thread
)
933 /* Make sure nobody already set it */
934 ASSERT(Thread
->SwapBusy
== FALSE
);
936 /* Set it ourselves */
937 Thread
->SwapBusy
= TRUE
;
941 // This routine acquires the PRCB lock so that only one caller can touch
942 // volatile PRCB data.
944 // Since this is a simple optimized spin-lock, it must be be only acquired
945 // at dispatcher level or higher!
949 KiAcquirePrcbLock(IN PKPRCB Prcb
)
951 /* Make sure we're at a safe level to touch the PRCB lock */
952 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
954 /* Start acquire loop */
957 /* Acquire the lock and break out if we acquired it first */
958 if (!InterlockedExchange(&Prcb
->PrcbLock
, 1)) break;
960 /* Loop until the other CPU releases it */
963 /* Let the CPU know that this is a loop */
965 } while (Prcb
->PrcbLock
);
970 // This routine releases the PRCB lock so that other callers can touch
971 // volatile PRCB data.
973 // Since this is a simple optimized spin-lock, it must be be only acquired
974 // at dispatcher level or higher!
978 KiReleasePrcbLock(IN PKPRCB Prcb
)
980 /* Make sure it's acquired! */
981 ASSERT(Prcb
->PrcbLock
!= 0);
984 InterlockedAnd(&Prcb
->PrcbLock
, 0);
988 // This routine acquires the thread lock so that only one caller can touch
989 // volatile thread data.
991 // Since this is a simple optimized spin-lock, it must be be only acquired
992 // at dispatcher level or higher!
996 KiAcquireThreadLock(IN PKTHREAD Thread
)
998 /* Make sure we're at a safe level to touch the thread lock */
999 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL
);
1001 /* Start acquire loop */
1004 /* Acquire the lock and break out if we acquired it first */
1005 if (!InterlockedExchange(&Thread
->ThreadLock
, 1)) break;
1007 /* Loop until the other CPU releases it */
1010 /* Let the CPU know that this is a loop */
1012 } while (Thread
->ThreadLock
);
1017 // This routine releases the thread lock so that other callers can touch
1018 // volatile thread data.
1020 // Since this is a simple optimized spin-lock, it must be be only acquired
1021 // at dispatcher level or higher!
1025 KiReleaseThreadLock(IN PKTHREAD Thread
)
1028 InterlockedAnd(&Thread
->ThreadLock
, 0);
1033 KiTryThreadLock(IN PKTHREAD Thread
)
1037 /* If the lock isn't acquired, return false */
1038 if (!Thread
->ThreadLock
) return FALSE
;
1040 /* Otherwise, try to acquire it and check the result */
1042 Value
= InterlockedExchange(&Thread
->ThreadLock
, &Value
);
1044 /* Return the lock state */
1045 return (Value
== TRUE
);
1050 KiCheckDeferredReadyList(IN PKPRCB Prcb
)
1052 /* Scan the deferred ready lists if required */
1053 if (Prcb
->DeferredReadyListHead
.Next
) KiProcessDeferredReadyList(Prcb
);
1058 KiRequestApcInterrupt(IN BOOLEAN NeedApc
,
1061 /* Check if we need to request APC delivery */
1064 /* Check if it's on another CPU */
1065 if (KeGetPcr()->Number
!= Cpu
)
1067 /* Send an IPI to request delivery */
1068 KiIpiSendRequest(AFFINITY_MASK(Cpu
), IPI_DPC
);
1072 /* Request a software interrupt */
1073 HalRequestSoftwareInterrupt(APC_LEVEL
);
1082 KiAcquireApcLock(IN PKTHREAD Thread
,
1083 IN PKLOCK_QUEUE_HANDLE Handle
)
1085 /* Acquire the lock and raise to synchronization level */
1086 KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread
->ApcQueueLock
, Handle
);
1091 KiAcquireApcLockAtDpcLevel(IN PKTHREAD Thread
,
1092 IN PKLOCK_QUEUE_HANDLE Handle
)
1094 /* Acquire the lock */
1095 KeAcquireInStackQueuedSpinLockAtDpcLevel(&Thread
->ApcQueueLock
, Handle
);
1100 KiAcquireApcLockAtApcLevel(IN PKTHREAD Thread
,
1101 IN PKLOCK_QUEUE_HANDLE Handle
)
1103 /* Acquire the lock */
1104 KeAcquireInStackQueuedSpinLock(&Thread
->ApcQueueLock
, Handle
);
1109 KiReleaseApcLock(IN PKLOCK_QUEUE_HANDLE Handle
)
1111 /* Release the lock */
1112 KeReleaseInStackQueuedSpinLock(Handle
);
1117 KiReleaseApcLockFromDpcLevel(IN PKLOCK_QUEUE_HANDLE Handle
)
1119 /* Release the lock */
1120 KeReleaseInStackQueuedSpinLockFromDpcLevel(Handle
);
1125 KiAcquireProcessLock(IN PKPROCESS Process
,
1126 IN PKLOCK_QUEUE_HANDLE Handle
)
1128 /* Acquire the lock and raise to synchronization level */
1129 KeAcquireInStackQueuedSpinLockRaiseToSynch(&Process
->ProcessLock
, Handle
);
1134 KiReleaseProcessLock(IN PKLOCK_QUEUE_HANDLE Handle
)
1136 /* Release the lock */
1137 KeReleaseInStackQueuedSpinLock(Handle
);
1142 KiReleaseProcessLockFromDpcLevel(IN PKLOCK_QUEUE_HANDLE Handle
)
1144 /* Release the lock */
1145 KeReleaseInStackQueuedSpinLockFromDpcLevel(Handle
);
1150 KiAcquireDeviceQueueLock(IN PKDEVICE_QUEUE DeviceQueue
,
1151 IN PKLOCK_QUEUE_HANDLE DeviceLock
)
1153 /* Check if we were called from a threaded DPC */
1154 if (KeGetCurrentPrcb()->DpcThreadActive
)
1156 /* Lock the Queue, we're not at DPC level */
1157 KeAcquireInStackQueuedSpinLock(&DeviceQueue
->Lock
, DeviceLock
);
1161 /* We must be at DPC level, acquire the lock safely */
1162 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL
);
1163 KeAcquireInStackQueuedSpinLockAtDpcLevel(&DeviceQueue
->Lock
,
1170 KiReleaseDeviceQueueLock(IN PKLOCK_QUEUE_HANDLE DeviceLock
)
1172 /* Check if we were called from a threaded DPC */
1173 if (KeGetCurrentPrcb()->DpcThreadActive
)
1175 /* Unlock the Queue, we're not at DPC level */
1176 KeReleaseInStackQueuedSpinLock(DeviceLock
);
1180 /* We must be at DPC level, release the lock safely */
1181 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL
);
1182 KeReleaseInStackQueuedSpinLockFromDpcLevel(DeviceLock
);
1187 // This routine queues a thread that is ready on the PRCB's ready lists.
1188 // If this thread cannot currently run on this CPU, then the thread is
1189 // added to the deferred ready list instead.
1191 // This routine must be entered with the PRCB lock held and it will exit
1192 // with the PRCB lock released!
1196 KxQueueReadyThread(IN PKTHREAD Thread
,
1203 ASSERT(Prcb
== KeGetCurrentPrcb());
1204 ASSERT(Thread
->State
== Running
);
1205 ASSERT(Thread
->NextProcessor
== Prcb
->Number
);
1207 /* Check if this thread is allowed to run in this CPU */
1209 if ((Thread
->Affinity
) & (Prcb
->SetMember
))
1214 /* Set thread ready for execution */
1215 Thread
->State
= Ready
;
1217 /* Save current priority and if someone had pre-empted it */
1218 Priority
= Thread
->Priority
;
1219 Preempted
= Thread
->Preempted
;
1221 /* We're not pre-empting now, and set the wait time */
1222 Thread
->Preempted
= FALSE
;
1223 Thread
->WaitTime
= KeTickCount
.LowPart
;
1226 ASSERT((Priority
>= 0) && (Priority
<= HIGH_PRIORITY
));
1228 /* Insert this thread in the appropriate order */
1229 Preempted
? InsertHeadList(&Prcb
->DispatcherReadyListHead
[Priority
],
1230 &Thread
->WaitListEntry
) :
1231 InsertTailList(&Prcb
->DispatcherReadyListHead
[Priority
],
1232 &Thread
->WaitListEntry
);
1234 /* Update the ready summary */
1235 Prcb
->ReadySummary
|= PRIORITY_MASK(Priority
);
1238 ASSERT(Priority
== Thread
->Priority
);
1240 /* Release the PRCB lock */
1241 KiReleasePrcbLock(Prcb
);
1245 /* Otherwise, prepare this thread to be deferred */
1246 Thread
->State
= DeferredReady
;
1247 Thread
->DeferredProcessor
= Prcb
->Number
;
1249 /* Release the lock and defer scheduling */
1250 KiReleasePrcbLock(Prcb
);
1251 KiDeferredReadyThread(Thread
);
1256 // This routine scans for an appropriate ready thread to select at the
1257 // given priority and for the given CPU.
1261 KiSelectReadyThread(IN KPRIORITY Priority
,
1264 LONG PriorityMask
, PrioritySet
, HighPriority
;
1265 PLIST_ENTRY ListEntry
;
1268 /* Save the current mask and get the priority set for the CPU */
1269 PriorityMask
= Priority
;
1270 PrioritySet
= Prcb
->ReadySummary
>> (UCHAR
)Priority
;
1271 if (!PrioritySet
) return NULL
;
1273 /* Get the highest priority possible */
1274 BitScanReverse((PULONG
)&HighPriority
, PrioritySet
);
1275 ASSERT((PrioritySet
& PRIORITY_MASK(HighPriority
)) != 0);
1276 HighPriority
+= PriorityMask
;
1278 /* Make sure the list isn't at highest priority */
1279 ASSERT(IsListEmpty(&Prcb
->DispatcherReadyListHead
[HighPriority
]) == FALSE
);
1281 /* Get the first thread on the list */
1282 ListEntry
= &Prcb
->DispatcherReadyListHead
[HighPriority
];
1283 Thread
= CONTAINING_RECORD(ListEntry
, KTHREAD
, WaitListEntry
);
1285 /* Make sure this thread is here for a reason */
1286 ASSERT(HighPriority
== Thread
->Priority
);
1287 ASSERT(Thread
->Affinity
& AFFINITY_MASK(Prcb
->Number
));
1288 ASSERT(Thread
->NextProcessor
== Prcb
->Number
);
1290 /* Remove it from the list */
1291 RemoveEntryList(&Thread
->WaitListEntry
);
1292 if (IsListEmpty(&Thread
->WaitListEntry
))
1294 /* The list is empty now, reset the ready summary */
1295 Prcb
->ReadySummary
^= PRIORITY_MASK(HighPriority
);
1298 /* Sanity check and return the thread */
1299 ASSERT((Thread
== NULL
) ||
1300 (Thread
->BasePriority
== 0) ||
1301 (Thread
->Priority
!= 0));
1306 // This routine computes the new priority for a thread. It is only valid for
1307 // threads with priorities in the dynamic priority range.
1311 KiComputeNewPriority(IN PKTHREAD Thread
)
1315 /* Priority sanity checks */
1316 ASSERT((Thread
->PriorityDecrement
>= 0) &&
1317 (Thread
->PriorityDecrement
<= Thread
->Priority
));
1318 ASSERT((Thread
->Priority
< LOW_REALTIME_PRIORITY
) ?
1319 TRUE
: (Thread
->PriorityDecrement
== 0));
1321 /* Get the current priority */
1322 Priority
= Thread
->Priority
;
1323 if (Priority
< LOW_REALTIME_PRIORITY
)
1325 /* Decrease priority by the priority decrement */
1326 Priority
-= (Thread
->PriorityDecrement
+ 1);
1328 /* Don't go out of bounds */
1329 if (Priority
< Thread
->BasePriority
) Priority
= Thread
->BasePriority
;
1331 /* Reset the priority decrement */
1332 Thread
->PriorityDecrement
= 0;
1336 ASSERT((Thread
->BasePriority
== 0) || (Priority
!= 0));
1338 /* Return the new priority */
1344 KeGetCurrentThread(VOID
)
1346 /* Return the current thread */
1347 return ((PKIPCR
)KeGetPcr())->PrcbData
.CurrentThread
;
1352 KeGetPreviousMode(VOID
)
1354 /* Return the current mode */
1355 return KeGetCurrentThread()->PreviousMode
;