2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/ke/thrdobj.c
5 * PURPOSE: Implements routines to manage the Kernel Thread Object
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
9 /* INCLUDES ******************************************************************/
15 extern EX_WORK_QUEUE ExWorkerQueue
[MaximumWorkQueue
];
16 extern LIST_ENTRY PspReaperListHead
;
18 ULONG KiMask32Array
[MAXIMUM_PRIORITY
] =
20 0x1, 0x2, 0x4, 0x8, 0x10, 0x20,
21 0x40, 0x80, 0x100, 0x200, 0x400, 0x800,
22 0x1000, 0x2000, 0x4000, 0x8000, 0x10000, 0x20000,
23 0x40000, 0x80000, 0x100000, 0x200000, 0x400000, 0x800000,
24 0x1000000, 0x2000000, 0x4000000, 0x8000000, 0x10000000, 0x20000000,
25 0x40000000, 0x80000000
28 /* FUNCTIONS *****************************************************************/
32 KeFindNextRightSetAffinity(IN UCHAR Number
,
38 /* Calculate the mask */
39 Bit
= (AFFINITY_MASK(Number
) - 1) & Set
;
41 /* If it's 0, use the one we got */
44 /* Now find the right set and return it */
45 BitScanReverse(&Result
, Bit
);
51 KeReadStateThread(IN PKTHREAD Thread
)
53 ASSERT_THREAD(Thread
);
55 /* Return signal state */
56 return (BOOLEAN
)Thread
->Header
.SignalState
;
61 KeQueryBasePriorityThread(IN PKTHREAD Thread
)
66 ASSERT_THREAD(Thread
);
67 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
69 /* Raise IRQL to synch level */
70 OldIrql
= KeRaiseIrqlToSynchLevel();
73 KiAcquireThreadLock(Thread
);
76 Process
= Thread
->ApcStatePointer
[0]->Process
;
78 /* Calculate the base increment */
79 BaseIncrement
= Thread
->BasePriority
- Process
->BasePriority
;
81 /* If saturation occured, return the saturation increment instead */
82 if (Thread
->Saturation
) BaseIncrement
= (HIGH_PRIORITY
+ 1) / 2 *
85 /* Release thread lock */
86 KiReleaseThreadLock(Thread
);
88 /* Lower IRQl and return Increment */
95 KeSetDisableBoostThread(IN OUT PKTHREAD Thread
,
98 ASSERT_THREAD(Thread
);
100 /* Check if we're enabling or disabling */
104 return InterlockedBitTestAndSet(&Thread
->ThreadFlags
, 1);
109 return InterlockedBitTestAndReset(&Thread
->ThreadFlags
, 1);
115 KeReadyThread(IN PKTHREAD Thread
)
118 ASSERT_THREAD(Thread
);
119 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
121 /* Lock the Dispatcher Database */
122 OldIrql
= KiAcquireDispatcherLock();
124 /* Make the thread ready */
125 KiReadyThread(Thread
);
127 /* Unlock dispatcher database */
128 KiReleaseDispatcherLock(OldIrql
);
133 KeAlertResumeThread(IN PKTHREAD Thread
)
136 KLOCK_QUEUE_HANDLE ApcLock
;
137 ASSERT_THREAD(Thread
);
138 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
140 /* Lock the Dispatcher Database and the APC Queue */
141 KiAcquireApcLock(Thread
, &ApcLock
);
142 KiAcquireDispatcherLockAtDpcLevel();
144 /* Return if Thread is already alerted. */
145 if (!Thread
->Alerted
[KernelMode
])
147 /* If it's Blocked, unblock if it we should */
148 if ((Thread
->State
== Waiting
) && (Thread
->Alertable
))
151 KiUnwaitThread(Thread
, STATUS_ALERTED
, THREAD_ALERT_INCREMENT
);
155 /* If not, simply Alert it */
156 Thread
->Alerted
[KernelMode
] = TRUE
;
160 /* Save the old Suspend Count */
161 PreviousCount
= Thread
->SuspendCount
;
163 /* If the thread is suspended, decrease one of the suspend counts */
166 /* Decrease count. If we are now zero, unwait it completely */
167 Thread
->SuspendCount
--;
168 if (!(Thread
->SuspendCount
) && !(Thread
->FreezeCount
))
170 /* Signal and satisfy */
171 Thread
->SuspendSemaphore
.Header
.SignalState
++;
172 KiWaitTest(&Thread
->SuspendSemaphore
.Header
, IO_NO_INCREMENT
);
176 /* Release Locks and return the Old State */
177 KiReleaseDispatcherLockFromDpcLevel();
178 KiReleaseApcLockFromDpcLevel(&ApcLock
);
179 KiExitDispatcher(ApcLock
.OldIrql
);
180 return PreviousCount
;
185 KeAlertThread(IN PKTHREAD Thread
,
186 IN KPROCESSOR_MODE AlertMode
)
188 BOOLEAN PreviousState
;
189 KLOCK_QUEUE_HANDLE ApcLock
;
190 ASSERT_THREAD(Thread
);
191 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
193 /* Lock the Dispatcher Database and the APC Queue */
194 KiAcquireApcLock(Thread
, &ApcLock
);
195 KiAcquireDispatcherLockAtDpcLevel();
197 /* Save the Previous State */
198 PreviousState
= Thread
->Alerted
[AlertMode
];
200 /* Check if it's already alerted */
203 /* Check if the thread is alertable, and blocked in the given mode */
204 if ((Thread
->State
== Waiting
) &&
205 (Thread
->Alertable
) &&
206 (AlertMode
<= Thread
->WaitMode
))
208 /* Abort the wait to alert the thread */
209 KiUnwaitThread(Thread
, STATUS_ALERTED
, THREAD_ALERT_INCREMENT
);
213 /* Otherwise, merely set the alerted state */
214 Thread
->Alerted
[AlertMode
] = TRUE
;
218 /* Release the Dispatcher Lock */
219 KiReleaseDispatcherLockFromDpcLevel();
220 KiReleaseApcLockFromDpcLevel(&ApcLock
);
221 KiExitDispatcher(ApcLock
.OldIrql
);
223 /* Return the old state */
224 return PreviousState
;
229 KeBoostPriorityThread(IN PKTHREAD Thread
,
230 IN KPRIORITY Increment
)
234 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
236 /* Lock the Dispatcher Database */
237 OldIrql
= KiAcquireDispatcherLock();
239 /* Only threads in the dynamic range get boosts */
240 if (Thread
->Priority
< LOW_REALTIME_PRIORITY
)
242 /* Lock the thread */
243 KiAcquireThreadLock(Thread
);
245 /* Check again, and make sure there's not already a boost */
246 if ((Thread
->Priority
< LOW_REALTIME_PRIORITY
) &&
247 !(Thread
->PriorityDecrement
))
249 /* Compute the new priority and see if it's higher */
250 Priority
= Thread
->BasePriority
+ Increment
;
251 if (Priority
> Thread
->Priority
)
253 if (Priority
>= LOW_REALTIME_PRIORITY
)
255 Priority
= LOW_REALTIME_PRIORITY
- 1;
258 /* Reset the quantum */
259 Thread
->Quantum
= Thread
->QuantumReset
;
261 /* Set the new Priority */
262 KiSetPriorityThread(Thread
, Priority
);
266 /* Release thread lock */
267 KiReleaseThreadLock(Thread
);
270 /* Release the dispatcher lokc */
271 KiReleaseDispatcherLock(OldIrql
);
276 KeForceResumeThread(IN PKTHREAD Thread
)
278 KLOCK_QUEUE_HANDLE ApcLock
;
280 ASSERT_THREAD(Thread
);
281 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
283 /* Lock the APC Queue */
284 KiAcquireApcLock(Thread
, &ApcLock
);
286 /* Save the old Suspend Count */
287 PreviousCount
= Thread
->SuspendCount
+ Thread
->FreezeCount
;
289 /* If the thread is suspended, wake it up!!! */
292 /* Unwait it completely */
293 Thread
->SuspendCount
= 0;
294 Thread
->FreezeCount
= 0;
296 /* Lock the dispatcher */
297 KiAcquireDispatcherLockAtDpcLevel();
299 /* Signal and satisfy */
300 Thread
->SuspendSemaphore
.Header
.SignalState
++;
301 KiWaitTest(&Thread
->SuspendSemaphore
.Header
, IO_NO_INCREMENT
);
303 /* Release the dispatcher */
304 KiReleaseDispatcherLockFromDpcLevel();
307 /* Release Lock and return the Old State */
308 KiReleaseApcLockFromDpcLevel(&ApcLock
);
309 KiExitDispatcher(ApcLock
.OldIrql
);
310 return PreviousCount
;
315 KeFreezeAllThreads(VOID
)
317 KLOCK_QUEUE_HANDLE LockHandle
, ApcLock
;
318 PKTHREAD Current
, CurrentThread
= KeGetCurrentThread();
319 PKPROCESS Process
= CurrentThread
->ApcState
.Process
;
320 PLIST_ENTRY ListHead
, NextEntry
;
322 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
324 /* Lock the process */
325 KiAcquireProcessLock(Process
, &LockHandle
);
327 /* If someone is already trying to free us, try again */
328 while (CurrentThread
->FreezeCount
)
330 /* Release and re-acquire the process lock so the APC will go through */
331 KiReleaseProcessLock(&LockHandle
);
332 KiAcquireProcessLock(Process
, &LockHandle
);
335 /* Enter a critical region */
336 KeEnterCriticalRegion();
338 /* Loop the Process's Threads */
339 ListHead
= &Process
->ThreadListHead
;
340 NextEntry
= ListHead
->Flink
;
343 /* Get the current thread */
344 Current
= CONTAINING_RECORD(NextEntry
, KTHREAD
, ThreadListEntry
);
347 KiAcquireApcLockAtDpcLevel(Current
, &ApcLock
);
349 /* Make sure it's not ours, and check if APCs are enabled */
350 if ((Current
!= CurrentThread
) && (Current
->ApcQueueable
))
353 OldCount
= Current
->SuspendCount
;
354 ASSERT(OldCount
!= MAXIMUM_SUSPEND_COUNT
);
356 /* Increase the freeze count */
357 Current
->FreezeCount
++;
359 /* Make sure it wasn't already suspended */
360 if (!(OldCount
) && !(Current
->SuspendCount
))
362 /* Did we already insert it? */
363 if (!Current
->SuspendApc
.Inserted
)
366 Current
->SuspendApc
.Inserted
= TRUE
;
367 KiInsertQueueApc(&Current
->SuspendApc
, IO_NO_INCREMENT
);
371 /* Lock the dispatcher */
372 KiAcquireDispatcherLockAtDpcLevel();
374 /* Unsignal the semaphore, the APC was already inserted */
375 Current
->SuspendSemaphore
.Header
.SignalState
--;
377 /* Release the dispatcher */
378 KiReleaseDispatcherLockFromDpcLevel();
383 /* Release the APC lock */
384 KiReleaseApcLockFromDpcLevel(&ApcLock
);
386 /* Move to the next thread */
387 NextEntry
= NextEntry
->Flink
;
388 } while (NextEntry
!= ListHead
);
390 /* Release the process lock and exit the dispatcher */
391 KiReleaseProcessLockFromDpcLevel(&LockHandle
);
392 KiExitDispatcher(LockHandle
.OldIrql
);
397 KeResumeThread(IN PKTHREAD Thread
)
399 KLOCK_QUEUE_HANDLE ApcLock
;
401 ASSERT_THREAD(Thread
);
402 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
404 /* Lock the APC Queue */
405 KiAcquireApcLock(Thread
, &ApcLock
);
407 /* Save the Old Count */
408 PreviousCount
= Thread
->SuspendCount
;
410 /* Check if it existed */
413 /* Decrease the suspend count */
414 Thread
->SuspendCount
--;
416 /* Check if the thrad is still suspended or not */
417 if ((!Thread
->SuspendCount
) && (!Thread
->FreezeCount
))
419 /* Acquire the dispatcher lock */
420 KiAcquireDispatcherLockAtDpcLevel();
422 /* Signal the Suspend Semaphore */
423 Thread
->SuspendSemaphore
.Header
.SignalState
++;
424 KiWaitTest(&Thread
->SuspendSemaphore
.Header
, IO_NO_INCREMENT
);
426 /* Release the dispatcher lock */
427 KiReleaseDispatcherLockFromDpcLevel();
431 /* Release APC Queue lock and return the Old State */
432 KiReleaseApcLockFromDpcLevel(&ApcLock
);
433 KiExitDispatcher(ApcLock
.OldIrql
);
434 return PreviousCount
;
439 KeRundownThread(VOID
)
442 PKTHREAD Thread
= KeGetCurrentThread();
443 PLIST_ENTRY NextEntry
, ListHead
;
445 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
447 /* Optimized path if nothing is on the list at the moment */
448 if (IsListEmpty(&Thread
->MutantListHead
)) return;
450 /* Lock the Dispatcher Database */
451 OldIrql
= KiAcquireDispatcherLock();
453 /* Get the List Pointers */
454 ListHead
= &Thread
->MutantListHead
;
455 NextEntry
= ListHead
->Flink
;
456 while (NextEntry
!= ListHead
)
459 Mutant
= CONTAINING_RECORD(NextEntry
, KMUTANT
, MutantListEntry
);
461 /* Make sure it's not terminating with APCs off */
462 if (Mutant
->ApcDisable
)
464 /* Bugcheck the system */
465 KeBugCheckEx(THREAD_TERMINATE_HELD_MUTEX
,
472 /* Now we can remove it */
473 RemoveEntryList(&Mutant
->MutantListEntry
);
475 /* Unconditionally abandon it */
476 Mutant
->Header
.SignalState
= 1;
477 Mutant
->Abandoned
= TRUE
;
478 Mutant
->OwnerThread
= NULL
;
480 /* Check if the Wait List isn't empty */
481 if (!IsListEmpty(&Mutant
->Header
.WaitListHead
))
483 /* Wake the Mutant */
484 KiWaitTest(&Mutant
->Header
, MUTANT_INCREMENT
);
488 NextEntry
= NextEntry
->Flink
;
491 /* Release the Lock */
492 KiReleaseDispatcherLock(OldIrql
);
497 KeStartThread(IN OUT PKTHREAD Thread
)
499 KLOCK_QUEUE_HANDLE LockHandle
;
505 UCHAR IdealProcessor
= 0;
506 PKPROCESS Process
= Thread
->ApcState
.Process
;
508 /* Setup static fields from parent */
509 Thread
->DisableBoost
= Process
->DisableBoost
;
511 Thread
->Iopl
= Process
->Iopl
;
513 Thread
->Quantum
= Process
->QuantumReset
;
514 Thread
->QuantumReset
= Process
->QuantumReset
;
515 Thread
->SystemAffinityActive
= FALSE
;
517 /* Lock the process */
518 KiAcquireProcessLock(Process
, &LockHandle
);
520 /* Setup volatile data */
521 Thread
->Priority
= Process
->BasePriority
;
522 Thread
->BasePriority
= Process
->BasePriority
;
523 Thread
->Affinity
= Process
->Affinity
;
524 Thread
->UserAffinity
= Process
->Affinity
;
527 /* Get the KNODE and its PRCB */
528 Node
= KeNodeBlock
[Process
->IdealNode
];
529 NodePrcb
= KiProcessorBlock
[Process
->ThreadSeed
];
531 /* Calculate affinity mask */
532 Set
= ~NodePrcb
->MultiThreadProcessorSet
;
533 Mask
= (ULONG
)(Node
->ProcessorMask
& Process
->Affinity
);
537 /* Get the new thread seed */
538 IdealProcessor
= KeFindNextRightSetAffinity(Process
->ThreadSeed
, Mask
);
539 Process
->ThreadSeed
= IdealProcessor
;
542 ASSERT((Thread
->UserAffinity
& AFFINITY_MASK(IdealProcessor
)));
545 /* Set the Ideal Processor */
546 Thread
->IdealProcessor
= IdealProcessor
;
547 Thread
->UserIdealProcessor
= IdealProcessor
;
549 /* Lock the Dispatcher Database */
550 KiAcquireDispatcherLockAtDpcLevel();
552 /* Insert the thread into the process list */
553 InsertTailList(&Process
->ThreadListHead
, &Thread
->ThreadListEntry
);
555 /* Increase the stack count */
556 ASSERT(Process
->StackCount
!= MAXULONG_PTR
);
557 Process
->StackCount
++;
559 /* Release locks and return */
560 KiReleaseDispatcherLockFromDpcLevel();
561 KiReleaseProcessLock(&LockHandle
);
566 KiSuspendRundown(IN PKAPC Apc
)
569 UNREFERENCED_PARAMETER(Apc
);
574 KiSuspendNop(IN PKAPC Apc
,
575 IN PKNORMAL_ROUTINE
*NormalRoutine
,
576 IN PVOID
*NormalContext
,
577 IN PVOID
*SystemArgument1
,
578 IN PVOID
*SystemArgument2
)
581 UNREFERENCED_PARAMETER(Apc
);
582 UNREFERENCED_PARAMETER(NormalRoutine
);
583 UNREFERENCED_PARAMETER(NormalContext
);
584 UNREFERENCED_PARAMETER(SystemArgument1
);
585 UNREFERENCED_PARAMETER(SystemArgument2
);
590 KiSuspendThread(IN PVOID NormalContext
,
591 IN PVOID SystemArgument1
,
592 IN PVOID SystemArgument2
)
594 /* Non-alertable kernel-mode suspended wait */
595 KeWaitForSingleObject(&KeGetCurrentThread()->SuspendSemaphore
,
604 KeSuspendThread(PKTHREAD Thread
)
606 KLOCK_QUEUE_HANDLE ApcLock
;
608 ASSERT_THREAD(Thread
);
609 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
611 /* Lock the APC Queue */
612 KiAcquireApcLock(Thread
, &ApcLock
);
614 /* Save the Old Count */
615 PreviousCount
= Thread
->SuspendCount
;
617 /* Handle the maximum */
618 if (PreviousCount
== MAXIMUM_SUSPEND_COUNT
)
620 /* Raise an exception */
621 KiReleaseApcLock(&ApcLock
);
622 RtlRaiseStatus(STATUS_SUSPEND_COUNT_EXCEEDED
);
625 /* Should we bother to queue at all? */
626 if (Thread
->ApcQueueable
)
628 /* Increment the suspend count */
629 Thread
->SuspendCount
++;
631 /* Check if we should suspend it */
632 if (!(PreviousCount
) && !(Thread
->FreezeCount
))
634 /* Is the APC already inserted? */
635 if (!Thread
->SuspendApc
.Inserted
)
637 /* Not inserted, insert it */
638 Thread
->SuspendApc
.Inserted
= TRUE
;
639 KiInsertQueueApc(&Thread
->SuspendApc
, IO_NO_INCREMENT
);
643 /* Lock the dispatcher */
644 KiAcquireDispatcherLockAtDpcLevel();
646 /* Unsignal the semaphore, the APC was already inserted */
647 Thread
->SuspendSemaphore
.Header
.SignalState
--;
649 /* Release the dispatcher */
650 KiReleaseDispatcherLockFromDpcLevel();
655 /* Release Lock and return the Old State */
656 KiReleaseApcLockFromDpcLevel(&ApcLock
);
657 KiExitDispatcher(ApcLock
.OldIrql
);
658 return PreviousCount
;
663 KeThawAllThreads(VOID
)
665 KLOCK_QUEUE_HANDLE LockHandle
, ApcLock
;
666 PKTHREAD Current
, CurrentThread
= KeGetCurrentThread();
667 PKPROCESS Process
= CurrentThread
->ApcState
.Process
;
668 PLIST_ENTRY ListHead
, NextEntry
;
670 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
672 /* Lock the process */
673 KiAcquireProcessLock(Process
, &LockHandle
);
675 /* Loop the Process's Threads */
676 ListHead
= &Process
->ThreadListHead
;
677 NextEntry
= ListHead
->Flink
;
680 /* Get the current thread */
681 Current
= CONTAINING_RECORD(NextEntry
, KTHREAD
, ThreadListEntry
);
684 KiAcquireApcLockAtDpcLevel(Current
, &ApcLock
);
686 /* Make sure we are frozen */
687 OldCount
= Current
->FreezeCount
;
690 /* Decrease the freeze count */
691 Current
->FreezeCount
--;
693 /* Check if both counts are zero now */
694 if (!(Current
->SuspendCount
) && (!Current
->FreezeCount
))
696 /* Lock the dispatcher */
697 KiAcquireDispatcherLockAtDpcLevel();
699 /* Signal the suspend semaphore and wake it */
700 Current
->SuspendSemaphore
.Header
.SignalState
++;
701 KiWaitTest(&Current
->SuspendSemaphore
, 0);
703 /* Unlock the dispatcher */
704 KiReleaseDispatcherLockFromDpcLevel();
708 /* Release the APC lock */
709 KiReleaseApcLockFromDpcLevel(&ApcLock
);
711 /* Go to the next one */
712 NextEntry
= NextEntry
->Flink
;
713 } while (NextEntry
!= ListHead
);
715 /* Release the process lock and exit the dispatcher */
716 KiReleaseProcessLockFromDpcLevel(&LockHandle
);
717 KiExitDispatcher(LockHandle
.OldIrql
);
719 /* Leave the critical region */
720 KeLeaveCriticalRegion();
725 KeTestAlertThread(IN KPROCESSOR_MODE AlertMode
)
727 PKTHREAD Thread
= KeGetCurrentThread();
729 KLOCK_QUEUE_HANDLE ApcLock
;
730 ASSERT_THREAD(Thread
);
731 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
733 /* Lock the Dispatcher Database and the APC Queue */
734 KiAcquireApcLock(Thread
, &ApcLock
);
736 /* Save the old State */
737 OldState
= Thread
->Alerted
[AlertMode
];
739 /* Check the Thread is alerted */
742 /* Disable alert for this mode */
743 Thread
->Alerted
[AlertMode
] = FALSE
;
745 else if ((AlertMode
!= KernelMode
) &&
746 (!IsListEmpty(&Thread
->ApcState
.ApcListHead
[UserMode
])))
748 /* If the mode is User and the Queue isn't empty, set Pending */
749 Thread
->ApcState
.UserApcPending
= TRUE
;
752 /* Release Locks and return the Old State */
753 KiReleaseApcLock(&ApcLock
);
759 KeInitThread(IN OUT PKTHREAD Thread
,
760 IN PVOID KernelStack
,
761 IN PKSYSTEM_ROUTINE SystemRoutine
,
762 IN PKSTART_ROUTINE StartRoutine
,
763 IN PVOID StartContext
,
766 IN PKPROCESS Process
)
768 BOOLEAN AllocatedStack
= FALSE
;
770 PKWAIT_BLOCK TimerWaitBlock
;
774 /* Initalize the Dispatcher Header */
775 Thread
->Header
.Type
= ThreadObject
;
776 Thread
->Header
.ThreadControlFlags
= 0;
777 Thread
->Header
.DebugActive
= FALSE
;
778 Thread
->Header
.SignalState
= 0;
779 InitializeListHead(&(Thread
->Header
.WaitListHead
));
781 /* Initialize the Mutant List */
782 InitializeListHead(&Thread
->MutantListHead
);
784 /* Initialize the wait blocks */
785 for (i
= 0; i
< (THREAD_WAIT_OBJECTS
+ 1); i
++)
787 /* Put our pointer */
788 Thread
->WaitBlock
[i
].Thread
= Thread
;
791 /* Set swap settings */
792 Thread
->EnableStackSwap
= TRUE
;
793 Thread
->IdealProcessor
= 1;
794 Thread
->SwapBusy
= FALSE
;
795 Thread
->KernelStackResident
= TRUE
;
796 Thread
->AdjustReason
= AdjustNone
;
798 /* Initialize the lock */
799 KeInitializeSpinLock(&Thread
->ThreadLock
);
801 /* Setup the Service Descriptor Table for Native Calls */
802 Thread
->ServiceTable
= KeServiceDescriptorTable
;
804 /* Setup APC Fields */
805 InitializeListHead(&Thread
->ApcState
.ApcListHead
[0]);
806 InitializeListHead(&Thread
->ApcState
.ApcListHead
[1]);
807 Thread
->ApcState
.Process
= Process
;
808 Thread
->ApcStatePointer
[OriginalApcEnvironment
] = &Thread
->ApcState
;
809 Thread
->ApcStatePointer
[AttachedApcEnvironment
] = &Thread
->SavedApcState
;
810 Thread
->ApcStateIndex
= OriginalApcEnvironment
;
811 Thread
->ApcQueueable
= TRUE
;
812 KeInitializeSpinLock(&Thread
->ApcQueueLock
);
814 /* Initialize the Suspend APC */
815 KeInitializeApc(&Thread
->SuspendApc
,
817 OriginalApcEnvironment
,
824 /* Initialize the Suspend Semaphore */
825 KeInitializeSemaphore(&Thread
->SuspendSemaphore
, 0, 2);
827 /* Setup the timer */
828 Timer
= &Thread
->Timer
;
829 KeInitializeTimer(Timer
);
830 TimerWaitBlock
= &Thread
->WaitBlock
[TIMER_WAIT_BLOCK
];
831 TimerWaitBlock
->Object
= Timer
;
832 TimerWaitBlock
->WaitKey
= STATUS_TIMEOUT
;
833 TimerWaitBlock
->WaitType
= WaitAny
;
834 TimerWaitBlock
->NextWaitBlock
= NULL
;
836 /* Link the two wait lists together */
837 TimerWaitBlock
->WaitListEntry
.Flink
= &Timer
->Header
.WaitListHead
;
838 TimerWaitBlock
->WaitListEntry
.Blink
= &Timer
->Header
.WaitListHead
;
843 /* Check if we have a kernel stack */
846 /* We don't, allocate one */
847 KernelStack
= MmCreateKernelStack(FALSE
, 0);
848 if (!KernelStack
) return STATUS_INSUFFICIENT_RESOURCES
;
850 /* Remember for later */
851 AllocatedStack
= TRUE
;
854 /* Set the Thread Stacks */
855 Thread
->InitialStack
= KernelStack
;
856 Thread
->StackBase
= KernelStack
;
857 Thread
->StackLimit
= (ULONG_PTR
)KernelStack
- KERNEL_STACK_SIZE
;
858 Thread
->KernelStackResident
= TRUE
;
860 /* Enter SEH to avoid crashes due to user mode */
861 Status
= STATUS_SUCCESS
;
864 /* Initalize the Thread Context */
865 KiInitializeContextThread(Thread
,
871 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
873 /* Set failure status */
874 Status
= STATUS_UNSUCCESSFUL
;
876 /* Check if a stack was allocated */
879 /* Delete the stack */
880 MmDeleteKernelStack((PVOID
)Thread
->StackBase
, FALSE
);
881 Thread
->InitialStack
= NULL
;
886 /* Set the Thread to initalized */
887 Thread
->State
= Initialized
;
893 KeInitializeThread(IN PKPROCESS Process
,
894 IN OUT PKTHREAD Thread
,
895 IN PKSYSTEM_ROUTINE SystemRoutine
,
896 IN PKSTART_ROUTINE StartRoutine
,
897 IN PVOID StartContext
,
900 IN PVOID KernelStack
)
902 /* Initialize and start the thread on success */
903 if (NT_SUCCESS(KeInitThread(Thread
,
913 KeStartThread(Thread
);
919 KeUninitThread(IN PKTHREAD Thread
)
921 /* Delete the stack */
922 MmDeleteKernelStack((PVOID
)Thread
->StackBase
, FALSE
);
923 Thread
->InitialStack
= NULL
;
926 /* PUBLIC FUNCTIONS **********************************************************/
933 KeCapturePersistentThreadState(IN PVOID CurrentThread
,
939 IN PVOID ThreadState
)
947 #undef KeGetCurrentThread
950 KeGetCurrentThread(VOID
)
952 /* Return the current thread on this PCR */
953 return _KeGetCurrentThread();
959 #undef KeGetPreviousMode
962 KeGetPreviousMode(VOID
)
964 /* Return the previous mode of this thread */
965 return _KeGetPreviousMode();
973 KeQueryRuntimeThread(IN PKTHREAD Thread
,
976 ASSERT_THREAD(Thread
);
978 /* Return the User Time */
979 *UserTime
= Thread
->UserTime
;
981 /* Return the Kernel Time */
982 return Thread
->KernelTime
;
990 KeSetKernelStackSwapEnable(IN BOOLEAN Enable
)
992 BOOLEAN PreviousState
;
993 PKTHREAD Thread
= KeGetCurrentThread();
996 PreviousState
= Thread
->EnableStackSwap
;
999 Thread
->EnableStackSwap
= Enable
;
1001 /* Return Old State */
1002 return PreviousState
;
1010 KeQueryPriorityThread(IN PKTHREAD Thread
)
1012 ASSERT_THREAD(Thread
);
1014 /* Return the current priority */
1015 return Thread
->Priority
;
1023 KeRevertToUserAffinityThread(VOID
)
1027 PKTHREAD NextThread
, CurrentThread
= KeGetCurrentThread();
1028 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1029 ASSERT(CurrentThread
->SystemAffinityActive
!= FALSE
);
1031 /* Lock the Dispatcher Database */
1032 OldIrql
= KiAcquireDispatcherLock();
1034 /* Set the user affinity and processor and disable system affinity */
1035 CurrentThread
->Affinity
= CurrentThread
->UserAffinity
;
1036 CurrentThread
->IdealProcessor
= CurrentThread
->UserIdealProcessor
;
1037 CurrentThread
->SystemAffinityActive
= FALSE
;
1039 /* Get the current PRCB and check if it doesn't match this affinity */
1040 Prcb
= KeGetCurrentPrcb();
1041 if (!(Prcb
->SetMember
& CurrentThread
->Affinity
))
1044 KiAcquirePrcbLock(Prcb
);
1046 /* Check if there's no next thread scheduled */
1047 if (!Prcb
->NextThread
)
1049 /* Select a new thread and set it on standby */
1050 NextThread
= KiSelectNextThread(Prcb
);
1051 NextThread
->State
= Standby
;
1052 Prcb
->NextThread
= NextThread
;
1055 /* Release the PRCB lock */
1056 KiReleasePrcbLock(Prcb
);
1059 /* Unlock dispatcher database */
1060 KiReleaseDispatcherLock(OldIrql
);
1068 KeSetIdealProcessorThread(IN PKTHREAD Thread
,
1071 CCHAR OldIdealProcessor
;
1073 ASSERT(Processor
<= MAXIMUM_PROCESSORS
);
1075 /* Lock the Dispatcher Database */
1076 OldIrql
= KiAcquireDispatcherLock();
1078 /* Save Old Ideal Processor */
1079 OldIdealProcessor
= Thread
->UserIdealProcessor
;
1081 /* Make sure a valid CPU was given */
1082 if (Processor
< KeNumberProcessors
)
1084 /* Check if the user ideal CPU is in the affinity */
1085 if (Thread
->Affinity
& AFFINITY_MASK(Processor
))
1087 /* Set the ideal processor */
1088 Thread
->IdealProcessor
= Processor
;
1090 /* Check if system affinity is used */
1091 if (!Thread
->SystemAffinityActive
)
1093 /* It's not, so update the user CPU too */
1094 Thread
->UserIdealProcessor
= Processor
;
1099 /* Release dispatcher lock and return the old ideal CPU */
1100 KiReleaseDispatcherLock(OldIrql
);
1101 return OldIdealProcessor
;
1109 KeSetSystemAffinityThread(IN KAFFINITY Affinity
)
1113 PKTHREAD NextThread
, CurrentThread
= KeGetCurrentThread();
1114 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1115 ASSERT((Affinity
& KeActiveProcessors
) != 0);
1117 /* Lock the Dispatcher Database */
1118 OldIrql
= KiAcquireDispatcherLock();
1120 /* Restore the affinity and enable system affinity */
1121 CurrentThread
->Affinity
= Affinity
;
1122 CurrentThread
->SystemAffinityActive
= TRUE
;
1124 /* Check if the ideal processor is part of the affinity */
1126 if (!(Affinity
& AFFINITY_MASK(CurrentThread
->IdealProcessor
)))
1128 ULONG AffinitySet
, NodeMask
;
1130 /* It's not! Get the PRCB */
1131 Prcb
= KiProcessorBlock
[CurrentThread
->IdealProcessor
];
1133 /* Calculate the affinity set */
1134 AffinitySet
= KeActiveProcessors
& Affinity
;
1135 NodeMask
= Prcb
->ParentNode
->ProcessorMask
& AffinitySet
;
1138 /* Use the Node set instead */
1139 AffinitySet
= NodeMask
;
1142 /* Calculate the ideal CPU from the affinity set */
1143 BitScanReverse(&NodeMask
, AffinitySet
);
1144 CurrentThread
->IdealProcessor
= (UCHAR
)NodeMask
;
1148 /* Get the current PRCB and check if it doesn't match this affinity */
1149 Prcb
= KeGetCurrentPrcb();
1150 if (!(Prcb
->SetMember
& CurrentThread
->Affinity
))
1153 KiAcquirePrcbLock(Prcb
);
1155 /* Check if there's no next thread scheduled */
1156 if (!Prcb
->NextThread
)
1158 /* Select a new thread and set it on standby */
1159 NextThread
= KiSelectNextThread(Prcb
);
1160 NextThread
->State
= Standby
;
1161 Prcb
->NextThread
= NextThread
;
1164 /* Release the PRCB lock */
1165 KiReleasePrcbLock(Prcb
);
1168 /* Unlock dispatcher database */
1169 KiReleaseDispatcherLock(OldIrql
);
1177 KeSetBasePriorityThread(IN PKTHREAD Thread
,
1181 KPRIORITY OldBasePriority
, Priority
, BasePriority
;
1184 ASSERT_THREAD(Thread
);
1185 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1187 /* Get the process */
1188 Process
= Thread
->ApcState
.Process
;
1190 /* Lock the Dispatcher Database */
1191 OldIrql
= KiAcquireDispatcherLock();
1193 /* Lock the thread */
1194 KiAcquireThreadLock(Thread
);
1196 /* Save the old base priority and increment */
1197 OldBasePriority
= Thread
->BasePriority
;
1198 OldIncrement
= OldBasePriority
- Process
->BasePriority
;
1200 /* If priority saturation happened, use the saturated increment */
1201 if (Thread
->Saturation
) OldIncrement
= (HIGH_PRIORITY
+ 1) / 2 *
1204 /* Reset the saturation value */
1205 Thread
->Saturation
= 0;
1207 /* Now check if saturation is being used for the new value */
1208 if (abs(Increment
) >= ((HIGH_PRIORITY
+ 1) / 2))
1210 /* Check if we need positive or negative saturation */
1211 Thread
->Saturation
= (Increment
> 0) ? 1 : -1;
1214 /* Normalize the Base Priority */
1215 BasePriority
= Process
->BasePriority
+ Increment
;
1216 if (Process
->BasePriority
>= LOW_REALTIME_PRIORITY
)
1218 /* Check if it's too low */
1219 if (BasePriority
< LOW_REALTIME_PRIORITY
)
1221 /* Set it to the lowest real time level */
1222 BasePriority
= LOW_REALTIME_PRIORITY
;
1225 /* Check if it's too high */
1226 if (BasePriority
> HIGH_PRIORITY
) BasePriority
= HIGH_PRIORITY
;
1228 /* We are at real time, so use the raw base priority */
1229 Priority
= BasePriority
;
1233 /* Check if it's entering the real time range */
1234 if (BasePriority
>= LOW_REALTIME_PRIORITY
)
1236 /* Set it to the highest dynamic level */
1237 BasePriority
= LOW_REALTIME_PRIORITY
- 1;
1240 /* Check if it's too low and normalize it */
1241 if (BasePriority
<= LOW_PRIORITY
) BasePriority
= 1;
1243 /* Check if Saturation is used */
1244 if (Thread
->Saturation
)
1246 /* Use the raw base priority */
1247 Priority
= BasePriority
;
1251 /* Otherwise, calculate the new priority */
1252 Priority
= KiComputeNewPriority(Thread
, 0);
1253 Priority
+= (BasePriority
- OldBasePriority
);
1255 /* Check if it entered the real-time range */
1256 if (Priority
>= LOW_REALTIME_PRIORITY
)
1258 /* Normalize it down to the highest dynamic priority */
1259 Priority
= LOW_REALTIME_PRIORITY
- 1;
1261 else if (Priority
<= LOW_PRIORITY
)
1263 /* It went too low, normalize it */
1269 /* Finally set the new base priority */
1270 Thread
->BasePriority
= (SCHAR
)BasePriority
;
1272 /* Reset the decrements */
1273 Thread
->PriorityDecrement
= 0;
1275 /* Check if we're changing priority after all */
1276 if (Priority
!= Thread
->Priority
)
1278 /* Reset the quantum and do the actual priority modification */
1279 Thread
->Quantum
= Thread
->QuantumReset
;
1280 KiSetPriorityThread(Thread
, Priority
);
1283 /* Release thread lock */
1284 KiReleaseThreadLock(Thread
);
1286 /* Release the dispatcher database and return old increment */
1287 KiReleaseDispatcherLock(OldIrql
);
1288 return OldIncrement
;
1296 KeSetAffinityThread(IN PKTHREAD Thread
,
1297 IN KAFFINITY Affinity
)
1300 KAFFINITY OldAffinity
;
1301 ASSERT_THREAD(Thread
);
1302 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1304 /* Lock the dispatcher database */
1305 OldIrql
= KiAcquireDispatcherLock();
1307 /* Call the internal function */
1308 OldAffinity
= KiSetAffinityThread(Thread
, Affinity
);
1310 /* Release the dispatcher database and return old affinity */
1311 KiReleaseDispatcherLock(OldIrql
);
1320 KeSetPriorityThread(IN PKTHREAD Thread
,
1321 IN KPRIORITY Priority
)
1324 KPRIORITY OldPriority
;
1325 ASSERT_THREAD(Thread
);
1326 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1327 ASSERT((Priority
<= HIGH_PRIORITY
) && (Priority
>= LOW_PRIORITY
));
1328 ASSERT(KeIsExecutingDpc() == FALSE
);
1330 /* Lock the Dispatcher Database */
1331 OldIrql
= KiAcquireDispatcherLock();
1333 /* Lock the thread */
1334 KiAcquireThreadLock(Thread
);
1336 /* Save the old Priority and reset decrement */
1337 OldPriority
= Thread
->Priority
;
1338 Thread
->PriorityDecrement
= 0;
1340 /* Make sure that an actual change is being done */
1341 if (Priority
!= Thread
->Priority
)
1343 /* Reset the quantum */
1344 Thread
->Quantum
= Thread
->QuantumReset
;
1346 /* Check if priority is being set too low and normalize if so */
1347 if ((Thread
->BasePriority
!= 0) && !(Priority
)) Priority
= 1;
1349 /* Set the new Priority */
1350 KiSetPriorityThread(Thread
, Priority
);
1353 /* Release thread lock */
1354 KiReleaseThreadLock(Thread
);
1356 /* Release the dispatcher database */
1357 KiReleaseDispatcherLock(OldIrql
);
1359 /* Return Old Priority */
1368 KeTerminateThread(IN KPRIORITY Increment
)
1370 PLIST_ENTRY
*ListHead
;
1371 PETHREAD Entry
, SavedEntry
;
1372 PETHREAD
*ThreadAddr
;
1373 KLOCK_QUEUE_HANDLE LockHandle
;
1374 PKTHREAD Thread
= KeGetCurrentThread();
1375 PKPROCESS Process
= Thread
->ApcState
.Process
;
1376 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1378 /* Lock the process */
1379 KiAcquireProcessLock(Process
, &LockHandle
);
1381 /* Make sure we won't get Swapped */
1382 KiSetThreadSwapBusy(Thread
);
1384 /* Save the Kernel and User Times */
1385 Process
->KernelTime
+= Thread
->KernelTime
;
1386 Process
->UserTime
+= Thread
->UserTime
;
1388 /* Get the current entry and our Port */
1389 Entry
= (PETHREAD
)PspReaperListHead
.Flink
;
1390 ThreadAddr
= &((PETHREAD
)Thread
)->ReaperLink
;
1392 /* Add it to the reaper's list */
1395 /* Get the list head */
1396 ListHead
= &PspReaperListHead
.Flink
;
1398 /* Link ourselves */
1399 *ThreadAddr
= Entry
;
1402 /* Now try to do the exchange */
1403 Entry
= InterlockedCompareExchangePointer((PVOID
*)ListHead
,
1407 /* Break out if the change was succesful */
1408 } while (Entry
!= SavedEntry
);
1410 /* Acquire the dispatcher lock */
1411 KiAcquireDispatcherLockAtDpcLevel();
1413 /* Check if the reaper wasn't active */
1416 /* Activate it as a work item, directly through its Queue */
1417 KiInsertQueue(&ExWorkerQueue
[HyperCriticalWorkQueue
].WorkerQueue
,
1418 &PspReaperWorkItem
.List
,
1422 /* Check the thread has an associated queue */
1425 /* Remove it from the list, and handle the queue */
1426 RemoveEntryList(&Thread
->QueueListEntry
);
1427 KiActivateWaiterQueue(Thread
->Queue
);
1430 /* Signal the thread */
1431 Thread
->Header
.SignalState
= TRUE
;
1432 if (!IsListEmpty(&Thread
->Header
.WaitListHead
))
1434 /* Unwait the threads */
1435 KxUnwaitThread(&Thread
->Header
, Increment
);
1438 /* Remove the thread from the list */
1439 RemoveEntryList(&Thread
->ThreadListEntry
);
1441 /* Release the process lock */
1442 KiReleaseProcessLockFromDpcLevel(&LockHandle
);
1444 /* Set us as terminated, decrease the Process's stack count */
1445 Thread
->State
= Terminated
;
1447 /* Decrease stack count */
1448 ASSERT(Process
->StackCount
!= 0);
1449 ASSERT(Process
->State
== ProcessInMemory
);
1450 Process
->StackCount
--;
1451 if (!(Process
->StackCount
) && !(IsListEmpty(&Process
->ThreadListHead
)))
1453 /* FIXME: Swap stacks */
1456 /* Rundown arch-specific parts */
1457 KiRundownThread(Thread
);
1459 /* Swap to a new thread */
1460 KiReleaseDispatcherLockFromDpcLevel();
1461 KiSwapThread(Thread
, KeGetCurrentPrcb());