[NTOS]
[reactos.git] / reactos / ntoskrnl / include / internal / ke_x.h
1 /*
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)
7 */
8
9 #ifndef _M_ARM
10 FORCEINLINE
11 UCHAR
12 KeGetPreviousMode(VOID)
13 {
14 /* Return the current mode */
15 return KeGetCurrentThread()->PreviousMode;
16 }
17 #endif
18
19 //
20 // Enters a Guarded Region
21 //
22 #define KeEnterGuardedRegion() \
23 { \
24 PKTHREAD _Thread = KeGetCurrentThread(); \
25 \
26 /* Sanity checks */ \
27 ASSERT(KeGetCurrentIrql() <= APC_LEVEL); \
28 ASSERT(_Thread == KeGetCurrentThread()); \
29 ASSERT((_Thread->SpecialApcDisable <= 0) && \
30 (_Thread->SpecialApcDisable != -32768)); \
31 \
32 /* Disable Special APCs */ \
33 _Thread->SpecialApcDisable--; \
34 }
35
36 //
37 // Leaves a Guarded Region
38 //
39 #define KeLeaveGuardedRegion() \
40 { \
41 PKTHREAD _Thread = KeGetCurrentThread(); \
42 \
43 /* Sanity checks */ \
44 ASSERT(KeGetCurrentIrql() <= APC_LEVEL); \
45 ASSERT(_Thread == KeGetCurrentThread()); \
46 ASSERT(_Thread->SpecialApcDisable < 0); \
47 \
48 /* Leave region and check if APCs are OK now */ \
49 if (!(++_Thread->SpecialApcDisable)) \
50 { \
51 /* Check for Kernel APCs on the list */ \
52 if (!IsListEmpty(&_Thread->ApcState. \
53 ApcListHead[KernelMode])) \
54 { \
55 /* Check for APC Delivery */ \
56 KiCheckForKernelApcDelivery(); \
57 } \
58 } \
59 }
60
61 //
62 // Enters a Critical Region
63 //
64 #define KeEnterCriticalRegion() \
65 { \
66 PKTHREAD _Thread = KeGetCurrentThread(); \
67 \
68 /* Sanity checks */ \
69 ASSERT(_Thread == KeGetCurrentThread()); \
70 ASSERT((_Thread->KernelApcDisable <= 0) && \
71 (_Thread->KernelApcDisable != -32768)); \
72 \
73 /* Disable Kernel APCs */ \
74 _Thread->KernelApcDisable--; \
75 }
76
77 //
78 // Leaves a Critical Region
79 //
80 #define KeLeaveCriticalRegion() \
81 { \
82 PKTHREAD _Thread = KeGetCurrentThread(); \
83 \
84 /* Sanity checks */ \
85 ASSERT(_Thread == KeGetCurrentThread()); \
86 ASSERT(_Thread->KernelApcDisable < 0); \
87 \
88 /* Enable Kernel APCs */ \
89 _Thread->KernelApcDisable++; \
90 \
91 /* Check if Kernel APCs are now enabled */ \
92 if (!(_Thread->KernelApcDisable)) \
93 { \
94 /* Check if we need to request an APC Delivery */ \
95 if (!(IsListEmpty(&_Thread->ApcState.ApcListHead[KernelMode])) && \
96 !(_Thread->SpecialApcDisable)) \
97 { \
98 /* Check for the right environment */ \
99 KiCheckForKernelApcDelivery(); \
100 } \
101 } \
102 }
103
104 #ifndef CONFIG_SMP
105
106 //
107 // This routine protects against multiple CPU acquires, it's meaningless on UP.
108 //
109 FORCEINLINE
110 VOID
111 KiAcquireDispatcherObject(IN DISPATCHER_HEADER* Object)
112 {
113 UNREFERENCED_PARAMETER(Object);
114 }
115
116 //
117 // This routine protects against multiple CPU acquires, it's meaningless on UP.
118 //
119 FORCEINLINE
120 VOID
121 KiReleaseDispatcherObject(IN DISPATCHER_HEADER* Object)
122 {
123 UNREFERENCED_PARAMETER(Object);
124 }
125
126 FORCEINLINE
127 KIRQL
128 KiAcquireDispatcherLock(VOID)
129 {
130 /* Raise to DPC level */
131 return KeRaiseIrqlToDpcLevel();
132 }
133
134 FORCEINLINE
135 VOID
136 KiReleaseDispatcherLock(IN KIRQL OldIrql)
137 {
138 /* Just exit the dispatcher */
139 KiExitDispatcher(OldIrql);
140 }
141
142 FORCEINLINE
143 VOID
144 KiAcquireDispatcherLockAtDpcLevel(VOID)
145 {
146 /* This is a no-op at DPC Level for UP systems */
147 return;
148 }
149
150 FORCEINLINE
151 VOID
152 KiReleaseDispatcherLockFromDpcLevel(VOID)
153 {
154 /* This is a no-op at DPC Level for UP systems */
155 return;
156 }
157
158 //
159 // This routine makes the thread deferred ready on the boot CPU.
160 //
161 FORCEINLINE
162 VOID
163 KiInsertDeferredReadyList(IN PKTHREAD Thread)
164 {
165 /* Set the thread to deferred state and boot CPU */
166 Thread->State = DeferredReady;
167 Thread->DeferredProcessor = 0;
168
169 /* Make the thread ready immediately */
170 KiDeferredReadyThread(Thread);
171 }
172
173 FORCEINLINE
174 VOID
175 KiRescheduleThread(IN BOOLEAN NewThread,
176 IN ULONG Cpu)
177 {
178 /* This is meaningless on UP systems */
179 UNREFERENCED_PARAMETER(NewThread);
180 UNREFERENCED_PARAMETER(Cpu);
181 }
182
183 //
184 // This routine protects against multiple CPU acquires, it's meaningless on UP.
185 //
186 FORCEINLINE
187 VOID
188 KiSetThreadSwapBusy(IN PKTHREAD Thread)
189 {
190 UNREFERENCED_PARAMETER(Thread);
191 }
192
193 //
194 // This routine protects against multiple CPU acquires, it's meaningless on UP.
195 //
196 FORCEINLINE
197 VOID
198 KiAcquirePrcbLock(IN PKPRCB Prcb)
199 {
200 UNREFERENCED_PARAMETER(Prcb);
201 }
202
203 //
204 // This routine protects against multiple CPU acquires, it's meaningless on UP.
205 //
206 FORCEINLINE
207 VOID
208 KiReleasePrcbLock(IN PKPRCB Prcb)
209 {
210 UNREFERENCED_PARAMETER(Prcb);
211 }
212
213 //
214 // This routine protects against multiple CPU acquires, it's meaningless on UP.
215 //
216 FORCEINLINE
217 VOID
218 KiAcquireThreadLock(IN PKTHREAD Thread)
219 {
220 UNREFERENCED_PARAMETER(Thread);
221 }
222
223 //
224 // This routine protects against multiple CPU acquires, it's meaningless on UP.
225 //
226 FORCEINLINE
227 VOID
228 KiReleaseThreadLock(IN PKTHREAD Thread)
229 {
230 UNREFERENCED_PARAMETER(Thread);
231 }
232
233 //
234 // This routine protects against multiple CPU acquires, it's meaningless on UP.
235 //
236 FORCEINLINE
237 BOOLEAN
238 KiTryThreadLock(IN PKTHREAD Thread)
239 {
240 UNREFERENCED_PARAMETER(Thread);
241 return FALSE;
242 }
243
244 FORCEINLINE
245 VOID
246 KiCheckDeferredReadyList(IN PKPRCB Prcb)
247 {
248 /* There are no deferred ready lists on UP systems */
249 UNREFERENCED_PARAMETER(Prcb);
250 }
251
252 FORCEINLINE
253 VOID
254 KiRequestApcInterrupt(IN BOOLEAN NeedApc,
255 IN UCHAR Processor)
256 {
257 /* We deliver instantly on UP */
258 UNREFERENCED_PARAMETER(NeedApc);
259 UNREFERENCED_PARAMETER(Processor);
260 }
261
262 FORCEINLINE
263 PKSPIN_LOCK_QUEUE
264 KiAcquireTimerLock(IN ULONG Hand)
265 {
266 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
267
268 /* Nothing to do on UP */
269 UNREFERENCED_PARAMETER(Hand);
270 return NULL;
271 }
272
273 FORCEINLINE
274 VOID
275 KiReleaseTimerLock(IN PKSPIN_LOCK_QUEUE LockQueue)
276 {
277 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
278
279 /* Nothing to do on UP */
280 UNREFERENCED_PARAMETER(LockQueue);
281 }
282
283 #else
284
285 FORCEINLINE
286 VOID
287 KiAcquireDispatcherObject(IN DISPATCHER_HEADER* Object)
288 {
289 LONG OldValue;
290
291 /* Make sure we're at a safe level to touch the lock */
292 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
293
294 /* Start acquire loop */
295 do
296 {
297 /* Loop until the other CPU releases it */
298 while (TRUE)
299 {
300 /* Check if it got released */
301 OldValue = Object->Lock;
302 if ((OldValue & KOBJECT_LOCK_BIT) == 0) break;
303
304 /* Let the CPU know that this is a loop */
305 YieldProcessor();
306 }
307
308 /* Try acquiring the lock now */
309 } while (InterlockedCompareExchange(&Object->Lock,
310 OldValue | KOBJECT_LOCK_BIT,
311 OldValue) != OldValue);
312 }
313
314 FORCEINLINE
315 VOID
316 KiReleaseDispatcherObject(IN DISPATCHER_HEADER* Object)
317 {
318 /* Make sure we're at a safe level to touch the lock */
319 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
320
321 /* Release it */
322 InterlockedAnd(&Object->Lock, ~KOBJECT_LOCK_BIT);
323 }
324
325 FORCEINLINE
326 KIRQL
327 KiAcquireDispatcherLock(VOID)
328 {
329 /* Raise to synchronization level and acquire the dispatcher lock */
330 return KeAcquireQueuedSpinLockRaiseToSynch(LockQueueDispatcherLock);
331 }
332
333 FORCEINLINE
334 VOID
335 KiReleaseDispatcherLock(IN KIRQL OldIrql)
336 {
337 /* First release the lock */
338 KeReleaseQueuedSpinLockFromDpcLevel(&KeGetCurrentPrcb()->
339 LockQueue[LockQueueDispatcherLock]);
340
341 /* Then exit the dispatcher */
342 KiExitDispatcher(OldIrql);
343 }
344
345 FORCEINLINE
346 VOID
347 KiAcquireDispatcherLockAtDpcLevel(VOID)
348 {
349 /* Acquire the dispatcher lock */
350 KeAcquireQueuedSpinLockAtDpcLevel(&KeGetCurrentPrcb()->
351 LockQueue[LockQueueDispatcherLock]);
352 }
353
354 FORCEINLINE
355 VOID
356 KiReleaseDispatcherLockFromDpcLevel(VOID)
357 {
358 /* Release the dispatcher lock */
359 KeReleaseQueuedSpinLockFromDpcLevel(&KeGetCurrentPrcb()->
360 LockQueue[LockQueueDispatcherLock]);
361 }
362
363 //
364 // This routine inserts a thread into the deferred ready list of the current CPU
365 //
366 FORCEINLINE
367 VOID
368 KiInsertDeferredReadyList(IN PKTHREAD Thread)
369 {
370 PKPRCB Prcb = KeGetCurrentPrcb();
371
372 /* Set the thread to deferred state and CPU */
373 Thread->State = DeferredReady;
374 Thread->DeferredProcessor = Prcb->Number;
375
376 /* Add it on the list */
377 PushEntryList(&Prcb->DeferredReadyListHead, &Thread->SwapListEntry);
378 }
379
380 FORCEINLINE
381 VOID
382 KiRescheduleThread(IN BOOLEAN NewThread,
383 IN ULONG Cpu)
384 {
385 /* Check if a new thread needs to be scheduled on a different CPU */
386 if ((NewThread) && !(KeGetPcr()->Number == Cpu))
387 {
388 /* Send an IPI to request delivery */
389 KiIpiSend(AFFINITY_MASK(Cpu), IPI_DPC);
390 }
391 }
392
393 //
394 // This routine sets the current thread in a swap busy state, which ensure that
395 // nobody else tries to swap it concurrently.
396 //
397 FORCEINLINE
398 VOID
399 KiSetThreadSwapBusy(IN PKTHREAD Thread)
400 {
401 /* Make sure nobody already set it */
402 ASSERT(Thread->SwapBusy == FALSE);
403
404 /* Set it ourselves */
405 Thread->SwapBusy = TRUE;
406 }
407
408 //
409 // This routine acquires the PRCB lock so that only one caller can touch
410 // volatile PRCB data.
411 //
412 // Since this is a simple optimized spin-lock, it must only be acquired
413 // at dispatcher level or higher!
414 //
415 FORCEINLINE
416 VOID
417 KiAcquirePrcbLock(IN PKPRCB Prcb)
418 {
419 /* Make sure we're at a safe level to touch the PRCB lock */
420 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
421
422 /* Start acquire loop */
423 for (;;)
424 {
425 /* Acquire the lock and break out if we acquired it first */
426 if (!InterlockedExchange((PLONG)&Prcb->PrcbLock, 1)) break;
427
428 /* Loop until the other CPU releases it */
429 do
430 {
431 /* Let the CPU know that this is a loop */
432 YieldProcessor();
433 } while (Prcb->PrcbLock);
434 }
435 }
436
437 //
438 // This routine releases the PRCB lock so that other callers can touch
439 // volatile PRCB data.
440 //
441 // Since this is a simple optimized spin-lock, it must be be only acquired
442 // at dispatcher level or higher!
443 //
444 FORCEINLINE
445 VOID
446 KiReleasePrcbLock(IN PKPRCB Prcb)
447 {
448 /* Make sure we are above dispatch and the lock is acquired! */
449 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
450 ASSERT(Prcb->PrcbLock != 0);
451
452 /* Release it */
453 InterlockedAnd((PLONG)&Prcb->PrcbLock, 0);
454 }
455
456 //
457 // This routine acquires the thread lock so that only one caller can touch
458 // volatile thread data.
459 //
460 // Since this is a simple optimized spin-lock, it must be be only acquired
461 // at dispatcher level or higher!
462 //
463 FORCEINLINE
464 VOID
465 KiAcquireThreadLock(IN PKTHREAD Thread)
466 {
467 /* Make sure we're at a safe level to touch the thread lock */
468 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
469
470 /* Start acquire loop */
471 for (;;)
472 {
473 /* Acquire the lock and break out if we acquired it first */
474 if (!InterlockedExchange((PLONG)&Thread->ThreadLock, 1)) break;
475
476 /* Loop until the other CPU releases it */
477 do
478 {
479 /* Let the CPU know that this is a loop */
480 YieldProcessor();
481 } while (Thread->ThreadLock);
482 }
483 }
484
485 //
486 // This routine releases the thread lock so that other callers can touch
487 // volatile thread data.
488 //
489 // Since this is a simple optimized spin-lock, it must be be only acquired
490 // at dispatcher level or higher!
491 //
492 FORCEINLINE
493 VOID
494 KiReleaseThreadLock(IN PKTHREAD Thread)
495 {
496 /* Make sure we are still above dispatch */
497 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
498
499 /* Release it */
500 InterlockedAnd((PLONG)&Thread->ThreadLock, 0);
501 }
502
503 FORCEINLINE
504 BOOLEAN
505 KiTryThreadLock(IN PKTHREAD Thread)
506 {
507 LONG Value;
508
509 /* If the lock isn't acquired, return false */
510 if (!Thread->ThreadLock) return FALSE;
511
512 /* Otherwise, try to acquire it and check the result */
513 Value = 1;
514 Value = InterlockedExchange((PLONG)&Thread->ThreadLock, Value);
515
516 /* Return the lock state */
517 return (Value == TRUE);
518 }
519
520 FORCEINLINE
521 VOID
522 KiCheckDeferredReadyList(IN PKPRCB Prcb)
523 {
524 /* Scan the deferred ready lists if required */
525 if (Prcb->DeferredReadyListHead.Next) KiProcessDeferredReadyList(Prcb);
526 }
527
528 FORCEINLINE
529 VOID
530 KiRequestApcInterrupt(IN BOOLEAN NeedApc,
531 IN UCHAR Processor)
532 {
533 /* Check if we need to request APC delivery */
534 if (NeedApc)
535 {
536 /* Check if it's on another CPU */
537 if (KeGetPcr()->Number != Processor)
538 {
539 /* Send an IPI to request delivery */
540 KiIpiSend(AFFINITY_MASK(Processor), IPI_APC);
541 }
542 else
543 {
544 /* Request a software interrupt */
545 HalRequestSoftwareInterrupt(APC_LEVEL);
546 }
547 }
548 }
549
550 FORCEINLINE
551 PKSPIN_LOCK_QUEUE
552 KiAcquireTimerLock(IN ULONG Hand)
553 {
554 PKSPIN_LOCK_QUEUE LockQueue;
555 ULONG LockIndex;
556 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
557
558 /* Get the lock index */
559 LockIndex = Hand >> LOCK_QUEUE_TIMER_LOCK_SHIFT;
560 LockIndex &= (LOCK_QUEUE_TIMER_TABLE_LOCKS - 1);
561
562 /* Now get the lock */
563 LockQueue = &KeGetCurrentPrcb()->LockQueue[LockQueueTimerTableLock + LockIndex];
564
565 /* Acquire it and return */
566 KeAcquireQueuedSpinLockAtDpcLevel(LockQueue);
567 return LockQueue;
568 }
569
570 FORCEINLINE
571 VOID
572 KiReleaseTimerLock(IN PKSPIN_LOCK_QUEUE LockQueue)
573 {
574 ASSERT(KeGetCurrentIrql() >= DISPATCH_LEVEL);
575
576 /* Release the lock */
577 KeReleaseQueuedSpinLockFromDpcLevel(LockQueue);
578 }
579
580 #endif
581
582 FORCEINLINE
583 VOID
584 KiAcquireApcLock(IN PKTHREAD Thread,
585 IN PKLOCK_QUEUE_HANDLE Handle)
586 {
587 /* Acquire the lock and raise to synchronization level */
588 KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock, Handle);
589 }
590
591 FORCEINLINE
592 VOID
593 KiAcquireApcLockAtDpcLevel(IN PKTHREAD Thread,
594 IN PKLOCK_QUEUE_HANDLE Handle)
595 {
596 /* Acquire the lock */
597 KeAcquireInStackQueuedSpinLockAtDpcLevel(&Thread->ApcQueueLock, Handle);
598 }
599
600 FORCEINLINE
601 VOID
602 KiAcquireApcLockAtApcLevel(IN PKTHREAD Thread,
603 IN PKLOCK_QUEUE_HANDLE Handle)
604 {
605 /* Acquire the lock */
606 KeAcquireInStackQueuedSpinLock(&Thread->ApcQueueLock, Handle);
607 }
608
609 FORCEINLINE
610 VOID
611 KiReleaseApcLock(IN PKLOCK_QUEUE_HANDLE Handle)
612 {
613 /* Release the lock */
614 KeReleaseInStackQueuedSpinLock(Handle);
615 }
616
617 FORCEINLINE
618 VOID
619 KiReleaseApcLockFromDpcLevel(IN PKLOCK_QUEUE_HANDLE Handle)
620 {
621 /* Release the lock */
622 KeReleaseInStackQueuedSpinLockFromDpcLevel(Handle);
623 }
624
625 FORCEINLINE
626 VOID
627 KiAcquireProcessLock(IN PKPROCESS Process,
628 IN PKLOCK_QUEUE_HANDLE Handle)
629 {
630 /* Acquire the lock and raise to synchronization level */
631 KeAcquireInStackQueuedSpinLockRaiseToSynch(&Process->ProcessLock, Handle);
632 }
633
634 FORCEINLINE
635 VOID
636 KiReleaseProcessLock(IN PKLOCK_QUEUE_HANDLE Handle)
637 {
638 /* Release the lock */
639 KeReleaseInStackQueuedSpinLock(Handle);
640 }
641
642 FORCEINLINE
643 VOID
644 KiReleaseProcessLockFromDpcLevel(IN PKLOCK_QUEUE_HANDLE Handle)
645 {
646 /* Release the lock */
647 KeReleaseInStackQueuedSpinLockFromDpcLevel(Handle);
648 }
649
650 FORCEINLINE
651 VOID
652 KiAcquireDeviceQueueLock(IN PKDEVICE_QUEUE DeviceQueue,
653 IN PKLOCK_QUEUE_HANDLE DeviceLock)
654 {
655 /* Check if we were called from a threaded DPC */
656 if (KeGetCurrentPrcb()->DpcThreadActive)
657 {
658 /* Lock the Queue, we're not at DPC level */
659 KeAcquireInStackQueuedSpinLock(&DeviceQueue->Lock, DeviceLock);
660 }
661 else
662 {
663 /* We must be at DPC level, acquire the lock safely */
664 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL);
665 KeAcquireInStackQueuedSpinLockAtDpcLevel(&DeviceQueue->Lock,
666 DeviceLock);
667 }
668 }
669
670 FORCEINLINE
671 VOID
672 KiReleaseDeviceQueueLock(IN PKLOCK_QUEUE_HANDLE DeviceLock)
673 {
674 /* Check if we were called from a threaded DPC */
675 if (KeGetCurrentPrcb()->DpcThreadActive)
676 {
677 /* Unlock the Queue, we're not at DPC level */
678 KeReleaseInStackQueuedSpinLock(DeviceLock);
679 }
680 else
681 {
682 /* We must be at DPC level, release the lock safely */
683 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL);
684 KeReleaseInStackQueuedSpinLockFromDpcLevel(DeviceLock);
685 }
686 }
687
688 //
689 // Satisfies the wait of any dispatcher object
690 //
691 #define KiSatisfyObjectWait(Object, Thread) \
692 { \
693 /* Special case for Mutants */ \
694 if ((Object)->Header.Type == MutantObject) \
695 { \
696 /* Decrease the Signal State */ \
697 (Object)->Header.SignalState--; \
698 \
699 /* Check if it's now non-signaled */ \
700 if (!(Object)->Header.SignalState) \
701 { \
702 /* Set the Owner Thread */ \
703 (Object)->OwnerThread = Thread; \
704 \
705 /* Disable APCs if needed */ \
706 Thread->KernelApcDisable = Thread->KernelApcDisable - \
707 (Object)->ApcDisable; \
708 \
709 /* Check if it's abandoned */ \
710 if ((Object)->Abandoned) \
711 { \
712 /* Unabandon it */ \
713 (Object)->Abandoned = FALSE; \
714 \
715 /* Return Status */ \
716 Thread->WaitStatus = STATUS_ABANDONED; \
717 } \
718 \
719 /* Insert it into the Mutant List */ \
720 InsertHeadList(Thread->MutantListHead.Blink, \
721 &(Object)->MutantListEntry); \
722 } \
723 } \
724 else if (((Object)->Header.Type & TIMER_OR_EVENT_TYPE) == \
725 EventSynchronizationObject) \
726 { \
727 /* Synchronization Timers and Events just get un-signaled */ \
728 (Object)->Header.SignalState = 0; \
729 } \
730 else if ((Object)->Header.Type == SemaphoreObject) \
731 { \
732 /* These ones can have multiple states, so we only decrease it */ \
733 (Object)->Header.SignalState--; \
734 } \
735 }
736
737 //
738 // Satisfies the wait of a mutant dispatcher object
739 //
740 #define KiSatisfyMutantWait(Object, Thread) \
741 { \
742 /* Decrease the Signal State */ \
743 (Object)->Header.SignalState--; \
744 \
745 /* Check if it's now non-signaled */ \
746 if (!(Object)->Header.SignalState) \
747 { \
748 /* Set the Owner Thread */ \
749 (Object)->OwnerThread = Thread; \
750 \
751 /* Disable APCs if needed */ \
752 Thread->KernelApcDisable = Thread->KernelApcDisable - \
753 (Object)->ApcDisable; \
754 \
755 /* Check if it's abandoned */ \
756 if ((Object)->Abandoned) \
757 { \
758 /* Unabandon it */ \
759 (Object)->Abandoned = FALSE; \
760 \
761 /* Return Status */ \
762 Thread->WaitStatus = STATUS_ABANDONED; \
763 } \
764 \
765 /* Insert it into the Mutant List */ \
766 InsertHeadList(Thread->MutantListHead.Blink, \
767 &(Object)->MutantListEntry); \
768 } \
769 }
770
771 //
772 // Satisfies the wait of any nonmutant dispatcher object
773 //
774 #define KiSatisfyNonMutantWait(Object) \
775 { \
776 if (((Object)->Header.Type & TIMER_OR_EVENT_TYPE) == \
777 EventSynchronizationObject) \
778 { \
779 /* Synchronization Timers and Events just get un-signaled */ \
780 (Object)->Header.SignalState = 0; \
781 } \
782 else if ((Object)->Header.Type == SemaphoreObject) \
783 { \
784 /* These ones can have multiple states, so we only decrease it */ \
785 (Object)->Header.SignalState--; \
786 } \
787 }
788
789 //
790 // Recalculates the due time
791 //
792 FORCEINLINE
793 PLARGE_INTEGER
794 KiRecalculateDueTime(IN PLARGE_INTEGER OriginalDueTime,
795 IN PLARGE_INTEGER DueTime,
796 IN OUT PLARGE_INTEGER NewDueTime)
797 {
798 /* Don't do anything for absolute waits */
799 if (OriginalDueTime->QuadPart >= 0) return OriginalDueTime;
800
801 /* Otherwise, query the interrupt time and recalculate */
802 NewDueTime->QuadPart = KeQueryInterruptTime();
803 NewDueTime->QuadPart -= DueTime->QuadPart;
804 return NewDueTime;
805 }
806
807 //
808 // Determines whether a thread should be added to the wait list
809 //
810 FORCEINLINE
811 BOOLEAN
812 KiCheckThreadStackSwap(IN PKTHREAD Thread,
813 IN KPROCESSOR_MODE WaitMode)
814 {
815 /* Check the required conditions */
816 if ((WaitMode != KernelMode) &&
817 (Thread->EnableStackSwap) &&
818 (Thread->Priority >= (LOW_REALTIME_PRIORITY + 9)))
819 {
820 /* We are go for swap */
821 return TRUE;
822 }
823 else
824 {
825 /* Don't swap the thread */
826 return FALSE;
827 }
828 }
829
830 //
831 // Adds a thread to the wait list
832 //
833 #define KiAddThreadToWaitList(Thread, Swappable) \
834 { \
835 /* Make sure it's swappable */ \
836 if (Swappable) \
837 { \
838 /* Insert it into the PRCB's List */ \
839 InsertTailList(&KeGetCurrentPrcb()->WaitListHead, \
840 &Thread->WaitListEntry); \
841 } \
842 }
843
844 //
845 // Checks if a wait in progress should be interrupted by APCs or an alertable
846 // state.
847 //
848 FORCEINLINE
849 NTSTATUS
850 KiCheckAlertability(IN PKTHREAD Thread,
851 IN BOOLEAN Alertable,
852 IN KPROCESSOR_MODE WaitMode)
853 {
854 /* Check if the wait is alertable */
855 if (Alertable)
856 {
857 /* It is, first check if the thread is alerted in this mode */
858 if (Thread->Alerted[WaitMode])
859 {
860 /* It is, so bail out of the wait */
861 Thread->Alerted[WaitMode] = FALSE;
862 return STATUS_ALERTED;
863 }
864 else if ((WaitMode != KernelMode) &&
865 (!IsListEmpty(&Thread->ApcState.ApcListHead[UserMode])))
866 {
867 /* It's isn't, but this is a user wait with queued user APCs */
868 Thread->ApcState.UserApcPending = TRUE;
869 return STATUS_USER_APC;
870 }
871 else if (Thread->Alerted[KernelMode])
872 {
873 /* It isn't that either, but we're alered in kernel mode */
874 Thread->Alerted[KernelMode] = FALSE;
875 return STATUS_ALERTED;
876 }
877 }
878 else if ((WaitMode != KernelMode) && (Thread->ApcState.UserApcPending))
879 {
880 /* Not alertable, but this is a user wait with pending user APCs */
881 return STATUS_USER_APC;
882 }
883
884 /* Otherwise, we're fine */
885 return STATUS_WAIT_0;
886 }
887
888 //
889 // Called from KiCompleteTimer, KiInsertTreeTimer, KeSetSystemTime
890 // to remove timer entries
891 // See Windows HPI blog for more information.
892 FORCEINLINE
893 VOID
894 KiRemoveEntryTimer(IN PKTIMER Timer)
895 {
896 ULONG Hand;
897 PKTIMER_TABLE_ENTRY TableEntry;
898
899 /* Remove the timer from the timer list and check if it's empty */
900 Hand = Timer->Header.Hand;
901 if (RemoveEntryList(&Timer->TimerListEntry))
902 {
903 /* Get the respective timer table entry */
904 TableEntry = &KiTimerTableListHead[Hand];
905 if (&TableEntry->Entry == TableEntry->Entry.Flink)
906 {
907 /* Set the entry to an infinite absolute time */
908 TableEntry->Time.HighPart = 0xFFFFFFFF;
909 }
910 }
911
912 /* Clear the list entries on dbg builds so we can tell the timer is gone */
913 #if DBG
914 Timer->TimerListEntry.Flink = NULL;
915 Timer->TimerListEntry.Blink = NULL;
916 #endif
917 }
918
919 //
920 // Called by Wait and Queue code to insert a timer for dispatching.
921 // Also called by KeSetTimerEx to insert a timer from the caller.
922 //
923 FORCEINLINE
924 VOID
925 KxInsertTimer(IN PKTIMER Timer,
926 IN ULONG Hand)
927 {
928 PKSPIN_LOCK_QUEUE LockQueue;
929
930 /* Acquire the lock and release the dispatcher lock */
931 LockQueue = KiAcquireTimerLock(Hand);
932 KiReleaseDispatcherLockFromDpcLevel();
933
934 /* Try to insert the timer */
935 if (KiInsertTimerTable(Timer, Hand))
936 {
937 /* Complete it */
938 KiCompleteTimer(Timer, LockQueue);
939 }
940 else
941 {
942 /* Do nothing, just release the lock */
943 KiReleaseTimerLock(LockQueue);
944 }
945 }
946
947 //
948 // Called by KeSetTimerEx and KiInsertTreeTimer to calculate Due Time
949 // See the Windows HPI Blog for more information
950 //
951 FORCEINLINE
952 BOOLEAN
953 KiComputeDueTime(IN PKTIMER Timer,
954 IN LARGE_INTEGER DueTime,
955 OUT PULONG Hand)
956 {
957 LARGE_INTEGER InterruptTime, SystemTime, DifferenceTime;
958
959 /* Convert to relative time if needed */
960 Timer->Header.Absolute = FALSE;
961 if (DueTime.HighPart >= 0)
962 {
963 /* Get System Time */
964 KeQuerySystemTime(&SystemTime);
965
966 /* Do the conversion */
967 DifferenceTime.QuadPart = SystemTime.QuadPart - DueTime.QuadPart;
968
969 /* Make sure it hasn't already expired */
970 Timer->Header.Absolute = TRUE;
971 if (DifferenceTime.HighPart >= 0)
972 {
973 /* Cancel everything */
974 Timer->Header.SignalState = TRUE;
975 Timer->Header.Hand = 0;
976 Timer->DueTime.QuadPart = 0;
977 *Hand = 0;
978 return FALSE;
979 }
980
981 /* Set the time as Absolute */
982 DueTime = DifferenceTime;
983 }
984
985 /* Get the Interrupt Time */
986 InterruptTime.QuadPart = KeQueryInterruptTime();
987
988 /* Recalculate due time */
989 Timer->DueTime.QuadPart = InterruptTime.QuadPart - DueTime.QuadPart;
990
991 /* Get the handle */
992 *Hand = KiComputeTimerTableIndex(Timer->DueTime.QuadPart);
993 Timer->Header.Hand = (UCHAR)*Hand;
994 Timer->Header.Inserted = TRUE;
995 return TRUE;
996 }
997
998 //
999 // Called from Unlink and Queue Insert Code.
1000 // Also called by timer code when canceling an inserted timer.
1001 // Removes a timer from it's tree.
1002 //
1003 FORCEINLINE
1004 VOID
1005 KxRemoveTreeTimer(IN PKTIMER Timer)
1006 {
1007 ULONG Hand = Timer->Header.Hand;
1008 PKSPIN_LOCK_QUEUE LockQueue;
1009 PKTIMER_TABLE_ENTRY TimerEntry;
1010
1011 /* Acquire timer lock */
1012 LockQueue = KiAcquireTimerLock(Hand);
1013
1014 /* Set the timer as non-inserted */
1015 Timer->Header.Inserted = FALSE;
1016
1017 /* Remove it from the timer list */
1018 if (RemoveEntryList(&Timer->TimerListEntry))
1019 {
1020 /* Get the entry and check if it's empty */
1021 TimerEntry = &KiTimerTableListHead[Hand];
1022 if (IsListEmpty(&TimerEntry->Entry))
1023 {
1024 /* Clear the time then */
1025 TimerEntry->Time.HighPart = 0xFFFFFFFF;
1026 }
1027 }
1028
1029 /* Release the timer lock */
1030 KiReleaseTimerLock(LockQueue);
1031 }
1032
1033 FORCEINLINE
1034 VOID
1035 KxSetTimerForThreadWait(IN PKTIMER Timer,
1036 IN LARGE_INTEGER Interval,
1037 OUT PULONG Hand)
1038 {
1039 ULONGLONG DueTime;
1040 LARGE_INTEGER InterruptTime, SystemTime, TimeDifference;
1041
1042 /* Check the timer's interval to see if it's absolute */
1043 Timer->Header.Absolute = FALSE;
1044 if (Interval.HighPart >= 0)
1045 {
1046 /* Get the system time and calculate the relative time */
1047 KeQuerySystemTime(&SystemTime);
1048 TimeDifference.QuadPart = SystemTime.QuadPart - Interval.QuadPart;
1049 Timer->Header.Absolute = TRUE;
1050
1051 /* Check if we've already expired */
1052 if (TimeDifference.HighPart >= 0)
1053 {
1054 /* Reset everything */
1055 Timer->DueTime.QuadPart = 0;
1056 *Hand = 0;
1057 Timer->Header.Hand = 0;
1058 return;
1059 }
1060 else
1061 {
1062 /* Update the interval */
1063 Interval = TimeDifference;
1064 }
1065 }
1066
1067 /* Calculate the due time */
1068 InterruptTime.QuadPart = KeQueryInterruptTime();
1069 DueTime = InterruptTime.QuadPart - Interval.QuadPart;
1070 Timer->DueTime.QuadPart = DueTime;
1071
1072 /* Calculate the timer handle */
1073 *Hand = KiComputeTimerTableIndex(DueTime);
1074 Timer->Header.Hand = (UCHAR)*Hand;
1075 }
1076
1077 #define KxDelayThreadWait() \
1078 \
1079 /* Setup the Wait Block */ \
1080 Thread->WaitBlockList = TimerBlock; \
1081 \
1082 /* Setup the timer */ \
1083 KxSetTimerForThreadWait(Timer, *Interval, &Hand); \
1084 \
1085 /* Save the due time for the caller */ \
1086 DueTime.QuadPart = Timer->DueTime.QuadPart; \
1087 \
1088 /* Link the timer to this Wait Block */ \
1089 TimerBlock->NextWaitBlock = TimerBlock; \
1090 Timer->Header.WaitListHead.Flink = &TimerBlock->WaitListEntry; \
1091 Timer->Header.WaitListHead.Blink = &TimerBlock->WaitListEntry; \
1092 \
1093 /* Clear wait status */ \
1094 Thread->WaitStatus = STATUS_SUCCESS; \
1095 \
1096 /* Setup wait fields */ \
1097 Thread->Alertable = Alertable; \
1098 Thread->WaitReason = DelayExecution; \
1099 Thread->WaitMode = WaitMode; \
1100 \
1101 /* Check if we can swap the thread's stack */ \
1102 Thread->WaitListEntry.Flink = NULL; \
1103 Swappable = KiCheckThreadStackSwap(Thread, WaitMode); \
1104 \
1105 /* Set the wait time */ \
1106 Thread->WaitTime = KeTickCount.LowPart;
1107
1108 #define KxMultiThreadWait() \
1109 /* Link wait block array to the thread */ \
1110 Thread->WaitBlockList = WaitBlockArray; \
1111 \
1112 /* Reset the index */ \
1113 Index = 0; \
1114 \
1115 /* Loop wait blocks */ \
1116 do \
1117 { \
1118 /* Fill out the wait block */ \
1119 WaitBlock = &WaitBlockArray[Index]; \
1120 WaitBlock->Object = Object[Index]; \
1121 WaitBlock->WaitKey = (USHORT)Index; \
1122 WaitBlock->WaitType = WaitType; \
1123 WaitBlock->Thread = Thread; \
1124 \
1125 /* Link to next block */ \
1126 WaitBlock->NextWaitBlock = &WaitBlockArray[Index + 1]; \
1127 Index++; \
1128 } while (Index < Count); \
1129 \
1130 /* Link the last block */ \
1131 WaitBlock->NextWaitBlock = WaitBlockArray; \
1132 \
1133 /* Set default wait status */ \
1134 Thread->WaitStatus = STATUS_WAIT_0; \
1135 \
1136 /* Check if we have a timer */ \
1137 if (Timeout) \
1138 { \
1139 /* Link to the block */ \
1140 TimerBlock->NextWaitBlock = WaitBlockArray; \
1141 \
1142 /* Setup the timer */ \
1143 KxSetTimerForThreadWait(Timer, *Timeout, &Hand); \
1144 \
1145 /* Save the due time for the caller */ \
1146 DueTime.QuadPart = Timer->DueTime.QuadPart; \
1147 \
1148 /* Initialize the list */ \
1149 InitializeListHead(&Timer->Header.WaitListHead); \
1150 } \
1151 \
1152 /* Set wait settings */ \
1153 Thread->Alertable = Alertable; \
1154 Thread->WaitMode = WaitMode; \
1155 Thread->WaitReason = WaitReason; \
1156 \
1157 /* Check if we can swap the thread's stack */ \
1158 Thread->WaitListEntry.Flink = NULL; \
1159 Swappable = KiCheckThreadStackSwap(Thread, WaitMode); \
1160 \
1161 /* Set the wait time */ \
1162 Thread->WaitTime = KeTickCount.LowPart;
1163
1164 #define KxSingleThreadWait() \
1165 /* Setup the Wait Block */ \
1166 Thread->WaitBlockList = WaitBlock; \
1167 WaitBlock->WaitKey = STATUS_SUCCESS; \
1168 WaitBlock->Object = Object; \
1169 WaitBlock->WaitType = WaitAny; \
1170 \
1171 /* Clear wait status */ \
1172 Thread->WaitStatus = STATUS_SUCCESS; \
1173 \
1174 /* Check if we have a timer */ \
1175 if (Timeout) \
1176 { \
1177 /* Setup the timer */ \
1178 KxSetTimerForThreadWait(Timer, *Timeout, &Hand); \
1179 \
1180 /* Save the due time for the caller */ \
1181 DueTime.QuadPart = Timer->DueTime.QuadPart; \
1182 \
1183 /* Pointer to timer block */ \
1184 WaitBlock->NextWaitBlock = TimerBlock; \
1185 TimerBlock->NextWaitBlock = WaitBlock; \
1186 \
1187 /* Link the timer to this Wait Block */ \
1188 Timer->Header.WaitListHead.Flink = &TimerBlock->WaitListEntry; \
1189 Timer->Header.WaitListHead.Blink = &TimerBlock->WaitListEntry; \
1190 } \
1191 else \
1192 { \
1193 /* No timer block, just ourselves */ \
1194 WaitBlock->NextWaitBlock = WaitBlock; \
1195 } \
1196 \
1197 /* Set wait settings */ \
1198 Thread->Alertable = Alertable; \
1199 Thread->WaitMode = WaitMode; \
1200 Thread->WaitReason = WaitReason; \
1201 \
1202 /* Check if we can swap the thread's stack */ \
1203 Thread->WaitListEntry.Flink = NULL; \
1204 Swappable = KiCheckThreadStackSwap(Thread, WaitMode); \
1205 \
1206 /* Set the wait time */ \
1207 Thread->WaitTime = KeTickCount.LowPart;
1208
1209 #define KxQueueThreadWait() \
1210 /* Setup the Wait Block */ \
1211 Thread->WaitBlockList = WaitBlock; \
1212 WaitBlock->WaitKey = STATUS_SUCCESS; \
1213 WaitBlock->Object = Queue; \
1214 WaitBlock->WaitType = WaitAny; \
1215 WaitBlock->Thread = Thread; \
1216 \
1217 /* Clear wait status */ \
1218 Thread->WaitStatus = STATUS_SUCCESS; \
1219 \
1220 /* Check if we have a timer */ \
1221 if (Timeout) \
1222 { \
1223 /* Setup the timer */ \
1224 KxSetTimerForThreadWait(Timer, *Timeout, &Hand); \
1225 \
1226 /* Save the due time for the caller */ \
1227 DueTime.QuadPart = Timer->DueTime.QuadPart; \
1228 \
1229 /* Pointer to timer block */ \
1230 WaitBlock->NextWaitBlock = TimerBlock; \
1231 TimerBlock->NextWaitBlock = WaitBlock; \
1232 \
1233 /* Link the timer to this Wait Block */ \
1234 Timer->Header.WaitListHead.Flink = &TimerBlock->WaitListEntry; \
1235 Timer->Header.WaitListHead.Blink = &TimerBlock->WaitListEntry; \
1236 } \
1237 else \
1238 { \
1239 /* No timer block, just ourselves */ \
1240 WaitBlock->NextWaitBlock = WaitBlock; \
1241 } \
1242 \
1243 /* Set wait settings */ \
1244 Thread->Alertable = FALSE; \
1245 Thread->WaitMode = WaitMode; \
1246 Thread->WaitReason = WrQueue; \
1247 \
1248 /* Check if we can swap the thread's stack */ \
1249 Thread->WaitListEntry.Flink = NULL; \
1250 Swappable = KiCheckThreadStackSwap(Thread, WaitMode); \
1251 \
1252 /* Set the wait time */ \
1253 Thread->WaitTime = KeTickCount.LowPart;
1254
1255 //
1256 // Unwaits a Thread
1257 //
1258 FORCEINLINE
1259 VOID
1260 KxUnwaitThread(IN DISPATCHER_HEADER *Object,
1261 IN KPRIORITY Increment)
1262 {
1263 PLIST_ENTRY WaitEntry, WaitList;
1264 PKWAIT_BLOCK WaitBlock;
1265 PKTHREAD WaitThread;
1266 ULONG WaitKey;
1267
1268 /* Loop the Wait Entries */
1269 WaitList = &Object->WaitListHead;
1270 ASSERT(IsListEmpty(&Object->WaitListHead) == FALSE);
1271 WaitEntry = WaitList->Flink;
1272 do
1273 {
1274 /* Get the current wait block */
1275 WaitBlock = CONTAINING_RECORD(WaitEntry, KWAIT_BLOCK, WaitListEntry);
1276
1277 /* Get the waiting thread */
1278 WaitThread = WaitBlock->Thread;
1279
1280 /* Check the current Wait Mode */
1281 if (WaitBlock->WaitType == WaitAny)
1282 {
1283 /* Use the actual wait key */
1284 WaitKey = WaitBlock->WaitKey;
1285 }
1286 else
1287 {
1288 /* Otherwise, use STATUS_KERNEL_APC */
1289 WaitKey = STATUS_KERNEL_APC;
1290 }
1291
1292 /* Unwait the thread */
1293 KiUnwaitThread(WaitThread, WaitKey, Increment);
1294
1295 /* Next entry */
1296 WaitEntry = WaitList->Flink;
1297 } while (WaitEntry != WaitList);
1298 }
1299
1300 //
1301 // Unwaits a Thread waiting on an event
1302 //
1303 FORCEINLINE
1304 VOID
1305 KxUnwaitThreadForEvent(IN PKEVENT Event,
1306 IN KPRIORITY Increment)
1307 {
1308 PLIST_ENTRY WaitEntry, WaitList;
1309 PKWAIT_BLOCK WaitBlock;
1310 PKTHREAD WaitThread;
1311
1312 /* Loop the Wait Entries */
1313 WaitList = &Event->Header.WaitListHead;
1314 ASSERT(IsListEmpty(&Event->Header.WaitListHead) == FALSE);
1315 WaitEntry = WaitList->Flink;
1316 do
1317 {
1318 /* Get the current wait block */
1319 WaitBlock = CONTAINING_RECORD(WaitEntry, KWAIT_BLOCK, WaitListEntry);
1320
1321 /* Get the waiting thread */
1322 WaitThread = WaitBlock->Thread;
1323
1324 /* Check the current Wait Mode */
1325 if (WaitBlock->WaitType == WaitAny)
1326 {
1327 /* Un-signal it */
1328 Event->Header.SignalState = 0;
1329
1330 /* Un-signal the event and unwait the thread */
1331 KiUnwaitThread(WaitThread, WaitBlock->WaitKey, Increment);
1332 break;
1333 }
1334
1335 /* Unwait the thread with STATUS_KERNEL_APC */
1336 KiUnwaitThread(WaitThread, STATUS_KERNEL_APC, Increment);
1337
1338 /* Next entry */
1339 WaitEntry = WaitList->Flink;
1340 } while (WaitEntry != WaitList);
1341 }
1342
1343 //
1344 // This routine queues a thread that is ready on the PRCB's ready lists.
1345 // If this thread cannot currently run on this CPU, then the thread is
1346 // added to the deferred ready list instead.
1347 //
1348 // This routine must be entered with the PRCB lock held and it will exit
1349 // with the PRCB lock released!
1350 //
1351 FORCEINLINE
1352 VOID
1353 KxQueueReadyThread(IN PKTHREAD Thread,
1354 IN PKPRCB Prcb)
1355 {
1356 BOOLEAN Preempted;
1357 KPRIORITY Priority;
1358
1359 /* Sanity checks */
1360 ASSERT(Prcb == KeGetCurrentPrcb());
1361 ASSERT(Thread->State == Running);
1362 ASSERT(Thread->NextProcessor == Prcb->Number);
1363
1364 /* Check if this thread is allowed to run in this CPU */
1365 #ifdef CONFIG_SMP
1366 if ((Thread->Affinity) & (Prcb->SetMember))
1367 #else
1368 if (TRUE)
1369 #endif
1370 {
1371 /* Set thread ready for execution */
1372 Thread->State = Ready;
1373
1374 /* Save current priority and if someone had pre-empted it */
1375 Priority = Thread->Priority;
1376 Preempted = Thread->Preempted;
1377
1378 /* We're not pre-empting now, and set the wait time */
1379 Thread->Preempted = FALSE;
1380 Thread->WaitTime = KeTickCount.LowPart;
1381
1382 /* Sanity check */
1383 ASSERT((Priority >= 0) && (Priority <= HIGH_PRIORITY));
1384
1385 /* Insert this thread in the appropriate order */
1386 Preempted ? InsertHeadList(&Prcb->DispatcherReadyListHead[Priority],
1387 &Thread->WaitListEntry) :
1388 InsertTailList(&Prcb->DispatcherReadyListHead[Priority],
1389 &Thread->WaitListEntry);
1390
1391 /* Update the ready summary */
1392 Prcb->ReadySummary |= PRIORITY_MASK(Priority);
1393
1394 /* Sanity check */
1395 ASSERT(Priority == Thread->Priority);
1396
1397 /* Release the PRCB lock */
1398 KiReleasePrcbLock(Prcb);
1399 }
1400 else
1401 {
1402 /* Otherwise, prepare this thread to be deferred */
1403 Thread->State = DeferredReady;
1404 Thread->DeferredProcessor = Prcb->Number;
1405
1406 /* Release the lock and defer scheduling */
1407 KiReleasePrcbLock(Prcb);
1408 KiDeferredReadyThread(Thread);
1409 }
1410 }
1411
1412 //
1413 // This routine scans for an appropriate ready thread to select at the
1414 // given priority and for the given CPU.
1415 //
1416 FORCEINLINE
1417 PKTHREAD
1418 KiSelectReadyThread(IN KPRIORITY Priority,
1419 IN PKPRCB Prcb)
1420 {
1421 ULONG PrioritySet;
1422 LONG HighPriority;
1423 PLIST_ENTRY ListEntry;
1424 PKTHREAD Thread = NULL;
1425
1426 /* Save the current mask and get the priority set for the CPU */
1427 PrioritySet = Prcb->ReadySummary >> Priority;
1428 if (!PrioritySet) goto Quickie;
1429
1430 /* Get the highest priority possible */
1431 BitScanReverse((PULONG)&HighPriority, PrioritySet);
1432 ASSERT((PrioritySet & PRIORITY_MASK(HighPriority)) != 0);
1433 HighPriority += Priority;
1434
1435 /* Make sure the list isn't empty at the highest priority */
1436 ASSERT(IsListEmpty(&Prcb->DispatcherReadyListHead[HighPriority]) == FALSE);
1437
1438 /* Get the first thread on the list */
1439 ListEntry = Prcb->DispatcherReadyListHead[HighPriority].Flink;
1440 Thread = CONTAINING_RECORD(ListEntry, KTHREAD, WaitListEntry);
1441
1442 /* Make sure this thread is here for a reason */
1443 ASSERT(HighPriority == Thread->Priority);
1444 ASSERT(Thread->Affinity & AFFINITY_MASK(Prcb->Number));
1445 ASSERT(Thread->NextProcessor == Prcb->Number);
1446
1447 /* Remove it from the list */
1448 if (RemoveEntryList(&Thread->WaitListEntry))
1449 {
1450 /* The list is empty now, reset the ready summary */
1451 Prcb->ReadySummary ^= PRIORITY_MASK(HighPriority);
1452 }
1453
1454 /* Sanity check and return the thread */
1455 Quickie:
1456 ASSERT((Thread == NULL) ||
1457 (Thread->BasePriority == 0) ||
1458 (Thread->Priority != 0));
1459 return Thread;
1460 }
1461
1462 //
1463 // This routine computes the new priority for a thread. It is only valid for
1464 // threads with priorities in the dynamic priority range.
1465 //
1466 FORCEINLINE
1467 SCHAR
1468 KiComputeNewPriority(IN PKTHREAD Thread,
1469 IN SCHAR Adjustment)
1470 {
1471 SCHAR Priority;
1472
1473 /* Priority sanity checks */
1474 ASSERT((Thread->PriorityDecrement >= 0) &&
1475 (Thread->PriorityDecrement <= Thread->Priority));
1476 ASSERT((Thread->Priority < LOW_REALTIME_PRIORITY) ?
1477 TRUE : (Thread->PriorityDecrement == 0));
1478
1479 /* Get the current priority */
1480 Priority = Thread->Priority;
1481 if (Priority < LOW_REALTIME_PRIORITY)
1482 {
1483 /* Decrease priority by the priority decrement */
1484 Priority -= (Thread->PriorityDecrement + Adjustment);
1485
1486 /* Don't go out of bounds */
1487 if (Priority < Thread->BasePriority) Priority = Thread->BasePriority;
1488
1489 /* Reset the priority decrement */
1490 Thread->PriorityDecrement = 0;
1491 }
1492
1493 /* Sanity check */
1494 ASSERT((Thread->BasePriority == 0) || (Priority != 0));
1495
1496 /* Return the new priority */
1497 return Priority;
1498 }
1499
1500 //
1501 // Guarded Mutex Routines
1502 //
1503 FORCEINLINE
1504 VOID
1505 _KeInitializeGuardedMutex(OUT PKGUARDED_MUTEX GuardedMutex)
1506 {
1507 /* Setup the Initial Data */
1508 GuardedMutex->Count = GM_LOCK_BIT;
1509 GuardedMutex->Owner = NULL;
1510 GuardedMutex->Contention = 0;
1511
1512 /* Initialize the Wait Gate */
1513 KeInitializeGate(&GuardedMutex->Gate);
1514 }
1515
1516 FORCEINLINE
1517 VOID
1518 _KeAcquireGuardedMutexUnsafe(IN OUT PKGUARDED_MUTEX GuardedMutex)
1519 {
1520 PKTHREAD Thread = KeGetCurrentThread();
1521
1522 /* Sanity checks */
1523 ASSERT((KeGetCurrentIrql() == APC_LEVEL) ||
1524 (Thread->SpecialApcDisable < 0) ||
1525 (Thread->Teb == NULL) ||
1526 (Thread->Teb >= (PTEB)MM_SYSTEM_RANGE_START));
1527 ASSERT(GuardedMutex->Owner != Thread);
1528
1529 /* Remove the lock */
1530 if (!InterlockedBitTestAndReset(&GuardedMutex->Count, GM_LOCK_BIT_V))
1531 {
1532 /* The Guarded Mutex was already locked, enter contented case */
1533 KiAcquireGuardedMutex(GuardedMutex);
1534 }
1535
1536 /* Set the Owner */
1537 GuardedMutex->Owner = Thread;
1538 }
1539
1540 FORCEINLINE
1541 VOID
1542 _KeReleaseGuardedMutexUnsafe(IN OUT PKGUARDED_MUTEX GuardedMutex)
1543 {
1544 LONG OldValue, NewValue;
1545
1546 /* Sanity checks */
1547 ASSERT((KeGetCurrentIrql() == APC_LEVEL) ||
1548 (KeGetCurrentThread()->SpecialApcDisable < 0) ||
1549 (KeGetCurrentThread()->Teb == NULL) ||
1550 (KeGetCurrentThread()->Teb >= (PTEB)MM_SYSTEM_RANGE_START));
1551 ASSERT(GuardedMutex->Owner == KeGetCurrentThread());
1552
1553 /* Destroy the Owner */
1554 GuardedMutex->Owner = NULL;
1555
1556 /* Add the Lock Bit */
1557 OldValue = InterlockedExchangeAdd(&GuardedMutex->Count, GM_LOCK_BIT);
1558 ASSERT((OldValue & GM_LOCK_BIT) == 0);
1559
1560 /* Check if it was already locked, but not woken */
1561 if ((OldValue) && !(OldValue & GM_LOCK_WAITER_WOKEN))
1562 {
1563 /* Update the Oldvalue to what it should be now */
1564 OldValue += GM_LOCK_BIT;
1565
1566 /* The mutex will be woken, minus one waiter */
1567 NewValue = OldValue + GM_LOCK_WAITER_WOKEN -
1568 GM_LOCK_WAITER_INC;
1569
1570 /* Remove the Woken bit */
1571 if (InterlockedCompareExchange(&GuardedMutex->Count,
1572 NewValue,
1573 OldValue) == OldValue)
1574 {
1575 /* Signal the Gate */
1576 KeSignalGateBoostPriority(&GuardedMutex->Gate);
1577 }
1578 }
1579 }
1580
1581 FORCEINLINE
1582 VOID
1583 _KeAcquireGuardedMutex(IN PKGUARDED_MUTEX GuardedMutex)
1584 {
1585 PKTHREAD Thread = KeGetCurrentThread();
1586
1587 /* Sanity checks */
1588 ASSERT(KeGetCurrentIrql() <= APC_LEVEL);
1589 ASSERT(GuardedMutex->Owner != Thread);
1590
1591 /* Disable Special APCs */
1592 KeEnterGuardedRegion();
1593
1594 /* Remove the lock */
1595 if (!InterlockedBitTestAndReset(&GuardedMutex->Count, GM_LOCK_BIT_V))
1596 {
1597 /* The Guarded Mutex was already locked, enter contented case */
1598 KiAcquireGuardedMutex(GuardedMutex);
1599 }
1600
1601 /* Set the Owner and Special APC Disable state */
1602 GuardedMutex->Owner = Thread;
1603 GuardedMutex->SpecialApcDisable = Thread->SpecialApcDisable;
1604 }
1605
1606 FORCEINLINE
1607 VOID
1608 _KeReleaseGuardedMutex(IN OUT PKGUARDED_MUTEX GuardedMutex)
1609 {
1610 LONG OldValue, NewValue;
1611
1612 /* Sanity checks */
1613 ASSERT(KeGetCurrentIrql() <= APC_LEVEL);
1614 ASSERT(GuardedMutex->Owner == KeGetCurrentThread());
1615 ASSERT(KeGetCurrentThread()->SpecialApcDisable ==
1616 GuardedMutex->SpecialApcDisable);
1617
1618 /* Destroy the Owner */
1619 GuardedMutex->Owner = NULL;
1620
1621 /* Add the Lock Bit */
1622 OldValue = InterlockedExchangeAdd(&GuardedMutex->Count, GM_LOCK_BIT);
1623 ASSERT((OldValue & GM_LOCK_BIT) == 0);
1624
1625 /* Check if it was already locked, but not woken */
1626 if ((OldValue) && !(OldValue & GM_LOCK_WAITER_WOKEN))
1627 {
1628 /* Update the Oldvalue to what it should be now */
1629 OldValue += GM_LOCK_BIT;
1630
1631 /* The mutex will be woken, minus one waiter */
1632 NewValue = OldValue + GM_LOCK_WAITER_WOKEN -
1633 GM_LOCK_WAITER_INC;
1634
1635 /* Remove the Woken bit */
1636 if (InterlockedCompareExchange(&GuardedMutex->Count,
1637 NewValue,
1638 OldValue) == OldValue)
1639 {
1640 /* Signal the Gate */
1641 KeSignalGateBoostPriority(&GuardedMutex->Gate);
1642 }
1643 }
1644
1645 /* Re-enable APCs */
1646 KeLeaveGuardedRegion();
1647 }
1648
1649 FORCEINLINE
1650 BOOLEAN
1651 _KeTryToAcquireGuardedMutex(IN OUT PKGUARDED_MUTEX GuardedMutex)
1652 {
1653 PKTHREAD Thread = KeGetCurrentThread();
1654
1655 /* Block APCs */
1656 KeEnterGuardedRegion();
1657
1658 /* Remove the lock */
1659 if (!InterlockedBitTestAndReset(&GuardedMutex->Count, GM_LOCK_BIT_V))
1660 {
1661 /* Re-enable APCs */
1662 KeLeaveGuardedRegion();
1663 YieldProcessor();
1664
1665 /* Return failure */
1666 return FALSE;
1667 }
1668
1669 /* Set the Owner and APC State */
1670 GuardedMutex->Owner = Thread;
1671 GuardedMutex->SpecialApcDisable = Thread->SpecialApcDisable;
1672 return TRUE;
1673 }