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
= NextEntry
->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 /* Initalize 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
[0]);
807 InitializeListHead(&Thread
->ApcState
.ApcListHead
[1]);
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
;
844 /* Check if we have a kernel stack */
847 /* We don't, allocate one */
848 KernelStack
= MmCreateKernelStack(FALSE
, 0);
849 if (!KernelStack
) return STATUS_INSUFFICIENT_RESOURCES
;
851 /* Remember for later */
852 AllocatedStack
= TRUE
;
855 /* Set the Thread Stacks */
856 Thread
->InitialStack
= KernelStack
;
857 Thread
->StackBase
= KernelStack
;
858 Thread
->StackLimit
= (ULONG_PTR
)KernelStack
- KERNEL_STACK_SIZE
;
859 Thread
->KernelStackResident
= TRUE
;
861 /* Enter SEH to avoid crashes due to user mode */
862 Status
= STATUS_SUCCESS
;
865 /* Initalize the Thread Context */
866 KiInitializeContextThread(Thread
,
872 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
874 /* Set failure status */
875 Status
= STATUS_UNSUCCESSFUL
;
877 /* Check if a stack was allocated */
880 /* Delete the stack */
881 MmDeleteKernelStack((PVOID
)Thread
->StackBase
, FALSE
);
882 Thread
->InitialStack
= NULL
;
887 /* Set the Thread to initalized */
888 Thread
->State
= Initialized
;
894 KeInitializeThread(IN PKPROCESS Process
,
895 IN OUT PKTHREAD Thread
,
896 IN PKSYSTEM_ROUTINE SystemRoutine
,
897 IN PKSTART_ROUTINE StartRoutine
,
898 IN PVOID StartContext
,
901 IN PVOID KernelStack
)
903 /* Initialize and start the thread on success */
904 if (NT_SUCCESS(KeInitThread(Thread
,
914 KeStartThread(Thread
);
920 KeUninitThread(IN PKTHREAD Thread
)
922 /* Delete the stack */
923 MmDeleteKernelStack((PVOID
)Thread
->StackBase
, FALSE
);
924 Thread
->InitialStack
= NULL
;
927 /* PUBLIC FUNCTIONS **********************************************************/
934 KeCapturePersistentThreadState(IN PVOID CurrentThread
,
940 IN PVOID ThreadState
)
948 #undef KeGetCurrentThread
951 KeGetCurrentThread(VOID
)
953 /* Return the current thread on this PCR */
954 return _KeGetCurrentThread();
960 #undef KeGetPreviousMode
963 KeGetPreviousMode(VOID
)
965 /* Return the previous mode of this thread */
966 return _KeGetPreviousMode();
974 KeQueryRuntimeThread(IN PKTHREAD Thread
,
977 ASSERT_THREAD(Thread
);
979 /* Return the User Time */
980 *UserTime
= Thread
->UserTime
;
982 /* Return the Kernel Time */
983 return Thread
->KernelTime
;
991 KeSetKernelStackSwapEnable(IN BOOLEAN Enable
)
993 BOOLEAN PreviousState
;
994 PKTHREAD Thread
= KeGetCurrentThread();
997 PreviousState
= Thread
->EnableStackSwap
;
1000 Thread
->EnableStackSwap
= Enable
;
1002 /* Return Old State */
1003 return PreviousState
;
1011 KeQueryPriorityThread(IN PKTHREAD Thread
)
1013 ASSERT_THREAD(Thread
);
1015 /* Return the current priority */
1016 return Thread
->Priority
;
1024 KeRevertToUserAffinityThread(VOID
)
1028 PKTHREAD NextThread
, CurrentThread
= KeGetCurrentThread();
1029 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1030 ASSERT(CurrentThread
->SystemAffinityActive
!= FALSE
);
1032 /* Lock the Dispatcher Database */
1033 OldIrql
= KiAcquireDispatcherLock();
1035 /* Set the user affinity and processor and disable system affinity */
1036 CurrentThread
->Affinity
= CurrentThread
->UserAffinity
;
1037 CurrentThread
->IdealProcessor
= CurrentThread
->UserIdealProcessor
;
1038 CurrentThread
->SystemAffinityActive
= FALSE
;
1040 /* Get the current PRCB and check if it doesn't match this affinity */
1041 Prcb
= KeGetCurrentPrcb();
1042 if (!(Prcb
->SetMember
& CurrentThread
->Affinity
))
1045 KiAcquirePrcbLock(Prcb
);
1047 /* Check if there's no next thread scheduled */
1048 if (!Prcb
->NextThread
)
1050 /* Select a new thread and set it on standby */
1051 NextThread
= KiSelectNextThread(Prcb
);
1052 NextThread
->State
= Standby
;
1053 Prcb
->NextThread
= NextThread
;
1056 /* Release the PRCB lock */
1057 KiReleasePrcbLock(Prcb
);
1060 /* Unlock dispatcher database */
1061 KiReleaseDispatcherLock(OldIrql
);
1069 KeSetIdealProcessorThread(IN PKTHREAD Thread
,
1072 CCHAR OldIdealProcessor
;
1074 ASSERT(Processor
<= MAXIMUM_PROCESSORS
);
1076 /* Lock the Dispatcher Database */
1077 OldIrql
= KiAcquireDispatcherLock();
1079 /* Save Old Ideal Processor */
1080 OldIdealProcessor
= Thread
->UserIdealProcessor
;
1082 /* Make sure a valid CPU was given */
1083 if (Processor
< KeNumberProcessors
)
1085 /* Check if the user ideal CPU is in the affinity */
1086 if (Thread
->Affinity
& AFFINITY_MASK(Processor
))
1088 /* Set the ideal processor */
1089 Thread
->IdealProcessor
= Processor
;
1091 /* Check if system affinity is used */
1092 if (!Thread
->SystemAffinityActive
)
1094 /* It's not, so update the user CPU too */
1095 Thread
->UserIdealProcessor
= Processor
;
1100 /* Release dispatcher lock and return the old ideal CPU */
1101 KiReleaseDispatcherLock(OldIrql
);
1102 return OldIdealProcessor
;
1110 KeSetSystemAffinityThread(IN KAFFINITY Affinity
)
1114 PKTHREAD NextThread
, CurrentThread
= KeGetCurrentThread();
1115 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1116 ASSERT((Affinity
& KeActiveProcessors
) != 0);
1118 /* Lock the Dispatcher Database */
1119 OldIrql
= KiAcquireDispatcherLock();
1121 /* Restore the affinity and enable system affinity */
1122 CurrentThread
->Affinity
= Affinity
;
1123 CurrentThread
->SystemAffinityActive
= TRUE
;
1125 /* Check if the ideal processor is part of the affinity */
1127 if (!(Affinity
& AFFINITY_MASK(CurrentThread
->IdealProcessor
)))
1129 ULONG AffinitySet
, NodeMask
;
1131 /* It's not! Get the PRCB */
1132 Prcb
= KiProcessorBlock
[CurrentThread
->IdealProcessor
];
1134 /* Calculate the affinity set */
1135 AffinitySet
= KeActiveProcessors
& Affinity
;
1136 NodeMask
= Prcb
->ParentNode
->ProcessorMask
& AffinitySet
;
1139 /* Use the Node set instead */
1140 AffinitySet
= NodeMask
;
1143 /* Calculate the ideal CPU from the affinity set */
1144 BitScanReverse(&NodeMask
, AffinitySet
);
1145 CurrentThread
->IdealProcessor
= (UCHAR
)NodeMask
;
1149 /* Get the current PRCB and check if it doesn't match this affinity */
1150 Prcb
= KeGetCurrentPrcb();
1151 if (!(Prcb
->SetMember
& CurrentThread
->Affinity
))
1154 KiAcquirePrcbLock(Prcb
);
1156 /* Check if there's no next thread scheduled */
1157 if (!Prcb
->NextThread
)
1159 /* Select a new thread and set it on standby */
1160 NextThread
= KiSelectNextThread(Prcb
);
1161 NextThread
->State
= Standby
;
1162 Prcb
->NextThread
= NextThread
;
1165 /* Release the PRCB lock */
1166 KiReleasePrcbLock(Prcb
);
1169 /* Unlock dispatcher database */
1170 KiReleaseDispatcherLock(OldIrql
);
1178 KeSetBasePriorityThread(IN PKTHREAD Thread
,
1182 KPRIORITY OldBasePriority
, Priority
, BasePriority
;
1185 ASSERT_THREAD(Thread
);
1186 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1188 /* Get the process */
1189 Process
= Thread
->ApcState
.Process
;
1191 /* Lock the Dispatcher Database */
1192 OldIrql
= KiAcquireDispatcherLock();
1194 /* Lock the thread */
1195 KiAcquireThreadLock(Thread
);
1197 /* Save the old base priority and increment */
1198 OldBasePriority
= Thread
->BasePriority
;
1199 OldIncrement
= OldBasePriority
- Process
->BasePriority
;
1201 /* If priority saturation happened, use the saturated increment */
1202 if (Thread
->Saturation
) OldIncrement
= (HIGH_PRIORITY
+ 1) / 2 *
1205 /* Reset the saturation value */
1206 Thread
->Saturation
= 0;
1208 /* Now check if saturation is being used for the new value */
1209 if (abs(Increment
) >= ((HIGH_PRIORITY
+ 1) / 2))
1211 /* Check if we need positive or negative saturation */
1212 Thread
->Saturation
= (Increment
> 0) ? 1 : -1;
1215 /* Normalize the Base Priority */
1216 BasePriority
= Process
->BasePriority
+ Increment
;
1217 if (Process
->BasePriority
>= LOW_REALTIME_PRIORITY
)
1219 /* Check if it's too low */
1220 if (BasePriority
< LOW_REALTIME_PRIORITY
)
1222 /* Set it to the lowest real time level */
1223 BasePriority
= LOW_REALTIME_PRIORITY
;
1226 /* Check if it's too high */
1227 if (BasePriority
> HIGH_PRIORITY
) BasePriority
= HIGH_PRIORITY
;
1229 /* We are at real time, so use the raw base priority */
1230 Priority
= BasePriority
;
1234 /* Check if it's entering the real time range */
1235 if (BasePriority
>= LOW_REALTIME_PRIORITY
)
1237 /* Set it to the highest dynamic level */
1238 BasePriority
= LOW_REALTIME_PRIORITY
- 1;
1241 /* Check if it's too low and normalize it */
1242 if (BasePriority
<= LOW_PRIORITY
) BasePriority
= 1;
1244 /* Check if Saturation is used */
1245 if (Thread
->Saturation
)
1247 /* Use the raw base priority */
1248 Priority
= BasePriority
;
1252 /* Otherwise, calculate the new priority */
1253 Priority
= KiComputeNewPriority(Thread
, 0);
1254 Priority
+= (BasePriority
- OldBasePriority
);
1256 /* Check if it entered the real-time range */
1257 if (Priority
>= LOW_REALTIME_PRIORITY
)
1259 /* Normalize it down to the highest dynamic priority */
1260 Priority
= LOW_REALTIME_PRIORITY
- 1;
1262 else if (Priority
<= LOW_PRIORITY
)
1264 /* It went too low, normalize it */
1270 /* Finally set the new base priority */
1271 Thread
->BasePriority
= (SCHAR
)BasePriority
;
1273 /* Reset the decrements */
1274 Thread
->PriorityDecrement
= 0;
1276 /* Check if we're changing priority after all */
1277 if (Priority
!= Thread
->Priority
)
1279 /* Reset the quantum and do the actual priority modification */
1280 Thread
->Quantum
= Thread
->QuantumReset
;
1281 KiSetPriorityThread(Thread
, Priority
);
1284 /* Release thread lock */
1285 KiReleaseThreadLock(Thread
);
1287 /* Release the dispatcher database and return old increment */
1288 KiReleaseDispatcherLock(OldIrql
);
1289 return OldIncrement
;
1297 KeSetAffinityThread(IN PKTHREAD Thread
,
1298 IN KAFFINITY Affinity
)
1301 KAFFINITY OldAffinity
;
1302 ASSERT_THREAD(Thread
);
1303 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1305 /* Lock the dispatcher database */
1306 OldIrql
= KiAcquireDispatcherLock();
1308 /* Call the internal function */
1309 OldAffinity
= KiSetAffinityThread(Thread
, Affinity
);
1311 /* Release the dispatcher database and return old affinity */
1312 KiReleaseDispatcherLock(OldIrql
);
1321 KeSetPriorityThread(IN PKTHREAD Thread
,
1322 IN KPRIORITY Priority
)
1325 KPRIORITY OldPriority
;
1326 ASSERT_THREAD(Thread
);
1327 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1328 ASSERT((Priority
<= HIGH_PRIORITY
) && (Priority
>= LOW_PRIORITY
));
1329 ASSERT(KeIsExecutingDpc() == FALSE
);
1331 /* Lock the Dispatcher Database */
1332 OldIrql
= KiAcquireDispatcherLock();
1334 /* Lock the thread */
1335 KiAcquireThreadLock(Thread
);
1337 /* Save the old Priority and reset decrement */
1338 OldPriority
= Thread
->Priority
;
1339 Thread
->PriorityDecrement
= 0;
1341 /* Make sure that an actual change is being done */
1342 if (Priority
!= Thread
->Priority
)
1344 /* Reset the quantum */
1345 Thread
->Quantum
= Thread
->QuantumReset
;
1347 /* Check if priority is being set too low and normalize if so */
1348 if ((Thread
->BasePriority
!= 0) && !(Priority
)) Priority
= 1;
1350 /* Set the new Priority */
1351 KiSetPriorityThread(Thread
, Priority
);
1354 /* Release thread lock */
1355 KiReleaseThreadLock(Thread
);
1357 /* Release the dispatcher database */
1358 KiReleaseDispatcherLock(OldIrql
);
1360 /* Return Old Priority */
1369 KeTerminateThread(IN KPRIORITY Increment
)
1371 PLIST_ENTRY
*ListHead
;
1372 PETHREAD Entry
, SavedEntry
;
1373 PETHREAD
*ThreadAddr
;
1374 KLOCK_QUEUE_HANDLE LockHandle
;
1375 PKTHREAD Thread
= KeGetCurrentThread();
1376 PKPROCESS Process
= Thread
->ApcState
.Process
;
1377 ASSERT_IRQL_LESS_OR_EQUAL(DISPATCH_LEVEL
);
1379 /* Lock the process */
1380 KiAcquireProcessLock(Process
, &LockHandle
);
1382 /* Make sure we won't get Swapped */
1383 KiSetThreadSwapBusy(Thread
);
1385 /* Save the Kernel and User Times */
1386 Process
->KernelTime
+= Thread
->KernelTime
;
1387 Process
->UserTime
+= Thread
->UserTime
;
1389 /* Get the current entry and our Port */
1390 Entry
= (PETHREAD
)PspReaperListHead
.Flink
;
1391 ThreadAddr
= &((PETHREAD
)Thread
)->ReaperLink
;
1393 /* Add it to the reaper's list */
1396 /* Get the list head */
1397 ListHead
= &PspReaperListHead
.Flink
;
1399 /* Link ourselves */
1400 *ThreadAddr
= Entry
;
1403 /* Now try to do the exchange */
1404 Entry
= InterlockedCompareExchangePointer((PVOID
*)ListHead
,
1408 /* Break out if the change was succesful */
1409 } while (Entry
!= SavedEntry
);
1411 /* Acquire the dispatcher lock */
1412 KiAcquireDispatcherLockAtDpcLevel();
1414 /* Check if the reaper wasn't active */
1417 /* Activate it as a work item, directly through its Queue */
1418 KiInsertQueue(&ExWorkerQueue
[HyperCriticalWorkQueue
].WorkerQueue
,
1419 &PspReaperWorkItem
.List
,
1423 /* Check the thread has an associated queue */
1426 /* Remove it from the list, and handle the queue */
1427 RemoveEntryList(&Thread
->QueueListEntry
);
1428 KiActivateWaiterQueue(Thread
->Queue
);
1431 /* Signal the thread */
1432 Thread
->Header
.SignalState
= TRUE
;
1433 if (!IsListEmpty(&Thread
->Header
.WaitListHead
))
1435 /* Unwait the threads */
1436 KxUnwaitThread(&Thread
->Header
, Increment
);
1439 /* Remove the thread from the list */
1440 RemoveEntryList(&Thread
->ThreadListEntry
);
1442 /* Release the process lock */
1443 KiReleaseProcessLockFromDpcLevel(&LockHandle
);
1445 /* Set us as terminated, decrease the Process's stack count */
1446 Thread
->State
= Terminated
;
1448 /* Decrease stack count */
1449 ASSERT(Process
->StackCount
!= 0);
1450 ASSERT(Process
->State
== ProcessInMemory
);
1451 Process
->StackCount
--;
1452 if (!(Process
->StackCount
) && !(IsListEmpty(&Process
->ThreadListHead
)))
1454 /* FIXME: Swap stacks */
1457 /* Rundown arch-specific parts */
1458 KiRundownThread(Thread
);
1460 /* Swap to a new thread */
1461 KiReleaseDispatcherLockFromDpcLevel();
1462 KiSwapThread(Thread
, KeGetCurrentPrcb());