Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2390 lines
59 KiB

  1. /*++
  2. Copyright (c) 1989 Microsoft Corporation
  3. Module Name:
  4. threadobj.c
  5. Abstract:
  6. This module implements the machine independent functions to manipulate
  7. the kernel thread object. Functions are provided to initialize, ready,
  8. alert, test alert, boost priority, enable APC queuing, disable APC
  9. queuing, confine, set affinity, set priority, suspend, resume, alert
  10. resume, terminate, read thread state, freeze, unfreeze, query data
  11. alignment handling mode, force resume, and enter and leave critical
  12. regions for thread objects.
  13. Author:
  14. David N. Cutler (davec) 4-Mar-1989
  15. Environment:
  16. Kernel mode only.
  17. Revision History:
  18. --*/
  19. #include "ki.h"
  20. #pragma alloc_text(INIT, KeInitializeThread)
  21. #pragma alloc_text(PAGE, KeInitThread)
  22. #pragma alloc_text(PAGE, KeUninitThread)
  23. //
  24. // The following assert macro is used to check that an input thread object is
  25. // really a kthread and not something else, like deallocated pool.
  26. //
  27. #define ASSERT_THREAD(E) { \
  28. ASSERT((E)->Header.Type == ThreadObject); \
  29. }
  30. NTSTATUS
  31. KeInitThread (
  32. IN PKTHREAD Thread,
  33. IN PVOID KernelStack OPTIONAL,
  34. IN PKSYSTEM_ROUTINE SystemRoutine,
  35. IN PKSTART_ROUTINE StartRoutine OPTIONAL,
  36. IN PVOID StartContext OPTIONAL,
  37. IN PCONTEXT ContextFrame OPTIONAL,
  38. IN PVOID Teb OPTIONAL,
  39. IN PKPROCESS Process
  40. )
  41. /*++
  42. Routine Description:
  43. This function initializes a thread object. The priority, affinity,
  44. and initial quantum are taken from the parent process object.
  45. N.B. This routine is carefully written so that if an access violation
  46. occurs while reading the specified context frame, then no kernel
  47. data structures will have been modified. It is the responsibility
  48. of the caller to handle the exception and provide necessary clean
  49. up.
  50. N.B. It is assumed that the thread object is zeroed.
  51. Arguments:
  52. Thread - Supplies a pointer to a dispatcher object of type thread.
  53. KernelStack - Supplies a pointer to the base of a kernel stack on which
  54. the context frame for the thread is to be constructed.
  55. SystemRoutine - Supplies a pointer to the system function that is to be
  56. called when the thread is first scheduled for execution.
  57. StartRoutine - Supplies an optional pointer to a function that is to be
  58. called after the system has finished initializing the thread. This
  59. parameter is specified if the thread is a system thread and will
  60. execute totally in kernel mode.
  61. StartContext - Supplies an optional pointer to an arbitrary data structure
  62. which will be passed to the StartRoutine as a parameter. This
  63. parameter is specified if the thread is a system thread and will
  64. execute totally in kernel mode.
  65. ContextFrame - Supplies an optional pointer a context frame which contains
  66. the initial user mode state of the thread. This parameter is specified
  67. if the thread is a user thread and will execute in user mode. If this
  68. parameter is not specified, then the Teb parameter is ignored.
  69. Teb - Supplies an optional pointer to the user mode thread environment
  70. block. This parameter is specified if the thread is a user thread and
  71. will execute in user mode. This parameter is ignored if the ContextFrame
  72. parameter is not specified.
  73. Process - Supplies a pointer to a control object of type process.
  74. Return Value:
  75. None.
  76. --*/
  77. {
  78. LONG Index;
  79. BOOLEAN KernelStackAllocated = FALSE;
  80. PKTIMER Timer;
  81. PKWAIT_BLOCK WaitBlock;
  82. //
  83. // Initialize the standard dispatcher object header and set the initial
  84. // state of the thread object.
  85. //
  86. Thread->Header.Type = ThreadObject;
  87. Thread->Header.Size = sizeof(KTHREAD) / sizeof(LONG);
  88. InitializeListHead(&Thread->Header.WaitListHead);
  89. //
  90. // Initialize the owned mutant listhead.
  91. //
  92. InitializeListHead(&Thread->MutantListHead);
  93. //
  94. // Initialize the thread field of all builtin wait blocks.
  95. //
  96. for (Index = 0; Index < (THREAD_WAIT_OBJECTS + 1); Index += 1) {
  97. Thread->WaitBlock[Index].Thread = Thread;
  98. }
  99. //
  100. // Initialize the alerted, preempted, debugactive, autoalignment,
  101. // kernel stack resident, enable kernel stack swap, and process
  102. // ready queue boolean values.
  103. //
  104. // N.B. Only nonzero values are initialized.
  105. //
  106. Thread->AutoAlignment = Process->AutoAlignment;
  107. Thread->EnableStackSwap = TRUE;
  108. Thread->KernelStackResident = TRUE;
  109. Thread->SwapBusy = FALSE;
  110. //
  111. // Initialize the thread lock and priority adjustment reason.
  112. //
  113. KeInitializeSpinLock(&Thread->ThreadLock);
  114. Thread->AdjustReason = AdjustNone;
  115. //
  116. // Set the system service table pointer to the address of the static
  117. // system service descriptor table. If the thread is later converted
  118. // to a Win32 thread this pointer will be change to a pointer to the
  119. // shadow system service descriptor table.
  120. //
  121. Thread->ServiceTable = (PVOID)&KeServiceDescriptorTable[0];
  122. //
  123. // Initialize the APC state pointers, the current APC state, the saved
  124. // APC state, and enable APC queuing.
  125. //
  126. Thread->ApcStatePointer[0] = &Thread->ApcState;
  127. Thread->ApcStatePointer[1] = &Thread->SavedApcState;
  128. InitializeListHead(&Thread->ApcState.ApcListHead[KernelMode]);
  129. InitializeListHead(&Thread->ApcState.ApcListHead[UserMode]);
  130. Thread->ApcState.Process = Process;
  131. Thread->Process = Process;
  132. Thread->ApcQueueable = TRUE;
  133. //
  134. // Initialize the kernel mode suspend APC and the suspend semaphore object.
  135. // and the builtin wait timeout timer object.
  136. //
  137. KeInitializeApc(&Thread->SuspendApc,
  138. Thread,
  139. OriginalApcEnvironment,
  140. (PKKERNEL_ROUTINE)KiSuspendNop,
  141. (PKRUNDOWN_ROUTINE)KiSuspendRundown,
  142. KiSuspendThread,
  143. KernelMode,
  144. NULL);
  145. KeInitializeSemaphore(&Thread->SuspendSemaphore, 0L, 2L);
  146. //
  147. // Initialize the builtin timer trimer wait wait block.
  148. //
  149. // N.B. This is the only time the wait block is initialized since this
  150. // information is constant.
  151. //
  152. Timer = &Thread->Timer;
  153. KeInitializeTimer(Timer);
  154. WaitBlock = &Thread->WaitBlock[TIMER_WAIT_BLOCK];
  155. WaitBlock->Object = Timer;
  156. WaitBlock->WaitKey = (CSHORT)STATUS_TIMEOUT;
  157. WaitBlock->WaitType = WaitAny;
  158. WaitBlock->WaitListEntry.Flink = &Timer->Header.WaitListHead;
  159. WaitBlock->WaitListEntry.Blink = &Timer->Header.WaitListHead;
  160. //
  161. // Initialize the APC queue spinlock.
  162. //
  163. KeInitializeSpinLock(&Thread->ApcQueueLock);
  164. //
  165. // Initialize the Thread Environment Block (TEB) pointer (can be NULL).
  166. //
  167. Thread->Teb = Teb;
  168. //
  169. // Allocate a kernel stack if necessary and set the initial kernel stack,
  170. // stack base, and stack limit.
  171. //
  172. if (KernelStack == NULL) {
  173. KernelStack = MmCreateKernelStack(FALSE, Process->IdealNode);
  174. if (KernelStack == NULL) {
  175. return STATUS_INSUFFICIENT_RESOURCES;
  176. }
  177. KernelStackAllocated = TRUE;
  178. }
  179. Thread->InitialStack = KernelStack;
  180. Thread->StackBase = KernelStack;
  181. Thread->StackLimit = (PVOID)((ULONG_PTR)KernelStack - KERNEL_STACK_SIZE);
  182. //
  183. // Initialize the thread context.
  184. //
  185. try {
  186. KiInitializeContextThread(Thread,
  187. SystemRoutine,
  188. StartRoutine,
  189. StartContext,
  190. ContextFrame);
  191. } except (EXCEPTION_EXECUTE_HANDLER) {
  192. if (KernelStackAllocated) {
  193. MmDeleteKernelStack(Thread->StackBase, FALSE);
  194. Thread->InitialStack = NULL;
  195. }
  196. return GetExceptionCode();
  197. }
  198. //
  199. // Set the base thread priority, the thread priority, the thread affinity,
  200. // the thread quantum, and the scheduling state.
  201. //
  202. Thread->State = Initialized;
  203. return STATUS_SUCCESS;
  204. }
  205. VOID
  206. KeUninitThread (
  207. IN PKTHREAD Thread
  208. )
  209. /*++
  210. Routine Description:
  211. This function frees the thread kernel stack and must be called before
  212. the thread is started.
  213. Arguments:
  214. Thread - Supplies a pointer to a dispatcher object of type thread.
  215. Return Value:
  216. None.
  217. --*/
  218. {
  219. MmDeleteKernelStack(Thread->StackBase, FALSE);
  220. Thread->InitialStack = NULL;
  221. return;
  222. }
  223. VOID
  224. KeStartThread (
  225. IN PKTHREAD Thread
  226. )
  227. /*++
  228. Routine Description:
  229. This function initializes remaining thread fields and inserts the thread
  230. in the thread's process list. From this point on the thread must run.
  231. Arguments:
  232. Thread - Supplies a pointer to a dispatcher object of type thread.
  233. Return Value:
  234. None.
  235. --*/
  236. {
  237. KLOCK_QUEUE_HANDLE LockHandle;
  238. PKPROCESS Process;
  239. #if !defined(NT_UP)
  240. ULONG IdealProcessor;
  241. KAFFINITY PreferredSet;
  242. #if defined(NT_SMT)
  243. KAFFINITY TempSet;
  244. #endif
  245. #endif
  246. //
  247. // Set thread disable boost and IOPL.
  248. //
  249. Process = Thread->ApcState.Process;
  250. Thread->DisableBoost = Process->DisableBoost;
  251. #if defined(_X86_)
  252. Thread->Iopl = Process->Iopl;
  253. #endif
  254. //
  255. // Initialize the thread quantum and set system affinity false.
  256. //
  257. Thread->Quantum = Process->ThreadQuantum;
  258. Thread->SystemAffinityActive = FALSE;
  259. //
  260. // Raise IRQL to SYNCH_LEVEL and acquire the process lock.
  261. //
  262. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Process->ProcessLock, &LockHandle);
  263. //
  264. // Set the thread priority and affinity.
  265. //
  266. Thread->BasePriority = Process->BasePriority;
  267. Thread->Priority = Thread->BasePriority;
  268. Thread->Affinity = Process->Affinity;
  269. Thread->UserAffinity = Process->Affinity;
  270. //
  271. // Initialize the ideal processor number and node for the thread.
  272. //
  273. // N.B. It is guaranteed that the process affinity intersects the process
  274. // ideal node affinity.
  275. //
  276. #if defined(NT_UP)
  277. Thread->IdealProcessor = 0;
  278. Thread->UserIdealProcessor = 0;
  279. #else
  280. //
  281. // Initialize the ideal processor number.
  282. //
  283. // N.B. It is guaranteed that the process affinity intersects the process
  284. // ideal node affinity.
  285. //
  286. // N.B. The preferred set, however, must be reduced by the process affinity.
  287. //
  288. IdealProcessor = Process->ThreadSeed;
  289. PreferredSet = KeNodeBlock[Process->IdealNode]->ProcessorMask & Process->Affinity;
  290. //
  291. // If possible bias the ideal processor to a different SMT set than the
  292. // last thread.
  293. //
  294. #if defined(NT_SMT)
  295. TempSet = ~KiProcessorBlock[IdealProcessor]->MultiThreadProcessorSet;
  296. if ((PreferredSet & TempSet) != 0) {
  297. PreferredSet &= TempSet;
  298. }
  299. #endif
  300. //
  301. // Find an ideal processor for thread and update the process thread seed.
  302. //
  303. IdealProcessor = KeFindNextRightSetAffinity(IdealProcessor, PreferredSet);
  304. Process->ThreadSeed = (UCHAR)IdealProcessor;
  305. ASSERT((Thread->UserAffinity & AFFINITY_MASK(IdealProcessor)) != 0);
  306. Thread->UserIdealProcessor = (UCHAR)IdealProcessor;
  307. Thread->IdealProcessor = (UCHAR)IdealProcessor;
  308. #endif
  309. //
  310. // Lock the dispatcher database.
  311. //
  312. KiLockDispatcherDatabaseAtSynchLevel();
  313. //
  314. // Insert the thread in the process thread list, and increment the kernel
  315. // stack count.
  316. //
  317. // N.B. The distinguished value MAXSHORT is used to signify that no
  318. // threads have been created for a process.
  319. //
  320. InsertTailList(&Process->ThreadListHead, &Thread->ThreadListEntry);
  321. if (Process->StackCount == MAXSHORT) {
  322. Process->StackCount = 1;
  323. } else {
  324. Process->StackCount += 1;
  325. }
  326. //
  327. // Unlock the dispatcher database, release the process lock, and lower
  328. // IRQL to its previous value.
  329. //
  330. KiUnlockDispatcherDatabaseFromSynchLevel();
  331. KeReleaseInStackQueuedSpinLock(&LockHandle);
  332. return;
  333. }
  334. NTSTATUS
  335. KeInitializeThread (
  336. IN PKTHREAD Thread,
  337. IN PVOID KernelStack OPTIONAL,
  338. IN PKSYSTEM_ROUTINE SystemRoutine,
  339. IN PKSTART_ROUTINE StartRoutine OPTIONAL,
  340. IN PVOID StartContext OPTIONAL,
  341. IN PCONTEXT ContextFrame OPTIONAL,
  342. IN PVOID Teb OPTIONAL,
  343. IN PKPROCESS Process
  344. )
  345. /*++
  346. Routine Description:
  347. This function initializes a thread object. The priority, affinity,
  348. and initial quantum are taken from the parent process object. The
  349. thread object is inserted at the end of the thread list for the
  350. parent process.
  351. N.B. This routine is carefully written so that if an access violation
  352. occurs while reading the specified context frame, then no kernel
  353. data structures will have been modified. It is the responsibility
  354. of the caller to handle the exception and provide necessary clean
  355. up.
  356. N.B. It is assumed that the thread object is zeroed.
  357. Arguments:
  358. Thread - Supplies a pointer to a dispatcher object of type thread.
  359. KernelStack - Supplies a pointer to the base of a kernel stack on which
  360. the context frame for the thread is to be constructed.
  361. SystemRoutine - Supplies a pointer to the system function that is to be
  362. called when the thread is first scheduled for execution.
  363. StartRoutine - Supplies an optional pointer to a function that is to be
  364. called after the system has finished initializing the thread. This
  365. parameter is specified if the thread is a system thread and will
  366. execute totally in kernel mode.
  367. StartContext - Supplies an optional pointer to an arbitrary data structure
  368. which will be passed to the StartRoutine as a parameter. This
  369. parameter is specified if the thread is a system thread and will
  370. execute totally in kernel mode.
  371. ContextFrame - Supplies an optional pointer a context frame which contains
  372. the initial user mode state of the thread. This parameter is specified
  373. if the thread is a user thread and will execute in user mode. If this
  374. parameter is not specified, then the Teb parameter is ignored.
  375. Teb - Supplies an optional pointer to the user mode thread environment
  376. block. This parameter is specified if the thread is a user thread and
  377. will execute in user mode. This parameter is ignored if the ContextFrame
  378. parameter is not specified.
  379. Process - Supplies a pointer to a control object of type process.
  380. Return Value:
  381. NTSTATUS - Status of operation
  382. --*/
  383. {
  384. NTSTATUS Status;
  385. Status = KeInitThread(Thread,
  386. KernelStack,
  387. SystemRoutine,
  388. StartRoutine,
  389. StartContext,
  390. ContextFrame,
  391. Teb,
  392. Process);
  393. if (!NT_SUCCESS(Status)) {
  394. return Status;
  395. }
  396. KeStartThread(Thread);
  397. return STATUS_SUCCESS;
  398. }
  399. BOOLEAN
  400. KeAlertThread (
  401. IN PKTHREAD Thread,
  402. IN KPROCESSOR_MODE AlertMode
  403. )
  404. /*++
  405. Routine Description:
  406. This function attempts to alert a thread and cause its execution to
  407. be continued if it is currently in an alertable Wait state. Otherwise
  408. it just sets the alerted variable for the specified processor mode.
  409. Arguments:
  410. Thread - Supplies a pointer to a dispatcher object of type thread.
  411. AlertMode - Supplies the processor mode for which the thread is
  412. to be alerted.
  413. Return Value:
  414. The previous state of the alerted variable for the specified processor
  415. mode.
  416. --*/
  417. {
  418. BOOLEAN Alerted;
  419. KLOCK_QUEUE_HANDLE LockHandle;
  420. ASSERT_THREAD(Thread);
  421. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  422. //
  423. // Raise IRQL to SYNCH_LEVEL, acquire the thread APC queue lock, and lock
  424. // the dispatcher database.
  425. //
  426. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock, &LockHandle);
  427. KiLockDispatcherDatabaseAtSynchLevel();
  428. //
  429. // Capture the current state of the alerted variable for the specified
  430. // processor mode.
  431. //
  432. Alerted = Thread->Alerted[AlertMode];
  433. //
  434. // If the alerted state for the specified processor mode is Not-Alerted,
  435. // then attempt to alert the thread.
  436. //
  437. if (Alerted == FALSE) {
  438. //
  439. // If the thread is currently in a Wait state, the Wait is alertable,
  440. // and the specified processor mode is less than or equal to the Wait
  441. // mode, then the thread is unwaited with a status of "alerted".
  442. //
  443. if ((Thread->State == Waiting) && (Thread->Alertable == TRUE) &&
  444. (AlertMode <= Thread->WaitMode)) {
  445. KiUnwaitThread(Thread, STATUS_ALERTED, ALERT_INCREMENT);
  446. } else {
  447. Thread->Alerted[AlertMode] = TRUE;
  448. }
  449. }
  450. //
  451. // Unlock the dispatcher database from SYNCH_LEVEL, release the thread
  452. // APC queue lock, exit the scheduler, and return the previous alerted
  453. // state for the specified mode.
  454. //
  455. KiUnlockDispatcherDatabaseFromSynchLevel();
  456. KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);
  457. KiExitDispatcher(LockHandle.OldIrql);
  458. return Alerted;
  459. }
  460. ULONG
  461. KeAlertResumeThread (
  462. IN PKTHREAD Thread
  463. )
  464. /*++
  465. Routine Description:
  466. This function attempts to alert a thread in kernel mode and cause its
  467. execution to be continued if it is currently in an alertable Wait state.
  468. In addition, a resume operation is performed on the specified thread.
  469. Arguments:
  470. Thread - Supplies a pointer to a dispatcher object of type thread.
  471. Return Value:
  472. The previous suspend count.
  473. --*/
  474. {
  475. KLOCK_QUEUE_HANDLE LockHandle;
  476. ULONG OldCount;
  477. ASSERT_THREAD(Thread);
  478. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  479. //
  480. // Raise IRQL to SYNCH_LEVEL, acquire the thread APC queue lock, and lock
  481. // the dispatcher database.
  482. //
  483. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock, &LockHandle);
  484. KiLockDispatcherDatabaseAtSynchLevel();
  485. //
  486. // If the kernel mode alerted state is FALSE, then attempt to alert
  487. // the thread for kernel mode.
  488. //
  489. if (Thread->Alerted[KernelMode] == FALSE) {
  490. //
  491. // If the thread is currently in a Wait state and the Wait is alertable,
  492. // then the thread is unwaited with a status of "alerted". Else set the
  493. // kernel mode alerted variable.
  494. //
  495. if ((Thread->State == Waiting) && (Thread->Alertable == TRUE)) {
  496. KiUnwaitThread(Thread, STATUS_ALERTED, ALERT_INCREMENT);
  497. } else {
  498. Thread->Alerted[KernelMode] = TRUE;
  499. }
  500. }
  501. //
  502. // Capture the current suspend count.
  503. //
  504. OldCount = Thread->SuspendCount;
  505. //
  506. // If the thread is currently suspended, then decrement its suspend count.
  507. //
  508. if (OldCount != 0) {
  509. Thread->SuspendCount -= 1;
  510. //
  511. // If the resultant suspend count is zero and the freeze count is
  512. // zero, then resume the thread by releasing its suspend semaphore.
  513. //
  514. if ((Thread->SuspendCount == 0) && (Thread->FreezeCount == 0)) {
  515. Thread->SuspendSemaphore.Header.SignalState += 1;
  516. KiWaitTest(&Thread->SuspendSemaphore, RESUME_INCREMENT);
  517. }
  518. }
  519. //
  520. // Unlock the dispatcher database from SYNCH_LEVEL, release the thread
  521. // APC queue lock, exit the scheduler, and return the previous suspend
  522. // count.
  523. //
  524. KiUnlockDispatcherDatabaseFromSynchLevel();
  525. KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);
  526. KiExitDispatcher(LockHandle.OldIrql);
  527. return OldCount;
  528. }
  529. VOID
  530. KeBoostPriorityThread (
  531. IN PKTHREAD Thread,
  532. IN KPRIORITY Increment
  533. )
  534. /*++
  535. Routine Description:
  536. This function boosts the priority of the specified thread using the
  537. same algorithm used when a thread gets a boost from a wait operation.
  538. Arguments:
  539. Thread - Supplies a pointer to a dispatcher object of type thread.
  540. Increment - Supplies the priority increment that is to be applied to
  541. the thread's priority.
  542. Return Value:
  543. None.
  544. --*/
  545. {
  546. KIRQL OldIrql;
  547. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  548. //
  549. // Raise IRQL to dispatcher level and lock dispatcher database.
  550. //
  551. KiLockDispatcherDatabase(&OldIrql);
  552. //
  553. // If the thread does not run at a realtime priority level, then boost
  554. // the thread priority.
  555. //
  556. if (Thread->Priority < LOW_REALTIME_PRIORITY) {
  557. KiBoostPriorityThread(Thread, Increment);
  558. }
  559. //
  560. // Unlock dispatcher database and lower IRQL to its previous
  561. // value.
  562. //
  563. KiUnlockDispatcherDatabase(OldIrql);
  564. return;
  565. }
  566. ULONG
  567. KeForceResumeThread (
  568. IN PKTHREAD Thread
  569. )
  570. /*++
  571. Routine Description:
  572. This function forces resumption of thread execution if the thread is
  573. suspended. If the specified thread is not suspended, then no operation
  574. is performed.
  575. Arguments:
  576. Thread - Supplies a pointer to a dispatcher object of type thread.
  577. Return Value:
  578. The sum of the previous suspend count and the freeze count.
  579. --*/
  580. {
  581. KLOCK_QUEUE_HANDLE LockHandle;
  582. ULONG OldCount;
  583. ASSERT_THREAD(Thread);
  584. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  585. //
  586. // Raise IRQL to SYNCH_LEVEL and acquire the thread APC queue lock.
  587. //
  588. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock,
  589. &LockHandle);
  590. //
  591. // Capture the current suspend count.
  592. //
  593. OldCount = Thread->SuspendCount + Thread->FreezeCount;
  594. //
  595. // If the thread is currently suspended, then force resumption of
  596. // thread execution.
  597. //
  598. if (OldCount != 0) {
  599. Thread->FreezeCount = 0;
  600. Thread->SuspendCount = 0;
  601. KiLockDispatcherDatabaseAtSynchLevel();
  602. Thread->SuspendSemaphore.Header.SignalState += 1;
  603. KiWaitTest(&Thread->SuspendSemaphore, RESUME_INCREMENT);
  604. KiUnlockDispatcherDatabaseFromSynchLevel();
  605. }
  606. //
  607. // Unlock he thread APC queue lock, exit the scheduler, and return the
  608. // previous suspend count.
  609. //
  610. KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);
  611. KiExitDispatcher(LockHandle.OldIrql);
  612. return OldCount;
  613. }
  614. VOID
  615. KeFreezeAllThreads (
  616. VOID
  617. )
  618. /*++
  619. Routine Description:
  620. This function suspends the execution of all thread in the current
  621. process except the current thread. If the freeze count overflows
  622. the maximum suspend count, then a condition is raised.
  623. Arguments:
  624. None.
  625. Return Value:
  626. None.
  627. --*/
  628. {
  629. PKTHREAD CurrentThread;
  630. PLIST_ENTRY ListHead;
  631. PLIST_ENTRY NextEntry;
  632. PKPROCESS Process;
  633. KLOCK_QUEUE_HANDLE ProcessHandle;
  634. PKTHREAD Thread;
  635. KLOCK_QUEUE_HANDLE ThreadHandle;
  636. ULONG OldCount;
  637. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  638. //
  639. // Set the address of the current thread object and the current process
  640. // object.
  641. //
  642. CurrentThread = KeGetCurrentThread();
  643. Process = CurrentThread->ApcState.Process;
  644. //
  645. // Raise IRQL to SYNCH_LEVEL and acquire the process lock.
  646. //
  647. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Process->ProcessLock,
  648. &ProcessHandle);
  649. //
  650. // If the freeze count of the current thread is not zero, then there
  651. // is another thread that is trying to freeze this thread. Unlock the
  652. // the process lock and lower IRQL to its previous value, allow the
  653. // suspend APC to occur, then raise IRQL to SYNCH_LEVEL and lock the
  654. // process lock.
  655. //
  656. while (CurrentThread->FreezeCount != 0) {
  657. KeReleaseInStackQueuedSpinLock(&ProcessHandle);
  658. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Process->ProcessLock,
  659. &ProcessHandle);
  660. }
  661. KeEnterCriticalRegion();
  662. //
  663. // Freeze all threads except the current thread.
  664. //
  665. ListHead = &Process->ThreadListHead;
  666. NextEntry = ListHead->Flink;
  667. do {
  668. //
  669. // Get the address of the next thread.
  670. //
  671. Thread = CONTAINING_RECORD(NextEntry, KTHREAD, ThreadListEntry);
  672. //
  673. // Acquire the thread APC queue lock.
  674. //
  675. KeAcquireInStackQueuedSpinLockAtDpcLevel(&Thread->ApcQueueLock,
  676. &ThreadHandle);
  677. //
  678. // If the thread is not the current thread and APCs are queueable,
  679. // then attempt to suspend the thread.
  680. //
  681. if ((Thread != CurrentThread) && (Thread->ApcQueueable == TRUE)) {
  682. //
  683. // Increment the freeze count. If the thread was not previously
  684. // suspended, then queue the thread's suspend APC.
  685. //
  686. OldCount = Thread->FreezeCount;
  687. ASSERT(OldCount != MAXIMUM_SUSPEND_COUNT);
  688. Thread->FreezeCount += 1;
  689. if ((OldCount == 0) && (Thread->SuspendCount == 0)) {
  690. if (Thread->SuspendApc.Inserted == TRUE) {
  691. KiLockDispatcherDatabaseAtSynchLevel();
  692. Thread->SuspendSemaphore.Header.SignalState -= 1;
  693. KiUnlockDispatcherDatabaseFromSynchLevel();
  694. } else {
  695. Thread->SuspendApc.Inserted = TRUE;
  696. KiInsertQueueApc(&Thread->SuspendApc, RESUME_INCREMENT);
  697. }
  698. }
  699. }
  700. //
  701. // Release the thread APC queue lock.
  702. //
  703. KeReleaseInStackQueuedSpinLockFromDpcLevel(&ThreadHandle);
  704. NextEntry = NextEntry->Flink;
  705. } while (NextEntry != ListHead);
  706. //
  707. // Release the process lock and exit the scheduler.
  708. //
  709. KeReleaseInStackQueuedSpinLockFromDpcLevel(&ProcessHandle);
  710. KiExitDispatcher(ProcessHandle.OldIrql);
  711. return;
  712. }
  713. BOOLEAN
  714. KeQueryAutoAlignmentThread (
  715. IN PKTHREAD Thread
  716. )
  717. /*++
  718. Routine Description:
  719. This function returns the data alignment handling mode for the specified
  720. thread.
  721. Arguments:
  722. None.
  723. Return Value:
  724. A value of TRUE is returned if data alignment exceptions are being
  725. automatically handled by the kernel. Otherwise, a value of FALSE
  726. is returned.
  727. --*/
  728. {
  729. ASSERT_THREAD(Thread);
  730. return Thread->AutoAlignment;
  731. }
  732. LONG
  733. KeQueryBasePriorityThread (
  734. IN PKTHREAD Thread
  735. )
  736. /*++
  737. Routine Description:
  738. This function returns the base priority increment of the specified
  739. thread.
  740. Arguments:
  741. Thread - Supplies a pointer to a dispatcher object of type thread.
  742. Return Value:
  743. The base priority increment of the specified thread.
  744. --*/
  745. {
  746. LONG Increment;
  747. KIRQL OldIrql;
  748. PKPROCESS Process;
  749. ASSERT_THREAD(Thread);
  750. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  751. //
  752. // Raise IRQL to SYNCH level and acquire the thread lock.
  753. //
  754. Process = Thread->Process;
  755. OldIrql = KeRaiseIrqlToSynchLevel();
  756. KiAcquireThreadLock(Thread);
  757. //
  758. // If priority saturation occured the last time the thread base priority
  759. // was set, then return the saturation increment value. Otherwise, compute
  760. // the increment value as the difference between the thread base priority
  761. // and the process base priority.
  762. //
  763. Increment = Thread->BasePriority - Process->BasePriority;
  764. if (Thread->Saturation != 0) {
  765. Increment = ((HIGH_PRIORITY + 1) / 2) * Thread->Saturation;
  766. }
  767. //
  768. // Release the thread lock, lower IRQL to its previous value, and
  769. // return the previous thread base priority increment.
  770. //
  771. KiReleaseThreadLock(Thread);
  772. KeLowerIrql(OldIrql);
  773. return Increment;
  774. }
  775. KPRIORITY
  776. KeQueryPriorityThread (
  777. IN PKTHREAD Thread
  778. )
  779. /*++
  780. Routine Description:
  781. This function returns the current priority of the specified thread.
  782. Arguments:
  783. Thread - Supplies a pointer to a dispatcher object of type thread.
  784. Return Value:
  785. The current priority of the specified thread.
  786. --*/
  787. {
  788. ASSERT_THREAD(Thread);
  789. return Thread->Priority;
  790. }
  791. ULONG
  792. KeQueryRuntimeThread (
  793. IN PKTHREAD Thread,
  794. OUT PULONG UserTime
  795. )
  796. /*++
  797. Routine Description:
  798. This function returns the kernel and user runtime for the specified
  799. thread.
  800. Arguments:
  801. Thread - Supplies a pointer to a dispatcher object of type thread.
  802. UserTime - Supplies a pointer to a variable that receives the user
  803. runtime for the specified thread.
  804. Return Value:
  805. The kernel runtime for the specfied thread is returned.
  806. --*/
  807. {
  808. ASSERT_THREAD(Thread);
  809. *UserTime = Thread->UserTime;
  810. return Thread->KernelTime;
  811. }
  812. BOOLEAN
  813. KeReadStateThread (
  814. IN PKTHREAD Thread
  815. )
  816. /*++
  817. Routine Description:
  818. This function reads the current signal state of a thread object.
  819. Arguments:
  820. Thread - Supplies a pointer to a dispatcher object of type thread.
  821. Return Value:
  822. The current signal state of the thread object.
  823. --*/
  824. {
  825. ASSERT_THREAD(Thread);
  826. //
  827. // Return current signal state of thread object.
  828. //
  829. return (BOOLEAN)Thread->Header.SignalState;
  830. }
  831. VOID
  832. KeReadyThread (
  833. IN PKTHREAD Thread
  834. )
  835. /*++
  836. Routine Description:
  837. This function readies a thread for execution. If the thread's process
  838. is currently not in the balance set, then the thread is inserted in the
  839. thread's process' ready queue. Else if the thread is higher priority than
  840. another thread that is currently running on a processor then the thread
  841. is selected for execution on that processor. Else the thread is inserted
  842. in the dispatcher ready queue selected by its priority.
  843. Arguments:
  844. Thread - Supplies a pointer to a dispatcher object of type thread.
  845. Return Value:
  846. None.
  847. --*/
  848. {
  849. KIRQL OldIrql;
  850. ASSERT_THREAD(Thread);
  851. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  852. //
  853. // Raise IRQL to dispatcher level, lock dispatcher database, ready the
  854. // specified thread for execution, unlock the dispatcher database, and
  855. // lower IRQL to its previous value.
  856. //
  857. KiLockDispatcherDatabase(&OldIrql);
  858. KiReadyThread(Thread);
  859. KiUnlockDispatcherDatabase(OldIrql);
  860. return;
  861. }
  862. ULONG
  863. KeResumeThread (
  864. IN PKTHREAD Thread
  865. )
  866. /*++
  867. Routine Description:
  868. This function resumes the execution of a suspended thread. If the
  869. specified thread is not suspended, then no operation is performed.
  870. Arguments:
  871. Thread - Supplies a pointer to a dispatcher object of type thread.
  872. Return Value:
  873. The previous suspend count.
  874. --*/
  875. {
  876. KLOCK_QUEUE_HANDLE LockHandle;
  877. ULONG OldCount;
  878. ASSERT_THREAD(Thread);
  879. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  880. //
  881. // Raise IRQL to SYNCH_LEVEL and lock the thread APC queue.
  882. //
  883. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock,
  884. &LockHandle);
  885. //
  886. // Capture the current suspend count.
  887. //
  888. OldCount = Thread->SuspendCount;
  889. //
  890. // If the thread is currently suspended, then decrement its suspend count.
  891. //
  892. if (OldCount != 0) {
  893. Thread->SuspendCount -= 1;
  894. //
  895. // If the resultant suspend count is zero and the freeze count is
  896. // zero, then resume the thread by releasing its suspend semaphore.
  897. //
  898. if ((Thread->SuspendCount == 0) && (Thread->FreezeCount == 0)) {
  899. KiLockDispatcherDatabaseAtSynchLevel();
  900. Thread->SuspendSemaphore.Header.SignalState += 1;
  901. KiWaitTest(&Thread->SuspendSemaphore, RESUME_INCREMENT);
  902. KiUnlockDispatcherDatabaseFromSynchLevel();
  903. }
  904. }
  905. //
  906. // Release the thread APC queue, exit the scheduler, and return the
  907. // previous suspend count.
  908. //
  909. KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);
  910. KiExitDispatcher(LockHandle.OldIrql);
  911. return OldCount;
  912. }
  913. VOID
  914. KeRevertToUserAffinityThread (
  915. VOID
  916. )
  917. /*++
  918. Routine Description:
  919. This function setss the affinity of the current thread to its user
  920. affinity.
  921. Arguments:
  922. None.
  923. Return Value:
  924. None.
  925. --*/
  926. {
  927. PKTHREAD CurrentThread;
  928. PKTHREAD NewThread;
  929. KIRQL OldIrql;
  930. PKPRCB Prcb;
  931. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  932. //
  933. // Raise IRQL to dispatcher level and lock dispatcher database.
  934. //
  935. CurrentThread = KeGetCurrentThread();
  936. ASSERT(CurrentThread->SystemAffinityActive != FALSE);
  937. KiLockDispatcherDatabase(&OldIrql);
  938. //
  939. // Set the current affinity to the user affinity and the ideal processor
  940. // to the user ideal processor.
  941. //
  942. CurrentThread->Affinity = CurrentThread->UserAffinity;
  943. #if !defined(NT_UP)
  944. CurrentThread->IdealProcessor = CurrentThread->UserIdealProcessor;
  945. #endif
  946. CurrentThread->SystemAffinityActive = FALSE;
  947. //
  948. // If the current processor is not in the new affinity set and another
  949. // thread has not already been selected for execution on the current
  950. // processor, then select a new thread for the current processor.
  951. //
  952. Prcb = KeGetCurrentPrcb();
  953. if ((Prcb->SetMember & CurrentThread->Affinity) == 0) {
  954. KiAcquirePrcbLock(Prcb);
  955. if (Prcb->NextThread == NULL) {
  956. NewThread = KiSelectNextThread(Prcb);
  957. NewThread->State = Standby;
  958. Prcb->NextThread = NewThread;
  959. }
  960. KiReleasePrcbLock(Prcb);
  961. }
  962. //
  963. // Unlock dispatcher database and lower IRQL to its previous value.
  964. //
  965. KiUnlockDispatcherDatabase(OldIrql);
  966. return;
  967. }
  968. VOID
  969. KeRundownThread (
  970. VOID
  971. )
  972. /*++
  973. Routine Description:
  974. This function is called by the executive to rundown thread structures
  975. which must be guarded by the dispatcher database lock and which must
  976. be processed before actually terminating the thread. An example of such
  977. a structure is the mutant ownership list that is anchored in the kernel
  978. thread object.
  979. Arguments:
  980. None.
  981. Return Value:
  982. None.
  983. --*/
  984. {
  985. PKMUTANT Mutant;
  986. PLIST_ENTRY NextEntry;
  987. KIRQL OldIrql;
  988. PKTHREAD Thread;
  989. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  990. //
  991. // If the mutant list is empty, then return immediately.
  992. //
  993. Thread = KeGetCurrentThread();
  994. if (IsListEmpty(&Thread->MutantListHead)) {
  995. return;
  996. }
  997. //
  998. // Raise IRQL to dispatcher level and lock dispatcher database.
  999. //
  1000. KiLockDispatcherDatabase(&OldIrql);
  1001. //
  1002. // Scan the list of owned mutant objects and release the mutant objects
  1003. // with an abandoned status. If the mutant is a kernel mutex, then bug
  1004. // check.
  1005. //
  1006. NextEntry = Thread->MutantListHead.Flink;
  1007. while (NextEntry != &Thread->MutantListHead) {
  1008. Mutant = CONTAINING_RECORD(NextEntry, KMUTANT, MutantListEntry);
  1009. if (Mutant->ApcDisable != 0) {
  1010. KeBugCheckEx(THREAD_TERMINATE_HELD_MUTEX,
  1011. (ULONG_PTR)Thread,
  1012. (ULONG_PTR)Mutant, 0, 0);
  1013. }
  1014. RemoveEntryList(&Mutant->MutantListEntry);
  1015. Mutant->Header.SignalState = 1;
  1016. Mutant->Abandoned = TRUE;
  1017. Mutant->OwnerThread = (PKTHREAD)NULL;
  1018. if (IsListEmpty(&Mutant->Header.WaitListHead) != TRUE) {
  1019. KiWaitTest(Mutant, MUTANT_INCREMENT);
  1020. }
  1021. NextEntry = Thread->MutantListHead.Flink;
  1022. }
  1023. //
  1024. // Release dispatcher database lock and lower IRQL to its previous value.
  1025. //
  1026. KiUnlockDispatcherDatabase(OldIrql);
  1027. return;
  1028. }
  1029. KAFFINITY
  1030. KeSetAffinityThread (
  1031. IN PKTHREAD Thread,
  1032. IN KAFFINITY Affinity
  1033. )
  1034. /*++
  1035. Routine Description:
  1036. This function sets the affinity of a specified thread to a new value.
  1037. Arguments:
  1038. Thread - Supplies a pointer to a dispatcher object of type thread.
  1039. Affinity - Supplies the new of set of processors on which the thread
  1040. can run.
  1041. Return Value:
  1042. The previous affinity of the specified thread.
  1043. --*/
  1044. {
  1045. KAFFINITY OldAffinity;
  1046. KIRQL OldIrql;
  1047. ASSERT_THREAD(Thread);
  1048. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  1049. //
  1050. // Raise IRQL to dispatcher level and lock dispatcher database.
  1051. //
  1052. KiLockDispatcherDatabase(&OldIrql);
  1053. //
  1054. // Set the thread affinity to the specified value.
  1055. //
  1056. OldAffinity = KiSetAffinityThread(Thread, Affinity);
  1057. //
  1058. // Unlock dispatcher database, lower IRQL to its previous value, and
  1059. // return the previous user affinity.
  1060. //
  1061. KiUnlockDispatcherDatabase(OldIrql);
  1062. return OldAffinity;
  1063. }
  1064. VOID
  1065. KeSetSystemAffinityThread (
  1066. IN KAFFINITY Affinity
  1067. )
  1068. /*++
  1069. Routine Description:
  1070. This function set the system affinity of the current thread.
  1071. Arguments:
  1072. Affinity - Supplies the new of set of processors on which the thread
  1073. can run.
  1074. Return Value:
  1075. None.
  1076. --*/
  1077. {
  1078. PKTHREAD CurrentThread;
  1079. #if !defined(NT_UP)
  1080. ULONG IdealProcessor;
  1081. PKNODE Node;
  1082. KAFFINITY TempSet;
  1083. #endif
  1084. PKTHREAD NewThread;
  1085. KIRQL OldIrql;
  1086. PKPRCB Prcb;
  1087. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  1088. ASSERT((Affinity & KeActiveProcessors) != 0);
  1089. //
  1090. // Raise IRQL to dispatcher level and lock dispatcher database.
  1091. //
  1092. CurrentThread = KeGetCurrentThread();
  1093. KiLockDispatcherDatabase(&OldIrql);
  1094. //
  1095. // Set the current affinity to the specified affinity and set system
  1096. // affinity active.
  1097. //
  1098. CurrentThread->Affinity = Affinity;
  1099. CurrentThread->SystemAffinityActive = TRUE;
  1100. //
  1101. // If the ideal processor is not a member of the new affinity set, then
  1102. // recompute the ideal processor.
  1103. //
  1104. // N.B. System affinity is only set temporarily, and therefore, the
  1105. // ideal processor is set to a convenient value if it is not
  1106. // already a member of the new affinity set.
  1107. //
  1108. #if !defined(NT_UP)
  1109. if ((Affinity & AFFINITY_MASK(CurrentThread->IdealProcessor)) == 0) {
  1110. TempSet = Affinity & KeActiveProcessors;
  1111. Node = KiProcessorBlock[CurrentThread->IdealProcessor]->ParentNode;
  1112. if ((TempSet & Node->ProcessorMask) != 0) {
  1113. TempSet &= Node->ProcessorMask;
  1114. }
  1115. KeFindFirstSetLeftAffinity(TempSet, &IdealProcessor);
  1116. CurrentThread->IdealProcessor = (UCHAR)IdealProcessor;
  1117. }
  1118. #endif
  1119. //
  1120. // If the current processor is not in the new affinity set and another
  1121. // thread has not already been selected for execution on the current
  1122. // processor, then select a new thread for the current processor.
  1123. //
  1124. Prcb = KeGetCurrentPrcb();
  1125. if ((Prcb->SetMember & CurrentThread->Affinity) == 0) {
  1126. KiAcquirePrcbLock(Prcb);
  1127. if (Prcb->NextThread == NULL) {
  1128. NewThread = KiSelectNextThread(Prcb);
  1129. NewThread->State = Standby;
  1130. Prcb->NextThread = NewThread;
  1131. }
  1132. KiReleasePrcbLock(Prcb);
  1133. }
  1134. //
  1135. // Unlock dispatcher database and lower IRQL to its previous value.
  1136. //
  1137. KiUnlockDispatcherDatabase(OldIrql);
  1138. return;
  1139. }
  1140. LONG
  1141. KeSetBasePriorityThread (
  1142. IN PKTHREAD Thread,
  1143. IN LONG Increment
  1144. )
  1145. /*++
  1146. Routine Description:
  1147. This function sets the base priority of the specified thread to a
  1148. new value. The new base priority for the thread is the process base
  1149. priority plus the increment.
  1150. Arguments:
  1151. Thread - Supplies a pointer to a dispatcher object of type thread.
  1152. Increment - Supplies the base priority increment of the subject thread.
  1153. N.B. If the absolute value of the increment is such that saturation
  1154. of the base priority is forced, then subsequent changes to the
  1155. parent process base priority will not change the base priority
  1156. of the thread.
  1157. Return Value:
  1158. The previous base priority increment of the specified thread.
  1159. --*/
  1160. {
  1161. KPRIORITY NewBase;
  1162. KPRIORITY NewPriority;
  1163. KPRIORITY OldBase;
  1164. LONG OldIncrement;
  1165. KIRQL OldIrql;
  1166. PKPROCESS Process;
  1167. ASSERT_THREAD(Thread);
  1168. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  1169. //
  1170. // Raise IRQL to dispatcher level and lock dispatcher database.
  1171. //
  1172. Process = Thread->Process;
  1173. KiLockDispatcherDatabase(&OldIrql);
  1174. //
  1175. // Acquire the thread lock, capture the base priority of the specified
  1176. // thread, and determine whether saturation if being forced.
  1177. //
  1178. KiAcquireThreadLock(Thread);
  1179. OldBase = Thread->BasePriority;
  1180. OldIncrement = OldBase - Process->BasePriority;
  1181. if (Thread->Saturation != 0) {
  1182. OldIncrement = ((HIGH_PRIORITY + 1) / 2) * Thread->Saturation;
  1183. }
  1184. Thread->Saturation = FALSE;
  1185. if (abs(Increment) >= (HIGH_PRIORITY + 1) / 2) {
  1186. Thread->Saturation = (Increment > 0) ? 1 : -1;
  1187. }
  1188. //
  1189. // Set the base priority of the specified thread. If the thread's process
  1190. // is in the realtime class, then limit the change to the realtime class.
  1191. // Otherwise, limit the change to the variable class.
  1192. //
  1193. NewBase = Process->BasePriority + Increment;
  1194. if (Process->BasePriority >= LOW_REALTIME_PRIORITY) {
  1195. if (NewBase < LOW_REALTIME_PRIORITY) {
  1196. NewBase = LOW_REALTIME_PRIORITY;
  1197. } else if (NewBase > HIGH_PRIORITY) {
  1198. NewBase = HIGH_PRIORITY;
  1199. }
  1200. //
  1201. // Set the new priority of the thread to the new base priority.
  1202. //
  1203. NewPriority = NewBase;
  1204. } else {
  1205. if (NewBase >= LOW_REALTIME_PRIORITY) {
  1206. NewBase = LOW_REALTIME_PRIORITY - 1;
  1207. } else if (NewBase <= LOW_PRIORITY) {
  1208. NewBase = 1;
  1209. }
  1210. //
  1211. // Compute the new thread priority.
  1212. //
  1213. if (Thread->Saturation != 0) {
  1214. NewPriority = NewBase;
  1215. } else {
  1216. //
  1217. // Compute the new thread priority.
  1218. //
  1219. NewPriority = KiComputeNewPriority(Thread, 0);
  1220. NewPriority += (NewBase - OldBase);
  1221. if (NewPriority >= LOW_REALTIME_PRIORITY) {
  1222. NewPriority = LOW_REALTIME_PRIORITY - 1;
  1223. } else if (NewPriority <= LOW_PRIORITY) {
  1224. NewPriority = 1;
  1225. }
  1226. }
  1227. }
  1228. //
  1229. // Set the new base priority and clear the priority decrement. If the
  1230. // new priority is not equal to the old priority, then set the new thread
  1231. // priority.
  1232. //
  1233. Thread->PriorityDecrement = 0;
  1234. Thread->BasePriority = (SCHAR)NewBase;
  1235. if (NewPriority != Thread->Priority) {
  1236. Thread->Quantum = Process->ThreadQuantum;
  1237. KiSetPriorityThread(Thread, NewPriority);
  1238. }
  1239. //
  1240. // Release the thread lock, unlock the dispatcher database, lower IRQL to
  1241. // its previous value, and return the previous thread base priority.
  1242. //
  1243. KiReleaseThreadLock(Thread);
  1244. KiUnlockDispatcherDatabase(OldIrql);
  1245. return OldIncrement;
  1246. }
  1247. LOGICAL
  1248. KeSetDisableBoostThread (
  1249. IN PKTHREAD Thread,
  1250. IN LOGICAL Disable
  1251. )
  1252. /*++
  1253. Routine Description:
  1254. This function disables priority boosts for the specified thread.
  1255. Arguments:
  1256. Thread - Supplies a pointer to a dispatcher object of type thread.
  1257. Disable - Supplies a logical value that determines whether priority
  1258. boosts for the thread are disabled or enabled.
  1259. Return Value:
  1260. The previous value of the disable boost state variable.
  1261. --*/
  1262. {
  1263. LOGICAL DisableBoost;
  1264. KIRQL OldIrql;
  1265. ASSERT_THREAD(Thread);
  1266. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  1267. //
  1268. // Raise IRQL to dispatcher level and lock dispatcher database.
  1269. //
  1270. KiLockDispatcherDatabase(&OldIrql);
  1271. //
  1272. // Capture the current state of the disable boost variable and set its
  1273. // state to TRUE.
  1274. //
  1275. DisableBoost = Thread->DisableBoost;
  1276. Thread->DisableBoost = (BOOLEAN)Disable;
  1277. //
  1278. // Unlock dispatcher database, lower IRQL to its previous value, and
  1279. // return the previous disable boost state.
  1280. //
  1281. KiUnlockDispatcherDatabase(OldIrql);
  1282. return DisableBoost;
  1283. }
  1284. UCHAR
  1285. KeSetIdealProcessorThread (
  1286. IN PKTHREAD Thread,
  1287. IN UCHAR Processor
  1288. )
  1289. /*++
  1290. Routine Description:
  1291. This function sets the ideal processor for the specified thread execution.
  1292. N.B. If the specified processor is less than the number of processors in
  1293. the system and is a member of the specified thread's current affinity
  1294. set, then the ideal processor is set. Otherwise, no operation is
  1295. performed.
  1296. Arguments:
  1297. Thread - Supplies a pointer to the thread whose ideal processor number is
  1298. set to the specfied value.
  1299. Processor - Supplies the number of the ideal processor.
  1300. Return Value:
  1301. The previous ideal processor number.
  1302. --*/
  1303. {
  1304. UCHAR OldProcessor;
  1305. KIRQL OldIrql;
  1306. ASSERT(Processor <= MAXIMUM_PROCESSORS);
  1307. //
  1308. // Raise IRQL, lock the dispatcher database, and capture the previous
  1309. // ideal processor value.
  1310. //
  1311. KiLockDispatcherDatabase(&OldIrql);
  1312. OldProcessor = Thread->UserIdealProcessor;
  1313. //
  1314. // If the specified processor is less than the number of processors in the
  1315. // system and is a member of the specified thread's current affinity set,
  1316. // then the ideal processor is set. Otherwise, no operation is performed.
  1317. //
  1318. if ((Processor < KeNumberProcessors) &&
  1319. ((Thread->Affinity & AFFINITY_MASK(Processor)) != 0)) {
  1320. Thread->IdealProcessor = Processor;
  1321. if (Thread->SystemAffinityActive == FALSE) {
  1322. Thread->UserIdealProcessor = Processor;
  1323. }
  1324. }
  1325. //
  1326. // Unlock dispatcher database, lower IRQL to its previous value, and
  1327. // return the previous ideal processor.
  1328. //
  1329. //
  1330. KiUnlockDispatcherDatabase(OldIrql);
  1331. return OldProcessor;
  1332. }
  1333. BOOLEAN
  1334. KeSetKernelStackSwapEnable (
  1335. IN BOOLEAN Enable
  1336. )
  1337. /*++
  1338. Routine Description:
  1339. This function sets the kernel stack swap enable value for the current
  1340. thread and returns the old swap enable value.
  1341. Arguments:
  1342. Enable - Supplies the new kernel stack swap enable value.
  1343. Return Value:
  1344. The previous kernel stack swap enable value.
  1345. --*/
  1346. {
  1347. BOOLEAN OldState;
  1348. PKTHREAD Thread;
  1349. //
  1350. // Capture the previous kernel stack swap enable value, set the new
  1351. // swap enable value, and return the old swap enable value for the
  1352. // current thread;
  1353. //
  1354. Thread = KeGetCurrentThread();
  1355. OldState = Thread->EnableStackSwap;
  1356. Thread->EnableStackSwap = Enable;
  1357. return OldState;
  1358. }
  1359. KPRIORITY
  1360. KeSetPriorityThread (
  1361. IN PKTHREAD Thread,
  1362. IN KPRIORITY Priority
  1363. )
  1364. /*++
  1365. Routine Description:
  1366. This function sets the priority of the specified thread to a new value.
  1367. If the new thread priority is lower than the old thread priority, then
  1368. resecheduling may take place if the thread is currently running on, or
  1369. about to run on, a processor.
  1370. Arguments:
  1371. Thread - Supplies a pointer to a dispatcher object of type thread.
  1372. Priority - Supplies the new priority of the subject thread.
  1373. Return Value:
  1374. The previous priority of the specified thread.
  1375. --*/
  1376. {
  1377. KIRQL OldIrql;
  1378. KPRIORITY OldPriority;
  1379. PKPROCESS Process;
  1380. ASSERT_THREAD(Thread);
  1381. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  1382. ASSERT(((Priority != 0) || (Thread->BasePriority == 0)) &&
  1383. (Priority <= HIGH_PRIORITY));
  1384. ASSERT(KeIsExecutingDpc() == FALSE);
  1385. //
  1386. // Raise IRQL to dispatcher level and lock dispatcher database.
  1387. //
  1388. Process = Thread->Process;
  1389. KiLockDispatcherDatabase(&OldIrql);
  1390. //
  1391. // Acquire the thread lock, capture the current thread priority, set the
  1392. // thread priority to the the new value, and replenish the thread quantum.
  1393. // It is assumed that the priority would not be set unless the thread had
  1394. // already lost it initial quantum.
  1395. //
  1396. KiAcquireThreadLock(Thread);
  1397. OldPriority = Thread->Priority;
  1398. Thread->PriorityDecrement = 0;
  1399. if (Priority != Thread->Priority) {
  1400. Thread->Quantum = Process->ThreadQuantum;
  1401. KiSetPriorityThread(Thread, Priority);
  1402. }
  1403. //
  1404. // Release the thread lock, unlock the dispatcher database, lower IRQL to
  1405. // its previous value, and return the previous thread priority.
  1406. //
  1407. KiReleaseThreadLock(Thread);
  1408. KiUnlockDispatcherDatabase(OldIrql);
  1409. return OldPriority;
  1410. }
  1411. ULONG
  1412. KeSuspendThread (
  1413. IN PKTHREAD Thread
  1414. )
  1415. /*++
  1416. Routine Description:
  1417. This function suspends the execution of a thread. If the suspend count
  1418. overflows the maximum suspend count, then a condition is raised.
  1419. Arguments:
  1420. Thread - Supplies a pointer to a dispatcher object of type thread.
  1421. Return Value:
  1422. The previous suspend count.
  1423. --*/
  1424. {
  1425. KLOCK_QUEUE_HANDLE LockHandle;
  1426. ULONG OldCount;
  1427. ASSERT_THREAD(Thread);
  1428. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  1429. //
  1430. // Raise IRQL to SYNCH_LEVEL and acquire the thread APC queue lock.
  1431. //
  1432. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock, &LockHandle);
  1433. //
  1434. // Capture the current suspend count.
  1435. //
  1436. // If the suspend count is at its maximum value, then unlock the
  1437. // dispatcher database, unlock the thread APC queue lock, lower IRQL
  1438. // to its previous value, and raise an error condition.
  1439. //
  1440. OldCount = Thread->SuspendCount;
  1441. if (OldCount == MAXIMUM_SUSPEND_COUNT) {
  1442. KeReleaseInStackQueuedSpinLock(&LockHandle);
  1443. ExRaiseStatus(STATUS_SUSPEND_COUNT_EXCEEDED);
  1444. }
  1445. //
  1446. // Don't suspend the thread if APC queuing is disabled. In this case the
  1447. // thread is being deleted.
  1448. //
  1449. if (Thread->ApcQueueable == TRUE) {
  1450. //
  1451. // Increment the suspend count. If the thread was not previously
  1452. // suspended, then queue the thread's suspend APC.
  1453. //
  1454. Thread->SuspendCount += 1;
  1455. if ((OldCount == 0) && (Thread->FreezeCount == 0)) {
  1456. if (Thread->SuspendApc.Inserted == TRUE) {
  1457. KiLockDispatcherDatabaseAtSynchLevel();
  1458. Thread->SuspendSemaphore.Header.SignalState -= 1;
  1459. KiUnlockDispatcherDatabaseFromSynchLevel();
  1460. } else {
  1461. Thread->SuspendApc.Inserted = TRUE;
  1462. KiInsertQueueApc(&Thread->SuspendApc, RESUME_INCREMENT);
  1463. }
  1464. }
  1465. }
  1466. //
  1467. // Release the thread APC queue lock, exit the scheduler, and return
  1468. // the old count.
  1469. //
  1470. KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);
  1471. KiExitDispatcher(LockHandle.OldIrql);
  1472. return OldCount;
  1473. }
  1474. VOID
  1475. KeTerminateThread (
  1476. IN KPRIORITY Increment
  1477. )
  1478. /*++
  1479. Routine Description:
  1480. This function terminates the execution of the current thread, sets the
  1481. signal state of the thread to Signaled, and attempts to satisfy as many
  1482. Waits as possible. The scheduling state of the thread is set to terminated,
  1483. and a new thread is selected to run on the current processor. There is no
  1484. return from this function.
  1485. Arguments:
  1486. None.
  1487. Return Value:
  1488. None.
  1489. --*/
  1490. {
  1491. PSINGLE_LIST_ENTRY ListHead;
  1492. KLOCK_QUEUE_HANDLE LockHandle;
  1493. PKPROCESS Process;
  1494. PKQUEUE Queue;
  1495. PKTHREAD Thread;
  1496. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  1497. //
  1498. // Raise IRQL to SYNCH_LEVEL, acquire the process lock, and set swap busy.
  1499. //
  1500. Thread = KeGetCurrentThread();
  1501. Process = Thread->ApcState.Process;
  1502. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Process->ProcessLock,
  1503. &LockHandle);
  1504. KiSetContextSwapBusy(Thread);
  1505. //
  1506. // Insert the thread in the reaper list.
  1507. //
  1508. // N.B. This code has knowledge of the reaper data structures and how
  1509. // worker threads are implemented.
  1510. //
  1511. ListHead = InterlockedPushEntrySingleList(&PsReaperListHead,
  1512. (PSINGLE_LIST_ENTRY)&((PETHREAD)Thread)->ReaperLink);
  1513. //
  1514. // Acquire the dispatcher database and check if a reaper work item should
  1515. // be queued.
  1516. //
  1517. KiLockDispatcherDatabaseAtSynchLevel();
  1518. if (ListHead == NULL) {
  1519. KiInsertQueue(&ExWorkerQueue[HyperCriticalWorkQueue].WorkerQueue,
  1520. &PsReaperWorkItem.List,
  1521. FALSE);
  1522. }
  1523. //
  1524. // If the current thread is processing a queue entry, then remove
  1525. // the thread from the queue object thread list and attempt to
  1526. // activate another thread that is blocked on the queue object.
  1527. //
  1528. Queue = Thread->Queue;
  1529. if (Queue != NULL) {
  1530. RemoveEntryList(&Thread->QueueListEntry);
  1531. KiActivateWaiterQueue(Queue);
  1532. }
  1533. //
  1534. // Set the state of the current thread object to Signaled, and attempt
  1535. // to satisfy as many Waits as possible.
  1536. //
  1537. Thread->Header.SignalState = TRUE;
  1538. if (IsListEmpty(&Thread->Header.WaitListHead) != TRUE) {
  1539. KiWaitTestWithoutSideEffects(Thread, Increment);
  1540. }
  1541. //
  1542. // Remove thread from its parent process' thread list.
  1543. //
  1544. RemoveEntryList(&Thread->ThreadListEntry);
  1545. //
  1546. // Release the process lock, but don't lower the IRQL.
  1547. //
  1548. KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);
  1549. //
  1550. // Set thread scheduling state to terminated, decrement the process'
  1551. // stack count, and initiate an outswap of the process if the stack
  1552. // count is zero.
  1553. //
  1554. Thread->State = Terminated;
  1555. Process->StackCount -= 1;
  1556. if (Process->StackCount == 0) {
  1557. if (Process->ThreadListHead.Flink != &Process->ThreadListHead) {
  1558. Process->State = ProcessOutTransition;
  1559. InterlockedPushEntrySingleList(&KiProcessOutSwapListHead,
  1560. &Process->SwapListEntry);
  1561. KiSetInternalEvent(&KiSwapEvent, KiSwappingThread);
  1562. }
  1563. }
  1564. //
  1565. // Rundown any architectural specific structures
  1566. //
  1567. KiRundownThread(Thread);
  1568. //
  1569. // Unlock the dispatcher database and get off the processor for the last
  1570. // time.
  1571. //
  1572. KiUnlockDispatcherDatabaseFromSynchLevel();
  1573. KiSwapThread(Thread, KeGetCurrentPrcb());
  1574. return;
  1575. }
  1576. BOOLEAN
  1577. KeTestAlertThread (
  1578. IN KPROCESSOR_MODE AlertMode
  1579. )
  1580. /*++
  1581. Routine Description:
  1582. This function tests to determine if the alerted variable for the
  1583. specified processor mode has a value of TRUE or whether a user mode
  1584. APC should be delivered to the current thread.
  1585. Arguments:
  1586. AlertMode - Supplies the processor mode which is to be tested
  1587. for an alerted condition.
  1588. Return Value:
  1589. The previous state of the alerted variable for the specified processor
  1590. mode.
  1591. --*/
  1592. {
  1593. BOOLEAN Alerted;
  1594. KLOCK_QUEUE_HANDLE LockHandle;
  1595. PKTHREAD Thread;
  1596. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  1597. //
  1598. // Raise IRQL to SYNCH_LEVEL and acquire the thread APC queue lock.
  1599. //
  1600. Thread = KeGetCurrentThread();
  1601. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock,
  1602. &LockHandle);
  1603. //
  1604. // If the current thread is alerted for the specified processor mode,
  1605. // then clear the alerted state. Else if the specified processor mode
  1606. // is user and the current thread's user mode APC queue contains an
  1607. // entry, then set user APC pending.
  1608. //
  1609. Alerted = Thread->Alerted[AlertMode];
  1610. if (Alerted == TRUE) {
  1611. Thread->Alerted[AlertMode] = FALSE;
  1612. } else if ((AlertMode == UserMode) &&
  1613. (IsListEmpty(&Thread->ApcState.ApcListHead[UserMode]) != TRUE)) {
  1614. Thread->ApcState.UserApcPending = TRUE;
  1615. }
  1616. //
  1617. // Release the thread APC queue lock, lower IRQL to its previous value,
  1618. // and return the previous alerted state for the specified mode.
  1619. //
  1620. KeReleaseInStackQueuedSpinLock(&LockHandle);
  1621. return Alerted;
  1622. }
  1623. VOID
  1624. KeThawAllThreads (
  1625. VOID
  1626. )
  1627. /*++
  1628. Routine Description:
  1629. This function resumes the execution of all suspended froozen threads
  1630. in the current process.
  1631. Arguments:
  1632. None.
  1633. Return Value:
  1634. None.
  1635. --*/
  1636. {
  1637. PLIST_ENTRY ListHead;
  1638. PLIST_ENTRY NextEntry;
  1639. ULONG OldCount;
  1640. PKPROCESS Process;
  1641. KLOCK_QUEUE_HANDLE ProcessHandle;
  1642. PKTHREAD Thread;
  1643. KLOCK_QUEUE_HANDLE ThreadHandle;
  1644. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  1645. //
  1646. // Raise IRQL to SYNCH_LEVEL and acquire the process lock.
  1647. //
  1648. Process = KeGetCurrentThread()->ApcState.Process;
  1649. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Process->ProcessLock,
  1650. &ProcessHandle);
  1651. //
  1652. // Thaw the execution of all threads in the current process that have
  1653. // been frozen.
  1654. //
  1655. ListHead = &Process->ThreadListHead;
  1656. NextEntry = ListHead->Flink;
  1657. do {
  1658. //
  1659. // Get the address of the next thread.
  1660. //
  1661. Thread = CONTAINING_RECORD(NextEntry, KTHREAD, ThreadListEntry);
  1662. //
  1663. // Acquire the thread APC queue lock.
  1664. //
  1665. KeAcquireInStackQueuedSpinLockAtDpcLevel(&Thread->ApcQueueLock,
  1666. &ThreadHandle);
  1667. //
  1668. // Thaw thread if its execution was previously froozen.
  1669. //
  1670. OldCount = Thread->FreezeCount;
  1671. if (OldCount != 0) {
  1672. Thread->FreezeCount -= 1;
  1673. //
  1674. // If the resultant suspend count is zero and the freeze count is
  1675. // zero, then resume the thread by releasing its suspend semaphore.
  1676. //
  1677. if ((Thread->SuspendCount == 0) && (Thread->FreezeCount == 0)) {
  1678. KiLockDispatcherDatabaseAtSynchLevel();
  1679. Thread->SuspendSemaphore.Header.SignalState += 1;
  1680. KiWaitTest(&Thread->SuspendSemaphore, RESUME_INCREMENT);
  1681. KiUnlockDispatcherDatabaseFromSynchLevel();
  1682. }
  1683. }
  1684. //
  1685. // Release the thread APC queue lock.
  1686. //
  1687. KeReleaseInStackQueuedSpinLockFromDpcLevel(&ThreadHandle);
  1688. NextEntry = NextEntry->Flink;
  1689. } while (NextEntry != ListHead);
  1690. //
  1691. // Release the process lock, exit the scheduler, and leave critical
  1692. // region.
  1693. //
  1694. KeReleaseInStackQueuedSpinLockFromDpcLevel(&ProcessHandle);
  1695. KiExitDispatcher(ProcessHandle.OldIrql);
  1696. KeLeaveCriticalRegion();
  1697. return;
  1698. }