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.

1442 lines
40 KiB

  1. /*++
  2. Copyright (c) 1989 Microsoft Corporation
  3. Module Name:
  4. procobj.c
  5. Abstract:
  6. This module implements the machine independent functions to manipulate
  7. the kernel process object. Functions are provided to initialize, attach,
  8. detach, exclude, include, and set the base priority of process objects.
  9. Author:
  10. David N. Cutler (davec) 7-Mar-1989
  11. Environment:
  12. Kernel mode only.
  13. Revision History:
  14. --*/
  15. #include "ki.h"
  16. #pragma alloc_text(PAGE, KeInitializeProcess)
  17. //
  18. // Define forward referenced function prototypes.
  19. //
  20. VOID
  21. KiAttachProcess (
  22. IN PRKTHREAD Thread,
  23. IN PRKPROCESS Process,
  24. IN PKLOCK_QUEUE_HANDLE LockHandle,
  25. OUT PRKAPC_STATE SavedApcState
  26. );
  27. VOID
  28. KiMoveApcState (
  29. IN PKAPC_STATE Source,
  30. OUT PKAPC_STATE Destination
  31. );
  32. //
  33. // The following assert macro is used to check that an input process is
  34. // really a kprocess and not something else, like deallocated pool.
  35. //
  36. #define ASSERT_PROCESS(E) { \
  37. ASSERT((E)->Header.Type == ProcessObject); \
  38. }
  39. #if !defined(NT_UP)
  40. FORCEINLINE
  41. VOID
  42. KiSetIdealNodeProcess (
  43. IN PKPROCESS Process,
  44. IN KAFFINITY Affinity
  45. )
  46. /*++
  47. Routine Description:
  48. This function sets the ideal node for a process based on the specified
  49. affinity and the node generation seed.
  50. Arguments:
  51. Process - Supplies a pointer to a dispatcher object of type process.
  52. Affinity - Supplies the set of processors on which children threads
  53. of the process can execute.
  54. Return Value:
  55. None.
  56. --*/
  57. {
  58. ULONG Index;
  59. PKNODE Node;
  60. ULONG NodeNumber;
  61. //
  62. // Select the ideal node for the process.
  63. //
  64. if (KeNumberNodes > 1) {
  65. NodeNumber = (KeProcessNodeSeed + 1) % KeNumberNodes;
  66. KeProcessNodeSeed = (UCHAR)NodeNumber;
  67. Index = 0;
  68. do {
  69. if ((KeNodeBlock[NodeNumber]->ProcessorMask & Affinity) != 0) {
  70. break;
  71. }
  72. Index += 1;
  73. NodeNumber = (NodeNumber + 1) % KeNumberNodes;
  74. } while (Index < KeNumberNodes);
  75. } else {
  76. NodeNumber = 0;
  77. }
  78. Process->IdealNode = (UCHAR)NodeNumber;
  79. Node = KeNodeBlock[NodeNumber];
  80. ASSERT((Node->ProcessorMask & Affinity) != 0);
  81. Process->ThreadSeed = (UCHAR)KeFindNextRightSetAffinity(Node->Seed,
  82. Node->ProcessorMask & Affinity);
  83. Node->Seed = Process->ThreadSeed;
  84. return;
  85. }
  86. #endif
  87. VOID
  88. KeInitializeProcess (
  89. IN PRKPROCESS Process,
  90. IN KPRIORITY BasePriority,
  91. IN KAFFINITY Affinity,
  92. IN ULONG_PTR DirectoryTableBase[2],
  93. IN BOOLEAN Enable
  94. )
  95. /*++
  96. Routine Description:
  97. This function initializes a kernel process object. The base priority,
  98. affinity, and page frame numbers for the process page table directory
  99. and hyper space are stored in the process object.
  100. N.B. It is assumed that the process object is zeroed.
  101. Arguments:
  102. Process - Supplies a pointer to a dispatcher object of type process.
  103. BasePriority - Supplies the base priority of the process.
  104. Affinity - Supplies the set of processors on which children threads
  105. of the process can execute.
  106. DirectoryTableBase - Supplies a pointer to an array whose fist element
  107. is the value that is to be loaded into the Directory Table Base
  108. register when a child thread is dispatched for execution and whose
  109. second element contains the page table entry that maps hyper space.
  110. Enable - Supplies a boolean value that determines the default
  111. handling of data alignment exceptions for child threads. A value
  112. of TRUE causes all data alignment exceptions to be automatically
  113. handled by the kernel. A value of FALSE causes all data alignment
  114. exceptions to be actually raised as exceptions.
  115. Return Value:
  116. None.
  117. --*/
  118. {
  119. //
  120. // Initialize the standard dispatcher object header and set the initial
  121. // signal state of the process object.
  122. //
  123. Process->Header.Type = ProcessObject;
  124. Process->Header.Size = sizeof(KPROCESS) / sizeof(LONG);
  125. InitializeListHead(&Process->Header.WaitListHead);
  126. //
  127. // Initialize the base priority, affinity, directory table base values,
  128. // autoalignment, and stack count.
  129. //
  130. // N.B. The distinguished value MAXSHORT is used to signify that no
  131. // threads have been created for the process.
  132. //
  133. Process->BasePriority = (SCHAR)BasePriority;
  134. Process->Affinity = Affinity;
  135. Process->AutoAlignment = Enable;
  136. Process->DirectoryTableBase[0] = DirectoryTableBase[0];
  137. Process->DirectoryTableBase[1] = DirectoryTableBase[1];
  138. Process->StackCount = MAXSHORT;
  139. //
  140. // Initialize the stack count, profile listhead, ready queue list head,
  141. // accumulated runtime, process quantum, thread quantum, and thread list
  142. // head.
  143. //
  144. InitializeListHead(&Process->ProfileListHead);
  145. InitializeListHead(&Process->ReadyListHead);
  146. InitializeListHead(&Process->ThreadListHead);
  147. Process->ThreadQuantum = THREAD_QUANTUM;
  148. //
  149. // Initialize the process state and set the thread processor selection
  150. // seed.
  151. //
  152. Process->State = ProcessInMemory;
  153. //
  154. // Select the ideal node for the process.
  155. //
  156. #if !defined(NT_UP)
  157. KiSetIdealNodeProcess(Process, Affinity);
  158. #endif
  159. //
  160. // Initialize IopmBase and Iopl flag for this process (i386 only)
  161. //
  162. #if defined(_X86_)
  163. Process->IopmOffset = KiComputeIopmOffset(IO_ACCESS_MAP_NONE);
  164. #endif // defined(_X86_)
  165. return;
  166. }
  167. VOID
  168. KeAttachProcess (
  169. IN PRKPROCESS Process
  170. )
  171. /*++
  172. Routine Description:
  173. This function attaches a thread to a target process' address space
  174. if, and only if, there is not already a process attached.
  175. Arguments:
  176. Process - Supplies a pointer to a dispatcher object of type process.
  177. Return Value:
  178. None.
  179. --*/
  180. {
  181. KLOCK_QUEUE_HANDLE LockHandle;
  182. PRKTHREAD Thread;
  183. ASSERT_PROCESS(Process);
  184. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  185. //
  186. // If the target process is not the current process, then attach the
  187. // target process.
  188. //
  189. Thread = KeGetCurrentThread();
  190. if (Thread->ApcState.Process != Process) {
  191. //
  192. // If the current thread is already attached or executing a DPC, then
  193. // bugcheck.
  194. //
  195. if ((Thread->ApcStateIndex != 0) ||
  196. (KeIsExecutingDpc() != FALSE)) {
  197. KeBugCheckEx(INVALID_PROCESS_ATTACH_ATTEMPT,
  198. (ULONG_PTR)Process,
  199. (ULONG_PTR)Thread->ApcState.Process,
  200. (ULONG)Thread->ApcStateIndex,
  201. (ULONG)KeIsExecutingDpc());
  202. }
  203. //
  204. // Raise IRQL to SYNCH_LEVEL, acquire the thread APC queue lock,
  205. // acquire the dispatcher database lock, and attach to the specified
  206. // process.
  207. //
  208. // N.B. All lock are released by the internal attach routine.
  209. //
  210. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock,
  211. &LockHandle);
  212. KiLockDispatcherDatabaseAtSynchLevel();
  213. KiAttachProcess(Thread, Process, &LockHandle, &Thread->SavedApcState);
  214. }
  215. return;
  216. }
  217. LOGICAL
  218. KeForceAttachProcess (
  219. IN PRKPROCESS Process
  220. )
  221. /*++
  222. Routine Description:
  223. This function forces an attach of a thread to a target process' address
  224. space if the process is not current being swapped into or out of memory.
  225. N.B. This function is for use by memory management ONLY.
  226. Arguments:
  227. Process - Supplies a pointer to a dispatcher object of type process.
  228. Return Value:
  229. None.
  230. --*/
  231. {
  232. KLOCK_QUEUE_HANDLE LockHandle;
  233. PRKTHREAD Thread;
  234. ASSERT_PROCESS(Process);
  235. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  236. //
  237. // If the current thread is already attached or executing a DPC, then
  238. // bugcheck.
  239. //
  240. Thread = KeGetCurrentThread();
  241. if ((Thread->ApcStateIndex != 0) ||
  242. (KeIsExecutingDpc() != FALSE)) {
  243. KeBugCheckEx(INVALID_PROCESS_ATTACH_ATTEMPT,
  244. (ULONG_PTR)Process,
  245. (ULONG_PTR)Thread->ApcState.Process,
  246. (ULONG)Thread->ApcStateIndex,
  247. (ULONG)KeIsExecutingDpc());
  248. }
  249. //
  250. // If the target process is not the current process, then attach the
  251. // target process if the process is not currently being swapped in or
  252. // out of memory.
  253. //
  254. if (Thread->ApcState.Process != Process) {
  255. //
  256. // Raise IRQL to SYNCH_LEVEL, acquire the thread APC queue lock, and
  257. // acquire the dispatcher database lock.
  258. //
  259. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock,
  260. &LockHandle);
  261. KiLockDispatcherDatabaseAtSynchLevel();
  262. //
  263. // If the target process is currently being swapped into or out of
  264. // memory, then return a value of FALSE. Otherwise, force the process
  265. // to be inswapped.
  266. //
  267. if ((Process->State == ProcessInSwap) ||
  268. (Process->State == ProcessInTransition) ||
  269. (Process->State == ProcessOutTransition) ||
  270. (Process->State == ProcessOutSwap)) {
  271. KiUnlockDispatcherDatabaseFromSynchLevel();
  272. KeReleaseInStackQueuedSpinLock(&LockHandle);
  273. return FALSE;
  274. } else {
  275. //
  276. // Force the process state to in memory and attach the target process.
  277. //
  278. // N.B. All lock are released by the internal attach routine.
  279. //
  280. Process->State = ProcessInMemory;
  281. KiAttachProcess(Thread, Process, &LockHandle, &Thread->SavedApcState);
  282. }
  283. }
  284. return TRUE;
  285. }
  286. VOID
  287. KeStackAttachProcess (
  288. IN PRKPROCESS Process,
  289. OUT PRKAPC_STATE ApcState
  290. )
  291. /*++
  292. Routine Description:
  293. This function attaches a thread to a target process' address space
  294. and returns information about a previous attached process.
  295. Arguments:
  296. Process - Supplies a pointer to a dispatcher object of type process.
  297. Return Value:
  298. None.
  299. --*/
  300. {
  301. KLOCK_QUEUE_HANDLE LockHandle;
  302. PRKTHREAD Thread;
  303. ASSERT_PROCESS(Process);
  304. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  305. //
  306. // If the current thread is executing a DPC, then bug check.
  307. //
  308. Thread = KeGetCurrentThread();
  309. if (KeIsExecutingDpc() != FALSE) {
  310. KeBugCheckEx(INVALID_PROCESS_ATTACH_ATTEMPT,
  311. (ULONG_PTR)Process,
  312. (ULONG_PTR)Thread->ApcState.Process,
  313. (ULONG)Thread->ApcStateIndex,
  314. (ULONG)KeIsExecutingDpc());
  315. }
  316. //
  317. // If the target process is not the current process, then attach the
  318. // target process. Otherwise, return a distinguished process value to
  319. // indicate that an attach was not performed.
  320. //
  321. if (Thread->ApcState.Process == Process) {
  322. ApcState->Process = (PRKPROCESS)1;
  323. } else {
  324. //
  325. // Raise IRQL to SYNCH_LEVEL, acquire the thread APC queue lock, and
  326. // acquire the dispatcher database lock.
  327. //
  328. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock,
  329. &LockHandle);
  330. KiLockDispatcherDatabaseAtSynchLevel();
  331. //
  332. // If the current thread is attached to a process, then save the
  333. // current APC state in the callers APC state structure. Otherwise,
  334. // save the current APC state in the saved APC state structure, and
  335. // return a NULL process pointer.
  336. //
  337. // N.B. All lock are released by the internal attach routine.
  338. //
  339. if (Thread->ApcStateIndex != 0) {
  340. KiAttachProcess(Thread, Process, &LockHandle, ApcState);
  341. } else {
  342. KiAttachProcess(Thread, Process, &LockHandle, &Thread->SavedApcState);
  343. ApcState->Process = NULL;
  344. }
  345. }
  346. return;
  347. }
  348. VOID
  349. KeDetachProcess (
  350. VOID
  351. )
  352. /*++
  353. Routine Description:
  354. This function detaches a thread from another process' address space.
  355. Arguments:
  356. None.
  357. Return Value:
  358. None.
  359. --*/
  360. {
  361. KLOCK_QUEUE_HANDLE LockHandle;
  362. PKPROCESS Process;
  363. PKTHREAD Thread;
  364. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  365. //
  366. // If the current thread is attached to another process, then detach
  367. // it.
  368. //
  369. Thread = KeGetCurrentThread();
  370. if (Thread->ApcStateIndex != 0) {
  371. //
  372. // Raise IRQL to SYNCH_LEVEL and acquire the thread APC queue lock.
  373. //
  374. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock,
  375. &LockHandle);
  376. //
  377. // Test to determine if a kernel APC is pending.
  378. //
  379. // If a kernel APC is pending, the special APC disable count is zero,
  380. // and the previous IRQL was less than APC_LEVEL, then a kernel APC
  381. // was queued by another processor just after IRQL was raised to
  382. // DISPATCH_LEVEL, but before the dispatcher database was locked.
  383. //
  384. // N.B. that this can only happen in a multiprocessor system.
  385. //
  386. #if !defined(NT_UP)
  387. while (Thread->ApcState.KernelApcPending &&
  388. (Thread->SpecialApcDisable == 0) &&
  389. (LockHandle.OldIrql < APC_LEVEL)) {
  390. //
  391. // Unlock the thread APC lock and lower IRQL to its previous
  392. // value. An APC interrupt will immediately occur which will
  393. // result in the delivery of the kernel APC if possible.
  394. //
  395. KiRequestSoftwareInterrupt(APC_LEVEL);
  396. KeReleaseInStackQueuedSpinLock(&LockHandle);
  397. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock,
  398. &LockHandle);
  399. }
  400. #endif
  401. //
  402. // If a kernel APC is in progress, the kernel APC queue is not empty,
  403. // or the user APC queues is not empty, then bug check.
  404. //
  405. #if DBG
  406. if ((Thread->ApcState.KernelApcInProgress) ||
  407. (IsListEmpty(&Thread->ApcState.ApcListHead[KernelMode]) == FALSE) ||
  408. (IsListEmpty(&Thread->ApcState.ApcListHead[UserMode]) == FALSE)) {
  409. KeBugCheck(INVALID_PROCESS_DETACH_ATTEMPT);
  410. }
  411. #endif
  412. //
  413. // Lock the dispatcher database, unbias current process stack count,
  414. // and check if the process should be swapped out of memory.
  415. //
  416. Process = Thread->ApcState.Process;
  417. KiLockDispatcherDatabaseAtSynchLevel();
  418. Process->StackCount -= 1;
  419. if ((Process->StackCount == 0) &&
  420. (IsListEmpty(&Process->ThreadListHead) == FALSE)) {
  421. Process->State = ProcessOutTransition;
  422. InterlockedPushEntrySingleList(&KiProcessOutSwapListHead,
  423. &Process->SwapListEntry);
  424. KiSetInternalEvent(&KiSwapEvent, KiSwappingThread);
  425. }
  426. //
  427. // Unlock dispatcher database, but remain at SYNCH_LEVEL.
  428. //
  429. KiUnlockDispatcherDatabaseFromSynchLevel();
  430. //
  431. // Restore APC state and check whether the kernel APC queue contains
  432. // an entry. If the kernel APC queue contains an entry then set kernel
  433. // APC pending and request a software interrupt at APC_LEVEL.
  434. //
  435. KiMoveApcState(&Thread->SavedApcState, &Thread->ApcState);
  436. Thread->SavedApcState.Process = (PKPROCESS)NULL;
  437. Thread->ApcStatePointer[0] = &Thread->ApcState;
  438. Thread->ApcStatePointer[1] = &Thread->SavedApcState;
  439. Thread->ApcStateIndex = 0;
  440. //
  441. // Release the thread APC queue lock, swap the address space back to
  442. // the parent process, and exit the scheduler.
  443. //
  444. KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);
  445. KiSwapProcess(Thread->ApcState.Process, Process);
  446. KiExitDispatcher(LockHandle.OldIrql);
  447. //
  448. // Initiate an APC interrupt if there are pending kernel APC's.
  449. //
  450. if (IsListEmpty(&Thread->ApcState.ApcListHead[KernelMode]) == FALSE) {
  451. Thread->ApcState.KernelApcPending = TRUE;
  452. KiRequestSoftwareInterrupt(APC_LEVEL);
  453. }
  454. }
  455. return;
  456. }
  457. VOID
  458. KeUnstackDetachProcess (
  459. IN PRKAPC_STATE ApcState
  460. )
  461. /*++
  462. Routine Description:
  463. This function detaches a thread from another process' address space
  464. and restores previous attach state.
  465. Arguments:
  466. ApcState - Supplies a pointer to an APC state structure that was returned
  467. from a previous call to stack attach process.
  468. Return Value:
  469. None.
  470. --*/
  471. {
  472. KLOCK_QUEUE_HANDLE LockHandle;
  473. PKPROCESS Process;
  474. PKTHREAD Thread;
  475. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  476. //
  477. // If the APC state has a distinguished process pointer value, then no
  478. // attach was performed on the paired call to stack attach process.
  479. //
  480. if (ApcState->Process != (PRKPROCESS)1) {
  481. //
  482. // Raise IRQL to SYNCH_LEVEL and acquire the thread APC queue lock.
  483. //
  484. Thread = KeGetCurrentThread();
  485. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock,
  486. &LockHandle);
  487. //
  488. // Test to determine if a kernel APC is pending.
  489. //
  490. // If a kernel APC is pending, the special APC disable count is zero,
  491. // and the previous IRQL was less than APC_LEVEL, then a kernel APC
  492. // was queued by another processor just after IRQL was raised to
  493. // DISPATCH_LEVEL, but before the dispatcher database was locked.
  494. //
  495. // N.B. that this can only happen in a multiprocessor system.
  496. //
  497. #if !defined(NT_UP)
  498. while (Thread->ApcState.KernelApcPending &&
  499. (Thread->SpecialApcDisable == 0) &&
  500. (LockHandle.OldIrql < APC_LEVEL)) {
  501. //
  502. // Unlock the thread APC lock and lower IRQL to its previous
  503. // value. An APC interrupt will immediately occur which will
  504. // result in the delivery of the kernel APC if possible.
  505. //
  506. KiRequestSoftwareInterrupt(APC_LEVEL);
  507. KeReleaseInStackQueuedSpinLock(&LockHandle);
  508. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock,
  509. &LockHandle);
  510. }
  511. #endif
  512. //
  513. // If the APC state is the original APC state, a kernel APC is in
  514. // progress, the kernel APC is nbot empty, or the user APC queues is
  515. // not empty, then bug check.
  516. //
  517. if ((Thread->ApcStateIndex == 0) ||
  518. (Thread->ApcState.KernelApcInProgress) ||
  519. (IsListEmpty(&Thread->ApcState.ApcListHead[KernelMode]) == FALSE) ||
  520. (IsListEmpty(&Thread->ApcState.ApcListHead[UserMode]) == FALSE)) {
  521. KeBugCheck(INVALID_PROCESS_DETACH_ATTEMPT);
  522. }
  523. //
  524. // Lock the dispatcher database, unbias current process stack count,
  525. // and check if the process should be swapped out of memory.
  526. //
  527. Process = Thread->ApcState.Process;
  528. KiLockDispatcherDatabaseAtSynchLevel();
  529. Process->StackCount -= 1;
  530. if ((Process->StackCount == 0) &&
  531. (IsListEmpty(&Process->ThreadListHead) == FALSE)) {
  532. Process->State = ProcessOutTransition;
  533. InterlockedPushEntrySingleList(&KiProcessOutSwapListHead,
  534. &Process->SwapListEntry);
  535. KiSetInternalEvent(&KiSwapEvent, KiSwappingThread);
  536. }
  537. //
  538. // Unlock dispatcher database, but remain at SYNCH_LEVEL.
  539. //
  540. KiUnlockDispatcherDatabaseFromSynchLevel();
  541. //
  542. // Restore APC state and check whether the kernel APC queue contains
  543. // an entry. If the kernel APC queue contains an entry then set kernel
  544. // APC pending and request a software interrupt at APC_LEVEL.
  545. //
  546. if (ApcState->Process != NULL) {
  547. KiMoveApcState(ApcState, &Thread->ApcState);
  548. } else {
  549. KiMoveApcState(&Thread->SavedApcState, &Thread->ApcState);
  550. Thread->SavedApcState.Process = (PKPROCESS)NULL;
  551. Thread->ApcStatePointer[0] = &Thread->ApcState;
  552. Thread->ApcStatePointer[1] = &Thread->SavedApcState;
  553. Thread->ApcStateIndex = 0;
  554. }
  555. //
  556. // Release the thread APC queue lock, swap the address space back to
  557. // the parent process, and exit the scheduler.
  558. //
  559. KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);
  560. KiSwapProcess(Thread->ApcState.Process, Process);
  561. KiExitDispatcher(LockHandle.OldIrql);
  562. //
  563. // Initiate an APC interrupt if we need to
  564. //
  565. if (IsListEmpty(&Thread->ApcState.ApcListHead[KernelMode]) == FALSE) {
  566. Thread->ApcState.KernelApcPending = TRUE;
  567. KiRequestSoftwareInterrupt(APC_LEVEL);
  568. }
  569. }
  570. return;
  571. }
  572. LONG
  573. KeReadStateProcess (
  574. IN PRKPROCESS Process
  575. )
  576. /*++
  577. Routine Description:
  578. This function reads the current signal state of a process object.
  579. Arguments:
  580. Process - Supplies a pointer to a dispatcher object of type process.
  581. Return Value:
  582. The current signal state of the process object.
  583. --*/
  584. {
  585. ASSERT_PROCESS(Process);
  586. //
  587. // Return current signal state of process object.
  588. //
  589. return Process->Header.SignalState;
  590. }
  591. LONG
  592. KeSetProcess (
  593. IN PRKPROCESS Process,
  594. IN KPRIORITY Increment,
  595. IN BOOLEAN Wait
  596. )
  597. /*++
  598. Routine Description:
  599. This function sets the signal state of a proces object to Signaled
  600. and attempts to satisfy as many Waits as possible. The previous
  601. signal state of the process object is returned as the function value.
  602. Arguments:
  603. Process - Supplies a pointer to a dispatcher object of type process.
  604. Increment - Supplies the priority increment that is to be applied
  605. if setting the process causes a Wait to be satisfied.
  606. Wait - Supplies a boolean value that signifies whether the call to
  607. KeSetProcess will be immediately followed by a call to one of the
  608. kernel Wait functions.
  609. Return Value:
  610. The previous signal state of the process object.
  611. --*/
  612. {
  613. KIRQL OldIrql;
  614. LONG OldState;
  615. PRKTHREAD Thread;
  616. ASSERT_PROCESS(Process);
  617. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  618. //
  619. // Raise IRQL to dispatcher level and lock dispatcher database.
  620. //
  621. KiLockDispatcherDatabase(&OldIrql);
  622. //
  623. // If the previous state of the process object is Not-Signaled and
  624. // the wait queue is not empty, then satisfy as many Waits as
  625. // possible.
  626. //
  627. OldState = Process->Header.SignalState;
  628. Process->Header.SignalState = 1;
  629. if ((OldState == 0) &&
  630. (IsListEmpty(&Process->Header.WaitListHead) == FALSE)) {
  631. KiWaitTestWithoutSideEffects(Process, Increment);
  632. }
  633. //
  634. // If the value of the Wait argument is TRUE, then return to the
  635. // caller with IRQL raised and the dispatcher database locked. Else
  636. // release the dispatcher database lock and lower IRQL to its
  637. // previous value.
  638. //
  639. if (Wait) {
  640. Thread = KeGetCurrentThread();
  641. Thread->WaitNext = Wait;
  642. Thread->WaitIrql = OldIrql;
  643. } else {
  644. KiUnlockDispatcherDatabase(OldIrql);
  645. }
  646. //
  647. // Return previous signal state of process object.
  648. //
  649. return OldState;
  650. }
  651. KAFFINITY
  652. KeSetAffinityProcess (
  653. IN PKPROCESS Process,
  654. IN KAFFINITY Affinity
  655. )
  656. /*++
  657. Routine Description:
  658. This function sets the affinity of a process to the specified value and
  659. also sets the affinity of each thread in the process to the specified
  660. value.
  661. Arguments:
  662. Process - Supplies a pointer to a dispatcher object of type process.
  663. Affinity - Supplies the new of set of processors on which the threads
  664. in the process can run.
  665. Return Value:
  666. The previous affinity of the specified process is returned as the function
  667. value.
  668. --*/
  669. {
  670. KLOCK_QUEUE_HANDLE LockHandle;
  671. PLIST_ENTRY NextEntry;
  672. KAFFINITY OldAffinity;
  673. PKTHREAD Thread;
  674. ASSERT_PROCESS(Process);
  675. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  676. ASSERT((Affinity & KeActiveProcessors) != 0);
  677. //
  678. // Raise IRQL to SYNCH_LEVEL, acquire the process lock, and acquire the
  679. // dispatcher databack lock at SYNCH_LEVEL.
  680. //
  681. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Process->ProcessLock, &LockHandle);
  682. KiLockDispatcherDatabaseAtSynchLevel();
  683. //
  684. // Capture the current affinity of the specified process and set the
  685. // affinity of the process.
  686. //
  687. OldAffinity = Process->Affinity;
  688. Process->Affinity = Affinity;
  689. //
  690. // If the new affinity does not intersect with the process ideal node
  691. // affinity, then select a new process ideal node.
  692. //
  693. #if !defined(NT_UP)
  694. if ((Affinity & KeNodeBlock[Process->IdealNode]->ProcessorMask) == 0) {
  695. KiSetIdealNodeProcess(Process, Affinity);
  696. }
  697. #endif
  698. //
  699. // Set the affiity of all process threads.
  700. //
  701. NextEntry = Process->ThreadListHead.Flink;
  702. while (NextEntry != &Process->ThreadListHead) {
  703. Thread = CONTAINING_RECORD(NextEntry, KTHREAD, ThreadListEntry);
  704. KiSetAffinityThread(Thread, Affinity);
  705. NextEntry = NextEntry->Flink;
  706. }
  707. //
  708. // Unlock dispatcher database, unlock the process lock, exit the
  709. // scheduler, and return the previous process affinity.
  710. //
  711. KiUnlockDispatcherDatabaseFromSynchLevel();
  712. KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);
  713. KiExitDispatcher(LockHandle.OldIrql);
  714. return OldAffinity;
  715. }
  716. KPRIORITY
  717. KeSetPriorityProcess (
  718. IN PKPROCESS Process,
  719. IN KPRIORITY NewBase
  720. )
  721. /*++
  722. Routine Description:
  723. This function set the base priority of a process to a new value
  724. and adjusts the priority and base priority of all child threads
  725. as appropriate.
  726. Arguments:
  727. Process - Supplies a pointer to a dispatcher object of type process.
  728. NewBase - Supplies the new base priority of the process.
  729. Return Value:
  730. The previous base priority of the process.
  731. --*/
  732. {
  733. KPRIORITY Adjustment;
  734. KLOCK_QUEUE_HANDLE LockHandle;
  735. PLIST_ENTRY NextEntry;
  736. KPRIORITY NewPriority;
  737. KPRIORITY OldBase;
  738. PKTHREAD Thread;
  739. ASSERT_PROCESS(Process);
  740. ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
  741. //
  742. // If the new priority is equal to the old priority, then do not change
  743. // the process priority and return the old priority.
  744. //
  745. // N.B. This check can be made without holding the dispatcher lock since
  746. // nothing needs to be protected, and any race condition that can exist
  747. // calling this routine exists with or without the lock being held.
  748. //
  749. if (Process->BasePriority == NewBase) {
  750. return NewBase;
  751. }
  752. //
  753. // Raise IRQL to SYNCH level, acquire the process lock, and lock the
  754. // dispatcher database.
  755. //
  756. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Process->ProcessLock, &LockHandle);
  757. KiLockDispatcherDatabaseAtSynchLevel();
  758. //
  759. // Save the current process base priority, set the new process base
  760. // priority, compute the adjustment value, and adjust the priority
  761. // and base priority of all child threads as appropriate.
  762. //
  763. OldBase = Process->BasePriority;
  764. Process->BasePriority = (SCHAR)NewBase;
  765. Adjustment = NewBase - OldBase;
  766. NextEntry = Process->ThreadListHead.Flink;
  767. if (NewBase >= LOW_REALTIME_PRIORITY) {
  768. while (NextEntry != &Process->ThreadListHead) {
  769. Thread = CONTAINING_RECORD(NextEntry, KTHREAD, ThreadListEntry);
  770. //
  771. // Acquire the thread lock and compute the new base priority of
  772. // the thread.
  773. //
  774. KiAcquireThreadLock(Thread);
  775. NewPriority = Thread->BasePriority + Adjustment;
  776. //
  777. // If the new base priority is outside the realtime class,
  778. // then limit the change to the realtime class.
  779. //
  780. if (NewPriority < LOW_REALTIME_PRIORITY) {
  781. NewPriority = LOW_REALTIME_PRIORITY;
  782. } else if (NewPriority > HIGH_PRIORITY) {
  783. NewPriority = HIGH_PRIORITY;
  784. }
  785. //
  786. // Set the base priority and the current priority of the
  787. // thread to the appropriate value.
  788. //
  789. // N.B. If priority saturation occured the last time the thread
  790. // base priority was set and the new process base priority
  791. // is not crossing from variable to realtime, then it is not
  792. // necessary to change the thread priority.
  793. //
  794. if ((Thread->Saturation == 0) || (OldBase < LOW_REALTIME_PRIORITY)) {
  795. if (Thread->Saturation > 0) {
  796. NewPriority = HIGH_PRIORITY;
  797. } else if (Thread->Saturation < 0) {
  798. NewPriority = LOW_REALTIME_PRIORITY;
  799. }
  800. Thread->BasePriority = (SCHAR)NewPriority;
  801. Thread->Quantum = Process->ThreadQuantum;
  802. Thread->PriorityDecrement = 0;
  803. KiSetPriorityThread(Thread, NewPriority);
  804. }
  805. KiReleaseThreadLock(Thread);
  806. NextEntry = NextEntry->Flink;
  807. }
  808. } else {
  809. while (NextEntry != &Process->ThreadListHead) {
  810. Thread = CONTAINING_RECORD(NextEntry, KTHREAD, ThreadListEntry);
  811. //
  812. // Acquire the thread lock and compute the new base priority of
  813. // the thread.
  814. //
  815. KiAcquireThreadLock(Thread);
  816. NewPriority = Thread->BasePriority + Adjustment;
  817. //
  818. // If the new base priority is outside the variable class,
  819. // then limit the change to the variable class.
  820. //
  821. if (NewPriority >= LOW_REALTIME_PRIORITY) {
  822. NewPriority = LOW_REALTIME_PRIORITY - 1;
  823. } else if (NewPriority <= LOW_PRIORITY) {
  824. NewPriority = 1;
  825. }
  826. //
  827. // Set the base priority and the current priority of the
  828. // thread to the computed value and reset the thread quantum.
  829. //
  830. // N.B. If priority saturation occured the last time the thread
  831. // base priority was set and the new process base priority
  832. // is not crossing from realtime to variable, then it is not
  833. // necessary to change the thread priority.
  834. //
  835. if ((Thread->Saturation == 0) || (OldBase >= LOW_REALTIME_PRIORITY)) {
  836. if (Thread->Saturation > 0) {
  837. NewPriority = LOW_REALTIME_PRIORITY - 1;
  838. } else if (Thread->Saturation < 0) {
  839. NewPriority = 1;
  840. }
  841. Thread->BasePriority = (SCHAR)NewPriority;
  842. Thread->Quantum = Process->ThreadQuantum;
  843. Thread->PriorityDecrement = 0;
  844. KiSetPriorityThread(Thread, NewPriority);
  845. }
  846. KiReleaseThreadLock(Thread);
  847. NextEntry = NextEntry->Flink;
  848. }
  849. }
  850. //
  851. // Unlock dispatcher database, unlock the process lock, exit the
  852. // scheduler, and return the previous base priority.
  853. //
  854. KiUnlockDispatcherDatabaseFromSynchLevel();
  855. KeReleaseInStackQueuedSpinLockFromDpcLevel(&LockHandle);
  856. KiExitDispatcher(LockHandle.OldIrql);
  857. return OldBase;
  858. }
  859. LOGICAL
  860. KeSetDisableQuantumProcess (
  861. IN PKPROCESS Process,
  862. IN LOGICAL Disable
  863. )
  864. /*++
  865. Routine Description:
  866. This function disables quantum runout for realtime threads in the
  867. specified process.
  868. Arguments:
  869. Process - Supplies a pointer to a dispatcher object of type process.
  870. Disable - Supplies a logical value that determines whether quantum
  871. runout for realtime threads in the specified process are disabled
  872. or enabled.
  873. Return Value:
  874. The previous value of the disable quantum state variable.
  875. --*/
  876. {
  877. LOGICAL DisableQuantum;
  878. ASSERT_PROCESS(Process);
  879. //
  880. // Capture the current state of the disable boost variable and set its
  881. // state to TRUE.
  882. //
  883. DisableQuantum = Process->DisableQuantum;
  884. Process->DisableQuantum = (BOOLEAN)Disable;
  885. //
  886. // Return the previous disable quantum state.
  887. //
  888. return DisableQuantum;
  889. }
  890. VOID
  891. KiAttachProcess (
  892. IN PRKTHREAD Thread,
  893. IN PKPROCESS Process,
  894. IN PKLOCK_QUEUE_HANDLE LockHandle,
  895. OUT PRKAPC_STATE SavedApcState
  896. )
  897. /*++
  898. Routine Description:
  899. This function attaches a thread to a target process' address space.
  900. N.B. The dispatcher database lock and the thread APC queue lock must be
  901. held when this routine is called.
  902. Arguments:
  903. Thread - Supplies a pointer to the current thread object.
  904. Process - Supplies a pointer to the current process object.
  905. Lockhandle - Supplies the address of the lock handle that was used to
  906. acquire the thread APC lock.
  907. SavedApcState - Supplies a pointer to the APC state structure that
  908. receives the saved APC state.
  909. Return Value:
  910. None.
  911. --*/
  912. {
  913. PLIST_ENTRY NextEntry;
  914. PRKTHREAD OutThread;
  915. ASSERT(Process != Thread->ApcState.Process);
  916. //
  917. // Bias the stack count of the target process to signify that a
  918. // thread exists in that process with a stack that is resident.
  919. //
  920. Process->StackCount += 1;
  921. //
  922. // Save current APC state and initialize a new APC state.
  923. //
  924. KiMoveApcState(&Thread->ApcState, SavedApcState);
  925. InitializeListHead(&Thread->ApcState.ApcListHead[KernelMode]);
  926. InitializeListHead(&Thread->ApcState.ApcListHead[UserMode]);
  927. Thread->ApcState.KernelApcInProgress = FALSE;
  928. Thread->ApcState.KernelApcPending = FALSE;
  929. Thread->ApcState.UserApcPending = FALSE;
  930. if (SavedApcState == &Thread->SavedApcState) {
  931. Thread->ApcStatePointer[0] = &Thread->SavedApcState;
  932. Thread->ApcStatePointer[1] = &Thread->ApcState;
  933. Thread->ApcStateIndex = 1;
  934. }
  935. //
  936. // If the target process is in memory, then immediately enter the
  937. // new address space by loading a new Directory Table Base. Otherwise,
  938. // insert the current thread in the target process ready list, inswap
  939. // the target process if necessary, select a new thread to run on the
  940. // the current processor and context switch to the new thread.
  941. //
  942. if (Process->State == ProcessInMemory) {
  943. Thread->ApcState.Process = Process;
  944. //
  945. // It is possible that the process is in memory, but there exist
  946. // threads in the process ready list. This can happen when memory
  947. // management forces a process attach.
  948. //
  949. NextEntry = Process->ReadyListHead.Flink;
  950. while (NextEntry != &Process->ReadyListHead) {
  951. OutThread = CONTAINING_RECORD(NextEntry, KTHREAD, WaitListEntry);
  952. RemoveEntryList(NextEntry);
  953. OutThread->ProcessReadyQueue = FALSE;
  954. KiReadyThread(OutThread);
  955. NextEntry = Process->ReadyListHead.Flink;
  956. }
  957. //
  958. // Unlock dispatcher database, unlock the thread APC lock, swap the
  959. // address space to the target process, and exit the scheduler.
  960. //
  961. KiUnlockDispatcherDatabaseFromSynchLevel();
  962. KeReleaseInStackQueuedSpinLockFromDpcLevel(LockHandle);
  963. KiSwapProcess(Process, SavedApcState->Process);
  964. KiExitDispatcher(LockHandle->OldIrql);
  965. } else {
  966. Thread->State = Ready;
  967. Thread->ProcessReadyQueue = TRUE;
  968. InsertTailList(&Process->ReadyListHead, &Thread->WaitListEntry);
  969. if (Process->State == ProcessOutOfMemory) {
  970. Process->State = ProcessInTransition;
  971. InterlockedPushEntrySingleList(&KiProcessInSwapListHead,
  972. &Process->SwapListEntry);
  973. KiSetInternalEvent(&KiSwapEvent, KiSwappingThread);
  974. }
  975. //
  976. // Set the current thread wait IRQL, release the thread APC lock,
  977. // set swap busy for the current thread, unlock the dispatcher
  978. // database, and swap context to a new thread.
  979. //
  980. Thread->WaitIrql = LockHandle->OldIrql;
  981. KeReleaseInStackQueuedSpinLockFromDpcLevel(LockHandle);
  982. KiSetContextSwapBusy(Thread);
  983. KiUnlockDispatcherDatabaseFromSynchLevel();
  984. KiSwapThread(Thread, KeGetCurrentPrcb());
  985. //
  986. // Acquire the APC lock, acquire the dispather database lock, set
  987. // the new process object address, unlock the dispatcher database,
  988. // unlock the APC lock, swap the address space to the target process,
  989. // and exit the scheduler.
  990. //
  991. KeAcquireInStackQueuedSpinLockRaiseToSynch(&Thread->ApcQueueLock,
  992. LockHandle);
  993. KiLockDispatcherDatabaseAtSynchLevel();
  994. Thread->ApcState.Process = Process;
  995. KiUnlockDispatcherDatabaseFromSynchLevel();
  996. KeReleaseInStackQueuedSpinLockFromDpcLevel(LockHandle);
  997. KiSwapProcess(Process, SavedApcState->Process);
  998. KiExitDispatcher(LockHandle->OldIrql);
  999. }
  1000. return;
  1001. }
  1002. VOID
  1003. KiMoveApcState (
  1004. IN PKAPC_STATE Source,
  1005. OUT PKAPC_STATE Destination
  1006. )
  1007. /*++
  1008. Routine Description:
  1009. This function moves the APC state from the source structure to the
  1010. destination structure and reinitializes list headers as appropriate.
  1011. Arguments:
  1012. Source - Supplies a pointer to the source APC state structure.
  1013. Destination - Supplies a pointer to the destination APC state structure.
  1014. Return Value:
  1015. None.
  1016. --*/
  1017. {
  1018. PLIST_ENTRY First;
  1019. PLIST_ENTRY Last;
  1020. //
  1021. // Copy the APC state from the source to the destination.
  1022. //
  1023. *Destination = *Source;
  1024. if (IsListEmpty(&Source->ApcListHead[KernelMode]) != FALSE) {
  1025. InitializeListHead(&Destination->ApcListHead[KernelMode]);
  1026. } else {
  1027. First = Source->ApcListHead[KernelMode].Flink;
  1028. Last = Source->ApcListHead[KernelMode].Blink;
  1029. Destination->ApcListHead[KernelMode].Flink = First;
  1030. Destination->ApcListHead[KernelMode].Blink = Last;
  1031. First->Blink = &Destination->ApcListHead[KernelMode];
  1032. Last->Flink = &Destination->ApcListHead[KernelMode];
  1033. }
  1034. if (IsListEmpty(&Source->ApcListHead[UserMode]) != FALSE) {
  1035. InitializeListHead(&Destination->ApcListHead[UserMode]);
  1036. } else {
  1037. First = Source->ApcListHead[UserMode].Flink;
  1038. Last = Source->ApcListHead[UserMode].Blink;
  1039. Destination->ApcListHead[UserMode].Flink = First;
  1040. Destination->ApcListHead[UserMode].Blink = Last;
  1041. First->Blink = &Destination->ApcListHead[UserMode];
  1042. Last->Flink = &Destination->ApcListHead[UserMode];
  1043. }
  1044. return;
  1045. }