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.

2969 lines
78 KiB

  1. /*++
  2. Copyright (c) 1994 Microsoft Corporation
  3. Module Name:
  4. resource.c
  5. Abstract:
  6. This module implements the executive functions to acquire and release
  7. a shared resource.
  8. Author:
  9. Gary D. Kimura [GaryKi] 25-Jun-1989
  10. David N. Cutler (davec) 20-Mar-1994
  11. Substantially rewritten to make fastlock optimizations portable
  12. across all platforms and to improve the algorithms used to be
  13. perfectly synchronized.
  14. Environment:
  15. Kernel mode only.
  16. Revision History:
  17. --*/
  18. //#define _COLLECT_RESOURCE_DATA_ 1
  19. #include "exp.h"
  20. #pragma hdrstop
  21. #include "nturtl.h"
  22. //
  23. // Define local macros to test resource state.
  24. //
  25. #define IsExclusiveWaiting(a) ((a)->NumberOfExclusiveWaiters != 0)
  26. #define IsSharedWaiting(a) ((a)->NumberOfSharedWaiters != 0)
  27. #define IsOwnedExclusive(a) (((a)->Flag & ResourceOwnedExclusive) != 0)
  28. #define IsBoostAllowed(a) (((a)->Flag & DisablePriorityBoost) == 0)
  29. //
  30. // Define priority boost flags.
  31. //
  32. #define DisablePriorityBoost 0x08
  33. LARGE_INTEGER ExShortTime = {(ULONG)(-10 * 1000 * 10), -1}; // 10 milliseconds
  34. //
  35. // Define resource assertion macro.
  36. //
  37. #if DBG
  38. VOID
  39. ExpAssertResource(
  40. IN PERESOURCE Resource
  41. );
  42. #define ASSERT_RESOURCE(_Resource) ExpAssertResource(_Resource)
  43. #else
  44. #define ASSERT_RESOURCE(_Resource)
  45. #endif
  46. //
  47. // Define locking primitives.
  48. // On UP systems, fastlocks are used.
  49. // On MP systems, a queued spinlock is used.
  50. //
  51. #if defined(NT_UP)
  52. #define EXP_LOCK_HANDLE KIRQL
  53. #define PEXP_LOCK_HANDLE PKIRQL
  54. #define EXP_LOCK_RESOURCE(_resource_, _plockhandle_) UNREFERENCED_PARAMETER(_plockhandle_); ExAcquireFastLock(&(_resource_)->SpinLock, (_plockhandle_))
  55. #define EXP_UNLOCK_RESOURCE(_resource_, _plockhandle_) ExReleaseFastLock(&(_resource_)->SpinLock, *(_plockhandle_))
  56. #else
  57. #define EXP_LOCK_HANDLE KLOCK_QUEUE_HANDLE
  58. #define PEXP_LOCK_HANDLE PKLOCK_QUEUE_HANDLE
  59. #define EXP_LOCK_RESOURCE(_resource_, _plockhandle_) KeAcquireInStackQueuedSpinLock(&(_resource_)->SpinLock, (_plockhandle_))
  60. #define EXP_UNLOCK_RESOURCE(_resource_, _plockhandle_) KeReleaseInStackQueuedSpinLock(_plockhandle_)
  61. #endif
  62. //
  63. // Define private function prototypes.
  64. //
  65. VOID
  66. FASTCALL
  67. ExpWaitForResource (
  68. IN PERESOURCE Resource,
  69. IN PVOID Object
  70. );
  71. POWNER_ENTRY
  72. FASTCALL
  73. ExpFindCurrentThread(
  74. IN PERESOURCE Resource,
  75. IN ERESOURCE_THREAD CurrentThread,
  76. IN PEXP_LOCK_HANDLE LockHandle OPTIONAL
  77. );
  78. //
  79. // Resource wait time out value.
  80. //
  81. LARGE_INTEGER ExpTimeout;
  82. //
  83. // Consecutive time outs before message. Note this is registry-settable.
  84. //
  85. ULONG ExResourceTimeoutCount = 648000;
  86. //
  87. // Global spinlock to guard access to resource lists.
  88. //
  89. KSPIN_LOCK ExpResourceSpinLock;
  90. //
  91. // Resource list used to record all resources in the system.
  92. //
  93. LIST_ENTRY ExpSystemResourcesList;
  94. //
  95. // Define executive resource performance data.
  96. //
  97. #if defined(_COLLECT_RESOURCE_DATA_)
  98. #define ExpIncrementCounter(Member) ExpResourcePerformanceData.Member += 1
  99. RESOURCE_PERFORMANCE_DATA ExpResourcePerformanceData;
  100. #else
  101. #define ExpIncrementCounter(Member)
  102. #endif
  103. #ifdef ALLOC_PRAGMA
  104. #pragma alloc_text(INIT, ExpResourceInitialization)
  105. #pragma alloc_text(PAGELK, ExQuerySystemLockInformation)
  106. #endif
  107. //
  108. // Resource strict verification (checked builds only)
  109. //
  110. // When acquiring a resource while running in a thread that is not a system
  111. // thread and runs at passive level we need to disable kernel APCs first
  112. // (KeEnterCriticalRegion()). Otherwise any user mode code can call
  113. // NtSuspendThread() which is implemented using kernel APCs and can
  114. // suspend the thread while having a resource acquired.
  115. // This will potentially deadlock the whole system.
  116. //
  117. #if DBG
  118. ULONG ExResourceStrict = 1;
  119. VOID
  120. ExCheckIfKernelApcsShouldBeDisabled (
  121. IN KIRQL Irql,
  122. IN PVOID Resource,
  123. IN PKTHREAD Thread)
  124. {
  125. if ((ExResourceStrict == 0) ||
  126. (Irql >= APC_LEVEL) ||
  127. (IS_SYSTEM_THREAD((PETHREAD)Thread)) ||
  128. (Thread->KernelApcDisable != 0)) {
  129. return;
  130. }
  131. DbgPrint ("EX: resource: APCs still enabled before resource %p acquire !!!\n", Resource);
  132. DbgBreakPoint ();
  133. }
  134. #define EX_ENSURE_APCS_DISABLED(Irql, Resource, Thread) \
  135. ExCheckIfKernelApcsShouldBeDisabled (Irql, Resource, Thread);
  136. #else
  137. #define EX_ENSURE_APCS_DISABLED(Irql, Resource, Thread)
  138. #endif // DBG
  139. BOOLEAN
  140. ExpResourceInitialization(
  141. VOID
  142. )
  143. /*++
  144. Routine Description:
  145. This function initializes global data during system initialization.
  146. Arguments:
  147. None.
  148. Return Value:
  149. BOOLEAN - TRUE
  150. --*/
  151. {
  152. #if defined(_COLLECT_RESOURCE_DATA_)
  153. ULONG Index;
  154. #endif
  155. //
  156. // Initialize resource timeout value, the system resource listhead,
  157. // and the resource spinlock.
  158. //
  159. ExpTimeout.QuadPart = Int32x32To64(4 * 1000, -10000);
  160. InitializeListHead(&ExpSystemResourcesList);
  161. KeInitializeSpinLock(&ExpResourceSpinLock);
  162. //
  163. // Initialize resource performance data.
  164. //
  165. #if defined(_COLLECT_RESOURCE_DATA_)
  166. ExpResourcePerformanceData.ActiveResourceCount = 0;
  167. ExpResourcePerformanceData.TotalResourceCount = 0;
  168. ExpResourcePerformanceData.ExclusiveAcquire = 0;
  169. ExpResourcePerformanceData.SharedFirstLevel = 0;
  170. ExpResourcePerformanceData.SharedSecondLevel = 0;
  171. ExpResourcePerformanceData.StarveFirstLevel = 0;
  172. ExpResourcePerformanceData.StarveSecondLevel = 0;
  173. ExpResourcePerformanceData.WaitForExclusive = 0;
  174. ExpResourcePerformanceData.OwnerTableExpands = 0;
  175. ExpResourcePerformanceData.MaximumTableExpand = 0;
  176. for (Index = 0; Index < RESOURCE_HASH_TABLE_SIZE; Index += 1) {
  177. InitializeListHead(&ExpResourcePerformanceData.HashTable[Index]);
  178. }
  179. #endif
  180. return TRUE;
  181. }
  182. VOID
  183. ExpAllocateExclusiveWaiterEvent (
  184. IN PERESOURCE Resource,
  185. IN PEXP_LOCK_HANDLE LockHandle
  186. )
  187. /*++
  188. Routine Description:
  189. This function allocates and initializes the exclusive waiter event
  190. for a resource.
  191. N.B. The resource spin lock is held on entry and exit of this routine.
  192. Arguments:
  193. Resource - Supplies a pointer to the resource.
  194. LockHandle - Supplies a pointer to a lock handle.
  195. Return Value:
  196. None.
  197. --*/
  198. {
  199. PKEVENT Event;
  200. //
  201. // Allocate an exclusive wait event and retry the acquire operation.
  202. //
  203. EXP_UNLOCK_RESOURCE(Resource, LockHandle);
  204. do {
  205. Event = ExAllocatePoolWithTag(NonPagedPool,
  206. sizeof(KEVENT),
  207. 'vEeR');
  208. if (Event != NULL) {
  209. KeInitializeEvent(Event, SynchronizationEvent, FALSE);
  210. if (InterlockedCompareExchangePointer(&Resource->ExclusiveWaiters,
  211. Event,
  212. NULL) != NULL) {
  213. ExFreePool(Event);
  214. }
  215. break;
  216. }
  217. KeDelayExecutionThread(KernelMode, FALSE, &ExShortTime);
  218. } while (TRUE);
  219. EXP_LOCK_RESOURCE(Resource, LockHandle);
  220. return;
  221. }
  222. VOID
  223. ExpAllocateSharedWaiterSemaphore (
  224. IN PERESOURCE Resource,
  225. IN PEXP_LOCK_HANDLE LockHandle
  226. )
  227. /*++
  228. Routine Description:
  229. This function allocates and initializes the shared waiter semaphore
  230. for a resource.
  231. N.B. The resource spin lock is held on entry and exit of this routine.
  232. Arguments:
  233. Resource - Supplies a pointer to the resource.
  234. LockHandle - Supplies a pointer to a lock handle.
  235. Return Value:
  236. None.
  237. --*/
  238. {
  239. PKSEMAPHORE Semaphore;
  240. //
  241. // Allocate and initialize a shared wait semaphore for the specified
  242. // resource.
  243. //
  244. EXP_UNLOCK_RESOURCE(Resource, LockHandle);
  245. do {
  246. Semaphore = ExAllocatePoolWithTag(NonPagedPool,
  247. sizeof(KSEMAPHORE),
  248. 'eSeR');
  249. if (Semaphore != NULL) {
  250. KeInitializeSemaphore(Semaphore, 0, MAXLONG);
  251. if (InterlockedCompareExchangePointer(&Resource->SharedWaiters,
  252. Semaphore,
  253. NULL) != NULL) {
  254. ExFreePool(Semaphore);
  255. }
  256. break;
  257. }
  258. KeDelayExecutionThread(KernelMode, FALSE, &ExShortTime);
  259. } while (TRUE);
  260. EXP_LOCK_RESOURCE(Resource, LockHandle);
  261. return;
  262. }
  263. NTSTATUS
  264. ExInitializeResourceLite(
  265. IN PERESOURCE Resource
  266. )
  267. /*++
  268. Routine Description:
  269. This routine initializes the specified resource.
  270. Arguments:
  271. Resource - Supplies a pointer to the resource to initialize.
  272. Return Value:
  273. STATUS_SUCCESS.
  274. --*/
  275. {
  276. #if defined(_COLLECT_RESOURCE_DATA_)
  277. PVOID CallersCaller;
  278. #endif
  279. ASSERT(MmDeterminePoolType(Resource) == NonPagedPool);
  280. //
  281. // Initialize the specified resource.
  282. //
  283. // N.B. All fields are initialized to zero (NULL pointers) except
  284. // the list entry and spinlock.
  285. //
  286. RtlZeroMemory(Resource, sizeof(ERESOURCE));
  287. KeInitializeSpinLock(&Resource->SpinLock);
  288. if (NtGlobalFlag & FLG_KERNEL_STACK_TRACE_DB) {
  289. Resource->CreatorBackTraceIndex = RtlLogStackBackTrace();
  290. }
  291. else {
  292. Resource->CreatorBackTraceIndex = 0;
  293. }
  294. ExInterlockedInsertTailList(&ExpSystemResourcesList,
  295. &Resource->SystemResourcesList,
  296. &ExpResourceSpinLock);
  297. //
  298. // Initialize performance data entry for the resource.
  299. //
  300. #if defined(_COLLECT_RESOURCE_DATA_)
  301. RtlGetCallersAddress(&Resource->Address, &CallersCaller);
  302. ExpResourcePerformanceData.TotalResourceCount += 1;
  303. ExpResourcePerformanceData.ActiveResourceCount += 1;
  304. #endif
  305. return STATUS_SUCCESS;
  306. }
  307. NTSTATUS
  308. ExReinitializeResourceLite(
  309. IN PERESOURCE Resource
  310. )
  311. /*++
  312. Routine Description:
  313. This routine reinitializes the specified resource.
  314. Arguments:
  315. Resource - Supplies a pointer to the resource to initialize.
  316. Return Value:
  317. STATUS_SUCCESS.
  318. --*/
  319. {
  320. PKEVENT Event;
  321. ULONG Index;
  322. POWNER_ENTRY OwnerTable;
  323. PKSEMAPHORE Semaphore;
  324. ULONG TableSize;
  325. ASSERT(MmDeterminePoolType(Resource) == NonPagedPool);
  326. //
  327. // If the resource has an owner table, then zero the owner table.
  328. //
  329. OwnerTable = Resource->OwnerTable;
  330. if (OwnerTable != NULL) {
  331. TableSize = OwnerTable->TableSize;
  332. for (Index = 1; Index < TableSize; Index += 1) {
  333. OwnerTable[Index].OwnerThread = 0;
  334. OwnerTable[Index].OwnerCount = 0;
  335. }
  336. }
  337. //
  338. // Set the active count and flags to zero.
  339. //
  340. Resource->ActiveCount = 0;
  341. Resource->Flag = 0;
  342. //
  343. // If the resource has a shared waiter semaphore, then reinitialize
  344. // it.
  345. //
  346. Semaphore = Resource->SharedWaiters;
  347. if (Semaphore != NULL) {
  348. KeInitializeSemaphore(Semaphore, 0, MAXLONG);
  349. }
  350. //
  351. // If the resource has a exclusive waiter event, then reinitialize
  352. // it.
  353. //
  354. Event = Resource->ExclusiveWaiters;
  355. if (Event != NULL) {
  356. KeInitializeEvent(Event, SynchronizationEvent, FALSE);
  357. }
  358. //
  359. // Initialize the builtin owner table.
  360. //
  361. Resource->OwnerThreads[0].OwnerThread = 0;
  362. Resource->OwnerThreads[0].OwnerCount = 0;
  363. Resource->OwnerThreads[1].OwnerThread = 0;
  364. Resource->OwnerThreads[1].OwnerCount = 0;
  365. //
  366. // Set the contention count, number of shared waiters, and number
  367. // of exclusive waiters to zero.
  368. //
  369. Resource->ContentionCount = 0;
  370. Resource->NumberOfSharedWaiters = 0;
  371. Resource->NumberOfExclusiveWaiters = 0;
  372. //
  373. // Reinitialize the resource spinlock.
  374. //
  375. KeInitializeSpinLock(&Resource->SpinLock);
  376. return STATUS_SUCCESS;
  377. }
  378. VOID
  379. ExDisableResourceBoostLite(
  380. IN PERESOURCE Resource
  381. )
  382. /*++
  383. Routine Description:
  384. This routine disables priority inversion boosting for the specified
  385. resource.
  386. Arguments:
  387. Resource - Supplies a pointer to the resource for which priority
  388. boosting is disabled.
  389. Return Value:
  390. None.
  391. --*/
  392. {
  393. EXP_LOCK_HANDLE LockHandle;
  394. //
  395. // Disable priority boosts for the specified resource.
  396. //
  397. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  398. ASSERT_RESOURCE(Resource);
  399. Resource->Flag |= DisablePriorityBoost;
  400. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  401. return;
  402. }
  403. BOOLEAN
  404. ExAcquireResourceExclusiveLite(
  405. IN PERESOURCE Resource,
  406. IN BOOLEAN Wait
  407. )
  408. /*++
  409. Routine Description:
  410. The routine acquires the specified resource for exclusive access.
  411. Arguments:
  412. Resource - Supplies a pointer to the resource that is acquired
  413. for exclusive access.
  414. Wait - A boolean value that specifies whether to wait for the
  415. resource to become available if access cannot be granted
  416. immediately.
  417. Return Value:
  418. BOOLEAN - TRUE if the resource is acquired and FALSE otherwise.
  419. --*/
  420. {
  421. ERESOURCE_THREAD CurrentThread;
  422. EXP_LOCK_HANDLE LockHandle;
  423. BOOLEAN Result;
  424. ASSERT((Resource->Flag & ResourceNeverExclusive) == 0);
  425. //
  426. // Acquire exclusive access to the specified resource.
  427. //
  428. CurrentThread = (ERESOURCE_THREAD)PsGetCurrentThread();
  429. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  430. ASSERT(KeIsExecutingDpc() == FALSE);
  431. ASSERT_RESOURCE(Resource);
  432. //
  433. // Resource acquisition must be protected from thread suspends.
  434. //
  435. EX_ENSURE_APCS_DISABLED (LockHandle.OldIrql,
  436. Resource,
  437. KeGetCurrentThread());
  438. ExpIncrementCounter(ExclusiveAcquire);
  439. //
  440. // If the active count of the resource is zero, then there is neither
  441. // an exclusive owner nor a shared owner and access to the resource can
  442. // be immediately granted. Otherwise, there is either a shared owner or
  443. // an exclusive owner.
  444. //
  445. retry:
  446. if (Resource->ActiveCount != 0) {
  447. //
  448. // The resource is either owned exclusive or shared.
  449. //
  450. // If the resource is owned exclusive and the current thread is the
  451. // owner, then increment the recursion count.
  452. //
  453. if (IsOwnedExclusive(Resource) &&
  454. (Resource->OwnerThreads[0].OwnerThread == CurrentThread)) {
  455. Resource->OwnerThreads[0].OwnerCount += 1;
  456. Result = TRUE;
  457. } else {
  458. //
  459. // The resource is either owned exclusive by some other thread,
  460. // or owned shared.
  461. //
  462. // If wait is not specified, then return that the resource was
  463. // not acquired. Otherwise, wait for exclusive access to the
  464. // resource to be granted.
  465. //
  466. if (Wait == FALSE) {
  467. Result = FALSE;
  468. } else {
  469. //
  470. // If the exclusive wait event has not yet been allocated,
  471. // then the long path code must be taken.
  472. //
  473. if (Resource->ExclusiveWaiters == NULL) {
  474. ExpAllocateExclusiveWaiterEvent(Resource, &LockHandle);
  475. goto retry;
  476. }
  477. //
  478. // Wait for exclusive access to the resource to be granted
  479. // and set the owner thread.
  480. //
  481. Resource->NumberOfExclusiveWaiters += 1;
  482. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  483. ExpWaitForResource(Resource, Resource->ExclusiveWaiters);
  484. //
  485. // N.B. It is "safe" to store the owner thread without
  486. // obtaining any locks since the thread has already
  487. // been granted exclusive ownership.
  488. //
  489. Resource->OwnerThreads[0].OwnerThread = (ERESOURCE_THREAD)PsGetCurrentThread();
  490. return TRUE;
  491. }
  492. }
  493. } else {
  494. //
  495. // The resource is not owned.
  496. //
  497. Resource->Flag |= ResourceOwnedExclusive;
  498. Resource->OwnerThreads[0].OwnerThread = CurrentThread;
  499. Resource->OwnerThreads[0].OwnerCount = 1;
  500. Resource->ActiveCount = 1;
  501. Result = TRUE;
  502. }
  503. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  504. return Result;
  505. }
  506. BOOLEAN
  507. ExTryToAcquireResourceExclusiveLite(
  508. IN PERESOURCE Resource
  509. )
  510. /*++
  511. Routine Description:
  512. The routine attempts to acquire the specified resource for exclusive
  513. access.
  514. Arguments:
  515. Resource - Supplies a pointer to the resource that is acquired
  516. for exclusive access.
  517. Return Value:
  518. BOOLEAN - TRUE if the resource is acquired and FALSE otherwise.
  519. --*/
  520. {
  521. ERESOURCE_THREAD CurrentThread;
  522. EXP_LOCK_HANDLE LockHandle;
  523. BOOLEAN Result;
  524. ASSERT((Resource->Flag & ResourceNeverExclusive) == 0);
  525. //
  526. // Attempt to acquire exclusive access to the specified resource.
  527. //
  528. CurrentThread = (ERESOURCE_THREAD)PsGetCurrentThread();
  529. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  530. ASSERT(KeIsExecutingDpc() == FALSE);
  531. ASSERT_RESOURCE(Resource);
  532. //
  533. // If the active count of the resource is zero, then there is neither
  534. // an exclusive owner nor a shared owner and access to the resource can
  535. // be immediately granted. Otherwise, if the resource is owned exclusive
  536. // and the current thread is the owner, then access to the resource can
  537. // be immediately granted. Otherwise, access cannot be granted.
  538. //
  539. Result = FALSE;
  540. if (Resource->ActiveCount == 0) {
  541. ExpIncrementCounter(ExclusiveAcquire);
  542. Resource->Flag |= ResourceOwnedExclusive;
  543. Resource->OwnerThreads[0].OwnerThread = CurrentThread;
  544. Resource->OwnerThreads[0].OwnerCount = 1;
  545. Resource->ActiveCount = 1;
  546. Result = TRUE;
  547. } else if (IsOwnedExclusive(Resource) &&
  548. (Resource->OwnerThreads[0].OwnerThread == CurrentThread)) {
  549. ExpIncrementCounter(ExclusiveAcquire);
  550. Resource->OwnerThreads[0].OwnerCount += 1;
  551. Result = TRUE;
  552. }
  553. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  554. return Result;
  555. }
  556. BOOLEAN
  557. ExAcquireResourceSharedLite(
  558. IN PERESOURCE Resource,
  559. IN BOOLEAN Wait
  560. )
  561. /*++
  562. Routine Description:
  563. The routine acquires the specified resource for shared access.
  564. Arguments:
  565. Resource - Supplies a pointer to the resource that is acquired
  566. for shared access.
  567. Wait - A boolean value that specifies whether to wait for the
  568. resource to become available if access cannot be granted
  569. immediately.
  570. Return Value:
  571. BOOLEAN - TRUE if the resource is acquired and FALSE otherwise.
  572. --*/
  573. {
  574. ERESOURCE_THREAD CurrentThread;
  575. EXP_LOCK_HANDLE LockHandle;
  576. POWNER_ENTRY OwnerEntry;
  577. //
  578. // Acquire exclusive access to the specified resource.
  579. //
  580. CurrentThread = (ERESOURCE_THREAD)PsGetCurrentThread();
  581. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  582. ASSERT(KeIsExecutingDpc() == FALSE);
  583. ASSERT_RESOURCE(Resource);
  584. //
  585. // Resource acquisition must be protected from thread suspends.
  586. //
  587. EX_ENSURE_APCS_DISABLED (LockHandle.OldIrql,
  588. Resource,
  589. KeGetCurrentThread());
  590. ExpIncrementCounter(SharedFirstLevel);
  591. //
  592. // If the active count of the resource is zero, then there is neither
  593. // an exclusive owner nor a shared owner and access to the resource can
  594. // be immediately granted.
  595. //
  596. retry:
  597. if (Resource->ActiveCount == 0) {
  598. Resource->OwnerThreads[1].OwnerThread = CurrentThread;
  599. Resource->OwnerThreads[1].OwnerCount = 1;
  600. Resource->ActiveCount = 1;
  601. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  602. return TRUE;
  603. }
  604. //
  605. // The resource is either owned exclusive or shared.
  606. //
  607. // If the resource is owned exclusive and the current thread is the
  608. // owner, then treat the shared request as an exclusive request and
  609. // increment the recursion count. Otherwise, it is owned shared.
  610. //
  611. if (IsOwnedExclusive(Resource)) {
  612. if (Resource->OwnerThreads[0].OwnerThread == CurrentThread) {
  613. Resource->OwnerThreads[0].OwnerCount += 1;
  614. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  615. return TRUE;
  616. }
  617. //
  618. // Find an empty entry in the thread array.
  619. //
  620. OwnerEntry = ExpFindCurrentThread(Resource, 0, &LockHandle);
  621. if (OwnerEntry == NULL) {
  622. goto retry;
  623. }
  624. } else {
  625. //
  626. // The resource is owned shared.
  627. //
  628. // If the current thread already has acquired the resource for
  629. // shared access, then increment the recursion count. Otherwise
  630. // grant shared access if there are no exclusive waiters.
  631. //
  632. OwnerEntry = ExpFindCurrentThread(Resource, CurrentThread, &LockHandle);
  633. if (OwnerEntry == NULL) {
  634. goto retry;
  635. }
  636. if (OwnerEntry->OwnerThread == CurrentThread) {
  637. OwnerEntry->OwnerCount += 1;
  638. ASSERT(OwnerEntry->OwnerCount != 0);
  639. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  640. return TRUE;
  641. }
  642. //
  643. // If there are no exclusive waiters, then grant shared access
  644. // to the resource. Otherwise, wait for the resource to become
  645. // available.
  646. //
  647. if (IsExclusiveWaiting(Resource) == FALSE) {
  648. OwnerEntry->OwnerThread = CurrentThread;
  649. OwnerEntry->OwnerCount = 1;
  650. Resource->ActiveCount += 1;
  651. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  652. return TRUE;
  653. }
  654. }
  655. //
  656. // The resource is either owned exclusive by some other thread, or
  657. // owned shared by some other threads, but there is an exclusive
  658. // waiter and the current thread does not already have shared access
  659. // to the resource.
  660. //
  661. // If wait is not specified, then return that the resource was
  662. // not acquired.
  663. //
  664. if (Wait == FALSE) {
  665. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  666. return FALSE;
  667. }
  668. //
  669. // If the shared wait semaphore has not yet been allocated, then the
  670. // long path must be taken.
  671. //
  672. if (Resource->SharedWaiters == NULL) {
  673. ExpAllocateSharedWaiterSemaphore(Resource, &LockHandle);
  674. goto retry;
  675. }
  676. //
  677. // Wait for shared access to the resource to be granted and increment
  678. // the recursion count.
  679. //
  680. OwnerEntry->OwnerThread = CurrentThread;
  681. OwnerEntry->OwnerCount = 1;
  682. Resource->NumberOfSharedWaiters += 1;
  683. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  684. ExpWaitForResource(Resource, Resource->SharedWaiters);
  685. return TRUE;
  686. }
  687. BOOLEAN
  688. ExAcquireSharedStarveExclusive(
  689. IN PERESOURCE Resource,
  690. IN BOOLEAN Wait
  691. )
  692. /*++
  693. Routine Description:
  694. This routine acquires the specified resource for shared access and
  695. does not wait for any pending exclusive owners.
  696. Arguments:
  697. Resource - Supplies a pointer to the resource that is acquired
  698. for shared access.
  699. Wait - A boolean value that specifies whether to wait for the
  700. resource to become available if access cannot be granted
  701. immediately.
  702. Return Value:
  703. BOOLEAN - TRUE if the resource is acquired and FALSE otherwise.
  704. --*/
  705. {
  706. ERESOURCE_THREAD CurrentThread;
  707. EXP_LOCK_HANDLE LockHandle;
  708. POWNER_ENTRY OwnerEntry;
  709. //
  710. // Acquire exclusive access to the specified resource.
  711. //
  712. CurrentThread = (ERESOURCE_THREAD)PsGetCurrentThread();
  713. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  714. ASSERT(KeIsExecutingDpc() == FALSE);
  715. ASSERT_RESOURCE(Resource);
  716. ExpIncrementCounter(StarveFirstLevel);
  717. //
  718. // If the active count of the resource is zero, then there is neither
  719. // an exclusive owner nor a shared owner and access to the resource can
  720. // be immediately granted.
  721. //
  722. retry:
  723. if (Resource->ActiveCount == 0) {
  724. Resource->OwnerThreads[1].OwnerThread = CurrentThread;
  725. Resource->OwnerThreads[1].OwnerCount = 1;
  726. Resource->ActiveCount = 1;
  727. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  728. return TRUE;
  729. }
  730. //
  731. // The resource is either owned exclusive or shared.
  732. //
  733. // If the resource is owned exclusive and the current thread is the
  734. // owner, then treat the shared request as an exclusive request and
  735. // increment the recursion count. Otherwise, it is owned shared.
  736. //
  737. if (IsOwnedExclusive(Resource)) {
  738. if (Resource->OwnerThreads[0].OwnerThread == CurrentThread) {
  739. Resource->OwnerThreads[0].OwnerCount += 1;
  740. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  741. return TRUE;
  742. }
  743. //
  744. // Find an empty entry in the thread array.
  745. //
  746. OwnerEntry = ExpFindCurrentThread(Resource, 0, &LockHandle);
  747. if (OwnerEntry == NULL) {
  748. goto retry;
  749. }
  750. } else {
  751. //
  752. // The resource is owned shared.
  753. //
  754. // If the current thread already has acquired the resource for
  755. // shared access, then increment the recursion count. Otherwise
  756. // grant shared access to the current thread.
  757. //
  758. OwnerEntry = ExpFindCurrentThread(Resource, CurrentThread, &LockHandle);
  759. if (OwnerEntry == NULL) {
  760. goto retry;
  761. }
  762. if (OwnerEntry->OwnerThread == CurrentThread) {
  763. OwnerEntry->OwnerCount += 1;
  764. ASSERT(OwnerEntry->OwnerCount != 0);
  765. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  766. return TRUE;
  767. }
  768. //
  769. // Grant the current thread shared access to the resource.
  770. //
  771. OwnerEntry->OwnerThread = CurrentThread;
  772. OwnerEntry->OwnerCount = 1;
  773. Resource->ActiveCount += 1;
  774. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  775. return TRUE;
  776. }
  777. //
  778. // The resource is owned exclusive by some other thread.
  779. //
  780. // If wait is not specified, then return that the resource was
  781. // not acquired.
  782. //
  783. if (Wait == FALSE) {
  784. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  785. return FALSE;
  786. }
  787. //
  788. // If the shared wait semaphore has not yet been allocated, then the
  789. // long path must be taken.
  790. //
  791. if (Resource->SharedWaiters == NULL) {
  792. ExpAllocateSharedWaiterSemaphore(Resource, &LockHandle);
  793. goto retry;
  794. }
  795. //
  796. // Wait for shared access to the resource to be granted and increment
  797. // the recursion count.
  798. //
  799. OwnerEntry->OwnerThread = CurrentThread;
  800. OwnerEntry->OwnerCount = 1;
  801. Resource->NumberOfSharedWaiters += 1;
  802. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  803. ExpWaitForResource(Resource, Resource->SharedWaiters);
  804. return TRUE;
  805. }
  806. BOOLEAN
  807. ExAcquireSharedWaitForExclusive(
  808. IN PERESOURCE Resource,
  809. IN BOOLEAN Wait
  810. )
  811. /*++
  812. Routine Description:
  813. This routine acquires the specified resource for shared access, but
  814. waits for any pending exclusive owners.
  815. Arguments:
  816. Resource - Supplies a pointer to the resource that is acquired
  817. for shared access.
  818. Wait - A boolean value that specifies whether to wait for the
  819. resource to become available if access cannot be granted
  820. immediately.
  821. Return Value:
  822. BOOLEAN - TRUE if the resource is acquired and FALSE otherwise.
  823. --*/
  824. {
  825. ERESOURCE_THREAD CurrentThread;
  826. EXP_LOCK_HANDLE LockHandle;
  827. POWNER_ENTRY OwnerEntry;
  828. //
  829. // Acquire exclusive access to the specified resource.
  830. //
  831. CurrentThread = (ERESOURCE_THREAD)PsGetCurrentThread();
  832. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  833. ASSERT(KeIsExecutingDpc() == FALSE);
  834. ASSERT_RESOURCE(Resource);
  835. ExpIncrementCounter(WaitForExclusive);
  836. //
  837. // If the active count of the resource is zero, then there is neither
  838. // an exclusive owner nor a shared owner and access to the resource can
  839. // be immediately granted.
  840. //
  841. retry:
  842. if (Resource->ActiveCount == 0) {
  843. Resource->OwnerThreads[1].OwnerThread = CurrentThread;
  844. Resource->OwnerThreads[1].OwnerCount = 1;
  845. Resource->ActiveCount = 1;
  846. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  847. return TRUE;
  848. }
  849. //
  850. // The resource is either owned exclusive or shared.
  851. //
  852. // If the resource is owned exclusive and the current thread is the
  853. // owner, then treat the shared request as an exclusive request and
  854. // increment the recursion count. Otherwise, it is owned shared.
  855. //
  856. if (IsOwnedExclusive(Resource)) {
  857. if (Resource->OwnerThreads[0].OwnerThread == CurrentThread) {
  858. Resource->OwnerThreads[0].OwnerCount += 1;
  859. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  860. return TRUE;
  861. }
  862. //
  863. // Find an empty entry in the thread array.
  864. //
  865. OwnerEntry = ExpFindCurrentThread(Resource, 0, &LockHandle);
  866. if (OwnerEntry == NULL) {
  867. goto retry;
  868. }
  869. } else {
  870. //
  871. // The resource is owned shared.
  872. //
  873. // If there is an exclusive waiter, then wait for the exclusive
  874. // waiter to gain access to the resource, then acquire the resource
  875. // shared without regard to exclusive waiters. Otherwise, if the
  876. // current thread already has acquired the resource for shared access,
  877. // then increment the recursion count. Otherwise grant shared access
  878. // to the current thread.
  879. //
  880. if (IsExclusiveWaiting(Resource)) {
  881. //
  882. // The resource is shared, but there is an exclusive waiter.
  883. //
  884. // It doesn't matter if this thread is already one of the shared
  885. // owner(s) - if TRUE is specified, this thread must block - an APC
  886. // will release the resource to unjam things and callers count on
  887. // this behavior.
  888. //
  889. #if 0
  890. //
  891. // This code must NOT be enabled as per the comment above.
  892. //
  893. OwnerEntry = ExpFindCurrentThread(Resource, CurrentThread, NULL);
  894. if ((OwnerEntry != NULL) &&
  895. (OwnerEntry->OwnerThread == CurrentThread)) {
  896. ASSERT(OwnerEntry->OwnerCount != 0);
  897. OwnerEntry->OwnerCount += 1;
  898. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  899. return TRUE;
  900. }
  901. #endif
  902. //
  903. // If wait is not specified, then return that the resource was
  904. // not acquired.
  905. //
  906. if (Wait == FALSE) {
  907. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  908. return FALSE;
  909. }
  910. //
  911. // If the shared wait semaphore has not yet been allocated, then
  912. // allocate and initialize it.
  913. //
  914. if (Resource->SharedWaiters == NULL) {
  915. ExpAllocateSharedWaiterSemaphore(Resource, &LockHandle);
  916. goto retry;
  917. }
  918. //
  919. // Increment the number of shared waiters and wait for shared
  920. // access to the resource to be granted to some other set of
  921. // threads, and then acquire the resource shared without regard
  922. // to exclusive access.
  923. //
  924. // N.B. The resource is left in a state such that the calling
  925. // thread does not have a reference in the owner table
  926. // for the requested access even though the active count
  927. // is incremented when control is returned. However, the
  928. // resource is owned shared at this point, so an owner
  929. // entry can simply be allocated and the owner count set
  930. // to one.
  931. //
  932. Resource->NumberOfSharedWaiters += 1;
  933. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  934. ExpWaitForResource(Resource, Resource->SharedWaiters);
  935. //
  936. // Reacquire the resource spin lock, allocate an owner entry,
  937. // and initialize the owner count to one. The active count
  938. // was already incremented when shared access was granted.
  939. //
  940. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  941. do {
  942. } while ((OwnerEntry = ExpFindCurrentThread(Resource,
  943. CurrentThread,
  944. &LockHandle)) == NULL);
  945. ASSERT(IsOwnedExclusive(Resource) == FALSE);
  946. ASSERT(Resource->ActiveCount > 0);
  947. ASSERT(OwnerEntry->OwnerThread != CurrentThread);
  948. OwnerEntry->OwnerThread = CurrentThread;
  949. OwnerEntry->OwnerCount = 1;
  950. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  951. return TRUE;
  952. } else {
  953. OwnerEntry = ExpFindCurrentThread(Resource, CurrentThread, &LockHandle);
  954. if (OwnerEntry == NULL) {
  955. goto retry;
  956. }
  957. if (OwnerEntry->OwnerThread == CurrentThread) {
  958. OwnerEntry->OwnerCount += 1;
  959. ASSERT(OwnerEntry->OwnerCount != 0);
  960. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  961. return TRUE;
  962. }
  963. //
  964. // Grant the current thread shared access to the resource.
  965. //
  966. OwnerEntry->OwnerThread = CurrentThread;
  967. OwnerEntry->OwnerCount = 1;
  968. Resource->ActiveCount += 1;
  969. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  970. return TRUE;
  971. }
  972. }
  973. //
  974. // The resource is owned exclusive by some other thread.
  975. //
  976. // If wait is not specified, then return that the resource was
  977. // not acquired.
  978. //
  979. if (Wait == FALSE) {
  980. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  981. return FALSE;
  982. }
  983. //
  984. // If the shared wait semaphore has not yet been allocated, then allocate
  985. // and initialize it.
  986. //
  987. if (Resource->SharedWaiters == NULL) {
  988. ExpAllocateSharedWaiterSemaphore(Resource, &LockHandle);
  989. goto retry;
  990. }
  991. //
  992. // Wait for shared access to the resource to be granted and increment
  993. // the recursion count.
  994. //
  995. OwnerEntry->OwnerThread = CurrentThread;
  996. OwnerEntry->OwnerCount = 1;
  997. Resource->NumberOfSharedWaiters += 1;
  998. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  999. ExpWaitForResource(Resource, Resource->SharedWaiters);
  1000. return TRUE;
  1001. }
  1002. VOID
  1003. FASTCALL
  1004. ExReleaseResourceLite(
  1005. IN PERESOURCE Resource
  1006. )
  1007. /*++
  1008. Routine Description:
  1009. This routine releases the specified resource for the current thread
  1010. and decrements the recursion count. If the count reaches zero, then
  1011. the resource may also be released.
  1012. Arguments:
  1013. Resource - Supplies a pointer to the resource to release.
  1014. Return Value:
  1015. None.
  1016. --*/
  1017. {
  1018. ERESOURCE_THREAD CurrentThread;
  1019. ULONG Index;
  1020. ULONG Number;
  1021. EXP_LOCK_HANDLE LockHandle;
  1022. POWNER_ENTRY OwnerEntry, OwnerEnd;
  1023. CurrentThread = (ERESOURCE_THREAD)PsGetCurrentThread();
  1024. //
  1025. // Acquire exclusive access to the specified resource.
  1026. //
  1027. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  1028. ASSERT_RESOURCE(Resource);
  1029. //
  1030. // Resource release must be protected from thread suspends.
  1031. //
  1032. EX_ENSURE_APCS_DISABLED (LockHandle.OldIrql,
  1033. Resource,
  1034. KeGetCurrentThread());
  1035. //
  1036. // If the resource is exclusively owned, then release exclusive
  1037. // ownership. Otherwise, release shared ownership.
  1038. //
  1039. // N.B. The two release paths are split since this is such a high
  1040. // frequency function.
  1041. //
  1042. if (IsOwnedExclusive(Resource)) {
  1043. #if DBG
  1044. //
  1045. // This can only be enabled in checked builds because this (unusual)
  1046. // behavior might have worked in earlier releases of NT. However,
  1047. // in the checked builds, this can be enabled because callers really
  1048. // should convert to using ExReleaseResourceForThreadLite instead.
  1049. //
  1050. if (Resource->OwnerThreads[0].OwnerThread != CurrentThread) {
  1051. KeBugCheckEx(RESOURCE_NOT_OWNED,
  1052. (ULONG_PTR)Resource,
  1053. (ULONG_PTR)CurrentThread,
  1054. (ULONG_PTR)Resource->OwnerTable,
  1055. 0x1);
  1056. }
  1057. #endif
  1058. //
  1059. // Decrement the recursion count and check if ownership can be
  1060. // released.
  1061. //
  1062. ASSERT(Resource->OwnerThreads[0].OwnerCount > 0);
  1063. if (--Resource->OwnerThreads[0].OwnerCount != 0) {
  1064. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1065. return;
  1066. }
  1067. //
  1068. // Clear the owner thread.
  1069. //
  1070. Resource->OwnerThreads[0].OwnerThread = 0;
  1071. //
  1072. // The thread recursion count reached zero so decrement the resource
  1073. // active count. If the active count reaches zero, then the resource
  1074. // is no longer owned and an attempt should be made to grant access to
  1075. // another thread.
  1076. //
  1077. ASSERT(Resource->ActiveCount > 0);
  1078. if (--Resource->ActiveCount == 0) {
  1079. //
  1080. // If there are shared waiters, then grant shared access to the
  1081. // resource. Otherwise, grant exclusive ownership if there are
  1082. // exclusive waiters.
  1083. //
  1084. if (IsSharedWaiting(Resource)) {
  1085. Resource->Flag &= ~ResourceOwnedExclusive;
  1086. Number = Resource->NumberOfSharedWaiters;
  1087. Resource->ActiveCount = (SHORT)Number;
  1088. Resource->NumberOfSharedWaiters = 0;
  1089. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1090. KeReleaseSemaphore(Resource->SharedWaiters, 0, Number, FALSE);
  1091. return;
  1092. } else if (IsExclusiveWaiting(Resource)) {
  1093. Resource->OwnerThreads[0].OwnerThread = 1;
  1094. Resource->OwnerThreads[0].OwnerCount = 1;
  1095. Resource->ActiveCount = 1;
  1096. Resource->NumberOfExclusiveWaiters -= 1;
  1097. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1098. KeSetEventBoostPriority(Resource->ExclusiveWaiters,
  1099. (PRKTHREAD *)&Resource->OwnerThreads[0].OwnerThread);
  1100. return;
  1101. }
  1102. Resource->Flag &= ~ResourceOwnedExclusive;
  1103. }
  1104. } else {
  1105. if (Resource->OwnerThreads[1].OwnerThread == CurrentThread) {
  1106. OwnerEntry = &Resource->OwnerThreads[1];
  1107. } else if (Resource->OwnerThreads[0].OwnerThread == CurrentThread) {
  1108. OwnerEntry = &Resource->OwnerThreads[0];
  1109. } else {
  1110. Index = ((PKTHREAD)(CurrentThread))->ResourceIndex;
  1111. OwnerEntry = Resource->OwnerTable;
  1112. if (OwnerEntry == NULL) {
  1113. KeBugCheckEx(RESOURCE_NOT_OWNED,
  1114. (ULONG_PTR)Resource,
  1115. (ULONG_PTR)CurrentThread,
  1116. (ULONG_PTR)Resource->OwnerTable,
  1117. 0x2);
  1118. }
  1119. //
  1120. // If the resource hint is not within range or the resource
  1121. // table entry does match the current thread, then search
  1122. // the owner table for a match.
  1123. //
  1124. if ((Index >= OwnerEntry->TableSize) ||
  1125. (OwnerEntry[Index].OwnerThread != CurrentThread)) {
  1126. OwnerEnd = &OwnerEntry[OwnerEntry->TableSize];
  1127. while (1) {
  1128. OwnerEntry += 1;
  1129. if (OwnerEntry >= OwnerEnd) {
  1130. KeBugCheckEx(RESOURCE_NOT_OWNED,
  1131. (ULONG_PTR)Resource,
  1132. (ULONG_PTR)CurrentThread,
  1133. (ULONG_PTR)Resource->OwnerTable,
  1134. 0x3);
  1135. }
  1136. if (OwnerEntry->OwnerThread == CurrentThread) {
  1137. break;
  1138. }
  1139. }
  1140. } else {
  1141. OwnerEntry = &OwnerEntry[Index];
  1142. }
  1143. }
  1144. //
  1145. // Decrement the recursion count and check if ownership can be
  1146. // released.
  1147. //
  1148. ASSERT(OwnerEntry->OwnerThread == CurrentThread);
  1149. ASSERT(OwnerEntry->OwnerCount > 0);
  1150. if (--OwnerEntry->OwnerCount != 0) {
  1151. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1152. return;
  1153. }
  1154. //
  1155. // Clear the owner thread.
  1156. //
  1157. OwnerEntry->OwnerThread = 0;
  1158. //
  1159. // The thread recursion count reached zero so decrement the resource
  1160. // active count. If the active count reaches zero, then the resource
  1161. // is no longer owned and an attempt should be made to grant access to
  1162. // another thread.
  1163. //
  1164. ASSERT(Resource->ActiveCount > 0);
  1165. if (--Resource->ActiveCount == 0) {
  1166. //
  1167. // If there are exclusive waiters, then grant exclusive access
  1168. // to the resource.
  1169. //
  1170. if (IsExclusiveWaiting(Resource)) {
  1171. Resource->Flag |= ResourceOwnedExclusive;
  1172. Resource->OwnerThreads[0].OwnerThread = 1;
  1173. Resource->OwnerThreads[0].OwnerCount = 1;
  1174. Resource->ActiveCount = 1;
  1175. Resource->NumberOfExclusiveWaiters -= 1;
  1176. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1177. KeSetEventBoostPriority(Resource->ExclusiveWaiters,
  1178. (PRKTHREAD *)&Resource->OwnerThreads[0].OwnerThread);
  1179. return;
  1180. }
  1181. }
  1182. }
  1183. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1184. return;
  1185. }
  1186. VOID
  1187. ExReleaseResourceForThreadLite(
  1188. IN PERESOURCE Resource,
  1189. IN ERESOURCE_THREAD CurrentThread
  1190. )
  1191. /*++
  1192. Routine Description:
  1193. This routine release the specified resource for the specified thread
  1194. and decrements the recursion count. If the count reaches zero, then
  1195. the resource may also be released.
  1196. Arguments:
  1197. Resource - Supplies a pointer to the resource to release.
  1198. Thread - Supplies the thread that originally acquired the resource.
  1199. Return Value:
  1200. None.
  1201. --*/
  1202. {
  1203. ULONG Index;
  1204. ULONG Number;
  1205. EXP_LOCK_HANDLE LockHandle;
  1206. POWNER_ENTRY OwnerEntry, OwnerEnd;
  1207. ASSERT(CurrentThread != 0);
  1208. //
  1209. // Acquire exclusive access to the specified resource.
  1210. //
  1211. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  1212. ASSERT_RESOURCE(Resource);
  1213. //
  1214. // Resource release must be protected from thread suspends.
  1215. //
  1216. EX_ENSURE_APCS_DISABLED (LockHandle.OldIrql,
  1217. Resource,
  1218. KeGetCurrentThread());
  1219. //
  1220. // If the resource is exclusively owned, then release exclusive
  1221. // ownership. Otherwise, release shared ownership.
  1222. //
  1223. // N.B. The two release paths are split since this is such a high
  1224. // frequency function.
  1225. //
  1226. if (IsOwnedExclusive(Resource)) {
  1227. ASSERT(Resource->OwnerThreads[0].OwnerThread == CurrentThread);
  1228. //
  1229. // Decrement the recursion count and check if ownership can be
  1230. // released.
  1231. //
  1232. ASSERT(Resource->OwnerThreads[0].OwnerCount > 0);
  1233. if (--Resource->OwnerThreads[0].OwnerCount != 0) {
  1234. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1235. return;
  1236. }
  1237. //
  1238. // Clear the owner thread.
  1239. //
  1240. Resource->OwnerThreads[0].OwnerThread = 0;
  1241. //
  1242. // The thread recursion count reached zero so decrement the resource
  1243. // active count. If the active count reaches zero, then the resource
  1244. // is no longer owned and an attempt should be made to grant access to
  1245. // another thread.
  1246. //
  1247. ASSERT(Resource->ActiveCount > 0);
  1248. if (--Resource->ActiveCount == 0) {
  1249. //
  1250. // If there are shared waiters, then grant shared access to the
  1251. // resource. Otherwise, grant exclusive ownership if there are
  1252. // exclusive waiters.
  1253. //
  1254. if (IsSharedWaiting(Resource)) {
  1255. Resource->Flag &= ~ResourceOwnedExclusive;
  1256. Number = Resource->NumberOfSharedWaiters;
  1257. Resource->ActiveCount = (SHORT)Number;
  1258. Resource->NumberOfSharedWaiters = 0;
  1259. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1260. KeReleaseSemaphore(Resource->SharedWaiters, 0, Number, FALSE);
  1261. return;
  1262. } else if (IsExclusiveWaiting(Resource)) {
  1263. Resource->OwnerThreads[0].OwnerThread = 1;
  1264. Resource->OwnerThreads[0].OwnerCount = 1;
  1265. Resource->ActiveCount = 1;
  1266. Resource->NumberOfExclusiveWaiters -= 1;
  1267. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1268. KeSetEventBoostPriority(Resource->ExclusiveWaiters,
  1269. (PRKTHREAD *)&Resource->OwnerThreads[0].OwnerThread);
  1270. return;
  1271. }
  1272. Resource->Flag &= ~ResourceOwnedExclusive;
  1273. }
  1274. } else {
  1275. if (Resource->OwnerThreads[1].OwnerThread == CurrentThread) {
  1276. OwnerEntry = &Resource->OwnerThreads[1];
  1277. } else if (Resource->OwnerThreads[0].OwnerThread == CurrentThread) {
  1278. OwnerEntry = &Resource->OwnerThreads[0];
  1279. } else {
  1280. //
  1281. // If the specified current thread is an owner address (low
  1282. // bits are nonzero), then set the hint index to the first
  1283. // entry. Otherwise, set the hint index from the owner thread.
  1284. //
  1285. Index = 1;
  1286. if (((ULONG)CurrentThread & 3) == 0) {
  1287. Index = ((PKTHREAD)(CurrentThread))->ResourceIndex;
  1288. }
  1289. OwnerEntry = Resource->OwnerTable;
  1290. ASSERT(OwnerEntry != NULL);
  1291. //
  1292. // If the resource hint is not within range or the resource
  1293. // table entry does match the current thread, then search
  1294. // the owner table for a match.
  1295. //
  1296. if ((Index >= OwnerEntry->TableSize) ||
  1297. (OwnerEntry[Index].OwnerThread != CurrentThread)) {
  1298. OwnerEnd = &OwnerEntry[OwnerEntry->TableSize];
  1299. while (1) {
  1300. OwnerEntry += 1;
  1301. if (OwnerEntry >= OwnerEnd) {
  1302. KeBugCheckEx(RESOURCE_NOT_OWNED,
  1303. (ULONG_PTR)Resource,
  1304. (ULONG_PTR)CurrentThread,
  1305. (ULONG_PTR)Resource->OwnerTable,
  1306. 0x3);
  1307. }
  1308. if (OwnerEntry->OwnerThread == CurrentThread) {
  1309. break;
  1310. }
  1311. }
  1312. } else {
  1313. OwnerEntry = &OwnerEntry[Index];
  1314. }
  1315. }
  1316. //
  1317. // Decrement the recursion count and check if ownership can be
  1318. // released.
  1319. //
  1320. ASSERT(OwnerEntry->OwnerThread == CurrentThread);
  1321. ASSERT(OwnerEntry->OwnerCount > 0);
  1322. if (--OwnerEntry->OwnerCount != 0) {
  1323. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1324. return;
  1325. }
  1326. //
  1327. // Clear the owner thread.
  1328. //
  1329. OwnerEntry->OwnerThread = 0;
  1330. //
  1331. // The thread recursion count reached zero so decrement the resource
  1332. // active count. If the active count reaches zero, then the resource
  1333. // is no longer owned and an attempt should be made to grant access to
  1334. // another thread.
  1335. //
  1336. ASSERT(Resource->ActiveCount > 0);
  1337. if (--Resource->ActiveCount == 0) {
  1338. //
  1339. // If there are exclusive waiters, then grant exclusive access
  1340. // to the resource.
  1341. //
  1342. if (IsExclusiveWaiting(Resource)) {
  1343. Resource->Flag |= ResourceOwnedExclusive;
  1344. Resource->OwnerThreads[0].OwnerThread = 1;
  1345. Resource->OwnerThreads[0].OwnerCount = 1;
  1346. Resource->ActiveCount = 1;
  1347. Resource->NumberOfExclusiveWaiters -= 1;
  1348. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1349. KeSetEventBoostPriority(Resource->ExclusiveWaiters,
  1350. (PRKTHREAD *)&Resource->OwnerThreads[0].OwnerThread);
  1351. return;
  1352. }
  1353. }
  1354. }
  1355. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1356. return;
  1357. }
  1358. VOID
  1359. ExSetResourceOwnerPointer(
  1360. IN PERESOURCE Resource,
  1361. IN PVOID OwnerPointer
  1362. )
  1363. /*++
  1364. Routine Description:
  1365. This routine locates the owner entry for the current thread and stores
  1366. the specified owner address as the owner thread. Subsequent to calling
  1367. this routine, the only routine which may be called for this resource is
  1368. ExReleaseResourceForThreadLite, supplying the owner address as the "thread".
  1369. Owner addresses must obey the following rules:
  1370. They must be a unique pointer to a structure allocated in system space,
  1371. and they must point to a structure which remains allocated until after
  1372. the call to ExReleaseResourceForThreadLite. This is to eliminate aliasing
  1373. with a thread or other owner address.
  1374. The low order two bits of the owner address must be set by the caller,
  1375. so that other routines in the resource package can distinguish owner
  1376. address from thread addresses.
  1377. Arguments:
  1378. Resource - Supplies a pointer to the resource to release.
  1379. OwnerPointer - Supplies a pointer to an allocated structure with the low
  1380. order two bits set.
  1381. Return Value:
  1382. None.
  1383. --*/
  1384. {
  1385. ERESOURCE_THREAD CurrentThread;
  1386. ULONG Index;
  1387. EXP_LOCK_HANDLE LockHandle;
  1388. POWNER_ENTRY OwnerEntry, OwnerEnd;
  1389. ASSERT((OwnerPointer != 0) && (((ULONG_PTR)OwnerPointer & 3) == 3));
  1390. CurrentThread = (ERESOURCE_THREAD)PsGetCurrentThread();
  1391. //
  1392. // Acquire exclusive access to the specified resource.
  1393. //
  1394. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  1395. ASSERT_RESOURCE(Resource);
  1396. //
  1397. // If the resource is exclusively owned, then it is the first owner entry.
  1398. //
  1399. if (IsOwnedExclusive(Resource)) {
  1400. ASSERT(Resource->OwnerThreads[0].OwnerThread == CurrentThread);
  1401. //
  1402. // Set the owner address.
  1403. //
  1404. ASSERT(Resource->OwnerThreads[0].OwnerCount > 0);
  1405. Resource->OwnerThreads[0].OwnerThread = (ULONG_PTR)OwnerPointer;
  1406. //
  1407. // For shared access we have to search for the current thread to set
  1408. // the owner address.
  1409. //
  1410. } else {
  1411. if (Resource->OwnerThreads[1].OwnerThread == CurrentThread) {
  1412. Resource->OwnerThreads[1].OwnerThread = (ULONG_PTR)OwnerPointer;
  1413. } else if (Resource->OwnerThreads[0].OwnerThread == CurrentThread) {
  1414. Resource->OwnerThreads[0].OwnerThread = (ULONG_PTR)OwnerPointer;
  1415. } else {
  1416. Index = ((PKTHREAD)(CurrentThread))->ResourceIndex;
  1417. OwnerEntry = Resource->OwnerTable;
  1418. ASSERT(OwnerEntry != NULL);
  1419. //
  1420. // If the resource hint is not within range or the resource
  1421. // table entry does match the current thread, then search
  1422. // the owner table for a match.
  1423. //
  1424. if ((Index >= OwnerEntry->TableSize) ||
  1425. (OwnerEntry[Index].OwnerThread != CurrentThread)) {
  1426. OwnerEnd = &OwnerEntry[OwnerEntry->TableSize];
  1427. while (1) {
  1428. OwnerEntry += 1;
  1429. if (OwnerEntry >= OwnerEnd) {
  1430. KeBugCheckEx(RESOURCE_NOT_OWNED,
  1431. (ULONG_PTR)Resource,
  1432. (ULONG_PTR)CurrentThread,
  1433. (ULONG_PTR)Resource->OwnerTable,
  1434. 0x3);
  1435. }
  1436. if (OwnerEntry->OwnerThread == CurrentThread) {
  1437. break;
  1438. }
  1439. }
  1440. } else {
  1441. OwnerEntry = &OwnerEntry[Index];
  1442. }
  1443. OwnerEntry->OwnerThread = (ULONG_PTR)OwnerPointer;
  1444. }
  1445. }
  1446. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1447. return;
  1448. }
  1449. VOID
  1450. ExConvertExclusiveToSharedLite(
  1451. IN PERESOURCE Resource
  1452. )
  1453. /*++
  1454. Routine Description:
  1455. This routine converts the specified resource from acquired for exclusive
  1456. access to acquired for shared access.
  1457. Arguments:
  1458. Resource - Supplies a pointer to the resource to acquire for shared access. it
  1459. Return Value:
  1460. None.
  1461. --*/
  1462. {
  1463. ULONG Number;
  1464. EXP_LOCK_HANDLE LockHandle;
  1465. //
  1466. // Acquire exclusive access to the specified resource.
  1467. //
  1468. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  1469. ASSERT(KeIsExecutingDpc() == FALSE);
  1470. ASSERT_RESOURCE(Resource);
  1471. ASSERT(IsOwnedExclusive(Resource));
  1472. ASSERT(Resource->OwnerThreads[0].OwnerThread == (ERESOURCE_THREAD)PsGetCurrentThread());
  1473. //
  1474. // Convert the granted access from exclusive to shared.
  1475. //
  1476. Resource->Flag &= ~ResourceOwnedExclusive;
  1477. //
  1478. // If there are any shared waiters, then grant them shared access.
  1479. //
  1480. if (IsSharedWaiting(Resource)) {
  1481. Number = Resource->NumberOfSharedWaiters;
  1482. Resource->ActiveCount = (SHORT)(Resource->ActiveCount + Number);
  1483. Resource->NumberOfSharedWaiters = 0;
  1484. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1485. KeReleaseSemaphore(Resource->SharedWaiters, 0, Number, FALSE);
  1486. return;
  1487. }
  1488. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1489. return;
  1490. }
  1491. NTSTATUS
  1492. ExDeleteResourceLite(
  1493. IN PERESOURCE Resource
  1494. )
  1495. /*++
  1496. Routine Description:
  1497. This routine deallocates any pool allocated to support the specified
  1498. resource.
  1499. Arguments:
  1500. Resource - Supplies a pointer to the resource whose allocated pool
  1501. is freed.
  1502. Return Value:
  1503. STATUS_SUCCESS.
  1504. --*/
  1505. {
  1506. #if defined(_COLLECT_RESOURCE_DATA_)
  1507. ULONG Hash;
  1508. PLIST_ENTRY NextEntry;
  1509. PRESOURCE_HASH_ENTRY MatchEntry;
  1510. PRESOURCE_HASH_ENTRY HashEntry;
  1511. #endif
  1512. KIRQL OldIrql;
  1513. ASSERT(IsSharedWaiting(Resource) == FALSE);
  1514. ASSERT(IsExclusiveWaiting(Resource) == FALSE);
  1515. //
  1516. // Acquire the executive resource spinlock and remove the resource from
  1517. // the system resource list.
  1518. //
  1519. ExAcquireSpinLock(&ExpResourceSpinLock, &OldIrql);
  1520. ASSERT(KeIsExecutingDpc() == FALSE);
  1521. ASSERT_RESOURCE(Resource);
  1522. RemoveEntryList(&Resource->SystemResourcesList);
  1523. #if defined(_COLLECT_RESOURCE_DATA_)
  1524. //
  1525. // Lookup resource initialization address in resource hash table. If
  1526. // the address does not exist in the table, then create a new entry.
  1527. //
  1528. Hash = (ULONG)Resource->Address;
  1529. Hash = ((Hash >> 24) ^ (Hash >> 16) ^ (Hash >> 8) ^ (Hash)) & (RESOURCE_HASH_TABLE_SIZE - 1);
  1530. MatchEntry = NULL;
  1531. NextEntry = ExpResourcePerformanceData.HashTable[Hash].Flink;
  1532. while (NextEntry != &ExpResourcePerformanceData.HashTable[Hash]) {
  1533. HashEntry = CONTAINING_RECORD(NextEntry,
  1534. RESOURCE_HASH_ENTRY,
  1535. ListEntry);
  1536. if (HashEntry->Address == Resource->Address) {
  1537. MatchEntry = HashEntry;
  1538. break;
  1539. }
  1540. NextEntry = NextEntry->Flink;
  1541. }
  1542. //
  1543. // If a matching initialization address was found, then update the call
  1544. // site statistics. Otherwise, allocate a new hash entry and initialize
  1545. // call site statistics.
  1546. //
  1547. if (MatchEntry != NULL) {
  1548. MatchEntry->ContentionCount += Resource->ContentionCount;
  1549. MatchEntry->Number += 1;
  1550. } else {
  1551. MatchEntry = ExAllocatePoolWithTag(NonPagedPool,
  1552. sizeof(RESOURCE_HASH_ENTRY),
  1553. 'vEpR');
  1554. if (MatchEntry != NULL) {
  1555. MatchEntry->Address = Resource->Address;
  1556. MatchEntry->ContentionCount = Resource->ContentionCount;
  1557. MatchEntry->Number = 1;
  1558. InsertTailList(&ExpResourcePerformanceData.HashTable[Hash],
  1559. &MatchEntry->ListEntry);
  1560. }
  1561. }
  1562. ExpResourcePerformanceData.ActiveResourceCount -= 1;
  1563. #endif
  1564. ExReleaseSpinLock(&ExpResourceSpinLock, OldIrql);
  1565. //
  1566. // If an owner table was allocated, then free it to pool.
  1567. //
  1568. if (Resource->OwnerTable != NULL) {
  1569. ExFreePool(Resource->OwnerTable);
  1570. }
  1571. //
  1572. // If a semaphore was allocated, then free it to pool.
  1573. //
  1574. if (Resource->SharedWaiters) {
  1575. ExFreePool(Resource->SharedWaiters);
  1576. }
  1577. //
  1578. // If an event was allocated, then free it to pool.
  1579. //
  1580. if (Resource->ExclusiveWaiters) {
  1581. ExFreePool(Resource->ExclusiveWaiters);
  1582. }
  1583. return STATUS_SUCCESS;
  1584. }
  1585. ULONG
  1586. ExGetExclusiveWaiterCount(
  1587. IN PERESOURCE Resource
  1588. )
  1589. /*++
  1590. Routine Description:
  1591. This routine returns the exclusive waiter count.
  1592. Arguments:
  1593. Resource - Supplies a pointer to and executive resource.
  1594. Return Value:
  1595. The current number of exclusive waiters is returned as the function
  1596. value.
  1597. --*/
  1598. {
  1599. return Resource->NumberOfExclusiveWaiters;
  1600. }
  1601. ULONG
  1602. ExGetSharedWaiterCount(
  1603. IN PERESOURCE Resource
  1604. )
  1605. /*++
  1606. Routine Description:
  1607. This routine returns the shared waiter count.
  1608. Arguments:
  1609. Resource - Supplies a pointer to and executive resource.
  1610. Return Value:
  1611. The current number of shared waiters is returned as the function
  1612. value.
  1613. --*/
  1614. {
  1615. return Resource->NumberOfSharedWaiters;
  1616. }
  1617. BOOLEAN
  1618. ExIsResourceAcquiredExclusiveLite(
  1619. IN PERESOURCE Resource
  1620. )
  1621. /*++
  1622. Routine Description:
  1623. This routine determines if a resource is acquired exclusive by the
  1624. calling thread.
  1625. Arguments:
  1626. Resource - Supplies a pointer the resource to query.
  1627. Return Value:
  1628. If the current thread has acquired the resource exclusive, a value of
  1629. TRUE is returned. Otherwise, a value of FALSE is returned.
  1630. --*/
  1631. {
  1632. ERESOURCE_THREAD CurrentThread;
  1633. EXP_LOCK_HANDLE LockHandle;
  1634. BOOLEAN Result;
  1635. //
  1636. // Acquire exclusive access to the specified resource.
  1637. //
  1638. CurrentThread = (ERESOURCE_THREAD)PsGetCurrentThread();
  1639. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  1640. ASSERT_RESOURCE(Resource);
  1641. //
  1642. // If the resource is owned exclusive and the current thread is the
  1643. // owner, then set the return value of TRUE. Otherwise, set the return
  1644. // value to FALSE.
  1645. //
  1646. Result = FALSE;
  1647. if ((IsOwnedExclusive(Resource)) &&
  1648. (Resource->OwnerThreads[0].OwnerThread == CurrentThread)) {
  1649. Result = TRUE;
  1650. }
  1651. //
  1652. // Release exclusive access to the specified resource.
  1653. //
  1654. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1655. return Result;
  1656. }
  1657. ULONG
  1658. ExIsResourceAcquiredSharedLite(
  1659. IN PERESOURCE Resource
  1660. )
  1661. /*++
  1662. Routine Description:
  1663. This routine determines if a resource is acquired either shared or
  1664. exclusive by the calling thread.
  1665. Arguments:
  1666. Resource - Supplies a pointer to the resource to query.
  1667. Return Value:
  1668. If the current thread has not acquired the resource a value of zero
  1669. is returned. Otherwise, the thread's acquire count is returned.
  1670. --*/
  1671. {
  1672. ERESOURCE_THREAD CurrentThread;
  1673. ULONG Index;
  1674. ULONG Number;
  1675. POWNER_ENTRY OwnerEntry;
  1676. ULONG Result;
  1677. EXP_LOCK_HANDLE LockHandle;
  1678. //
  1679. // Acquire exclusive access to the specified resource.
  1680. //
  1681. CurrentThread = (ERESOURCE_THREAD)PsGetCurrentThread();
  1682. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  1683. ASSERT_RESOURCE(Resource);
  1684. //
  1685. // Find the current thread in the thread array and return the count.
  1686. //
  1687. // N.B. If the thread is not found a value of zero will be returned.
  1688. //
  1689. if (Resource->OwnerThreads[0].OwnerThread == CurrentThread) {
  1690. Result = Resource->OwnerThreads[0].OwnerCount;
  1691. } else if (Resource->OwnerThreads[1].OwnerThread == CurrentThread) {
  1692. Result = Resource->OwnerThreads[1].OwnerCount;
  1693. } else {
  1694. //
  1695. // If the resource hint is not within range or the resource table
  1696. // entry does not match the current thread, then search the owner
  1697. // table for a match.
  1698. //
  1699. OwnerEntry = Resource->OwnerTable;
  1700. Result = 0;
  1701. if (OwnerEntry != NULL) {
  1702. Index = ((PKTHREAD)(CurrentThread))->ResourceIndex;
  1703. Number = OwnerEntry->TableSize;
  1704. if ((Index >= Number) ||
  1705. (OwnerEntry[Index].OwnerThread != CurrentThread)) {
  1706. for (Index = 1; Index < Number; Index += 1) {
  1707. OwnerEntry += 1;
  1708. if (OwnerEntry->OwnerThread == CurrentThread) {
  1709. Result = OwnerEntry->OwnerCount;
  1710. break;
  1711. }
  1712. }
  1713. } else {
  1714. Result = OwnerEntry[Index].OwnerCount;
  1715. }
  1716. }
  1717. }
  1718. //
  1719. // Release exclusive access to the specified resource.
  1720. //
  1721. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1722. return Result;
  1723. }
  1724. NTSTATUS
  1725. ExQuerySystemLockInformation(
  1726. OUT PRTL_PROCESS_LOCKS LockInformation,
  1727. IN ULONG LockInformationLength,
  1728. OUT PULONG ReturnLength OPTIONAL
  1729. )
  1730. {
  1731. NTSTATUS Status;
  1732. KIRQL OldIrql;
  1733. ULONG RequiredLength;
  1734. PLIST_ENTRY Head, Next;
  1735. PRTL_PROCESS_LOCK_INFORMATION LockInfo;
  1736. PERESOURCE Resource;
  1737. PETHREAD OwningThread;
  1738. RequiredLength = FIELD_OFFSET(RTL_PROCESS_LOCKS, Locks);
  1739. if (LockInformationLength < RequiredLength) {
  1740. Status = STATUS_INFO_LENGTH_MISMATCH;
  1741. } else {
  1742. Status = STATUS_SUCCESS;
  1743. ExAcquireSpinLock(&ExpResourceSpinLock, &OldIrql);
  1744. try {
  1745. LockInformation->NumberOfLocks = 0;
  1746. LockInfo = &LockInformation->Locks[0];
  1747. Head = &ExpSystemResourcesList;
  1748. Next = Head->Flink;
  1749. while (Next != Head) {
  1750. Resource = CONTAINING_RECORD(Next,
  1751. ERESOURCE,
  1752. SystemResourcesList);
  1753. LockInformation->NumberOfLocks += 1;
  1754. RequiredLength += sizeof(RTL_PROCESS_LOCK_INFORMATION);
  1755. if (LockInformationLength < RequiredLength) {
  1756. Status = STATUS_INFO_LENGTH_MISMATCH;
  1757. } else {
  1758. LockInfo->Address = Resource;
  1759. LockInfo->Type = RTL_RESOURCE_TYPE;
  1760. LockInfo->CreatorBackTraceIndex = 0;
  1761. #if i386 && !FPO
  1762. LockInfo->CreatorBackTraceIndex = (USHORT)Resource->CreatorBackTraceIndex;
  1763. #endif // i386 && !FPO
  1764. if ((Resource->OwnerThreads[0].OwnerThread != 0) &&
  1765. ((Resource->OwnerThreads[0].OwnerThread & 3) == 0)) {
  1766. OwningThread = (PETHREAD)(Resource->OwnerThreads[0].OwnerThread);
  1767. LockInfo->OwningThread = OwningThread->Cid.UniqueThread;
  1768. } else {
  1769. LockInfo->OwningThread = 0;
  1770. }
  1771. LockInfo->LockCount = Resource->ActiveCount;
  1772. LockInfo->ContentionCount = Resource->ContentionCount;
  1773. LockInfo->NumberOfWaitingShared = Resource->NumberOfSharedWaiters;
  1774. LockInfo->NumberOfWaitingExclusive = Resource->NumberOfExclusiveWaiters;
  1775. LockInfo += 1;
  1776. }
  1777. if (Next == Next->Flink) {
  1778. Next = Head;
  1779. } else {
  1780. Next = Next->Flink;
  1781. }
  1782. }
  1783. } finally {
  1784. ExReleaseSpinLock(&ExpResourceSpinLock, OldIrql);
  1785. }
  1786. }
  1787. if (ARGUMENT_PRESENT(ReturnLength)) {
  1788. *ReturnLength = RequiredLength;
  1789. }
  1790. return Status;
  1791. }
  1792. VOID
  1793. FASTCALL
  1794. ExpBoostOwnerThread (
  1795. IN PKTHREAD CurrentThread,
  1796. IN PKTHREAD OwnerThread
  1797. )
  1798. /*++
  1799. Routine Description:
  1800. This function boots the priority of the specified owner thread iff
  1801. its priority is less than that of the current thread and is also
  1802. less than fourteen.
  1803. N.B. this function is called with the dispatcher database lock held.
  1804. Arguments:
  1805. CurrentThread - Supplies a pointer to the current thread object.
  1806. OwnerThread - Supplies a pointer to the owner thread object.
  1807. Return Value:
  1808. None.
  1809. --*/
  1810. {
  1811. //
  1812. // If the owner thread is lower priority than the current thread, the
  1813. // current thread is running at a priority less than 14, then boost the
  1814. // priority of the owner thread for a quantum.
  1815. //
  1816. // N.B. A thread that has already been boosted may be reboosted to allow
  1817. // it to execute and release resources. When the boost is removed,
  1818. // the thread will return to its priority before any boosting.
  1819. //
  1820. if (((ULONG_PTR)OwnerThread & 0x3) == 0) {
  1821. if ((OwnerThread->Priority < CurrentThread->Priority) &&
  1822. (OwnerThread->Priority < 14)) {
  1823. OwnerThread->PriorityDecrement += 14 - OwnerThread->Priority;
  1824. OwnerThread->DecrementCount = ROUND_TRIP_DECREMENT_COUNT;
  1825. KiSetPriorityThread(OwnerThread, 14);
  1826. OwnerThread->Quantum = OwnerThread->ApcState.Process->ThreadQuantum;
  1827. }
  1828. }
  1829. return;
  1830. }
  1831. VOID
  1832. FASTCALL
  1833. ExpWaitForResource (
  1834. IN PERESOURCE Resource,
  1835. IN PVOID Object
  1836. )
  1837. /*++
  1838. Routine Description:
  1839. The routine waits for the specified resource object to be set. If the
  1840. wait is too long the priority of the current owners of the resource
  1841. are boosted.
  1842. Arguments:
  1843. Resource - Supplies a pointer to the resource to wait for.
  1844. Object - Supplies a pointer to an event (exclusive) or semaphore
  1845. (shared) to wait for.
  1846. Return Value:
  1847. None.
  1848. --*/
  1849. {
  1850. ULONG Index;
  1851. ULONG Limit;
  1852. ULONG Number;
  1853. POWNER_ENTRY OwnerEntry;
  1854. PKTHREAD OwnerThread;
  1855. NTSTATUS Status;
  1856. PKTHREAD CurrentThread;
  1857. LARGE_INTEGER Timeout;
  1858. #if DBG
  1859. EXP_LOCK_HANDLE LockHandle;
  1860. #endif
  1861. //
  1862. // Increment the contention count for the resource, set the initial
  1863. // timeout value, and wait for the specified object to be signalled
  1864. // or a timeout to occur.
  1865. //
  1866. Limit = 0;
  1867. Resource->ContentionCount += 1;
  1868. Timeout.QuadPart = 500 * -10000;
  1869. do {
  1870. Status = KeWaitForSingleObject (
  1871. Object,
  1872. Executive,
  1873. KernelMode,
  1874. FALSE,
  1875. &Timeout );
  1876. if (Status != STATUS_TIMEOUT) {
  1877. break;
  1878. }
  1879. //
  1880. // The limit has been exceeded, then output status information.
  1881. //
  1882. Limit += 1;
  1883. Timeout = ExpTimeout;
  1884. if (Limit > ExResourceTimeoutCount) {
  1885. Limit = 0;
  1886. #if DBG
  1887. //
  1888. // Output information for the specified resource.
  1889. //
  1890. EXP_LOCK_RESOURCE(Resource, &LockHandle);
  1891. DbgPrint("Resource @ %p\n", Resource);
  1892. DbgPrint(" ActiveCount = %04lx Flags = %s%s%s\n",
  1893. Resource->ActiveCount,
  1894. IsOwnedExclusive(Resource) ? "IsOwnedExclusive " : "",
  1895. IsSharedWaiting(Resource) ? "SharedWaiter " : "",
  1896. IsExclusiveWaiting(Resource) ? "ExclusiveWaiter " : "");
  1897. DbgPrint(" NumberOfExclusiveWaiters = %04lx\n", Resource->NumberOfExclusiveWaiters);
  1898. DbgPrint(" Thread = %p, Count = %02x\n",
  1899. Resource->OwnerThreads[0].OwnerThread,
  1900. Resource->OwnerThreads[0].OwnerCount);
  1901. DbgPrint(" Thread = %p, Count = %02x\n",
  1902. Resource->OwnerThreads[1].OwnerThread,
  1903. Resource->OwnerThreads[1].OwnerCount);
  1904. OwnerEntry = Resource->OwnerTable;
  1905. if (OwnerEntry != NULL) {
  1906. Number = OwnerEntry->TableSize;
  1907. for(Index = 1; Index < Number; Index += 1) {
  1908. OwnerEntry += 1;
  1909. DbgPrint(" Thread = %p, Count = %02x\n",
  1910. OwnerEntry->OwnerThread,
  1911. OwnerEntry->OwnerCount);
  1912. }
  1913. }
  1914. DbgBreakPoint();
  1915. DbgPrint("EX - Rewaiting\n");
  1916. EXP_UNLOCK_RESOURCE(Resource, &LockHandle);
  1917. #endif
  1918. }
  1919. //
  1920. // If priority boosts are allowed, then attempt to boost the priority
  1921. // of owner threads.
  1922. //
  1923. if (IsBoostAllowed(Resource)) {
  1924. //
  1925. // Get the current thread address, lock the dispatcher database,
  1926. // and set wait next in the current thread so the dispatcher
  1927. // database lock does not need to be released before waiting
  1928. // for the resource.
  1929. //
  1930. // N.B. Since the dispatcher database lock instead of the resource
  1931. // lock is being used to synchronize access to the resource,
  1932. // it is possible for the information being read from the
  1933. // resource to be stale. However, the important thing that
  1934. // cannot change is a valid thread address. Thus a thread
  1935. // could possibly get boosted that actually has dropped its
  1936. // access to the resource, but it guaranteed that the thread
  1937. // cannot be terminated or otherwise deleted.
  1938. //
  1939. // N.B. The dispatcher lock is released by the wait at the top of
  1940. // loop.
  1941. //
  1942. CurrentThread = KeGetCurrentThread();
  1943. KiLockDispatcherDatabase(&CurrentThread->WaitIrql);
  1944. CurrentThread->WaitNext = TRUE;
  1945. //
  1946. // Attempt to boost the one owner that can be shared or exclusive.
  1947. //
  1948. OwnerThread = (PKTHREAD)Resource->OwnerThreads[0].OwnerThread;
  1949. if (OwnerThread != NULL) {
  1950. ExpBoostOwnerThread(CurrentThread, OwnerThread);
  1951. }
  1952. //
  1953. // If the specified resource is not owned exclusive, then attempt
  1954. // to boost all the owning shared threads priority.
  1955. //
  1956. if (!IsOwnedExclusive(Resource)) {
  1957. OwnerThread = (PKTHREAD)Resource->OwnerThreads[1].OwnerThread;
  1958. if (OwnerThread != NULL) {
  1959. ExpBoostOwnerThread(CurrentThread, OwnerThread);
  1960. }
  1961. OwnerEntry = Resource->OwnerTable;
  1962. if (OwnerEntry != NULL) {
  1963. Number = OwnerEntry->TableSize;
  1964. for(Index = 1; Index < Number; Index += 1) {
  1965. OwnerEntry += 1;
  1966. OwnerThread = (PKTHREAD)OwnerEntry->OwnerThread;
  1967. if (OwnerThread != NULL) {
  1968. ExpBoostOwnerThread(CurrentThread, OwnerThread);
  1969. }
  1970. }
  1971. }
  1972. }
  1973. }
  1974. } while (TRUE);
  1975. return;
  1976. }
  1977. POWNER_ENTRY
  1978. FASTCALL
  1979. ExpFindCurrentThread(
  1980. IN PERESOURCE Resource,
  1981. IN ERESOURCE_THREAD CurrentThread,
  1982. IN PEXP_LOCK_HANDLE LockHandle OPTIONAL
  1983. )
  1984. /*++
  1985. Routine Description:
  1986. This function searches for the specified thread in the resource
  1987. thread array. If the thread is located, then a pointer to the
  1988. array entry is returned as the function value. Otherwise, a pointer
  1989. to a free entry is returned.
  1990. N.B. This routine is entered with the resource lock held and returns
  1991. with the resource lock held. If the resource lock is released
  1992. to expand the owner table, then the return value will be NULL.
  1993. This is a signal to the caller that the complete operation must
  1994. be repeated. This is done to avoid holding the resource lock
  1995. while memory is allocated and freed.
  1996. Arguments:
  1997. Resource - Supplies a pointer to the resource for which the search
  1998. is performed.
  1999. CurrentThread - Supplies the identification of the thread to search
  2000. for.
  2001. LockHandle - Supplies a pointer to a lock handle. If NULL, then the
  2002. caller just wants to know if the requested thread is an owner of
  2003. this resource. No free entry index is returned and no table
  2004. expansion is performed. Instead NULL is returned if the requested
  2005. thread cannot be found in the table.
  2006. Return Value:
  2007. A pointer to an owner entry is returned or NULL if one could not be
  2008. allocated.
  2009. --*/
  2010. {
  2011. POWNER_ENTRY FreeEntry;
  2012. ULONG NewSize;
  2013. ULONG OldSize;
  2014. POWNER_ENTRY OldTable;
  2015. POWNER_ENTRY OwnerEntry;
  2016. POWNER_ENTRY OwnerBound;
  2017. POWNER_ENTRY OwnerTable;
  2018. KIRQL OldIrql;
  2019. //
  2020. // Search the owner threads for the specified thread and return either
  2021. // a pointer to the found thread or a pointer to a free thread table
  2022. // entry.
  2023. //
  2024. if (Resource->OwnerThreads[0].OwnerThread == CurrentThread) {
  2025. return &Resource->OwnerThreads[0];
  2026. } else if (Resource->OwnerThreads[1].OwnerThread == CurrentThread) {
  2027. return &Resource->OwnerThreads[1];
  2028. } else {
  2029. FreeEntry = NULL;
  2030. if (Resource->OwnerThreads[1].OwnerThread == 0) {
  2031. FreeEntry = &Resource->OwnerThreads[1];
  2032. }
  2033. OwnerEntry = Resource->OwnerTable;
  2034. if (OwnerEntry == NULL) {
  2035. OldSize = 0;
  2036. } else {
  2037. OldSize = OwnerEntry->TableSize;
  2038. OwnerBound = &OwnerEntry[OldSize];
  2039. OwnerEntry += 1;
  2040. do {
  2041. if (OwnerEntry->OwnerThread == CurrentThread) {
  2042. KeGetCurrentThread()->ResourceIndex = (UCHAR)(OwnerEntry - Resource->OwnerTable);
  2043. return OwnerEntry;
  2044. }
  2045. if ((FreeEntry == NULL) &&
  2046. (OwnerEntry->OwnerThread == 0)) {
  2047. FreeEntry = OwnerEntry;
  2048. }
  2049. OwnerEntry += 1;
  2050. } while (OwnerEntry != OwnerBound);
  2051. }
  2052. }
  2053. if (!ARGUMENT_PRESENT(LockHandle)) {
  2054. //
  2055. // No argument indicates the caller does not want a free entry or
  2056. // automatic table expansion. The caller just wants to know if the
  2057. // requested thread is a resource owner. And clearly the answer is
  2058. // NO at this point.
  2059. //
  2060. return NULL;
  2061. }
  2062. //
  2063. // If a free entry was found in the table, then return the address of the
  2064. // free entry. Otherwise, expand the size of the owner thread table.
  2065. //
  2066. if (FreeEntry != NULL) {
  2067. KeGetCurrentThread()->ResourceIndex = (UCHAR)(FreeEntry - Resource->OwnerTable);
  2068. return FreeEntry;
  2069. }
  2070. //
  2071. // Save previous owner table address and allocate an expanded owner table.
  2072. //
  2073. ExpIncrementCounter(OwnerTableExpands);
  2074. OldTable = Resource->OwnerTable;
  2075. EXP_UNLOCK_RESOURCE(Resource, LockHandle);
  2076. if (OldSize == 0 ) {
  2077. NewSize = 3;
  2078. } else {
  2079. NewSize = OldSize + 4;
  2080. }
  2081. OwnerTable = ExAllocatePoolWithTag(NonPagedPool,
  2082. NewSize * sizeof(OWNER_ENTRY),
  2083. 'aTeR');
  2084. if (OwnerTable == NULL) {
  2085. KeDelayExecutionThread(KernelMode, FALSE, &ExShortTime);
  2086. } else {
  2087. //
  2088. // Zero the expansion area of the new owner table.
  2089. //
  2090. RtlZeroMemory(OwnerTable + OldSize,
  2091. (NewSize - OldSize) * sizeof(OWNER_ENTRY));
  2092. //
  2093. // Acquire the resource lock and determine if the owner table
  2094. // has been expanded by another thread while the new owner table
  2095. // was being allocated. If the owner table has been expanded by
  2096. // another thread, then release the new owner table. Otherwise,
  2097. // copy the owner table to the new owner table and establish the
  2098. // new owner table as the owner table.
  2099. //
  2100. EXP_LOCK_RESOURCE(Resource, LockHandle);
  2101. if ((OldTable != Resource->OwnerTable) ||
  2102. ((OldTable != NULL) && (OldSize != OldTable->TableSize))) {
  2103. EXP_UNLOCK_RESOURCE(Resource, LockHandle);
  2104. ExFreePool(OwnerTable);
  2105. } else {
  2106. RtlCopyMemory(OwnerTable,
  2107. OldTable,
  2108. OldSize * sizeof(OWNER_ENTRY));
  2109. //
  2110. // Swapping of the owner table must be done while owning the
  2111. // dispatcher lock to prevent a priority boost scan from occuring
  2112. // while the table is being changed. The priority boost scan is
  2113. // done when a time out occurs on a specific resource.
  2114. //
  2115. KiLockDispatcherDatabase(&OldIrql);
  2116. OwnerTable->TableSize = NewSize;
  2117. Resource->OwnerTable = OwnerTable;
  2118. KiUnlockDispatcherDatabase(OldIrql);
  2119. ASSERT_RESOURCE(Resource);
  2120. #if defined(_COLLECT_RESOURCE_DATA_)
  2121. if (NewSize > ExpResourcePerformanceData.MaximumTableExpand) {
  2122. ExpResourcePerformanceData.MaximumTableExpand = NewSize;
  2123. }
  2124. #endif
  2125. //
  2126. // Release the resource lock and free the old owner table.
  2127. //
  2128. EXP_UNLOCK_RESOURCE(Resource, LockHandle);
  2129. if (OldTable != NULL) {
  2130. ExFreePool(OldTable);
  2131. }
  2132. if (OldSize == 0) {
  2133. OldSize = 1;
  2134. }
  2135. }
  2136. }
  2137. //
  2138. // Set the hint index, acquire the resource lock, and return NULL
  2139. // as the function value. This will force a reevaluation of the
  2140. // calling resource function.
  2141. //
  2142. KeGetCurrentThread()->ResourceIndex = (CCHAR)OldSize;
  2143. EXP_LOCK_RESOURCE(Resource, LockHandle);
  2144. return NULL;
  2145. }
  2146. #if DBG
  2147. VOID
  2148. ExpAssertResource (
  2149. IN PERESOURCE Resource
  2150. )
  2151. {
  2152. //
  2153. // Assert that resource structure is correct.
  2154. //
  2155. // N.B. This routine is called with the resource lock held.
  2156. //
  2157. ASSERT(!Resource->SharedWaiters ||
  2158. Resource->SharedWaiters->Header.Type == SemaphoreObject);
  2159. ASSERT(!Resource->SharedWaiters ||
  2160. Resource->SharedWaiters->Header.Size == (sizeof(KSEMAPHORE) / sizeof(ULONG)));
  2161. ASSERT(!Resource->ExclusiveWaiters ||
  2162. Resource->ExclusiveWaiters->Header.Type == SynchronizationEvent);
  2163. ASSERT(!Resource->ExclusiveWaiters ||
  2164. Resource->ExclusiveWaiters->Header.Size == (sizeof(KEVENT) / sizeof(ULONG)));
  2165. }
  2166. #endif
  2167. PVOID
  2168. ExpCheckForResource (
  2169. IN PVOID p,
  2170. IN SIZE_T Size
  2171. )
  2172. {
  2173. KIRQL OldIrql;
  2174. PLIST_ENTRY Head, Next;
  2175. volatile PLIST_ENTRY Last;
  2176. PERESOURCE Resource;
  2177. PCHAR BeginBlock;
  2178. PCHAR EndBlock;
  2179. //
  2180. // This can cause a deadlock on MP machines.
  2181. //
  2182. if (KeNumberProcessors > 1) {
  2183. return NULL;
  2184. }
  2185. BeginBlock = (PCHAR)p;
  2186. EndBlock = (PCHAR)p + Size;
  2187. ExAcquireSpinLock (&ExpResourceSpinLock, &OldIrql);
  2188. Head = &ExpSystemResourcesList;
  2189. Next = Head->Flink;
  2190. while (Next != Head) {
  2191. Resource = CONTAINING_RECORD(Next,
  2192. ERESOURCE,
  2193. SystemResourcesList);
  2194. if ((PCHAR)Resource >= BeginBlock && (PCHAR)Resource < EndBlock) {
  2195. DbgPrint("EX: ExFreePool( %p, %lx ) contains an ERESOURCE structure that has not been ExDeleteResourced\n",
  2196. p,
  2197. Size);
  2198. DbgBreakPoint ();
  2199. ExReleaseSpinLock (&ExpResourceSpinLock, OldIrql);
  2200. return (PVOID)Resource;
  2201. }
  2202. //
  2203. // Save the last ptr in a volatile variable for debugging when a flink is bad
  2204. //
  2205. Last = Next;
  2206. Next = Next->Flink;
  2207. }
  2208. ExReleaseSpinLock(&ExpResourceSpinLock, OldIrql);
  2209. return NULL;
  2210. }