Source code of Windows XP (NT5)
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.

1324 lines
42 KiB

  1. /*++
  2. Copyright (c) 1989 Microsoft Corporation
  3. Module Name:
  4. wait.c
  5. Abstract:
  6. This module implements the generic kernel wait routines. Functions
  7. are provided to delay execution, wait for multiple objects, wait for
  8. a single object, and ot set a client event and wait for a server event.
  9. N.B. This module is written to be a fast as possible and not as small
  10. as possible. Therefore some code sequences are duplicated to avoid
  11. procedure calls. It would also be possible to combine wait for
  12. single object into wait for multiple objects at the cost of some
  13. speed. Since wait for single object is the most common case, the
  14. two routines have been separated.
  15. Author:
  16. David N. Cutler (davec) 23-Mar-89
  17. Environment:
  18. Kernel mode only.
  19. Revision History:
  20. --*/
  21. #include "ki.h"
  22. //
  23. // Test for alertable condition.
  24. //
  25. // If alertable is TRUE and the thread is alerted for a processor
  26. // mode that is equal to the wait mode, then return immediately
  27. // with a wait completion status of ALERTED.
  28. //
  29. // Else if alertable is TRUE, the wait mode is user, and the user APC
  30. // queue is not empty, then set user APC pending, and return immediately
  31. // with a wait completion status of USER_APC.
  32. //
  33. // Else if alertable is TRUE and the thread is alerted for kernel
  34. // mode, then return immediately with a wait completion status of
  35. // ALERTED.
  36. //
  37. // Else if alertable is FALSE and the wait mode is user and there is a
  38. // user APC pending, then return immediately with a wait completion
  39. // status of USER_APC.
  40. //
  41. #define TestForAlertPending(Alertable) \
  42. if (Alertable) { \
  43. if (Thread->Alerted[WaitMode] != FALSE) { \
  44. Thread->Alerted[WaitMode] = FALSE; \
  45. WaitStatus = STATUS_ALERTED; \
  46. break; \
  47. } else if ((WaitMode != KernelMode) && \
  48. (IsListEmpty(&Thread->ApcState.ApcListHead[UserMode])) == FALSE) { \
  49. Thread->ApcState.UserApcPending = TRUE; \
  50. WaitStatus = STATUS_USER_APC; \
  51. break; \
  52. } else if (Thread->Alerted[KernelMode] != FALSE) { \
  53. Thread->Alerted[KernelMode] = FALSE; \
  54. WaitStatus = STATUS_ALERTED; \
  55. break; \
  56. } \
  57. } else if ((WaitMode != KernelMode) && (Thread->ApcState.UserApcPending)) { \
  58. WaitStatus = STATUS_USER_APC; \
  59. break; \
  60. }
  61. VOID
  62. KiAdjustQuantumThread (
  63. IN PKTHREAD Thread
  64. )
  65. /*++
  66. Routine Description:
  67. If the current thread is not a time critical or realtime thread, then
  68. adjust its quantum in accordance with the adjustment that would have
  69. occured if the thread had actually waited.
  70. Arguments:
  71. Thread - Supplies a pointer to the current thread.
  72. Return Value:
  73. None.
  74. --*/
  75. {
  76. PKPRCB Prcb;
  77. PKPROCESS Process;
  78. PKTHREAD NewThread;
  79. SCHAR ThreadPriority;
  80. if ((Thread->Priority < LOW_REALTIME_PRIORITY) &&
  81. (Thread->BasePriority < TIME_CRITICAL_PRIORITY_BOUND)) {
  82. Thread->Quantum -= WAIT_QUANTUM_DECREMENT;
  83. if (Thread->Quantum <= 0) {
  84. Process = Thread->ApcState.Process;
  85. Thread->Quantum = Process->ThreadQuantum;
  86. ThreadPriority = Thread->Priority - (Thread->PriorityDecrement + 1);
  87. if (ThreadPriority < Thread->BasePriority) {
  88. ThreadPriority = Thread->BasePriority;
  89. }
  90. Thread->PriorityDecrement = 0;
  91. if (ThreadPriority != Thread->Priority) {
  92. KiSetPriorityThread(Thread, ThreadPriority);
  93. } else {
  94. Prcb = KeGetCurrentPrcb();
  95. if (Prcb->NextThread == NULL) {
  96. NewThread = KiFindReadyThread(Thread->NextProcessor,
  97. ThreadPriority);
  98. if (NewThread != NULL) {
  99. NewThread->State = Standby;
  100. Prcb->NextThread = NewThread;
  101. }
  102. }
  103. }
  104. }
  105. }
  106. return;
  107. }
  108. //
  109. // The following macro initializes thread local variables for the delay
  110. // execution thread kernel service while context switching is disabled.
  111. //
  112. // N.B. IRQL must be raised to DPC level prior to the invocation of this
  113. // macro.
  114. //
  115. // N.B. Initialization is done in this manner so this code does not get
  116. // executed inside the dispatcher lock.
  117. //
  118. #define InitializeDelayExecution() \
  119. Thread->WaitBlockList = WaitBlock; \
  120. Thread->WaitStatus = 0; \
  121. WaitBlock->NextWaitBlock = WaitBlock; \
  122. Timer->Header.WaitListHead.Flink = &WaitBlock->WaitListEntry; \
  123. Timer->Header.WaitListHead.Blink = &WaitBlock->WaitListEntry; \
  124. Thread->Alertable = Alertable; \
  125. Thread->WaitMode = WaitMode; \
  126. Thread->WaitReason = DelayExecution; \
  127. Thread->WaitListEntry.Flink = NULL; \
  128. StackSwappable = KiIsKernelStackSwappable(WaitMode, Thread); \
  129. Thread->WaitTime = KiQueryLowTickCount()
  130. NTSTATUS
  131. KeDelayExecutionThread (
  132. IN KPROCESSOR_MODE WaitMode,
  133. IN BOOLEAN Alertable,
  134. IN PLARGE_INTEGER Interval
  135. )
  136. /*++
  137. Routine Description:
  138. This function delays the execution of the current thread for the specified
  139. interval of time.
  140. Arguments:
  141. WaitMode - Supplies the processor mode in which the delay is to occur.
  142. Alertable - Supplies a boolean value that specifies whether the delay
  143. is alertable.
  144. Interval - Supplies a pointer to the absolute or relative time over which
  145. the delay is to occur.
  146. Return Value:
  147. The wait completion status. A value of STATUS_SUCCESS is returned if
  148. the delay occurred. A value of STATUS_ALERTED is returned if the wait
  149. was aborted to deliver an alert to the current thread. A value of
  150. STATUS_USER_APC is returned if the wait was aborted to deliver a user
  151. APC to the current thread.
  152. --*/
  153. {
  154. LARGE_INTEGER DueTime;
  155. LARGE_INTEGER NewTime;
  156. PLARGE_INTEGER OriginalTime;
  157. PKPRCB Prcb;
  158. KPRIORITY Priority;
  159. PRKQUEUE Queue;
  160. LOGICAL StackSwappable;
  161. PRKTHREAD Thread;
  162. PRKTIMER Timer;
  163. PKWAIT_BLOCK WaitBlock;
  164. NTSTATUS WaitStatus;
  165. //
  166. // Set constant variables.
  167. //
  168. Thread = KeGetCurrentThread();
  169. OriginalTime = Interval;
  170. Timer = &Thread->Timer;
  171. WaitBlock = &Thread->WaitBlock[TIMER_WAIT_BLOCK];
  172. //
  173. // If the dispatcher database is already held, then initialize the thread
  174. // local variables. Otherwise, raise IRQL to DPC level, initialize the
  175. // thread local variables, and lock the dispatcher database.
  176. //
  177. if (Thread->WaitNext == FALSE) {
  178. goto WaitStart;
  179. }
  180. Thread->WaitNext = FALSE;
  181. InitializeDelayExecution();
  182. //
  183. // Start of delay loop.
  184. //
  185. // Note this loop is repeated if a kernel APC is delivered in the middle
  186. // of the delay or a kernel APC is pending on the first attempt through
  187. // the loop.
  188. //
  189. do {
  190. //
  191. // Test to determine if a kernel APC is pending.
  192. //
  193. // If a kernel APC is pending and the previous IRQL was less than
  194. // APC_LEVEL, then a kernel APC was queued by another processor just
  195. // after IRQL was raised to DISPATCH_LEVEL, but before the dispatcher
  196. // database was locked.
  197. //
  198. // N.B. that this can only happen in a multiprocessor system.
  199. //
  200. if (Thread->ApcState.KernelApcPending && (Thread->WaitIrql < APC_LEVEL)) {
  201. //
  202. // Unlock the dispatcher database and lower IRQL to its previous
  203. // value. An APC interrupt will immediately occur which will result
  204. // in the delivery of the kernel APC if possible.
  205. //
  206. KiUnlockDispatcherDatabase(Thread->WaitIrql);
  207. } else {
  208. //
  209. // Test for alert pending.
  210. //
  211. TestForAlertPending(Alertable);
  212. //
  213. // Insert the timer in the timer tree.
  214. //
  215. // N.B. The constant fields of the timer wait block are
  216. // initialized when the thread is initialized. The
  217. // constant fields include the wait object, wait key,
  218. // wait type, and the wait list entry link pointers.
  219. //
  220. if (KiInsertTreeTimer(Timer, *Interval) == FALSE) {
  221. //
  222. // If the thread is not a realtime thread, then drop the
  223. // thread priority to the base priority.
  224. //
  225. Prcb = KeGetCurrentPrcb();
  226. Priority = Thread->Priority;
  227. if (Priority < LOW_REALTIME_PRIORITY) {
  228. if (Priority != Thread->BasePriority) {
  229. Thread->PriorityDecrement = 0;
  230. KiSetPriorityThread(Thread, Thread->BasePriority);
  231. }
  232. }
  233. //
  234. // If a new thread has not been selected, then attempt to round
  235. // robin the thread with other threads at the same priority.
  236. //
  237. if (Prcb->NextThread == NULL) {
  238. Prcb->NextThread = KiFindReadyThread(Thread->NextProcessor,
  239. Thread->Priority);
  240. }
  241. //
  242. // If a new thread has been selected for execution, then
  243. // switch immediately to the selected thread.
  244. //
  245. if (Prcb->NextThread != NULL) {
  246. //
  247. // Give the current thread a new quantum and switch
  248. // context to selected thread.
  249. //
  250. // N.B. Control is returned at the original IRQL.
  251. //
  252. Thread->Preempted = FALSE;
  253. Thread->Quantum = Thread->ApcState.Process->ThreadQuantum;
  254. ASSERT(Thread->WaitIrql <= DISPATCH_LEVEL);
  255. //
  256. // Reready the thread without it being able to run on
  257. // another processor immediately.
  258. //
  259. Thread->State = Ready;
  260. InsertTailList(&KiDispatcherReadyListHead[Thread->Priority],
  261. &Thread->WaitListEntry);
  262. SetMember(Thread->Priority, KiReadySummary);
  263. WaitStatus = (NTSTATUS)KiSwapThread();
  264. goto WaitComplete;
  265. } else {
  266. WaitStatus = STATUS_SUCCESS;
  267. break;
  268. }
  269. }
  270. DueTime.QuadPart = Timer->DueTime.QuadPart;
  271. //
  272. // If the current thread is processing a queue entry, then attempt
  273. // to activate another thread that is blocked on the queue object.
  274. //
  275. Queue = Thread->Queue;
  276. if (Queue != NULL) {
  277. KiActivateWaiterQueue(Queue);
  278. }
  279. //
  280. // Set the thread wait parameters, set the thread dispatcher
  281. // state to Waiting, and insert the thread in the wait list if
  282. // the kernel stack of the current thread is swappable.
  283. //
  284. Thread->State = Waiting;
  285. if (StackSwappable != FALSE) {
  286. InsertTailList(&KiWaitListHead, &Thread->WaitListEntry);
  287. }
  288. //
  289. // Switch context to selected thread.
  290. //
  291. // N.B. Control is returned at the original IRQL.
  292. //
  293. ASSERT(Thread->WaitIrql <= DISPATCH_LEVEL);
  294. WaitStatus = (NTSTATUS)KiSwapThread();
  295. //
  296. // If the thread was not awakened to deliver a kernel mode APC,
  297. // then return the wait status.
  298. //
  299. WaitComplete:
  300. if (WaitStatus != STATUS_KERNEL_APC) {
  301. if (WaitStatus == STATUS_TIMEOUT) {
  302. WaitStatus = STATUS_SUCCESS;
  303. }
  304. return WaitStatus;
  305. }
  306. //
  307. // Reduce the time remaining before the time delay expires.
  308. //
  309. Interval = KiComputeWaitInterval(OriginalTime,
  310. &DueTime,
  311. &NewTime);
  312. }
  313. //
  314. // Raise IRQL to DPC level, initialize the thread local variables,
  315. // and lock the dispatcher database.
  316. //
  317. WaitStart:
  318. #if defined(NT_UP)
  319. Thread->WaitIrql = KeRaiseIrqlToDpcLevel();
  320. #else
  321. Thread->WaitIrql = KeRaiseIrqlToSynchLevel();
  322. #endif
  323. InitializeDelayExecution();
  324. KiLockDispatcherDatabaseAtSynchLevel();
  325. } while (TRUE);
  326. //
  327. // The thread is alerted or a user APC should be delivered. Unlock the
  328. // dispatcher database, lower IRQL to its previous value, and return the
  329. // wait status.
  330. //
  331. KiUnlockDispatcherDatabase(Thread->WaitIrql);
  332. return WaitStatus;
  333. }
  334. //
  335. // The following macro initializes thread local variables for the wait
  336. // for multiple objects kernel service while context switching is disabled.
  337. //
  338. // N.B. IRQL must be raised to DPC level prior to the invocation of this
  339. // macro.
  340. //
  341. // N.B. Initialization is done in this manner so this code does not get
  342. // executed inside the dispatcher lock.
  343. //
  344. #define InitializeWaitMultiple() \
  345. Thread->WaitBlockList = WaitBlockArray; \
  346. Thread->WaitStatus = 0; \
  347. InitializeListHead(&Timer->Header.WaitListHead); \
  348. Thread->Alertable = Alertable; \
  349. Thread->WaitMode = WaitMode; \
  350. Thread->WaitReason = (UCHAR)WaitReason; \
  351. Thread->WaitListEntry.Flink = NULL; \
  352. StackSwappable = KiIsKernelStackSwappable(WaitMode, Thread); \
  353. Thread->WaitTime= KiQueryLowTickCount()
  354. NTSTATUS
  355. KeWaitForMultipleObjects (
  356. IN ULONG Count,
  357. IN PVOID Object[],
  358. IN WAIT_TYPE WaitType,
  359. IN KWAIT_REASON WaitReason,
  360. IN KPROCESSOR_MODE WaitMode,
  361. IN BOOLEAN Alertable,
  362. IN PLARGE_INTEGER Timeout OPTIONAL,
  363. IN PKWAIT_BLOCK WaitBlockArray OPTIONAL
  364. )
  365. /*++
  366. Routine Description:
  367. This function waits until the specified objects attain a state of
  368. Signaled. The wait can be specified to wait until all of the objects
  369. attain a state of Signaled or until one of the objects attains a state
  370. of Signaled. An optional timeout can also be specified. If a timeout
  371. is not specified, then the wait will not be satisfied until the objects
  372. attain a state of Signaled. If a timeout is specified, and the objects
  373. have not attained a state of Signaled when the timeout expires, then
  374. the wait is automatically satisfied. If an explicit timeout value of
  375. zero is specified, then no wait will occur if the wait cannot be satisfied
  376. immediately. The wait can also be specified as alertable.
  377. Arguments:
  378. Count - Supplies a count of the number of objects that are to be waited
  379. on.
  380. Object[] - Supplies an array of pointers to dispatcher objects.
  381. WaitType - Supplies the type of wait to perform (WaitAll, WaitAny).
  382. WaitReason - Supplies the reason for the wait.
  383. WaitMode - Supplies the processor mode in which the wait is to occur.
  384. Alertable - Supplies a boolean value that specifies whether the wait is
  385. alertable.
  386. Timeout - Supplies a pointer to an optional absolute of relative time over
  387. which the wait is to occur.
  388. WaitBlockArray - Supplies an optional pointer to an array of wait blocks
  389. that are to used to describe the wait operation.
  390. Return Value:
  391. The wait completion status. A value of STATUS_TIMEOUT is returned if a
  392. timeout occurred. The index of the object (zero based) in the object
  393. pointer array is returned if an object satisfied the wait. A value of
  394. STATUS_ALERTED is returned if the wait was aborted to deliver an alert
  395. to the current thread. A value of STATUS_USER_APC is returned if the
  396. wait was aborted to deliver a user APC to the current thread.
  397. --*/
  398. {
  399. LARGE_INTEGER DueTime;
  400. ULONG Index;
  401. LARGE_INTEGER NewTime;
  402. PKMUTANT Objectx;
  403. PLARGE_INTEGER OriginalTime;
  404. PRKQUEUE Queue;
  405. LOGICAL StackSwappable;
  406. PRKTHREAD Thread;
  407. PRKTIMER Timer;
  408. PRKWAIT_BLOCK WaitBlock;
  409. BOOLEAN WaitSatisfied;
  410. NTSTATUS WaitStatus;
  411. PKWAIT_BLOCK WaitTimer;
  412. //
  413. // Set constant variables.
  414. //
  415. Thread = KeGetCurrentThread();
  416. OriginalTime = Timeout;
  417. Timer = &Thread->Timer;
  418. WaitTimer = &Thread->WaitBlock[TIMER_WAIT_BLOCK];
  419. //
  420. // If a wait block array has been specified, then the maximum number of
  421. // objects that can be waited on is specified by MAXIMUM_WAIT_OBJECTS.
  422. // Otherwise the builtin wait blocks in the thread object are used and
  423. // the maximum number of objects that can be waited on is specified by
  424. // THREAD_WAIT_OBJECTS. If the specified number of objects is not within
  425. // limits, then bug check.
  426. //
  427. if (ARGUMENT_PRESENT(WaitBlockArray)) {
  428. if (Count > MAXIMUM_WAIT_OBJECTS) {
  429. KeBugCheck(MAXIMUM_WAIT_OBJECTS_EXCEEDED);
  430. }
  431. } else {
  432. if (Count > THREAD_WAIT_OBJECTS) {
  433. KeBugCheck(MAXIMUM_WAIT_OBJECTS_EXCEEDED);
  434. }
  435. WaitBlockArray = &Thread->WaitBlock[0];
  436. }
  437. //
  438. // If the dispatcher database is already held, then initialize the thread
  439. // local variables. Otherwise, raise IRQL to DPC level, initialize the
  440. // thread local variables, and lock the dispatcher database.
  441. //
  442. if (Thread->WaitNext == FALSE) {
  443. goto WaitStart;
  444. }
  445. Thread->WaitNext = FALSE;
  446. InitializeWaitMultiple();
  447. //
  448. // Start of wait loop.
  449. //
  450. // Note this loop is repeated if a kernel APC is delivered in the middle
  451. // of the wait or a kernel APC is pending on the first attempt through
  452. // the loop.
  453. //
  454. do {
  455. //
  456. // Test to determine if a kernel APC is pending.
  457. //
  458. // If a kernel APC is pending and the previous IRQL was less than
  459. // APC_LEVEL, then a kernel APC was queued by another processor just
  460. // after IRQL was raised to DISPATCH_LEVEL, but before the dispatcher
  461. // database was locked.
  462. //
  463. // N.B. that this can only happen in a multiprocessor system.
  464. //
  465. if (Thread->ApcState.KernelApcPending && (Thread->WaitIrql < APC_LEVEL)) {
  466. //
  467. // Unlock the dispatcher database and lower IRQL to its previous
  468. // value. An APC interrupt will immediately occur which will result
  469. // in the delivery of the kernel APC if possible.
  470. //
  471. KiUnlockDispatcherDatabase(Thread->WaitIrql);
  472. } else {
  473. //
  474. // Construct wait blocks and check to determine if the wait is
  475. // already satisfied. If the wait is satisfied, then perform
  476. // wait completion and return. Else put current thread in a wait
  477. // state if an explicit timeout value of zero is not specified.
  478. //
  479. WaitSatisfied = TRUE;
  480. for (Index = 0; Index < Count; Index += 1) {
  481. //
  482. // Test if wait can be satisfied immediately.
  483. //
  484. Objectx = (PKMUTANT)Object[Index];
  485. ASSERT(Objectx->Header.Type != QueueObject);
  486. if (WaitType == WaitAny) {
  487. //
  488. // If the object is a mutant object and the mutant object
  489. // has been recursively acquired MINLONG times, then raise
  490. // an exception. Otherwise if the signal state of the mutant
  491. // object is greater than zero, or the current thread is
  492. // the owner of the mutant object, then satisfy the wait.
  493. //
  494. if (Objectx->Header.Type == MutantObject) {
  495. if ((Objectx->Header.SignalState > 0) ||
  496. (Thread == Objectx->OwnerThread)) {
  497. if (Objectx->Header.SignalState != MINLONG) {
  498. KiWaitSatisfyMutant(Objectx, Thread);
  499. WaitStatus = (NTSTATUS)(Index | Thread->WaitStatus);
  500. goto NoWait;
  501. } else {
  502. KiUnlockDispatcherDatabase(Thread->WaitIrql);
  503. ExRaiseStatus(STATUS_MUTANT_LIMIT_EXCEEDED);
  504. }
  505. }
  506. //
  507. // If the signal state is greater than zero, then satisfy
  508. // the wait.
  509. //
  510. } else if (Objectx->Header.SignalState > 0) {
  511. KiWaitSatisfyOther(Objectx);
  512. WaitStatus = (NTSTATUS)(Index);
  513. goto NoWait;
  514. }
  515. } else {
  516. //
  517. // If the object is a mutant object and the mutant object
  518. // has been recursively acquired MAXLONG times, then raise
  519. // an exception. Otherwise if the signal state of the mutant
  520. // object is less than or equal to zero and the current
  521. // thread is not the owner of the mutant object, then the
  522. // wait cannot be satisfied.
  523. //
  524. if (Objectx->Header.Type == MutantObject) {
  525. if ((Thread == Objectx->OwnerThread) &&
  526. (Objectx->Header.SignalState == MINLONG)) {
  527. KiUnlockDispatcherDatabase(Thread->WaitIrql);
  528. ExRaiseStatus(STATUS_MUTANT_LIMIT_EXCEEDED);
  529. } else if ((Objectx->Header.SignalState <= 0) &&
  530. (Thread != Objectx->OwnerThread)) {
  531. WaitSatisfied = FALSE;
  532. }
  533. //
  534. // If the signal state is less than or equal to zero, then
  535. // the wait cannot be satisfied.
  536. //
  537. } else if (Objectx->Header.SignalState <= 0) {
  538. WaitSatisfied = FALSE;
  539. }
  540. }
  541. //
  542. // Construct wait block for the current object.
  543. //
  544. WaitBlock = &WaitBlockArray[Index];
  545. WaitBlock->Object = (PVOID)Objectx;
  546. WaitBlock->WaitKey = (CSHORT)(Index);
  547. WaitBlock->WaitType = (USHORT)WaitType;
  548. WaitBlock->Thread = Thread;
  549. WaitBlock->NextWaitBlock = &WaitBlockArray[Index + 1];
  550. }
  551. //
  552. // If the wait type is wait all, then check to determine if the
  553. // wait can be satisfied immediately.
  554. //
  555. if ((WaitType == WaitAll) && (WaitSatisfied)) {
  556. WaitBlock->NextWaitBlock = &WaitBlockArray[0];
  557. KiWaitSatisfyAll(WaitBlock);
  558. WaitStatus = (NTSTATUS)Thread->WaitStatus;
  559. goto NoWait;
  560. }
  561. //
  562. // Test for alert pending.
  563. //
  564. TestForAlertPending(Alertable);
  565. //
  566. // The wait cannot be satisifed immediately. Check to determine if
  567. // a timeout value is specified.
  568. //
  569. if (ARGUMENT_PRESENT(Timeout)) {
  570. //
  571. // If the timeout value is zero, then return immediately without
  572. // waiting.
  573. //
  574. if (!(Timeout->LowPart | Timeout->HighPart)) {
  575. WaitStatus = (NTSTATUS)(STATUS_TIMEOUT);
  576. goto NoWait;
  577. }
  578. //
  579. // Initialize a wait block for the thread specific timer,
  580. // initialize timer wait list head, insert the timer in the
  581. // timer tree, and increment the number of wait objects.
  582. //
  583. // N.B. The constant fields of the timer wait block are
  584. // initialized when the thread is initialized. The
  585. // constant fields include the wait object, wait key,
  586. // wait type, and the wait list entry link pointers.
  587. //
  588. WaitBlock->NextWaitBlock = WaitTimer;
  589. WaitBlock = WaitTimer;
  590. if (KiInsertTreeTimer(Timer, *Timeout) == FALSE) {
  591. WaitStatus = (NTSTATUS)STATUS_TIMEOUT;
  592. goto NoWait;
  593. }
  594. DueTime.QuadPart = Timer->DueTime.QuadPart;
  595. }
  596. //
  597. // Close up the circular list of wait control blocks.
  598. //
  599. WaitBlock->NextWaitBlock = &WaitBlockArray[0];
  600. //
  601. // Insert wait blocks in object wait lists.
  602. //
  603. WaitBlock = &WaitBlockArray[0];
  604. do {
  605. Objectx = (PKMUTANT)WaitBlock->Object;
  606. InsertTailList(&Objectx->Header.WaitListHead, &WaitBlock->WaitListEntry);
  607. WaitBlock = WaitBlock->NextWaitBlock;
  608. } while (WaitBlock != &WaitBlockArray[0]);
  609. //
  610. // If the current thread is processing a queue entry, then attempt
  611. // to activate another thread that is blocked on the queue object.
  612. //
  613. Queue = Thread->Queue;
  614. if (Queue != NULL) {
  615. KiActivateWaiterQueue(Queue);
  616. }
  617. //
  618. // Set the thread wait parameters, set the thread dispatcher state
  619. // to Waiting, and insert the thread in the wait list.
  620. //
  621. Thread->State = Waiting;
  622. if (StackSwappable != FALSE) {
  623. InsertTailList(&KiWaitListHead, &Thread->WaitListEntry);
  624. }
  625. //
  626. // Switch context to selected thread.
  627. //
  628. // Control is returned at the original IRQL.
  629. //
  630. ASSERT(Thread->WaitIrql <= DISPATCH_LEVEL);
  631. WaitStatus = (NTSTATUS)KiSwapThread();
  632. //
  633. // If the thread was not awakened to deliver a kernel mode APC,
  634. // then return the wait status.
  635. //
  636. if (WaitStatus != STATUS_KERNEL_APC) {
  637. return WaitStatus;
  638. }
  639. if (ARGUMENT_PRESENT(Timeout)) {
  640. //
  641. // Reduce the amount of time remaining before timeout occurs.
  642. //
  643. Timeout = KiComputeWaitInterval(OriginalTime,
  644. &DueTime,
  645. &NewTime);
  646. }
  647. }
  648. //
  649. // Raise IRQL to DPC level, initialize the thread local variables,
  650. // and lock the dispatcher database.
  651. //
  652. WaitStart:
  653. #if defined(NT_UP)
  654. Thread->WaitIrql = KeRaiseIrqlToDpcLevel();
  655. #else
  656. Thread->WaitIrql = KeRaiseIrqlToSynchLevel();
  657. #endif
  658. InitializeWaitMultiple();
  659. KiLockDispatcherDatabaseAtSynchLevel();
  660. } while (TRUE);
  661. //
  662. // The thread is alerted or a user APC should be delivered. Unlock the
  663. // dispatcher database, lower IRQL to its previous value, and return
  664. // the wait status.
  665. //
  666. KiUnlockDispatcherDatabase(Thread->WaitIrql);
  667. return WaitStatus;
  668. //
  669. // The wait has been satisfied without actually waiting.
  670. //
  671. // If the thread priority that is less than time critical, then reduce
  672. // the thread quantum. If a quantum end occurs, then reduce the thread
  673. // priority.
  674. //
  675. NoWait:
  676. KiAdjustQuantumThread(Thread);
  677. //
  678. // Unlock the dispatcher database, lower IRQL to its previous value, and
  679. // return the wait status.
  680. //
  681. KiUnlockDispatcherDatabase(Thread->WaitIrql);
  682. return WaitStatus;
  683. }
  684. //
  685. // The following macro initializes thread local variables for the wait
  686. // for single object kernel service while context switching is disabled.
  687. //
  688. // N.B. IRQL must be raised to DPC level prior to the invocation of this
  689. // macro.
  690. //
  691. // N.B. Initialization is done in this manner so this code does not get
  692. // executed inside the dispatcher lock.
  693. //
  694. #define InitializeWaitSingle() \
  695. Thread->WaitBlockList = WaitBlock; \
  696. WaitBlock->Object = Object; \
  697. WaitBlock->WaitKey = (CSHORT)(STATUS_SUCCESS); \
  698. WaitBlock->WaitType = WaitAny; \
  699. Thread->WaitStatus = 0; \
  700. if (ARGUMENT_PRESENT(Timeout)) { \
  701. WaitBlock->NextWaitBlock = WaitTimer; \
  702. WaitTimer->NextWaitBlock = WaitBlock; \
  703. Timer->Header.WaitListHead.Flink = &WaitTimer->WaitListEntry; \
  704. Timer->Header.WaitListHead.Blink = &WaitTimer->WaitListEntry; \
  705. } else { \
  706. WaitBlock->NextWaitBlock = WaitBlock; \
  707. } \
  708. Thread->Alertable = Alertable; \
  709. Thread->WaitMode = WaitMode; \
  710. Thread->WaitReason = (UCHAR)WaitReason; \
  711. Thread->WaitListEntry.Flink = NULL; \
  712. StackSwappable = KiIsKernelStackSwappable(WaitMode, Thread); \
  713. Thread->WaitTime= KiQueryLowTickCount()
  714. NTSTATUS
  715. KeWaitForSingleObject (
  716. IN PVOID Object,
  717. IN KWAIT_REASON WaitReason,
  718. IN KPROCESSOR_MODE WaitMode,
  719. IN BOOLEAN Alertable,
  720. IN PLARGE_INTEGER Timeout OPTIONAL
  721. )
  722. /*++
  723. Routine Description:
  724. This function waits until the specified object attains a state of
  725. Signaled. An optional timeout can also be specified. If a timeout
  726. is not specified, then the wait will not be satisfied until the object
  727. attains a state of Signaled. If a timeout is specified, and the object
  728. has not attained a state of Signaled when the timeout expires, then
  729. the wait is automatically satisfied. If an explicit timeout value of
  730. zero is specified, then no wait will occur if the wait cannot be satisfied
  731. immediately. The wait can also be specified as alertable.
  732. Arguments:
  733. Object - Supplies a pointer to a dispatcher object.
  734. WaitReason - Supplies the reason for the wait.
  735. WaitMode - Supplies the processor mode in which the wait is to occur.
  736. Alertable - Supplies a boolean value that specifies whether the wait is
  737. alertable.
  738. Timeout - Supplies a pointer to an optional absolute of relative time over
  739. which the wait is to occur.
  740. Return Value:
  741. The wait completion status. A value of STATUS_TIMEOUT is returned if a
  742. timeout occurred. A value of STATUS_SUCCESS is returned if the specified
  743. object satisfied the wait. A value of STATUS_ALERTED is returned if the
  744. wait was aborted to deliver an alert to the current thread. A value of
  745. STATUS_USER_APC is returned if the wait was aborted to deliver a user
  746. APC to the current thread.
  747. --*/
  748. {
  749. LARGE_INTEGER DueTime;
  750. LARGE_INTEGER NewTime;
  751. PKMUTANT Objectx;
  752. PLARGE_INTEGER OriginalTime;
  753. PRKQUEUE Queue;
  754. LOGICAL StackSwappable;
  755. PRKTHREAD Thread;
  756. PRKTIMER Timer;
  757. PKWAIT_BLOCK WaitBlock;
  758. NTSTATUS WaitStatus;
  759. PKWAIT_BLOCK WaitTimer;
  760. //
  761. // Collect call data.
  762. //
  763. #if defined(_COLLECT_WAIT_SINGLE_CALLDATA_)
  764. RECORD_CALL_DATA(&KiWaitSingleCallData);
  765. #endif
  766. ASSERT((PsGetCurrentThread()->StartAddress != (PVOID)KeBalanceSetManager) || (ARGUMENT_PRESENT(Timeout)));
  767. //
  768. // Set constant variables.
  769. //
  770. Thread = KeGetCurrentThread();
  771. Objectx = (PKMUTANT)Object;
  772. OriginalTime = Timeout;
  773. Timer = &Thread->Timer;
  774. WaitBlock = &Thread->WaitBlock[0];
  775. WaitTimer = &Thread->WaitBlock[TIMER_WAIT_BLOCK];
  776. //
  777. // If the dispatcher database is already held, then initialize the thread
  778. // local variables. Otherwise, raise IRQL to DPC level, initialize the
  779. // thread local variables, and lock the dispatcher database.
  780. //
  781. if (Thread->WaitNext == FALSE) {
  782. goto WaitStart;
  783. }
  784. Thread->WaitNext = FALSE;
  785. InitializeWaitSingle();
  786. //
  787. // Start of wait loop.
  788. //
  789. // Note this loop is repeated if a kernel APC is delivered in the middle
  790. // of the wait or a kernel APC is pending on the first attempt through
  791. // the loop.
  792. //
  793. do {
  794. //
  795. // Test to determine if a kernel APC is pending.
  796. //
  797. // If a kernel APC is pending and the previous IRQL was less than
  798. // APC_LEVEL, then a kernel APC was queued by another processor just
  799. // after IRQL was raised to DISPATCH_LEVEL, but before the dispatcher
  800. // database was locked.
  801. //
  802. // N.B. that this can only happen in a multiprocessor system.
  803. //
  804. if (Thread->ApcState.KernelApcPending && (Thread->WaitIrql < APC_LEVEL)) {
  805. //
  806. // Unlock the dispatcher database and lower IRQL to its previous
  807. // value. An APC interrupt will immediately occur which will result
  808. // in the delivery of the kernel APC if possible.
  809. //
  810. KiUnlockDispatcherDatabase(Thread->WaitIrql);
  811. } else {
  812. //
  813. // If the object is a mutant object and the mutant object has been
  814. // recursively acquired MINLONG times, then raise an exception.
  815. // Otherwise if the signal state of the mutant object is greater
  816. // than zero, or the current thread is the owner of the mutant
  817. // object, then satisfy the wait.
  818. //
  819. ASSERT(Objectx->Header.Type != QueueObject);
  820. if (Objectx->Header.Type == MutantObject) {
  821. if ((Objectx->Header.SignalState > 0) ||
  822. (Thread == Objectx->OwnerThread)) {
  823. if (Objectx->Header.SignalState != MINLONG) {
  824. KiWaitSatisfyMutant(Objectx, Thread);
  825. WaitStatus = (NTSTATUS)(Thread->WaitStatus);
  826. goto NoWait;
  827. } else {
  828. KiUnlockDispatcherDatabase(Thread->WaitIrql);
  829. ExRaiseStatus(STATUS_MUTANT_LIMIT_EXCEEDED);
  830. }
  831. }
  832. //
  833. // If the signal state is greater than zero, then satisfy the wait.
  834. //
  835. } else if (Objectx->Header.SignalState > 0) {
  836. KiWaitSatisfyOther(Objectx);
  837. WaitStatus = (NTSTATUS)(0);
  838. goto NoWait;
  839. }
  840. //
  841. // Construct a wait block for the object.
  842. //
  843. //
  844. // Test for alert pending.
  845. //
  846. TestForAlertPending(Alertable);
  847. //
  848. // The wait cannot be satisifed immediately. Check to determine if
  849. // a timeout value is specified.
  850. //
  851. if (ARGUMENT_PRESENT(Timeout)) {
  852. //
  853. // If the timeout value is zero, then return immediately without
  854. // waiting.
  855. //
  856. if (!(Timeout->LowPart | Timeout->HighPart)) {
  857. WaitStatus = (NTSTATUS)(STATUS_TIMEOUT);
  858. goto NoWait;
  859. }
  860. //
  861. // Insert the timer in the timer tree.
  862. //
  863. // N.B. The constant fields of the timer wait block are
  864. // initialized when the thread is initialized. The
  865. // constant fields include the wait object, wait key,
  866. // wait type, and the wait list entry link pointers.
  867. //
  868. if (KiInsertTreeTimer(Timer, *Timeout) == FALSE) {
  869. WaitStatus = (NTSTATUS)STATUS_TIMEOUT;
  870. goto NoWait;
  871. }
  872. DueTime.QuadPart = Timer->DueTime.QuadPart;
  873. }
  874. //
  875. // Insert wait block in object wait list.
  876. //
  877. InsertTailList(&Objectx->Header.WaitListHead, &WaitBlock->WaitListEntry);
  878. //
  879. // If the current thread is processing a queue entry, then attempt
  880. // to activate another thread that is blocked on the queue object.
  881. //
  882. Queue = Thread->Queue;
  883. if (Queue != NULL) {
  884. KiActivateWaiterQueue(Queue);
  885. }
  886. //
  887. // Set the thread wait parameters, set the thread dispatcher state
  888. // to Waiting, and insert the thread in the wait list.
  889. //
  890. Thread->State = Waiting;
  891. if (StackSwappable != FALSE) {
  892. InsertTailList(&KiWaitListHead, &Thread->WaitListEntry);
  893. }
  894. //
  895. // Switch context to selected thread.
  896. //
  897. // Control is returned at the original IRQL.
  898. //
  899. ASSERT(Thread->WaitIrql <= DISPATCH_LEVEL);
  900. WaitStatus = (NTSTATUS)KiSwapThread();
  901. //
  902. // If the thread was not awakened to deliver a kernel mode APC,
  903. // then return wait status.
  904. //
  905. if (WaitStatus != STATUS_KERNEL_APC) {
  906. return WaitStatus;
  907. }
  908. if (ARGUMENT_PRESENT(Timeout)) {
  909. //
  910. // Reduce the amount of time remaining before timeout occurs.
  911. //
  912. Timeout = KiComputeWaitInterval(OriginalTime,
  913. &DueTime,
  914. &NewTime);
  915. }
  916. }
  917. //
  918. // Raise IRQL to DPC level, initialize the thread local variables,
  919. // and lock the dispatcher database.
  920. //
  921. WaitStart:
  922. #if defined(NT_UP)
  923. Thread->WaitIrql = KeRaiseIrqlToDpcLevel();
  924. #else
  925. Thread->WaitIrql = KeRaiseIrqlToSynchLevel();
  926. #endif
  927. InitializeWaitSingle();
  928. KiLockDispatcherDatabaseAtSynchLevel();
  929. } while (TRUE);
  930. //
  931. // The thread is alerted or a user APC should be delivered. Unlock the
  932. // dispatcher database, lower IRQL to its previous value, and return
  933. // the wait status.
  934. //
  935. KiUnlockDispatcherDatabase(Thread->WaitIrql);
  936. return WaitStatus;
  937. //
  938. // The wait has been satisfied without actually waiting.
  939. //
  940. // If the thread priority that is less than time critical, then reduce
  941. // the thread quantum. If a quantum end occurs, then reduce the thread
  942. // priority.
  943. //
  944. NoWait:
  945. KiAdjustQuantumThread(Thread);
  946. //
  947. // Unlock the dispatcher database, lower IRQL to its previous value, and
  948. // return the wait status.
  949. //
  950. KiUnlockDispatcherDatabase(Thread->WaitIrql);
  951. return WaitStatus;
  952. }
  953. NTSTATUS
  954. KiSetServerWaitClientEvent (
  955. IN PKEVENT ServerEvent,
  956. IN PKEVENT ClientEvent,
  957. IN ULONG WaitMode
  958. )
  959. /*++
  960. Routine Description:
  961. This function sets the specified server event and waits on specified
  962. client event. The wait is performed such that an optimal switch to
  963. the waiting thread occurs if possible. No timeout is associated with
  964. the wait, and thus, the issuing thread will wait until the client event
  965. is signaled or an APC is delivered.
  966. Arguments:
  967. ServerEvent - Supplies a pointer to a dispatcher object of type event.
  968. ClientEvent - Supplies a pointer to a dispatcher object of type event.
  969. WaitMode - Supplies the processor mode in which the wait is to occur.
  970. Return Value:
  971. The wait completion status. A value of STATUS_SUCCESS is returned if
  972. the specified object satisfied the wait. A value of STATUS_USER_APC is
  973. returned if the wait was aborted to deliver a user APC to the current
  974. thread.
  975. --*/
  976. {
  977. //
  978. // Set sever event and wait on client event atomically.
  979. //
  980. KeSetEvent(ServerEvent, EVENT_INCREMENT, TRUE);
  981. return KeWaitForSingleObject(ClientEvent,
  982. WrEventPair,
  983. (KPROCESSOR_MODE)WaitMode,
  984. FALSE,
  985. NULL);
  986. }
  987. PLARGE_INTEGER
  988. FASTCALL
  989. KiComputeWaitInterval (
  990. IN PLARGE_INTEGER OriginalTime,
  991. IN PLARGE_INTEGER DueTime,
  992. IN OUT PLARGE_INTEGER NewTime
  993. )
  994. /*++
  995. Routine Description:
  996. This function recomputes the wait interval after a thread has been
  997. awakened to deliver a kernel APC.
  998. Arguments:
  999. OriginalTime - Supplies a pointer to the original timeout value.
  1000. DueTime - Supplies a pointer to the previous due time.
  1001. NewTime - Supplies a pointer to a variable that receives the
  1002. recomputed wait interval.
  1003. Return Value:
  1004. A pointer to the new time is returned as the function value.
  1005. --*/
  1006. {
  1007. //
  1008. // If the original wait time was absolute, then return the same
  1009. // absolute time. Otherwise, reduce the wait time remaining before
  1010. // the time delay expires.
  1011. //
  1012. if (OriginalTime->QuadPart >= 0) {
  1013. return OriginalTime;
  1014. } else {
  1015. KiQueryInterruptTime(NewTime);
  1016. NewTime->QuadPart -= DueTime->QuadPart;
  1017. return NewTime;
  1018. }
  1019. }