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
);
460 ASSERT_MUTANT(Mutant
);
462 /* Make sure it's not terminating with APCs off */
463 if (Mutant
->ApcDisable
)
465 /* Bugcheck the system */
466 KeBugCheckEx(THREAD_TERMINATE_HELD_MUTEX
,
473 /* Now we can remove it */
474 RemoveEntryList(&Mutant
->MutantListEntry
);
476 /* Unconditionally abandon it */
477 Mutant
->Header
.SignalState
= 1;
478 Mutant
->Abandoned
= TRUE
;
479 Mutant
->OwnerThread
= NULL
;
481 /* Check if the Wait List isn't empty */
482 if (!IsListEmpty(&Mutant
->Header
.WaitListHead
))
484 /* Wake the Mutant */
485 KiWaitTest(&Mutant
->Header
, MUTANT_INCREMENT
);
489 NextEntry
= Thread
->MutantListHead
.Flink
;
492 /* Release the Lock */
493 KiReleaseDispatcherLock(OldIrql
);
498 KeStartThread(IN OUT PKTHREAD Thread
)
500 KLOCK_QUEUE_HANDLE LockHandle
;
506 UCHAR IdealProcessor
= 0;
507 PKPROCESS Process
= Thread
->ApcState
.Process
;
509 /* Setup static fields from parent */
510 Thread
->DisableBoost
= Process
->DisableBoost
;
512 Thread
->Iopl
= Process
->Iopl
;
514 Thread
->Quantum
= Process
->QuantumReset
;
515 Thread
->QuantumReset
= Process
->QuantumReset
;
516 Thread
->SystemAffinityActive
= FALSE
;
518 /* Lock the process */
519 KiAcquireProcessLock(Process
, &LockHandle
);
521 /* Setup volatile data */
522 Thread
->Priority
= Process
->BasePriority
;
523 Thread
->BasePriority
= Process
->BasePriority
;
524 Thread
->Affinity
= Process
->Affinity
;
525 Thread
->UserAffinity
= Process
->Affinity
;
528 /* Get the KNODE and its PRCB */
529 Node
= KeNodeBlock
[Process
->IdealNode
];
530 NodePrcb
= KiProcessorBlock
[Process
->ThreadSeed
];
532 /* Calculate affinity mask */
533 Set
= ~NodePrcb
->MultiThreadProcessorSet
;
534 Mask
= (ULONG
)(Node
->ProcessorMask
& Process
->Affinity
);
538 /* Get the new thread seed */
539 IdealProcessor
= KeFindNextRightSetAffinity(Process
->ThreadSeed
, Mask
);
540 Process
->ThreadSeed
= IdealProcessor
;
543 ASSERT((Thread
->UserAffinity
& AFFINITY_MASK(IdealProcessor
)));
546 /* Set the Ideal Processor */
547 Thread
->IdealProcessor
= IdealProcessor
;
548 Thread
->UserIdealProcessor
= IdealProcessor
;
550 /* Lock the Dispatcher Database */
551 KiAcquireDispatcherLockAtDpcLevel();
553 /* Insert the thread into the process list */
554 InsertTailList(&Process
->ThreadListHead
, &Thread
->ThreadListEntry
);
556 /* Increase the stack count */
557 ASSERT(Process
->StackCount
!= MAXULONG_PTR
);
558 Process
->StackCount
++;
560 /* Release locks and return */
561 KiReleaseDispatcherLockFromDpcLevel();
562 KiReleaseProcessLock(&LockHandle
);
567 KiSuspendRundown(IN PKAPC Apc
)
570 UNREFERENCED_PARAMETER(Apc
);
575 KiSuspendNop(IN PKAPC Apc
,
576 IN PKNORMAL_ROUTINE
*NormalRoutine
,
577 IN PVOID
*NormalContext
,
578 IN PVOID
*SystemArgument1
,
579 IN PVOID
*SystemArgument2
)
582 UNREFERENCED_PARAMETER(Apc
);
583 UNREFERENCED_PARAMETER(NormalRoutine
);
584 UNREFERENCED_PARAMETER(NormalContext
);
585 UNREFERENCED_PARAMETER(SystemArgument1
);
586 UNREFERENCED_PARAMETER(SystemArgument2
);
591 KiSuspendThread(IN PVOID NormalContext
,
592 IN PVOID SystemArgument1
,
593 IN PVOID SystemArgument2
)
595 /* Non-alertable kernel-mode suspended wait */
596 KeWaitForSingleObject(&KeGetCurrentThread()->SuspendSemaphore
,
605 KeSuspendThread(PKTHREAD Thread
)
607 KLOCK_QUEUE_HANDLE ApcLock
;
609 ASSERT_THREAD(Thread
);
610 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
612 /* Lock the APC Queue */
613 KiAcquireApcLock(Thread
, &ApcLock
);
615 /* Save the Old Count */
616 PreviousCount
= Thread
->SuspendCount
;
618 /* Handle the maximum */
619 if (PreviousCount
== MAXIMUM_SUSPEND_COUNT
)
621 /* Raise an exception */
622 KiReleaseApcLock(&ApcLock
);
623 RtlRaiseStatus(STATUS_SUSPEND_COUNT_EXCEEDED
);
626 /* Should we bother to queue at all? */
627 if (Thread
->ApcQueueable
)
629 /* Increment the suspend count */
630 Thread
->SuspendCount
++;
632 /* Check if we should suspend it */
633 if (!(PreviousCount
) && !(Thread
->FreezeCount
))
635 /* Is the APC already inserted? */
636 if (!Thread
->SuspendApc
.Inserted
)
638 /* Not inserted, insert it */
639 Thread
->SuspendApc
.Inserted
= TRUE
;
640 KiInsertQueueApc(&Thread
->SuspendApc
, IO_NO_INCREMENT
);
644 /* Lock the dispatcher */
645 KiAcquireDispatcherLockAtDpcLevel();
647 /* Unsignal the semaphore, the APC was already inserted */
648 Thread
->SuspendSemaphore
.Header
.SignalState
--;
650 /* Release the dispatcher */
651 KiReleaseDispatcherLockFromDpcLevel();
656 /* Release Lock and return the Old State */
657 KiReleaseApcLockFromDpcLevel(&ApcLock
);
658 KiExitDispatcher(ApcLock
.OldIrql
);
659 return PreviousCount
;
664 KeThawAllThreads(VOID
)
666 KLOCK_QUEUE_HANDLE LockHandle
, ApcLock
;
667 PKTHREAD Current
, CurrentThread
= KeGetCurrentThread();
668 PKPROCESS Process
= CurrentThread
->ApcState
.Process
;
669 PLIST_ENTRY ListHead
, NextEntry
;
671 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
673 /* Lock the process */
674 KiAcquireProcessLock(Process
, &LockHandle
);
676 /* Loop the Process's Threads */
677 ListHead
= &Process
->ThreadListHead
;
678 NextEntry
= ListHead
->Flink
;
681 /* Get the current thread */
682 Current
= CONTAINING_RECORD(NextEntry
, KTHREAD
, ThreadListEntry
);
685 KiAcquireApcLockAtDpcLevel(Current
, &ApcLock
);
687 /* Make sure we are frozen */
688 OldCount
= Current
->FreezeCount
;
691 /* Decrease the freeze count */
692 Current
->FreezeCount
--;
694 /* Check if both counts are zero now */
695 if (!(Current
->SuspendCount
) && (!Current
->FreezeCount
))
697 /* Lock the dispatcher */
698 KiAcquireDispatcherLockAtDpcLevel();
700 /* Signal the suspend semaphore and wake it */
701 Current
->SuspendSemaphore
.Header
.SignalState
++;
702 KiWaitTest(&Current
->SuspendSemaphore
, 0);
704 /* Unlock the dispatcher */
705 KiReleaseDispatcherLockFromDpcLevel();
709 /* Release the APC lock */
710 KiReleaseApcLockFromDpcLevel(&ApcLock
);
712 /* Go to the next one */
713 NextEntry
= NextEntry
->Flink
;
714 } while (NextEntry
!= ListHead
);
716 /* Release the process lock and exit the dispatcher */
717 KiReleaseProcessLockFromDpcLevel(&LockHandle
);
718 KiExitDispatcher(LockHandle
.OldIrql
);
720 /* Leave the critical region */
721 KeLeaveCriticalRegion();
726 KeTestAlertThread(IN KPROCESSOR_MODE AlertMode
)
728 PKTHREAD Thread
= KeGetCurrentThread();
730 KLOCK_QUEUE_HANDLE ApcLock
;
731 ASSERT_THREAD(Thread
);
732 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
734 /* Lock the Dispatcher Database and the APC Queue */
735 KiAcquireApcLock(Thread
, &ApcLock
);
737 /* Save the old State */
738 OldState
= Thread
->Alerted
[AlertMode
];
740 /* Check the Thread is alerted */
743 /* Disable alert for this mode */
744 Thread
->Alerted
[AlertMode
] = FALSE
;
746 else if ((AlertMode
!= KernelMode
) &&
747 (!IsListEmpty(&Thread
->ApcState
.ApcListHead
[UserMode
])))
749 /* If the mode is User and the Queue isn't empty, set Pending */
750 Thread
->ApcState
.UserApcPending
= TRUE
;
753 /* Release Locks and return the Old State */
754 KiReleaseApcLock(&ApcLock
);
760 KeInitThread(IN OUT PKTHREAD Thread
,
761 IN PVOID KernelStack
,
762 IN PKSYSTEM_ROUTINE SystemRoutine
,
763 IN PKSTART_ROUTINE StartRoutine
,
764 IN PVOID StartContext
,
767 IN PKPROCESS Process
)
769 BOOLEAN AllocatedStack
= FALSE
;
771 PKWAIT_BLOCK TimerWaitBlock
;
775 /* Initialize the Dispatcher Header */
776 Thread
->Header
.Type
= ThreadObject
;
777 Thread
->Header
.ThreadControlFlags
= 0;
778 Thread
->Header
.DebugActive
= FALSE
;
779 Thread
->Header
.SignalState
= 0;
780 InitializeListHead(&(Thread
->Header
.WaitListHead
));
782 /* Initialize the Mutant List */
783 InitializeListHead(&Thread
->MutantListHead
);
785 /* Initialize the wait blocks */
786 for (i
= 0; i
< (THREAD_WAIT_OBJECTS
+ 1); i
++)
788 /* Put our pointer */
789 Thread
->WaitBlock
[i
].Thread
= Thread
;
792 /* Set swap settings */
793 Thread
->EnableStackSwap
= TRUE
;
794 Thread
->IdealProcessor
= 1;
795 Thread
->SwapBusy
= FALSE
;
796 Thread
->KernelStackResident
= TRUE
;
797 Thread
->AdjustReason
= AdjustNone
;
799 /* Initialize the lock */
800 KeInitializeSpinLock(&Thread
->ThreadLock
);
802 /* Setup the Service Descriptor Table for Native Calls */
803 Thread
->ServiceTable
= KeServiceDescriptorTable
;
805 /* Setup APC Fields */
806 InitializeListHead(&Thread
->ApcState
.ApcListHead
[KernelMode
]);
807 InitializeListHead(&Thread
->ApcState
.ApcListHead
[UserMode
]);
808 Thread
->ApcState
.Process
= Process
;
809 Thread
->ApcStatePointer
[OriginalApcEnvironment
] = &Thread
->ApcState
;
810 Thread
->ApcStatePointer
[AttachedApcEnvironment
] = &Thread
->SavedApcState
;
811 Thread
->ApcStateIndex
= OriginalApcEnvironment
;
812 Thread
->ApcQueueable
= TRUE
;
813 KeInitializeSpinLock(&Thread
->ApcQueueLock
);
815 /* Initialize the Suspend APC */
816 KeInitializeApc(&Thread
->SuspendApc
,
818 OriginalApcEnvironment
,
825 /* Initialize the Suspend Semaphore */
826 KeInitializeSemaphore(&Thread
->SuspendSemaphore
, 0, 2);
828 /* Setup the timer */
829 Timer
= &Thread
->Timer
;
830 KeInitializeTimer(Timer
);
831 TimerWaitBlock
= &Thread
->WaitBlock
[TIMER_WAIT_BLOCK
];
832 TimerWaitBlock
->Object
= Timer
;
833 TimerWaitBlock
->WaitKey
= STATUS_TIMEOUT
;
834 TimerWaitBlock
->WaitType
= WaitAny
;
835 TimerWaitBlock
->NextWaitBlock
= NULL
;
837 /* Link the two wait lists together */
838 TimerWaitBlock
->WaitListEntry
.Flink
= &Timer
->Header
.WaitListHead
;
839 TimerWaitBlock
->WaitListEntry
.Blink
= &Timer
->Header
.WaitListHead
;
841 /* Set the TEB and process */
843 Thread
->Process
= Process
;
845 /* Check if we have a kernel stack */
848 /* We don't, allocate one */
849 KernelStack
= MmCreateKernelStack(FALSE
, 0);
850 if (!KernelStack
) return STATUS_INSUFFICIENT_RESOURCES
;
852 /* Remember for later */
853 AllocatedStack
= TRUE
;
856 /* Set the Thread Stacks */
857 Thread
->InitialStack
= KernelStack
;
858 Thread
->StackBase
= KernelStack
;
859 Thread
->StackLimit
= (ULONG_PTR
)KernelStack
- KERNEL_STACK_SIZE
;
860 Thread
->KernelStackResident
= TRUE
;
862 /* Enter SEH to avoid crashes due to user mode */
863 Status
= STATUS_SUCCESS
;
866 /* Initialize the Thread Context */
867 KiInitializeContextThread(Thread
,
873 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
875 /* Set failure status */
876 Status
= STATUS_UNSUCCESSFUL
;
878 /* Check if a stack was allocated */
881 /* Delete the stack */
882 MmDeleteKernelStack((PVOID
)Thread
->StackBase
, FALSE
);
883 Thread
->InitialStack
= NULL
;
888 /* Set the Thread to initialized */
889 Thread
->State
= Initialized
;
895 KeInitializeThread(IN PKPROCESS Process
,
896 IN OUT PKTHREAD Thread
,
897 IN PKSYSTEM_ROUTINE SystemRoutine
,
898 IN PKSTART_ROUTINE StartRoutine
,
899 IN PVOID StartContext
,
902 IN PVOID KernelStack
)
904 /* Initialize and start the thread on success */
905 if (NT_SUCCESS(KeInitThread(Thread
,
915 KeStartThread(Thread
);
921 KeUninitThread(IN PKTHREAD Thread
)
923 /* Delete the stack */
924 MmDeleteKernelStack((PVOID
)Thread
->StackBase
, FALSE
);
925 Thread
->InitialStack
= NULL
;
928 /* PUBLIC FUNCTIONS **********************************************************/
935 KeCapturePersistentThreadState(IN PVOID CurrentThread
,
941 IN PVOID ThreadState
)
949 #undef KeGetCurrentThread
952 KeGetCurrentThread(VOID
)
954 /* Return the current thread on this PCR */
955 return _KeGetCurrentThread();
961 #undef KeGetPreviousMode
964 KeGetPreviousMode(VOID
)
966 /* Return the previous mode of this thread */
967 return _KeGetPreviousMode();
975 KeQueryRuntimeThread(IN PKTHREAD Thread
,
978 ASSERT_THREAD(Thread
);
980 /* Return the User Time */
981 *UserTime
= Thread
->UserTime
;
983 /* Return the Kernel Time */
984 return Thread
->KernelTime
;
992 KeSetKernelStackSwapEnable(IN BOOLEAN Enable
)
994 BOOLEAN PreviousState
;
995 PKTHREAD Thread
= KeGetCurrentThread();
998 PreviousState
= Thread
->EnableStackSwap
;
1001 Thread
->EnableStackSwap
= Enable
;
1003 /* Return Old State */
1004 return PreviousState
;
1012 KeQueryPriorityThread(IN PKTHREAD Thread
)
1014 ASSERT_THREAD(Thread
);
1016 /* Return the current priority */
1017 return Thread
->Priority
;
1025 KeRevertToUserAffinityThread(VOID
)
1029 PKTHREAD NextThread
, CurrentThread
= KeGetCurrentThread();
1030 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1031 ASSERT(CurrentThread
->SystemAffinityActive
!= FALSE
);
1033 /* Lock the Dispatcher Database */
1034 OldIrql
= KiAcquireDispatcherLock();
1036 /* Set the user affinity and processor and disable system affinity */
1037 CurrentThread
->Affinity
= CurrentThread
->UserAffinity
;
1038 CurrentThread
->IdealProcessor
= CurrentThread
->UserIdealProcessor
;
1039 CurrentThread
->SystemAffinityActive
= FALSE
;
1041 /* Get the current PRCB and check if it doesn't match this affinity */
1042 Prcb
= KeGetCurrentPrcb();
1043 if (!(Prcb
->SetMember
& CurrentThread
->Affinity
))
1046 KiAcquirePrcbLock(Prcb
);
1048 /* Check if there's no next thread scheduled */
1049 if (!Prcb
->NextThread
)
1051 /* Select a new thread and set it on standby */
1052 NextThread
= KiSelectNextThread(Prcb
);
1053 NextThread
->State
= Standby
;
1054 Prcb
->NextThread
= NextThread
;
1057 /* Release the PRCB lock */
1058 KiReleasePrcbLock(Prcb
);
1061 /* Unlock dispatcher database */
1062 KiReleaseDispatcherLock(OldIrql
);
1070 KeSetIdealProcessorThread(IN PKTHREAD Thread
,
1073 CCHAR OldIdealProcessor
;
1075 ASSERT(Processor
<= MAXIMUM_PROCESSORS
);
1077 /* Lock the Dispatcher Database */
1078 OldIrql
= KiAcquireDispatcherLock();
1080 /* Save Old Ideal Processor */
1081 OldIdealProcessor
= Thread
->UserIdealProcessor
;
1083 /* Make sure a valid CPU was given */
1084 if (Processor
< KeNumberProcessors
)
1086 /* Check if the user ideal CPU is in the affinity */
1087 if (Thread
->Affinity
& AFFINITY_MASK(Processor
))
1089 /* Set the ideal processor */
1090 Thread
->IdealProcessor
= Processor
;
1092 /* Check if system affinity is used */
1093 if (!Thread
->SystemAffinityActive
)
1095 /* It's not, so update the user CPU too */
1096 Thread
->UserIdealProcessor
= Processor
;
1101 /* Release dispatcher lock and return the old ideal CPU */
1102 KiReleaseDispatcherLock(OldIrql
);
1103 return OldIdealProcessor
;
1111 KeSetSystemAffinityThread(IN KAFFINITY Affinity
)
1115 PKTHREAD NextThread
, CurrentThread
= KeGetCurrentThread();
1116 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1117 ASSERT((Affinity
& KeActiveProcessors
) != 0);
1119 /* Lock the Dispatcher Database */
1120 OldIrql
= KiAcquireDispatcherLock();
1122 /* Restore the affinity and enable system affinity */
1123 CurrentThread
->Affinity
= Affinity
;
1124 CurrentThread
->SystemAffinityActive
= TRUE
;
1126 /* Check if the ideal processor is part of the affinity */
1128 if (!(Affinity
& AFFINITY_MASK(CurrentThread
->IdealProcessor
)))
1130 ULONG AffinitySet
, NodeMask
;
1132 /* It's not! Get the PRCB */
1133 Prcb
= KiProcessorBlock
[CurrentThread
->IdealProcessor
];
1135 /* Calculate the affinity set */
1136 AffinitySet
= KeActiveProcessors
& Affinity
;
1137 NodeMask
= Prcb
->ParentNode
->ProcessorMask
& AffinitySet
;
1140 /* Use the Node set instead */
1141 AffinitySet
= NodeMask
;
1144 /* Calculate the ideal CPU from the affinity set */
1145 BitScanReverse(&NodeMask
, AffinitySet
);
1146 CurrentThread
->IdealProcessor
= (UCHAR
)NodeMask
;
1150 /* Get the current PRCB and check if it doesn't match this affinity */
1151 Prcb
= KeGetCurrentPrcb();
1152 if (!(Prcb
->SetMember
& CurrentThread
->Affinity
))
1155 KiAcquirePrcbLock(Prcb
);
1157 /* Check if there's no next thread scheduled */
1158 if (!Prcb
->NextThread
)
1160 /* Select a new thread and set it on standby */
1161 NextThread
= KiSelectNextThread(Prcb
);
1162 NextThread
->State
= Standby
;
1163 Prcb
->NextThread
= NextThread
;
1166 /* Release the PRCB lock */
1167 KiReleasePrcbLock(Prcb
);
1170 /* Unlock dispatcher database */
1171 KiReleaseDispatcherLock(OldIrql
);
1179 KeSetBasePriorityThread(IN PKTHREAD Thread
,
1183 KPRIORITY OldBasePriority
, Priority
, BasePriority
;
1186 ASSERT_THREAD(Thread
);
1187 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1189 /* Get the process */
1190 Process
= Thread
->ApcState
.Process
;
1192 /* Lock the Dispatcher Database */
1193 OldIrql
= KiAcquireDispatcherLock();
1195 /* Lock the thread */
1196 KiAcquireThreadLock(Thread
);
1198 /* Save the old base priority and increment */
1199 OldBasePriority
= Thread
->BasePriority
;
1200 OldIncrement
= OldBasePriority
- Process
->BasePriority
;
1202 /* If priority saturation happened, use the saturated increment */
1203 if (Thread
->Saturation
) OldIncrement
= (HIGH_PRIORITY
+ 1) / 2 *
1206 /* Reset the saturation value */
1207 Thread
->Saturation
= 0;
1209 /* Now check if saturation is being used for the new value */
1210 if (abs(Increment
) >= ((HIGH_PRIORITY
+ 1) / 2))
1212 /* Check if we need positive or negative saturation */
1213 Thread
->Saturation
= (Increment
> 0) ? 1 : -1;
1216 /* Normalize the Base Priority */
1217 BasePriority
= Process
->BasePriority
+ Increment
;
1218 if (Process
->BasePriority
>= LOW_REALTIME_PRIORITY
)
1220 /* Check if it's too low */
1221 if (BasePriority
< LOW_REALTIME_PRIORITY
)
1223 /* Set it to the lowest real time level */
1224 BasePriority
= LOW_REALTIME_PRIORITY
;
1227 /* Check if it's too high */
1228 if (BasePriority
> HIGH_PRIORITY
) BasePriority
= HIGH_PRIORITY
;
1230 /* We are at real time, so use the raw base priority */
1231 Priority
= BasePriority
;
1235 /* Check if it's entering the real time range */
1236 if (BasePriority
>= LOW_REALTIME_PRIORITY
)
1238 /* Set it to the highest dynamic level */
1239 BasePriority
= LOW_REALTIME_PRIORITY
- 1;
1242 /* Check if it's too low and normalize it */
1243 if (BasePriority
<= LOW_PRIORITY
) BasePriority
= 1;
1245 /* Check if Saturation is used */
1246 if (Thread
->Saturation
)
1248 /* Use the raw base priority */
1249 Priority
= BasePriority
;
1253 /* Otherwise, calculate the new priority */
1254 Priority
= KiComputeNewPriority(Thread
, 0);
1255 Priority
+= (BasePriority
- OldBasePriority
);
1257 /* Check if it entered the real-time range */
1258 if (Priority
>= LOW_REALTIME_PRIORITY
)
1260 /* Normalize it down to the highest dynamic priority */
1261 Priority
= LOW_REALTIME_PRIORITY
- 1;
1263 else if (Priority
<= LOW_PRIORITY
)
1265 /* It went too low, normalize it */
1271 /* Finally set the new base priority */
1272 Thread
->BasePriority
= (SCHAR
)BasePriority
;
1274 /* Reset the decrements */
1275 Thread
->PriorityDecrement
= 0;
1277 /* Check if we're changing priority after all */
1278 if (Priority
!= Thread
->Priority
)
1280 /* Reset the quantum and do the actual priority modification */
1281 Thread
->Quantum
= Thread
->QuantumReset
;
1282 KiSetPriorityThread(Thread
, Priority
);
1285 /* Release thread lock */
1286 KiReleaseThreadLock(Thread
);
1288 /* Release the dispatcher database and return old increment */
1289 KiReleaseDispatcherLock(OldIrql
);
1290 return OldIncrement
;
1298 KeSetAffinityThread(IN PKTHREAD Thread
,
1299 IN KAFFINITY Affinity
)
1302 KAFFINITY OldAffinity
;
1303 ASSERT_THREAD(Thread
);
1304 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1306 /* Lock the dispatcher database */
1307 OldIrql
= KiAcquireDispatcherLock();
1309 /* Call the internal function */
1310 OldAffinity
= KiSetAffinityThread(Thread
, Affinity
);
1312 /* Release the dispatcher database and return old affinity */
1313 KiReleaseDispatcherLock(OldIrql
);
1322 KeSetPriorityThread(IN PKTHREAD Thread
,
1323 IN KPRIORITY Priority
)
1326 KPRIORITY OldPriority
;
1327 ASSERT_THREAD(Thread
);
1328 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1329 ASSERT((Priority
<= HIGH_PRIORITY
) && (Priority
>= LOW_PRIORITY
));
1330 ASSERT(KeIsExecutingDpc() == FALSE
);
1332 /* Lock the Dispatcher Database */
1333 OldIrql
= KiAcquireDispatcherLock();
1335 /* Lock the thread */
1336 KiAcquireThreadLock(Thread
);
1338 /* Save the old Priority and reset decrement */
1339 OldPriority
= Thread
->Priority
;
1340 Thread
->PriorityDecrement
= 0;
1342 /* Make sure that an actual change is being done */
1343 if (Priority
!= Thread
->Priority
)
1345 /* Reset the quantum */
1346 Thread
->Quantum
= Thread
->QuantumReset
;
1348 /* Check if priority is being set too low and normalize if so */
1349 if ((Thread
->BasePriority
!= 0) && !(Priority
)) Priority
= 1;
1351 /* Set the new Priority */
1352 KiSetPriorityThread(Thread
, Priority
);
1355 /* Release thread lock */
1356 KiReleaseThreadLock(Thread
);
1358 /* Release the dispatcher database */
1359 KiReleaseDispatcherLock(OldIrql
);
1361 /* Return Old Priority */
1370 KeTerminateThread(IN KPRIORITY Increment
)
1372 PLIST_ENTRY
*ListHead
;
1373 PETHREAD Entry
, SavedEntry
;
1374 PETHREAD
*ThreadAddr
;
1375 KLOCK_QUEUE_HANDLE LockHandle
;
1376 PKTHREAD Thread
= KeGetCurrentThread();
1377 PKPROCESS Process
= Thread
->ApcState
.Process
;
1378 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1380 /* Lock the process */
1381 KiAcquireProcessLock(Process
, &LockHandle
);
1383 /* Make sure we won't get Swapped */
1384 KiSetThreadSwapBusy(Thread
);
1386 /* Save the Kernel and User Times */
1387 Process
->KernelTime
+= Thread
->KernelTime
;
1388 Process
->UserTime
+= Thread
->UserTime
;
1390 /* Get the current entry and our Port */
1391 Entry
= (PETHREAD
)PspReaperListHead
.Flink
;
1392 ThreadAddr
= &((PETHREAD
)Thread
)->ReaperLink
;
1394 /* Add it to the reaper's list */
1397 /* Get the list head */
1398 ListHead
= &PspReaperListHead
.Flink
;
1400 /* Link ourselves */
1401 *ThreadAddr
= Entry
;
1404 /* Now try to do the exchange */
1405 Entry
= InterlockedCompareExchangePointer((PVOID
*)ListHead
,
1409 /* Break out if the change was succesful */
1410 } while (Entry
!= SavedEntry
);
1412 /* Acquire the dispatcher lock */
1413 KiAcquireDispatcherLockAtDpcLevel();
1415 /* Check if the reaper wasn't active */
1418 /* Activate it as a work item, directly through its Queue */
1419 KiInsertQueue(&ExWorkerQueue
[HyperCriticalWorkQueue
].WorkerQueue
,
1420 &PspReaperWorkItem
.List
,
1424 /* Check the thread has an associated queue */
1427 /* Remove it from the list, and handle the queue */
1428 RemoveEntryList(&Thread
->QueueListEntry
);
1429 KiActivateWaiterQueue(Thread
->Queue
);
1432 /* Signal the thread */
1433 Thread
->Header
.SignalState
= TRUE
;
1434 if (!IsListEmpty(&Thread
->Header
.WaitListHead
))
1436 /* Unwait the threads */
1437 KxUnwaitThread(&Thread
->Header
, Increment
);
1440 /* Remove the thread from the list */
1441 RemoveEntryList(&Thread
->ThreadListEntry
);
1443 /* Release the process lock */
1444 KiReleaseProcessLockFromDpcLevel(&LockHandle
);
1446 /* Set us as terminated, decrease the Process's stack count */
1447 Thread
->State
= Terminated
;
1449 /* Decrease stack count */
1450 ASSERT(Process
->StackCount
!= 0);
1451 ASSERT(Process
->State
== ProcessInMemory
);
1452 Process
->StackCount
--;
1453 if (!(Process
->StackCount
) && !(IsListEmpty(&Process
->ThreadListHead
)))
1455 /* FIXME: Swap stacks */
1458 /* Rundown arch-specific parts */
1459 KiRundownThread(Thread
);
1461 /* Swap to a new thread */
1462 KiReleaseDispatcherLockFromDpcLevel();
1463 KiSwapThread(Thread
, KeGetCurrentPrcb());