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.

7193 lines
159 KiB

  1. #ifndef _SYNC_HXX_INCLUDED
  2. #define _SYNC_HXX_INCLUDED
  3. #include "nt.h"
  4. #include "ntrtl.h"
  5. #include "nturtl.h"
  6. #include "windows.h"
  7. #pragma warning ( disable : 4786 ) // we allow huge symbol names
  8. // Build Options
  9. #define SYNC_USE_X86_ASM // use x86 assembly for atomic memory manipulation
  10. //#define SYNC_ANALYZE_PERFORMANCE // analyze performance of synchronization objects
  11. #ifdef SYNC_ANALYZE_PERFORMANCE
  12. #define SYNC_DUMP_PERF_DATA // dump performance analysis of synchronization objects
  13. #endif // SYNC_ANALYZE_PERFORMANCE
  14. //#define SYNC_DEADLOCK_DETECTION // perform deadlock detection
  15. //#define SYNC_VALIDATE_IRKSEM_USAGE // validate IRKSEM (CReferencedKernelSemaphore) usage
  16. #ifdef DEBUG
  17. #ifdef DBG
  18. #else // !DBG
  19. #define SYNC_DEADLOCK_DETECTION // always perform deadlock detection in DEBUG
  20. #define SYNC_VALIDATE_IRKSEM_USAGE // always validate IRKSEM (CReferencedKernelSemaphore) usage in DEBUG
  21. #endif // DBG
  22. #endif // DEBUG
  23. // copied from basestd.h to make LONG_PTR available.
  24. #ifdef __cplusplus
  25. extern "C" {
  26. #endif
  27. //
  28. // The following types are guaranteed to be signed and 32 bits wide.
  29. //
  30. typedef int LONG32, *PLONG32;
  31. typedef int INT32, *PINT32;
  32. //
  33. // The following types are guaranteed to be unsigned and 32 bits wide.
  34. //
  35. typedef unsigned int ULONG32, *PULONG32;
  36. typedef unsigned int DWORD32, *PDWORD32;
  37. typedef unsigned int UINT32, *PUINT32;
  38. //
  39. // The INT_PTR is guaranteed to be the same size as a pointer. Its
  40. // size with change with pointer size (32/64). It should be used
  41. // anywhere that a pointer is cast to an integer type. UINT_PTR is
  42. // the unsigned variation.
  43. //
  44. // __int3264 is intrinsic to 64b MIDL but not to old MIDL or to C compiler.
  45. //
  46. #if ( 501 < __midl )
  47. typedef __int3264 INT_PTR, *PINT_PTR;
  48. typedef unsigned __int3264 UINT_PTR, *PUINT_PTR;
  49. typedef __int3264 LONG_PTR, *PLONG_PTR;
  50. typedef unsigned __int3264 ULONG_PTR, *PULONG_PTR;
  51. #else // midl64
  52. // old midl and C++ compiler
  53. #ifdef _WIN64
  54. typedef __int64 INT_PTR, *PINT_PTR;
  55. typedef unsigned __int64 UINT_PTR, *PUINT_PTR;
  56. typedef __int64 LONG_PTR, *PLONG_PTR;
  57. typedef unsigned __int64 ULONG_PTR, *PULONG_PTR;
  58. #define __int3264 __int64
  59. #else
  60. typedef int INT_PTR, *PINT_PTR;
  61. typedef unsigned int UINT_PTR, *PUINT_PTR;
  62. typedef long LONG_PTR, *PLONG_PTR;
  63. typedef unsigned long ULONG_PTR, *PULONG_PTR;
  64. #define __int3264 __int32
  65. #endif
  66. #endif //midl64
  67. typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR;
  68. //
  69. // The following types are guaranteed to be signed and 64 bits wide.
  70. //
  71. typedef __int64 LONG64, *PLONG64;
  72. typedef __int64 INT64, *PINT64;
  73. //
  74. // The following types are guaranteed to be unsigned and 64 bits wide.
  75. //
  76. typedef unsigned __int64 ULONG64, *PULONG64;
  77. typedef unsigned __int64 DWORD64, *PDWORD64;
  78. typedef unsigned __int64 UINT64, *PUINT64;
  79. //
  80. // SIZE_T used for counts or ranges which need to span the range of
  81. // of a pointer. SSIZE_T is the signed variation.
  82. //
  83. typedef ULONG_PTR SIZE_T, *PSIZE_T;
  84. typedef LONG_PTR SSIZE_T, *PSSIZE_T;
  85. //
  86. // useful macros for both 32/64
  87. //
  88. #define OffsetOf(s,m) (SIZE_T)&(((s *)0)->m)
  89. #ifdef __cplusplus
  90. }
  91. #endif
  92. #pragma warning ( disable : 4355 )
  93. #include <limits.h>
  94. #include <new.h>
  95. #include <stdarg.h>
  96. #include <stdlib.h>
  97. // calling convention
  98. #define OSSYNCAPI __stdcall
  99. // basic types
  100. typedef int BOOL;
  101. #define fFalse BOOL( 0 )
  102. #define fTrue BOOL( !0 )
  103. typedef unsigned char BYTE;
  104. typedef unsigned short WORD;
  105. typedef unsigned long DWORD;
  106. typedef unsigned __int64 QWORD;
  107. // Assertions
  108. // Assertion Failure action
  109. //
  110. // called to indicate to the developer that an assumption is not true
  111. void OSSYNCAPI AssertFail( const char* szMessage, const char* szFilename, long lLine );
  112. // Assert Macros
  113. // asserts that the given expression is true or else fails with the specified message
  114. #define OSSYNCAssertSzRTL( exp, sz ) ( ( exp ) ? (void) 0 : AssertFail( sz, __FILE__, __LINE__ ) )
  115. #ifdef DEBUG
  116. #define OSSYNCAssertSz( exp, sz ) OSSYNCAssertSzRTL( exp, sz )
  117. #else // !DEBUG
  118. #define OSSYNCAssertSz( exp, sz )
  119. #endif // DEBUG
  120. // asserts that the given expression is true or else fails with that expression
  121. #define OSSYNCAssertRTL( exp ) OSSYNCAssertSzRTL( exp, #exp )
  122. #define OSSYNCAssert( exp ) OSSYNCAssertSz( exp, #exp )
  123. // Enforces
  124. // Enforce Failure action
  125. //
  126. // called when a strictly enforced condition has been violated
  127. void OSSYNCAPI EnforceFail( const char* szMessage, const char* szFilename, long lLine );
  128. // Enforce Macros
  129. // the given expression MUST be true or else fails with the specified message
  130. #define OSSYNCEnforceSz( exp, sz ) ( ( exp ) ? (void) 0 : EnforceFail( sz, __FILE__, __LINE__ ) )
  131. // the given expression MUST be true or else fails with that expression
  132. #define OSSYNCEnforce( exp ) OSSYNCEnforceSz( exp, #exp )
  133. #ifdef SYNC_VALIDATE_IRKSEM_USAGE
  134. #define OSSYNCEnforceIrksem( exp, sz ) OSSYNCEnforceSz( exp, sz )
  135. #else // !SYNC_VALIDATE_IRKSEM_USAGE
  136. #define OSSYNCEnforceIrksem( exp, sz )
  137. #endif // SYNC_VALIDATE_IRKSEM_USAGE
  138. // OSSYNC_FOREVER marks all convergence loops
  139. #if defined( _M_IX86 ) && defined( SYNC_USE_X86_ASM )
  140. inline void OSSyncPause() { __asm rep nop }
  141. #else // !_M_IX86 || !SYNC_USE_X86_ASM
  142. inline void OSSyncPause() {}
  143. #endif // _M_IX86 && SYNC_USE_X86_ASM
  144. #ifdef DEBUG
  145. #define OSSYNC_FOREVER for ( int cLoop = 0; ; cLoop++, OSSyncPause() )
  146. #else // !DEBUG
  147. #define OSSYNC_FOREVER for ( ; ; OSSyncPause() )
  148. #endif // DEBUG
  149. namespace OSSYNC {
  150. class CDumpContext;
  151. // Context Local Storage
  152. class COwner;
  153. class CLockDeadlockDetectionInfo;
  154. struct CLS
  155. {
  156. #ifdef SYNC_DEADLOCK_DETECTION
  157. COwner* pownerLockHead; // list of locks owned by this context
  158. DWORD cDisableOwnershipTracking; // lock ownerships are not tracked for this context
  159. BOOL fOverrideDeadlock; // next lock ownership will not be a deadlock
  160. CLockDeadlockDetectionInfo* plddiLockWait; // lock for which this context is waiting
  161. DWORD groupLockWait; // lock group for which this context is waiting
  162. #endif // SYNC_DEADLOCK_DETECTION
  163. };
  164. // returns the pointer to the current context's local storage
  165. CLS* const OSSYNCAPI Pcls();
  166. // Processor Information
  167. // returns the maximum number of processors this process can utilize
  168. int OSSYNCAPI OSSyncGetProcessorCountMax();
  169. // returns the current number of processors this process can utilize
  170. int OSSYNCAPI OSSyncGetProcessorCount();
  171. // returns the processor number that the current context _MAY_ be executing on
  172. //
  173. // NOTE: the current context may change processors at any time
  174. int OSSYNCAPI OSSyncGetCurrentProcessor();
  175. // sets the processor number returned by OSSyncGetCurrentProcessor()
  176. void OSSYNCAPI OSSyncSetCurrentProcessor( const int iProc );
  177. // High Resolution Timer
  178. // returns the current HRT frequency
  179. QWORD OSSYNCAPI QwOSTimeHRTFreq();
  180. // returns the current HRT count
  181. QWORD OSSYNCAPI QwOSTimeHRTCount();
  182. // Timer
  183. // returns the current tick count where one tick is one millisecond
  184. DWORD OSSYNCAPI DwOSTimeGetTickCount();
  185. // Global Synchronization Constants
  186. // wait time used for testing the state of the kernel object
  187. extern const int cmsecTest;
  188. // wait time used for infinite wait on a kernel object
  189. extern const int cmsecInfinite;
  190. // maximum wait time on a kernel object before a deadlock is suspected
  191. extern const int cmsecDeadlock;
  192. // wait time used for infinite wait on a kernel object without deadlock
  193. extern const int cmsecInfiniteNoDeadlock;
  194. // cache line size
  195. extern const int cbCacheLine;
  196. // Atomic Memory Manipulations
  197. // returns fTrue if the given data is properly aligned for atomic modification
  198. inline const BOOL IsAtomicallyModifiable( long* plTarget )
  199. {
  200. return ULONG_PTR( plTarget ) % sizeof( long ) == 0;
  201. }
  202. inline const BOOL IsAtomicallyModifiablePointer( void*const* ppvTarget )
  203. {
  204. return ULONG_PTR( ppvTarget ) % sizeof( void* ) == 0;
  205. }
  206. #if defined( _M_IX86 ) && defined( SYNC_USE_X86_ASM )
  207. #pragma warning( disable: 4035 )
  208. // atomically compares the current value of the target with the specified
  209. // initial value and if equal sets the target to the specified final value.
  210. // the initial value of the target is returned. the exchange is successful
  211. // if the value returned equals the specified initial value. the target
  212. // must be aligned to a four byte boundary
  213. inline long AtomicCompareExchange( long* const plTarget, const long lInitial, const long lFinal )
  214. {
  215. OSSYNCAssert( IsAtomicallyModifiable( plTarget ) );
  216. __asm mov ecx, plTarget
  217. __asm mov edx, lFinal
  218. __asm mov eax, lInitial
  219. __asm lock cmpxchg [ecx], edx
  220. }
  221. inline void* AtomicCompareExchangePointer( void** const ppvTarget, void* const pvInitial, void* const pvFinal )
  222. {
  223. OSSYNCAssert( IsAtomicallyModifiablePointer( ppvTarget ) );
  224. return (void*) AtomicCompareExchange( (long* const) ppvTarget, (const long) pvInitial, (const long) pvFinal );
  225. }
  226. // atomically sets the target to the specified value, returning the target's
  227. // initial value. the target must be aligned to a four byte boundary
  228. inline long AtomicExchange( long* const plTarget, const long lValue )
  229. {
  230. OSSYNCAssert( IsAtomicallyModifiable( plTarget ) );
  231. __asm mov ecx, plTarget
  232. __asm mov eax, lValue
  233. __asm lock xchg [ecx], eax
  234. }
  235. inline void* AtomicExchangePointer( void* const * ppvTarget, void* const pvValue )
  236. {
  237. OSSYNCAssert( IsAtomicallyModifiablePointer( ppvTarget ) );
  238. return (void*) AtomicExchange( (long* const) ppvTarget, (const long) pvValue );
  239. }
  240. // atomically adds the specified value to the target, returning the target's
  241. // initial value. the target must be aligned to a four byte boundary
  242. inline long AtomicExchangeAdd( long* const plTarget, const long lValue )
  243. {
  244. OSSYNCAssert( IsAtomicallyModifiable( plTarget ) );
  245. __asm mov ecx, plTarget
  246. __asm mov eax, lValue
  247. __asm lock xadd [ecx], eax
  248. }
  249. #pragma warning( default: 4035 )
  250. #elif defined( _WIN64 )
  251. inline long AtomicExchange( long* const plTarget, const long lValue )
  252. {
  253. OSSYNCAssert( IsAtomicallyModifiable( plTarget ) );
  254. return InterlockedExchange( plTarget, lValue );
  255. }
  256. inline long AtomicExchangeAdd( long* const plTarget, const long lValue )
  257. {
  258. OSSYNCAssert( IsAtomicallyModifiable( plTarget ) );
  259. return InterlockedExchangeAdd( plTarget, lValue );
  260. }
  261. inline long AtomicCompareExchange( long* const plTarget, const long lInitial, const long lFinal )
  262. {
  263. OSSYNCAssert( IsAtomicallyModifiable( plTarget ) );
  264. return InterlockedCompareExchange( plTarget, lFinal, lInitial );
  265. }
  266. inline void* AtomicExchangePointer( void* const * ppvTarget, void* const pvValue )
  267. {
  268. OSSYNCAssert( IsAtomicallyModifiablePointer( ppvTarget ) );
  269. return InterlockedExchangePointer( (void **)ppvTarget, pvValue );
  270. }
  271. inline void* AtomicCompareExchangePointer( void** const ppvTarget, void* const pvInitial, void* const pvFinal )
  272. {
  273. OSSYNCAssert( IsAtomicallyModifiablePointer( ppvTarget ) );
  274. return InterlockedCompareExchangePointer( ppvTarget, pvFinal, pvInitial );
  275. }
  276. #else
  277. long OSSYNCAPI AtomicCompareExchange( long* const plTarget, const long lInitial, const long lFinal );
  278. void* OSSYNCAPI AtomicCompareExchangePointer( void** const ppvTarget, void* const pvInitial, void* const pvFinal );
  279. long OSSYNCAPI AtomicExchange( long* const plTarget, const long lValue );
  280. void* OSSYNCAPI AtomicExchangePointer( void* const * ppvTarget, void* const pvValue );
  281. long OSSYNCAPI AtomicExchangeAdd( long* const plTarget, const long lValue );
  282. #endif
  283. // atomically adds the specified value to the target, returning the target's
  284. // initial value. the target must be aligned to a pointer boundary.
  285. inline void* AtomicExchangeAddPointer( void** const ppvTarget, void* const pvValue )
  286. {
  287. void* pvInitial;
  288. void* pvFinal;
  289. void* pvResult;
  290. OSSYNCAssert( IsAtomicallyModifiablePointer( ppvTarget ) );
  291. OSSYNC_FOREVER
  292. {
  293. pvInitial = *((void* volatile *)ppvTarget);
  294. pvFinal = (void*)( ULONG_PTR( pvInitial ) + ULONG_PTR( pvValue ) );
  295. pvResult = AtomicCompareExchangePointer( ppvTarget, pvInitial, pvFinal );
  296. if ( pvResult == pvInitial )
  297. {
  298. break;
  299. }
  300. }
  301. return pvResult;
  302. }
  303. // atomically increments the target, returning the incremented value. the
  304. // target must be aligned to a four byte boundary
  305. inline long AtomicIncrement( long* const plTarget )
  306. {
  307. return AtomicExchangeAdd( plTarget, 1 ) + 1;
  308. }
  309. // atomically decrements the target, returning the decremented value. the
  310. // target must be aligned to a four byte boundary
  311. inline long AtomicDecrement( long* const plTarget )
  312. {
  313. return AtomicExchangeAdd( plTarget, -1 ) - 1;
  314. }
  315. // atomically adds the specified value to the target. the target must be
  316. // aligned to a four byte boundary
  317. inline void AtomicAdd( QWORD* const pqwTarget, const QWORD qwValue )
  318. {
  319. #ifdef _WIN64
  320. AtomicExchangeAddPointer( (VOID **)pqwTarget, (VOID *)qwValue );
  321. #else
  322. DWORD* const pdwTargetLow = (DWORD*)pqwTarget;
  323. DWORD* const pdwTargetHigh = pdwTargetLow + 1;
  324. const DWORD dwValueLow = DWORD( qwValue );
  325. DWORD dwValueHigh = DWORD( qwValue >> 32 );
  326. if ( dwValueLow )
  327. {
  328. if ( DWORD( AtomicExchangeAdd( (long*)pdwTargetLow, dwValueLow ) ) + dwValueLow < dwValueLow )
  329. {
  330. dwValueHigh++;
  331. }
  332. }
  333. if ( dwValueHigh )
  334. {
  335. AtomicExchangeAdd( (long*)pdwTargetHigh, dwValueHigh );
  336. }
  337. #endif
  338. }
  339. // Atomically increments a DWORD counter, returning TRUE if the final
  340. // value is less than or equal to a specified maximum, or FALSE otherwise.
  341. // The pre-incremented value is returned in *pdwInitial
  342. // WARNING: to determine if the maximum value has been reached, an UNSIGNED
  343. // comparison is performed
  344. inline BOOL FAtomicIncrementMax(
  345. volatile DWORD * const pdw,
  346. DWORD * const pdwInitial,
  347. const DWORD dwMax )
  348. {
  349. OSSYNC_FOREVER
  350. {
  351. const DWORD dwInitial = *pdw;
  352. if ( dwInitial < dwMax )
  353. {
  354. const DWORD dwFinal = dwInitial + 1;
  355. if ( dwInitial == (DWORD)AtomicCompareExchange( (LONG *)pdw, (LONG)dwInitial, (LONG)dwFinal ) )
  356. {
  357. *pdwInitial = dwInitial;
  358. return fTrue;
  359. }
  360. }
  361. else
  362. return fFalse;
  363. }
  364. // should be impossible
  365. OSSYNCAssert( fFalse );
  366. return fFalse;
  367. }
  368. // Atomically increments a pointer-sized counter, returning TRUE if the final
  369. // value is less than or equal to a specified maximum, or FALSE otherwise.
  370. // The pre-incremented value is returned in *ppvInitial
  371. // WARNING: to determine if the maximum value has been reached, an UNSIGNED
  372. // comparison is performed
  373. inline BOOL FAtomicIncrementPointerMax(
  374. volatile VOID ** const ppv,
  375. VOID ** const ppvInitial,
  376. const VOID * const pvMax )
  377. {
  378. OSSYNC_FOREVER
  379. {
  380. const QWORD qwInitial = QWORD( *ppv );
  381. if ( qwInitial < (QWORD)pvMax )
  382. {
  383. const QWORD qwFinal = qwInitial + 1;
  384. if ( qwInitial == (QWORD)AtomicCompareExchangePointer( (VOID **)ppv, (VOID *)qwInitial, (VOID *)qwFinal ) )
  385. {
  386. *ppvInitial = (VOID *)qwInitial;
  387. return fTrue;
  388. }
  389. }
  390. else
  391. return fFalse;
  392. }
  393. // should be impossible
  394. OSSYNCAssert( fFalse );
  395. return fFalse;
  396. }
  397. // Enhanced Synchronization Object State Container
  398. //
  399. // This class manages a "simple" or normal state for an arbitrary sync object
  400. // and its "enhanced" counterpart. Which type is used depends on the build.
  401. // The goal is to maintain a footprint equal to the normal state so that other
  402. // classes that contain this object do not fluctuate in size depending on what
  403. // build options have been selected. For example, a performance build might
  404. // need extra storage to collect performance stats on the object. This data
  405. // will force the object to be allocated elsewhere in memory but will not change
  406. // the size of the object in its containing class.
  407. //
  408. // Template Arguments:
  409. //
  410. // CState sync object state class
  411. // CStateInit sync object state class ctor arg type
  412. // CInformation sync object information class
  413. // CInformationInit sync object information class ctor arg type
  414. void* OSSYNCAPI ESMemoryNew( size_t cb );
  415. void OSSYNCAPI ESMemoryDelete( void* pv );
  416. // determine when enhanced state is needed
  417. #if defined( SYNC_ANALYZE_PERFORMANCE ) || defined( SYNC_DEADLOCK_DETECTION )
  418. #define SYNC_ENHANCED_STATE
  419. #endif // SYNC_ANALYZE_PERFORMANCE || SYNC_DEADLOCK_DETECTION
  420. template< class CState, class CStateInit, class CInformation, class CInformationInit >
  421. class CEnhancedStateContainer
  422. {
  423. public:
  424. // types
  425. // enhanced state
  426. class CEnhancedState
  427. : public CState,
  428. public CInformation
  429. {
  430. public:
  431. CEnhancedState( const CStateInit& si, const CInformationInit& ii )
  432. : CState( si ),
  433. CInformation( ii )
  434. {
  435. }
  436. void* operator new( size_t cb ) { return ESMemoryNew( cb ); }
  437. void operator delete( void* pv ) { ESMemoryDelete( pv ); }
  438. };
  439. // member functions
  440. // ctors / dtors
  441. CEnhancedStateContainer( const CStateInit& si, const CInformationInit& ii )
  442. {
  443. #ifdef SYNC_ENHANCED_STATE
  444. m_pes = new CEnhancedState( si, ii );
  445. #else // !SYNC_ENHANCED_STATE
  446. new( (CState*) m_rgbState ) CState( si );
  447. #endif // SYNC_ENHANCED_STATE
  448. }
  449. ~CEnhancedStateContainer()
  450. {
  451. #ifdef SYNC_ENHANCED_STATE
  452. delete m_pes;
  453. #ifdef DEBUG
  454. m_pes = NULL;
  455. #endif // DEBUG
  456. #else // !SYNC_ENHANCED_STATE
  457. ( (CState*) m_rgbState )->~CState();
  458. #endif // SYNC_ENHANCED_STATE
  459. }
  460. // accessors
  461. CEnhancedState& State() const
  462. {
  463. #ifdef SYNC_ENHANCED_STATE
  464. return *m_pes;
  465. #else // !SYNC_ENHANCED_STATE
  466. // NOTE: this assumes that CInformation has no storage!
  467. return *( (CEnhancedState*) m_rgbState );
  468. #endif // SYNC_ENHANCED_STATE
  469. }
  470. // debugging support
  471. void Dump( CDumpContext& dc ) const;
  472. private:
  473. // data members
  474. // either a pointer to the enhanced state elsewhere in memory or the
  475. // actual state data, depending on the mode of the sync object
  476. union
  477. {
  478. CEnhancedState* m_pes;
  479. BYTE m_rgbState[ sizeof( CState ) ];
  480. };
  481. };
  482. // Synchronization Object Base Class
  483. //
  484. // All Synchronization Objects are derived from this class
  485. class CSyncObject
  486. {
  487. public:
  488. // member functions
  489. // ctors / dtors
  490. CSyncObject() {}
  491. ~CSyncObject() {}
  492. private:
  493. // member functions
  494. // operators
  495. CSyncObject& operator=( CSyncObject& ); // disallowed
  496. };
  497. // Synchronization Object Basic Information
  498. class CSyncBasicInfo
  499. {
  500. public:
  501. // member functions
  502. // ctors / dtors
  503. CSyncBasicInfo( const char* szInstanceName );
  504. ~CSyncBasicInfo();
  505. // manipulators
  506. void SetTypeName( const char* szTypeName );
  507. void SetInstance( const CSyncObject* const psyncobj );
  508. // accessors
  509. #ifdef SYNC_ENHANCED_STATE
  510. const char* SzInstanceName() const { return m_szInstanceName; }
  511. const char* SzTypeName() const { return m_szTypeName; }
  512. const CSyncObject* const Instance() const { return m_psyncobj; }
  513. #endif // SYNC_ENHANCED_STATE
  514. // debugging support
  515. void Dump( CDumpContext& dc ) const;
  516. private:
  517. // member functions
  518. // operators
  519. CSyncBasicInfo& operator=( CSyncBasicInfo& ); // disallowed
  520. // data members
  521. #ifdef SYNC_ENHANCED_STATE
  522. // Instance Name
  523. const char* m_szInstanceName;
  524. // Type Name
  525. const char* m_szTypeName;
  526. // Instance
  527. const CSyncObject* m_psyncobj;
  528. #endif // SYNC_ENHANCED_STATE
  529. };
  530. // sets the type name for the synchronization object
  531. inline void CSyncBasicInfo::SetTypeName( const char* szTypeName )
  532. {
  533. #ifdef SYNC_ENHANCED_STATE
  534. m_szTypeName = szTypeName;
  535. #endif // SYNC_ENHANCED_STATE
  536. }
  537. // sets the instance pointer for the synchronization object
  538. inline void CSyncBasicInfo::SetInstance( const CSyncObject* const psyncobj )
  539. {
  540. #ifdef SYNC_ENHANCED_STATE
  541. m_psyncobj = psyncobj;
  542. #endif // SYNC_ENHANCED_STATE
  543. }
  544. // Synchronization Object Performance: Wait Times
  545. class CSyncPerfWait
  546. {
  547. public:
  548. // member functions
  549. // ctors / dtors
  550. CSyncPerfWait();
  551. ~CSyncPerfWait();
  552. // member functions
  553. // manipulators
  554. void StartWait();
  555. void StopWait();
  556. // accessors
  557. #ifdef SYNC_ANALYZE_PERFORMANCE
  558. QWORD CWaitTotal() const { return m_cWait; }
  559. double CsecWaitElapsed() const { return (double)(signed __int64)m_qwHRTWaitElapsed /
  560. (double)(signed __int64)QwOSTimeHRTFreq(); }
  561. #endif // SYNC_ANALYZE_PERFORMANCE
  562. // debugging support
  563. void Dump( CDumpContext& dc ) const;
  564. private:
  565. // member functions
  566. // operators
  567. CSyncPerfWait& operator=( CSyncPerfWait& ); // disallowed
  568. // data members
  569. #ifdef SYNC_ANALYZE_PERFORMANCE
  570. // wait count
  571. volatile QWORD m_cWait;
  572. // elapsed wait time
  573. volatile QWORD m_qwHRTWaitElapsed;
  574. #endif // SYNC_ANALYZE_PERFORMANCE
  575. };
  576. // starts the wait timer for the sync object
  577. inline void CSyncPerfWait::StartWait()
  578. {
  579. #ifdef SYNC_ANALYZE_PERFORMANCE
  580. // increment the wait count
  581. AtomicAdd( (QWORD*)&m_cWait, 1 );
  582. // subtract the start wait time from the elapsed wait time. this starts
  583. // an elapsed time computation for this context. StopWait() will later
  584. // add the end wait time to the elapsed time, causing the following net
  585. // effect:
  586. //
  587. // m_qwHRTWaitElapsed += <end time> - <start time>
  588. //
  589. // we simply choose to go ahead and do the subtraction now to save storage
  590. AtomicAdd( (QWORD*)&m_qwHRTWaitElapsed, QWORD( -__int64( QwOSTimeHRTCount() ) ) );
  591. #endif // SYNC_ANALYZE_PERFORMANCE
  592. }
  593. // stops the wait timer for the sync object
  594. inline void CSyncPerfWait::StopWait()
  595. {
  596. #ifdef SYNC_ANALYZE_PERFORMANCE
  597. // add the end wait time to the elapsed wait time. this completes the
  598. // computation started in StartWait()
  599. AtomicAdd( (QWORD*)&m_qwHRTWaitElapsed, QwOSTimeHRTCount() );
  600. #endif // SYNC_ANALYZE_PERFORMANCE
  601. }
  602. // Null Synchronization Object State Initializer
  603. class CSyncStateInitNull
  604. {
  605. };
  606. extern const CSyncStateInitNull syncstateNull;
  607. // Kernel Semaphore Information
  608. class CKernelSemaphoreInfo
  609. : public CSyncBasicInfo,
  610. public CSyncPerfWait
  611. {
  612. public:
  613. // member functions
  614. // ctors / dtors
  615. CKernelSemaphoreInfo( const CSyncBasicInfo& sbi )
  616. : CSyncBasicInfo( sbi )
  617. {
  618. }
  619. // debugging support
  620. void Dump( CDumpContext& dc ) const;
  621. };
  622. // Kernel Semaphore State
  623. class CKernelSemaphoreState
  624. {
  625. public:
  626. // member functions
  627. // ctors / dtors
  628. CKernelSemaphoreState( const CSyncStateInitNull& null ) : m_handle( 0 ) {}
  629. // manipulators
  630. void SetHandle( void * handle ) { m_handle = handle; }
  631. // accessors
  632. void* Handle() { return m_handle; }
  633. // debugging support
  634. void Dump( CDumpContext& dc ) const;
  635. private:
  636. // member functions
  637. // operators
  638. CKernelSemaphoreState& operator=( CKernelSemaphoreState& ); // disallowed
  639. // data members
  640. // kernel semaphore handle
  641. void* m_handle;
  642. };
  643. // Kernel Semaphore
  644. class CKernelSemaphore
  645. : private CSyncObject,
  646. private CEnhancedStateContainer< CKernelSemaphoreState, CSyncStateInitNull, CKernelSemaphoreInfo, CSyncBasicInfo >
  647. {
  648. public:
  649. // member functions
  650. // ctors / dtors
  651. CKernelSemaphore( const CSyncBasicInfo& sbi );
  652. ~CKernelSemaphore();
  653. // init / term
  654. const BOOL FInit();
  655. void Term();
  656. // manipulators
  657. void Acquire();
  658. const BOOL FTryAcquire();
  659. const BOOL FAcquire( const int cmsecTimeout );
  660. void Release( const int cToRelease = 1 );
  661. // accessors
  662. const BOOL FReset();
  663. // debugging support
  664. void Dump( CDumpContext& dc ) const;
  665. private:
  666. // member functions
  667. // operators
  668. CKernelSemaphore& operator=( CKernelSemaphore& ); // disallowed
  669. // accessors
  670. const BOOL FInitialized();
  671. };
  672. // acquire one count of the semaphore, waiting forever if necessary
  673. inline void CKernelSemaphore::Acquire()
  674. {
  675. // semaphore should be initialized
  676. OSSYNCAssert( FInitialized() );
  677. // wait for the semaphore
  678. const BOOL fAcquire = FAcquire( cmsecInfinite );
  679. OSSYNCAssert( fAcquire );
  680. }
  681. // try to acquire one count of the semaphore without waiting. returns 0 if a
  682. // count could not be acquired
  683. inline const BOOL CKernelSemaphore::FTryAcquire()
  684. {
  685. // semaphore should be initialized
  686. OSSYNCAssert( FInitialized() );
  687. // test the semaphore
  688. return FAcquire( cmsecTest );
  689. }
  690. // returns fTrue if the semaphore has no available counts
  691. inline const BOOL CKernelSemaphore::FReset()
  692. {
  693. // semaphore should be initialized
  694. OSSYNCAssert( FInitialized() );
  695. // test the semaphore
  696. return !FTryAcquire();
  697. }
  698. // returns fTrue if the semaphore has been initialized
  699. inline const BOOL CKernelSemaphore::FInitialized()
  700. {
  701. return State().Handle() != 0;
  702. }
  703. // Kernel Semaphore Pool
  704. class CKernelSemaphorePool
  705. {
  706. public:
  707. // types
  708. // index to a ref counted kernel semaphore
  709. typedef unsigned short IRKSEM;
  710. enum { irksemAllocated = 0xFFFE, irksemNil = 0xFFFF };
  711. // member functions
  712. // ctors / dtors
  713. CKernelSemaphorePool();
  714. ~CKernelSemaphorePool();
  715. // init / term
  716. const BOOL FInit();
  717. void Term();
  718. // manipulators
  719. const IRKSEM Allocate( const CSyncObject* const psyncobj );
  720. void Reference( const IRKSEM irksem );
  721. void Unreference( const IRKSEM irksem );
  722. // accessors
  723. CKernelSemaphore& Ksem( const IRKSEM irksem, const CSyncObject* const psyncobj ) const;
  724. const BOOL FInitialized() const;
  725. long CksemAlloc() const { return m_cksem; }
  726. private:
  727. // types
  728. // reference counted kernel semaphore
  729. class CReferencedKernelSemaphore
  730. : public CKernelSemaphore
  731. {
  732. public:
  733. // member functions
  734. // ctors / dtors
  735. CReferencedKernelSemaphore();
  736. ~CReferencedKernelSemaphore();
  737. // init / term
  738. const BOOL FInit();
  739. void Term();
  740. // manipulators
  741. BOOL FAllocate();
  742. void Release();
  743. void SetUser( const CSyncObject* const psyncobj );
  744. void Reference();
  745. const BOOL FUnreference();
  746. // accessors
  747. const BOOL FInUse() const { return m_fInUse; }
  748. const int CReference() const { return m_cReference; }
  749. #ifdef SYNC_VALIDATE_IRKSEM_USAGE
  750. const CSyncObject* const PsyncobjUser() const { return m_psyncobjUser; }
  751. #endif // SYNC_VALIDATE_IRKSEM_USAGE
  752. private:
  753. // member functions
  754. // operators
  755. CReferencedKernelSemaphore& operator=( CReferencedKernelSemaphore& ); // disallowed
  756. // data members
  757. // transacted state representation
  758. union
  759. {
  760. volatile long m_l;
  761. struct
  762. {
  763. volatile unsigned short m_cReference:15; // 0 <= m_cReference <= ( 1 << 15 ) - 1
  764. volatile unsigned short m_fInUse:1; // m_fInUse = { 0, 1 }
  765. };
  766. };
  767. volatile long m_fAvailable;
  768. #ifdef SYNC_VALIDATE_IRKSEM_USAGE
  769. // sync object currently using this semaphore
  770. const CSyncObject* volatile m_psyncobjUser;
  771. #else // SYNC_VALIDATE_IRKSEM_USAGE
  772. BYTE m_rgbReserved1[4];
  773. #endif // SYNC_VALIDATE_IRKSEM_USAGE
  774. BYTE m_rgbReserved2[16];
  775. };
  776. // member functions
  777. // operators
  778. CKernelSemaphorePool& operator=( CKernelSemaphorePool& ); // disallowed
  779. // manipulators
  780. const IRKSEM AllocateNew();
  781. void Free( const IRKSEM irksem );
  782. // data members
  783. // semaphore index to semaphore map
  784. CReferencedKernelSemaphore* m_mpirksemrksem;
  785. // semaphore count
  786. volatile long m_cksem;
  787. };
  788. // allocates an IRKSEM from the pool on behalf of the specified sync object
  789. //
  790. // NOTE: the returned IRKSEM has one reference count
  791. inline const CKernelSemaphorePool::IRKSEM CKernelSemaphorePool::Allocate( const CSyncObject* const psyncobj )
  792. {
  793. // semaphore pool should be initialized
  794. OSSYNCAssert( FInitialized() );
  795. // there are semaphores in the semaphore pool
  796. IRKSEM irksem = irksemNil;
  797. if ( m_cksem )
  798. {
  799. // hash into the semaphore pool based on this context's CLS and the time
  800. IRKSEM irksemHash = IRKSEM( UINT_PTR( UINT_PTR( Pcls() ) / sizeof( CLS ) + UINT_PTR( QwOSTimeHRTCount() ) ) % m_cksem );
  801. OSSYNCAssert( irksemHash >= 0 && irksemHash < m_cksem );
  802. // try to allocate a semaphore, scanning forwards through the pool
  803. for ( long cLoop = 0;
  804. cLoop < m_cksem;
  805. cLoop++, irksemHash = IRKSEM( ++irksemHash % m_cksem ) )
  806. {
  807. if ( m_mpirksemrksem[ irksemHash ].FAllocate() )
  808. {
  809. irksem = irksemHash;
  810. break;
  811. }
  812. }
  813. }
  814. // if we do not yet have a semaphore, allocate one
  815. if ( irksem == irksemNil )
  816. {
  817. irksem = AllocateNew();
  818. }
  819. // validate irksem retrieved
  820. OSSYNCAssert( irksem != irksemNil );
  821. OSSYNCAssert( irksem >= 0 );
  822. OSSYNCAssert( irksem < m_cksem );
  823. // set the user for this semaphore
  824. m_mpirksemrksem[irksem].SetUser( psyncobj );
  825. // ensure that the semaphore we retrieved is reset
  826. OSSYNCEnforceIrksem( m_mpirksemrksem[irksem].FReset(),
  827. "Illegal allocation of a Kernel Semaphore with available counts!" );
  828. // return the allocated semaphore
  829. return irksem;
  830. }
  831. // add a reference count to an IRKSEM
  832. inline void CKernelSemaphorePool::Reference( const IRKSEM irksem )
  833. {
  834. // validate IN args
  835. OSSYNCAssert( irksem != irksemNil );
  836. OSSYNCAssert( irksem >= 0 );
  837. OSSYNCAssert( irksem < m_cksem );
  838. // semaphore pool should be initialized
  839. OSSYNCAssert( FInitialized() );
  840. // increment the reference count for this IRKSEM
  841. m_mpirksemrksem[irksem].Reference();
  842. }
  843. // remove a reference count from an IRKSEM, freeing it if the reference count
  844. // drops to zero and it is not currently in use
  845. inline void CKernelSemaphorePool::Unreference( const IRKSEM irksem )
  846. {
  847. // validate IN args
  848. OSSYNCAssert( irksem != irksemNil );
  849. OSSYNCAssert( irksem >= 0 );
  850. OSSYNCAssert( irksem < m_cksem );
  851. // semaphore pool should be initialized
  852. OSSYNCAssert( FInitialized() );
  853. // decrement the reference count for this IRKSEM
  854. const BOOL fFree = m_mpirksemrksem[irksem].FUnreference();
  855. // we need to free the semaphore
  856. if ( fFree )
  857. {
  858. // free the IRKSEM back to the allocation stack
  859. Free( irksem );
  860. }
  861. }
  862. // returns the CKernelSemaphore object associated with the given IRKSEM
  863. inline CKernelSemaphore& CKernelSemaphorePool::Ksem( const IRKSEM irksem, const CSyncObject* const psyncobj ) const
  864. {
  865. // validate IN args
  866. OSSYNCAssert( irksem != irksemNil );
  867. OSSYNCAssert( irksem >= 0 );
  868. OSSYNCAssert( irksem < m_cksem );
  869. // semaphore pool should be initialized
  870. OSSYNCAssert( FInitialized() );
  871. // we had better be retrieving this semaphore for the right sync object
  872. OSSYNCEnforceIrksem( m_mpirksemrksem[irksem].PsyncobjUser() == psyncobj,
  873. "Illegal use of a Kernel Semaphore by another Synchronization Object" );
  874. // return kernel semaphore
  875. return m_mpirksemrksem[irksem];
  876. }
  877. // returns fTrue if the semaphore pool has been initialized
  878. inline const BOOL CKernelSemaphorePool::FInitialized() const
  879. {
  880. return m_mpirksemrksem != NULL;
  881. }
  882. // allocates a new irksem and adds it to the stack's irksem pool
  883. inline const CKernelSemaphorePool::IRKSEM CKernelSemaphorePool::AllocateNew()
  884. {
  885. // atomically allocate a position in the stack's irksem pool for our new
  886. // irksem
  887. const long lDelta = 0x00000001;
  888. const long lBI = AtomicExchangeAdd( (long*) &m_cksem, lDelta );
  889. const IRKSEM irksem = IRKSEM( lBI );
  890. // initialize this irksem
  891. new ( &m_mpirksemrksem[irksem] ) CReferencedKernelSemaphore;
  892. BOOL fInitKernelSemaphore = m_mpirksemrksem[irksem].FInit();
  893. OSSYNCEnforceSz( fInitKernelSemaphore, "Could not allocate a Kernel Semaphore" );
  894. // return the irksem for use
  895. return irksem;
  896. }
  897. // frees the given IRKSEM back to the allocation stack
  898. inline void CKernelSemaphorePool::Free( const IRKSEM irksem )
  899. {
  900. // validate IN args
  901. OSSYNCAssert( irksem != irksemNil );
  902. OSSYNCAssert( irksem >= 0 );
  903. OSSYNCAssert( irksem < m_cksem );
  904. // semaphore pool should be initialized
  905. OSSYNCAssert( FInitialized() );
  906. // the semaphore to free had better not be in use
  907. OSSYNCEnforceIrksem( !m_mpirksemrksem[irksem].FInUse(),
  908. "Illegal free of a Kernel Semaphore that is still in use" );
  909. // the semaphore had better not already be freed
  910. OSSYNCEnforceIrksem( !m_mpirksemrksem[irksem].FAllocate(),
  911. "Illegal free of a Kernel Semaphore that is already free" );
  912. // ensure that the semaphore to free is reset
  913. OSSYNCEnforceIrksem( m_mpirksemrksem[irksem].FReset(),
  914. "Illegal free of a Kernel Semaphore that has available counts" );
  915. // release the semaphore to the pool
  916. m_mpirksemrksem[irksem].Release();
  917. }
  918. // Referenced Kernel Semaphore
  919. // attempts to allocate the semaphore, returning fTrue on success
  920. inline BOOL CKernelSemaphorePool::CReferencedKernelSemaphore::FAllocate()
  921. {
  922. return m_fAvailable && AtomicExchange( (long*)&m_fAvailable, 0 );
  923. }
  924. // releases the semaphore
  925. inline void CKernelSemaphorePool::CReferencedKernelSemaphore::Release()
  926. {
  927. AtomicExchange( (long*)&m_fAvailable, 1 );
  928. }
  929. // sets the user for the semaphore and gives the user an initial reference
  930. inline void CKernelSemaphorePool::CReferencedKernelSemaphore::SetUser( const CSyncObject* const psyncobj )
  931. {
  932. // this semaphore had better not already be in use
  933. OSSYNCEnforceIrksem( !m_fInUse,
  934. "Illegal allocation of a Kernel Semaphore that is already in use" );
  935. OSSYNCEnforceIrksem( !m_psyncobjUser,
  936. "Illegal allocation of a Kernel Semaphore that is already in use" );
  937. // mark this semaphore as in use and add an initial reference count for the
  938. // user
  939. AtomicExchangeAdd( (long*) &m_l, 0x00008001 );
  940. #ifdef SYNC_VALIDATE_IRKSEM_USAGE
  941. m_psyncobjUser = psyncobj;
  942. #endif // SYNC_VALIDATE_IRKSEM_USAGE
  943. }
  944. // add a reference count to the semaphore
  945. inline void CKernelSemaphorePool::CReferencedKernelSemaphore::Reference()
  946. {
  947. // increment the reference count
  948. AtomicIncrement( (long*) &m_l );
  949. // there had better be at least one reference count!
  950. OSSYNCAssert( m_cReference > 0 );
  951. }
  952. // remove a reference count from the semaphore, returning fTrue if the last
  953. // reference count on the semaphore was removed and the semaphore was in use
  954. // (this is the condition on which we can free the semaphore to the stack)
  955. inline const BOOL CKernelSemaphorePool::CReferencedKernelSemaphore::FUnreference()
  956. {
  957. // there had better be at least one reference count!
  958. OSSYNCAssert( m_cReference > 0 );
  959. // try forever until we succeed in removing our reference count
  960. long lBI;
  961. OSSYNC_FOREVER
  962. {
  963. // read the current state of the control word as our expected before image
  964. const long lBIExpected = m_l;
  965. // compute the after image of the control word by decrementing the
  966. // reference count and reseting the In Use bit if and only if we are
  967. // removing the last reference count
  968. const long lAI = lBIExpected +
  969. ( lBIExpected == 0x00008001 ?
  970. 0xFFFF7FFF :
  971. 0xFFFFFFFF );
  972. // attempt to perform the transacted state transition on the control word
  973. lBI = AtomicCompareExchange( (long*)&m_l, lBIExpected, lAI );
  974. // the transaction failed
  975. if ( lBI != lBIExpected )
  976. {
  977. // try again
  978. continue;
  979. }
  980. // the transaction succeeded
  981. else
  982. {
  983. // we're done
  984. break;
  985. }
  986. }
  987. // return fTrue if we removed the last reference count and reset the In Use bit
  988. if ( lBI == 0x00008001 )
  989. {
  990. #ifdef SYNC_VALIDATE_IRKSEM_USAGE
  991. m_psyncobjUser = NULL;
  992. #endif // SYNC_VALIDATE_IRKSEM_USAGE
  993. return fTrue;
  994. }
  995. else
  996. {
  997. return fFalse;
  998. }
  999. }
  1000. // Global Kernel Semaphore Pool
  1001. extern CKernelSemaphorePool ksempoolGlobal;
  1002. // Synchronization Object Performance: Acquisition
  1003. class CSyncPerfAcquire
  1004. {
  1005. public:
  1006. // member functions
  1007. // ctors / dtors
  1008. CSyncPerfAcquire();
  1009. ~CSyncPerfAcquire();
  1010. // member functions
  1011. // manipulators
  1012. void SetAcquire();
  1013. void SetContend();
  1014. // accessors
  1015. #ifdef SYNC_ANALYZE_PERFORMANCE
  1016. QWORD CAcquireTotal() const { return m_cAcquire; }
  1017. QWORD CContendTotal() const { return m_cContend; }
  1018. #endif // SYNC_ANALYZE_PERFORMANCE
  1019. // debugging support
  1020. void Dump( CDumpContext& dc ) const;
  1021. private:
  1022. // member functions
  1023. // operators
  1024. CSyncPerfAcquire& operator=( CSyncPerfAcquire& ); // disallowed
  1025. // data members
  1026. #ifdef SYNC_ANALYZE_PERFORMANCE
  1027. // acquire count
  1028. volatile QWORD m_cAcquire;
  1029. // contend count
  1030. volatile QWORD m_cContend;
  1031. #endif // SYNC_ANALYZE_PERFORMANCE
  1032. };
  1033. // specifies that the sync object was acquired
  1034. inline void CSyncPerfAcquire::SetAcquire()
  1035. {
  1036. #ifdef SYNC_ANALYZE_PERFORMANCE
  1037. AtomicAdd( (QWORD*)&m_cAcquire, 1 );
  1038. #endif // SYNC_ANALYZE_PERFORMANCE
  1039. }
  1040. // specifies that a contention occurred while acquiring the sync object
  1041. inline void CSyncPerfAcquire::SetContend()
  1042. {
  1043. #ifdef SYNC_ANALYZE_PERFORMANCE
  1044. AtomicAdd( (QWORD*)&m_cContend, 1 );
  1045. #endif // SYNC_ANALYZE_PERFORMANCE
  1046. }
  1047. // Semaphore Information
  1048. class CSemaphoreInfo
  1049. : public CSyncBasicInfo,
  1050. public CSyncPerfWait,
  1051. public CSyncPerfAcquire
  1052. {
  1053. public:
  1054. // member functions
  1055. // ctors / dtors
  1056. CSemaphoreInfo( const CSyncBasicInfo& sbi )
  1057. : CSyncBasicInfo( sbi )
  1058. {
  1059. }
  1060. // debugging support
  1061. void Dump( CDumpContext& dc ) const;
  1062. };
  1063. // Semaphore State
  1064. class CSemaphoreState
  1065. {
  1066. public:
  1067. // member functions
  1068. // ctors / dtors
  1069. CSemaphoreState( const CSyncStateInitNull& null ) : m_cAvail( 0 ) {}
  1070. CSemaphoreState( const int cAvail );
  1071. CSemaphoreState( const int cWait, const int irksem );
  1072. ~CSemaphoreState() {}
  1073. // operators
  1074. CSemaphoreState& operator=( CSemaphoreState& state ) { m_cAvail = state.m_cAvail; return *this; }
  1075. // manipulators
  1076. const BOOL FChange( const CSemaphoreState& stateCur, const CSemaphoreState& stateNew );
  1077. const BOOL FIncAvail( const int cToInc );
  1078. const BOOL FDecAvail();
  1079. // accessors
  1080. const BOOL FNoWait() const { return m_cAvail >= 0; }
  1081. const BOOL FWait() const { return m_cAvail < 0; }
  1082. const BOOL FAvail() const { return m_cAvail > 0; }
  1083. const BOOL FNoWaitAndNoAvail() const { return m_cAvail == 0; }
  1084. const int CAvail() const { OSSYNCAssert( FNoWait() ); return m_cAvail; }
  1085. const int CWait() const { OSSYNCAssert( FWait() ); return -m_cWaitNeg; }
  1086. const CKernelSemaphorePool::IRKSEM Irksem() const { OSSYNCAssert( FWait() ); return CKernelSemaphorePool::IRKSEM( m_irksem ); }
  1087. // debugging support
  1088. void Dump( CDumpContext& dc ) const;
  1089. private:
  1090. // data members
  1091. // transacted state representation (switched on bit 31)
  1092. union
  1093. {
  1094. // Mode 0: no waiters
  1095. volatile long m_cAvail; // 0 <= m_cAvail <= ( 1 << 31 ) - 1
  1096. // Mode 1: waiters
  1097. struct
  1098. {
  1099. volatile unsigned short m_irksem; // 0 <= m_irksem <= ( 1 << 16 ) - 2
  1100. volatile short m_cWaitNeg; // -( ( 1 << 15 ) - 1 ) <= m_cWaitNeg <= -1
  1101. };
  1102. };
  1103. };
  1104. // ctor
  1105. inline CSemaphoreState::CSemaphoreState( const int cAvail )
  1106. {
  1107. // validate IN args
  1108. OSSYNCAssert( cAvail >= 0 );
  1109. OSSYNCAssert( cAvail <= 0x7FFFFFFF );
  1110. // set available count
  1111. m_cAvail = long( cAvail );
  1112. }
  1113. // ctor
  1114. inline CSemaphoreState::CSemaphoreState( const int cWait, const int irksem )
  1115. {
  1116. // validate IN args
  1117. OSSYNCAssert( cWait > 0 );
  1118. OSSYNCAssert( cWait <= 0x7FFF );
  1119. OSSYNCAssert( irksem >= 0 );
  1120. OSSYNCAssert( irksem <= 0xFFFE );
  1121. // set waiter count
  1122. m_cWaitNeg = short( -cWait );
  1123. // set semaphore
  1124. m_irksem = (unsigned short) irksem;
  1125. }
  1126. // changes the transacted state of the semaphore using a transacted memory
  1127. // compare/exchange operation, returning fFalse on failure
  1128. inline const BOOL CSemaphoreState::FChange( const CSemaphoreState& stateCur, const CSemaphoreState& stateNew )
  1129. {
  1130. return AtomicCompareExchange( (long*)&m_cAvail, stateCur.m_cAvail, stateNew.m_cAvail ) == stateCur.m_cAvail;
  1131. }
  1132. // tries to increase the available count on the semaphore by the count
  1133. // given using a transacted memory compare/exchange operation, returning fFalse
  1134. // on failure
  1135. __forceinline const BOOL CSemaphoreState::FIncAvail( const int cToInc )
  1136. {
  1137. // try forever to change the state of the semaphore
  1138. OSSYNC_FOREVER
  1139. {
  1140. // get current value
  1141. const long cAvail = m_cAvail;
  1142. // munge start value such that the transaction will only work if we are in
  1143. // mode 0 (we do this to save a branch)
  1144. const long cAvailStart = cAvail & 0x7FFFFFFF;
  1145. // compute end value relative to munged start value
  1146. const long cAvailEnd = cAvailStart + cToInc;
  1147. // validate transaction
  1148. OSSYNCAssert( cAvail < 0 || ( cAvailStart >= 0 && cAvailEnd <= 0x7FFFFFFF && cAvailEnd == cAvailStart + cToInc ) );
  1149. // attempt the transaction
  1150. const long cAvailOld = AtomicCompareExchange( (long*)&m_cAvail, cAvailStart, cAvailEnd );
  1151. // the transaction succeeded
  1152. if ( cAvailOld == cAvailStart )
  1153. {
  1154. // return success
  1155. return fTrue;
  1156. }
  1157. // the transaction failed
  1158. else
  1159. {
  1160. // the transaction failed because of a collision with another context
  1161. if ( cAvailOld >= 0 )
  1162. {
  1163. // try again
  1164. continue;
  1165. }
  1166. // the transaction failed because there are waiters
  1167. else
  1168. {
  1169. // return failure
  1170. return fFalse;
  1171. }
  1172. }
  1173. }
  1174. }
  1175. // tries to decrease the available count on the semaphore by one using a
  1176. // transacted memory compare/exchange operation, returning fFalse on failure
  1177. __forceinline const BOOL CSemaphoreState::FDecAvail()
  1178. {
  1179. // try forever to change the state of the semaphore
  1180. OSSYNC_FOREVER
  1181. {
  1182. // get current value
  1183. const long cAvail = m_cAvail;
  1184. // this function has no effect on 0x80000000, so this MUST be an illegal
  1185. // value!
  1186. OSSYNCAssert( cAvail != 0x80000000 );
  1187. // munge end value such that the transaction will only work if we are in
  1188. // mode 0 and we have at least one available count (we do this to save a
  1189. // branch)
  1190. const long cAvailEnd = ( cAvail - 1 ) & 0x7FFFFFFF;
  1191. // compute start value relative to munged end value
  1192. const long cAvailStart = cAvailEnd + 1;
  1193. // validate transaction
  1194. OSSYNCAssert( cAvail <= 0 || ( cAvailStart > 0 && cAvailEnd >= 0 && cAvailEnd == cAvail - 1 ) );
  1195. // attempt the transaction
  1196. const long cAvailOld = AtomicCompareExchange( (long*)&m_cAvail, cAvailStart, cAvailEnd );
  1197. // the transaction succeeded
  1198. if ( cAvailOld == cAvailStart )
  1199. {
  1200. // return success
  1201. return fTrue;
  1202. }
  1203. // the transaction failed
  1204. else
  1205. {
  1206. // the transaction failed because of a collision with another context
  1207. if ( cAvailOld > 0 )
  1208. {
  1209. // try again
  1210. continue;
  1211. }
  1212. // the transaction failed because there are no available counts
  1213. else
  1214. {
  1215. // return failure
  1216. return fFalse;
  1217. }
  1218. }
  1219. }
  1220. }
  1221. // Semaphore
  1222. class CSemaphore
  1223. : private CSyncObject,
  1224. private CEnhancedStateContainer< CSemaphoreState, CSyncStateInitNull, CSemaphoreInfo, CSyncBasicInfo >
  1225. {
  1226. public:
  1227. // member functions
  1228. // ctors / dtors
  1229. CSemaphore( const CSyncBasicInfo& sbi );
  1230. ~CSemaphore();
  1231. // manipulators
  1232. void Acquire();
  1233. const BOOL FTryAcquire();
  1234. const BOOL FAcquire( const int cmsecTimeout );
  1235. void Release( const int cToRelease = 1 );
  1236. // accessors
  1237. const int CWait() const;
  1238. const int CAvail() const;
  1239. // debugging support
  1240. void Dump( CDumpContext& dc ) const;
  1241. private:
  1242. // member functions
  1243. // operators
  1244. CSemaphore& operator=( CSemaphore& ); // disallowed
  1245. // manipulators
  1246. const BOOL _FAcquire( const int cmsecTimeout );
  1247. void _Release( const int cToRelease );
  1248. };
  1249. // acquire one count of the semaphore, waiting forever if necessary
  1250. inline void CSemaphore::Acquire()
  1251. {
  1252. // we will wait forever, so we should not timeout
  1253. int fAcquire = FAcquire( cmsecInfinite );
  1254. OSSYNCAssert( fAcquire );
  1255. }
  1256. // try to acquire one count of the semaphore without waiting or spinning.
  1257. // returns fFalse if a count could not be acquired
  1258. inline const BOOL CSemaphore::FTryAcquire()
  1259. {
  1260. // only try to perform a simple decrement of the available count
  1261. const BOOL fAcquire = State().FDecAvail();
  1262. // we did not acquire the semaphore
  1263. if ( !fAcquire )
  1264. {
  1265. // this is a contention
  1266. State().SetContend();
  1267. }
  1268. // we did acquire the semaphore
  1269. else
  1270. {
  1271. // note that we acquired a count
  1272. State().SetAcquire();
  1273. }
  1274. return fAcquire;
  1275. }
  1276. // acquire one count of the semaphore, waiting only for the specified interval.
  1277. // returns fFalse if the wait timed out before a count could be acquired
  1278. inline const BOOL CSemaphore::FAcquire( const int cmsecTimeout )
  1279. {
  1280. // first try to quickly grab an available count. if that doesn't work,
  1281. // retry acquire using the full state machine
  1282. return FTryAcquire() || _FAcquire( cmsecTimeout );
  1283. }
  1284. // releases the given number of counts to the semaphore, waking the appropriate
  1285. // number of waiters
  1286. inline void CSemaphore::Release( const int cToRelease )
  1287. {
  1288. // we failed to perform a simple increment of the available count
  1289. if ( !State().FIncAvail( cToRelease ) )
  1290. {
  1291. // retry release using the full state machine
  1292. _Release( cToRelease );
  1293. }
  1294. }
  1295. // returns the number of execution contexts waiting on the semaphore
  1296. inline const int CSemaphore::CWait() const
  1297. {
  1298. // read the current state of the semaphore
  1299. const CSemaphoreState stateCur = (CSemaphoreState&) State();
  1300. // return the waiter count
  1301. return stateCur.FWait() ? stateCur.CWait() : 0;
  1302. }
  1303. // returns the number of available counts on the semaphore
  1304. inline const int CSemaphore::CAvail() const
  1305. {
  1306. // read the current state of the semaphore
  1307. const CSemaphoreState stateCur = (CSemaphoreState&) State();
  1308. // return the available count
  1309. return stateCur.FNoWait() ? stateCur.CAvail() : 0;
  1310. }
  1311. // Auto-Reset Signal Information
  1312. class CAutoResetSignalInfo
  1313. : public CSyncBasicInfo,
  1314. public CSyncPerfWait,
  1315. public CSyncPerfAcquire
  1316. {
  1317. public:
  1318. // member functions
  1319. // ctors / dtors
  1320. CAutoResetSignalInfo( const CSyncBasicInfo& sbi )
  1321. : CSyncBasicInfo( sbi )
  1322. {
  1323. }
  1324. // debugging support
  1325. void Dump( CDumpContext& dc ) const;
  1326. };
  1327. // Auto-Reset Signal State
  1328. class CAutoResetSignalState
  1329. {
  1330. public:
  1331. // member functions
  1332. // ctors / dtors
  1333. CAutoResetSignalState( const CSyncStateInitNull& null ) : m_fSet( 0 ) {}
  1334. CAutoResetSignalState( const int fSet );
  1335. CAutoResetSignalState( const int cWait, const int irksem );
  1336. ~CAutoResetSignalState() {}
  1337. // operators
  1338. CAutoResetSignalState& operator=( CAutoResetSignalState& state ) { m_fSet = state.m_fSet; return *this; }
  1339. // manipulators
  1340. const BOOL FChange( const CAutoResetSignalState& stateCur, const CAutoResetSignalState& stateNew );
  1341. const BOOL FSimpleSet();
  1342. const BOOL FSimpleReset();
  1343. // accessors
  1344. const BOOL FNoWait() const { return m_fSet >= 0; }
  1345. const BOOL FWait() const { return m_fSet < 0; }
  1346. const BOOL FNoWaitAndSet() const { return m_fSet > 0; }
  1347. const BOOL FNoWaitAndNotSet() const { return m_fSet == 0; }
  1348. const BOOL FSet() const { OSSYNCAssert( FNoWait() ); return m_fSet; }
  1349. const int CWait() const { OSSYNCAssert( FWait() ); return -m_cWaitNeg; }
  1350. const CKernelSemaphorePool::IRKSEM Irksem() const { OSSYNCAssert( FWait() ); return CKernelSemaphorePool::IRKSEM( m_irksem ); }
  1351. // debugging support
  1352. void Dump( CDumpContext& dc ) const;
  1353. private:
  1354. // data members
  1355. // transacted state representation (switched on bit 31)
  1356. union
  1357. {
  1358. // Mode 0: no waiters
  1359. volatile long m_fSet; // m_fSet = { 0, 1 }
  1360. // Mode 1: waiters
  1361. struct
  1362. {
  1363. volatile unsigned short m_irksem; // 0 <= m_irksem <= ( 1 << 16 ) - 2
  1364. volatile short m_cWaitNeg; // -( ( 1 << 15 ) - 1 ) <= m_cWaitNeg <= -1
  1365. };
  1366. };
  1367. };
  1368. // ctor
  1369. inline CAutoResetSignalState::CAutoResetSignalState( const int fSet )
  1370. {
  1371. // validate IN args
  1372. OSSYNCAssert( fSet == 0 || fSet == 1 );
  1373. // set state
  1374. m_fSet = long( fSet );
  1375. }
  1376. // ctor
  1377. inline CAutoResetSignalState::CAutoResetSignalState( const int cWait, const int irksem )
  1378. {
  1379. // validate IN args
  1380. OSSYNCAssert( cWait > 0 );
  1381. OSSYNCAssert( cWait <= 0x7FFF );
  1382. OSSYNCAssert( irksem >= 0 );
  1383. OSSYNCAssert( irksem <= 0xFFFE );
  1384. // set waiter count
  1385. m_cWaitNeg = short( -cWait );
  1386. // set semaphore
  1387. m_irksem = (unsigned short) irksem;
  1388. }
  1389. // changes the transacted state of the signal using a transacted memory
  1390. // compare/exchange operation, returning 0 on failure
  1391. inline const BOOL CAutoResetSignalState::FChange( const CAutoResetSignalState& stateCur, const CAutoResetSignalState& stateNew )
  1392. {
  1393. return AtomicCompareExchange( (long*)&m_fSet, stateCur.m_fSet, stateNew.m_fSet ) == stateCur.m_fSet;
  1394. }
  1395. // tries to set the signal state from either the set or reset with no waiters states
  1396. // using a transacted memory compare/exchange operation, returning fFalse on failure
  1397. __forceinline const BOOL CAutoResetSignalState::FSimpleSet()
  1398. {
  1399. // try forever to change the state of the signal
  1400. OSSYNC_FOREVER
  1401. {
  1402. // get current value
  1403. const long fSet = m_fSet;
  1404. // munge start value such that the transaction will only work if we are in
  1405. // mode 0 (we do this to save a branch)
  1406. const long fSetStart = fSet & 0x7FFFFFFF;
  1407. // compute end value relative to munged start value
  1408. const long fSetEnd = 1;
  1409. // validate transaction
  1410. OSSYNCAssert( fSet < 0 || ( ( fSetStart == 0 || fSetStart == 1 ) && fSetEnd == 1 ) );
  1411. // attempt the transaction
  1412. const long fSetOld = AtomicCompareExchange( (long*)&m_fSet, fSetStart, fSetEnd );
  1413. // the transaction succeeded
  1414. if ( fSetOld == fSetStart )
  1415. {
  1416. // return success
  1417. return fTrue;
  1418. }
  1419. // the transaction failed
  1420. else
  1421. {
  1422. // the transaction failed because of a collision with another context
  1423. if ( fSetOld >= 0 )
  1424. {
  1425. // try again
  1426. continue;
  1427. }
  1428. // the transaction failed because there are waiters
  1429. else
  1430. {
  1431. // return failure
  1432. return fFalse;
  1433. }
  1434. }
  1435. }
  1436. }
  1437. // tries to reset the signal state from either the set or reset with no waiters states
  1438. // using a transacted memory compare/exchange operation, returning fFalse on failure
  1439. __forceinline const BOOL CAutoResetSignalState::FSimpleReset()
  1440. {
  1441. // try forever to change the state of the signal
  1442. OSSYNC_FOREVER
  1443. {
  1444. // get current value
  1445. const long fSet = m_fSet;
  1446. // munge start value such that the transaction will only work if we are in
  1447. // mode 0 (we do this to save a branch)
  1448. const long fSetStart = fSet & 0x7FFFFFFF;
  1449. // compute end value relative to munged start value
  1450. const long fSetEnd = 0;
  1451. // validate transaction
  1452. OSSYNCAssert( fSet < 0 || ( ( fSetStart == 0 || fSetStart == 1 ) && fSetEnd == 0 ) );
  1453. // attempt the transaction
  1454. const long fSetOld = AtomicCompareExchange( (long*)&m_fSet, fSetStart, fSetEnd );
  1455. // the transaction succeeded
  1456. if ( fSetOld == fSetStart )
  1457. {
  1458. // return success
  1459. return fTrue;
  1460. }
  1461. // the transaction failed
  1462. else
  1463. {
  1464. // the transaction failed because of a collision with another context
  1465. if ( fSetOld >= 0 )
  1466. {
  1467. // try again
  1468. continue;
  1469. }
  1470. // the transaction failed because there are waiters
  1471. else
  1472. {
  1473. // return failure
  1474. return fFalse;
  1475. }
  1476. }
  1477. }
  1478. }
  1479. // Auto-Reset Signal
  1480. class CAutoResetSignal
  1481. : private CSyncObject,
  1482. private CEnhancedStateContainer< CAutoResetSignalState, CSyncStateInitNull, CAutoResetSignalInfo, CSyncBasicInfo >
  1483. {
  1484. public:
  1485. // member functions
  1486. // ctors / dtors
  1487. CAutoResetSignal( const CSyncBasicInfo& sbi );
  1488. ~CAutoResetSignal();
  1489. // manipulators
  1490. void Wait();
  1491. const BOOL FTryWait();
  1492. const BOOL FWait( const int cmsecTimeout );
  1493. void Set();
  1494. void Reset();
  1495. void Pulse();
  1496. // debugging support
  1497. void Dump( CDumpContext& dc ) const;
  1498. private:
  1499. // member functions
  1500. // operators
  1501. CAutoResetSignal& operator=( CAutoResetSignal& ); // disallowed
  1502. // manipulators
  1503. const BOOL _FWait( const int cmsecTimeout );
  1504. void _Set();
  1505. void _Pulse();
  1506. };
  1507. // waits for the signal to be set, forever if necessary. when the wait completes,
  1508. // the signal will be reset
  1509. inline void CAutoResetSignal::Wait()
  1510. {
  1511. // we will wait forever, so we should not timeout
  1512. const BOOL fWait = FWait( cmsecInfinite );
  1513. OSSYNCAssert( fWait );
  1514. }
  1515. // tests the state of the signal without waiting or spinning, returning fFalse
  1516. // if the signal was not set. if the signal was set, the signal will be reset
  1517. inline const BOOL CAutoResetSignal::FTryWait()
  1518. {
  1519. // we can satisfy the wait if we can successfully change the state of the
  1520. // signal from set to reset with no waiters
  1521. const BOOL fSuccess = State().FChange( CAutoResetSignalState( 1 ), CAutoResetSignalState( 0 ) );
  1522. // we did not successfully wait for the signal
  1523. if ( !fSuccess )
  1524. {
  1525. // this is a contention
  1526. State().SetContend();
  1527. }
  1528. // we did successfully wait for the signal
  1529. else
  1530. {
  1531. // note that we acquired the signal
  1532. State().SetAcquire();
  1533. }
  1534. return fSuccess;
  1535. }
  1536. // wait for the signal to be set, but only for the specified interval,
  1537. // returning fFalse if the wait timed out before the signal was set. if the
  1538. // wait completes, the signal will be reset
  1539. inline const BOOL CAutoResetSignal::FWait( const int cmsecTimeout )
  1540. {
  1541. // first try to quickly pass through the signal. if that doesn't work,
  1542. // retry wait using the full state machine
  1543. return FTryWait() || _FWait( cmsecTimeout );
  1544. }
  1545. // sets the signal, releasing up to one waiter. if a waiter is released, then
  1546. // the signal will be reset. if a waiter is not released, the signal will
  1547. // remain set
  1548. inline void CAutoResetSignal::Set()
  1549. {
  1550. // we failed to change the signal state from reset with no waiters to set
  1551. // or from set to set (a nop)
  1552. if ( !State().FSimpleSet() )
  1553. {
  1554. // retry set using the full state machine
  1555. _Set();
  1556. }
  1557. }
  1558. // resets the signal
  1559. inline void CAutoResetSignal::Reset()
  1560. {
  1561. // if and only if the signal is in the set state, change it to the reset state
  1562. State().FChange( CAutoResetSignalState( 1 ), CAutoResetSignalState( 0 ) );
  1563. }
  1564. // resets the signal, releasing up to one waiter
  1565. inline void CAutoResetSignal::Pulse()
  1566. {
  1567. // wa failed to change the signal state from set to reset with no waiters
  1568. // or from reset with no waiters to reset with no waiters (a nop)
  1569. if ( !State().FSimpleReset() )
  1570. {
  1571. // retry pulse using the full state machine
  1572. _Pulse();
  1573. }
  1574. }
  1575. // Manual-Reset Signal Information
  1576. class CManualResetSignalInfo
  1577. : public CSyncBasicInfo,
  1578. public CSyncPerfWait,
  1579. public CSyncPerfAcquire
  1580. {
  1581. public:
  1582. // member functions
  1583. // ctors / dtors
  1584. CManualResetSignalInfo( const CSyncBasicInfo& sbi )
  1585. : CSyncBasicInfo( sbi )
  1586. {
  1587. }
  1588. // debugging support
  1589. void Dump( CDumpContext& dc ) const;
  1590. };
  1591. // Manual-Reset Signal State
  1592. class CManualResetSignalState
  1593. {
  1594. public:
  1595. // member functions
  1596. // ctors / dtors
  1597. CManualResetSignalState( const CSyncStateInitNull& null ) : m_fSet( 0 ) {}
  1598. CManualResetSignalState( const int fSet );
  1599. CManualResetSignalState( const int cWait, const int irksem );
  1600. ~CManualResetSignalState() {}
  1601. // operators
  1602. CManualResetSignalState& operator=( CManualResetSignalState& state ) { m_fSet = state.m_fSet; return *this; }
  1603. // manipulators
  1604. const BOOL FChange( const CManualResetSignalState& stateCur, const CManualResetSignalState& stateNew );
  1605. const CManualResetSignalState Set();
  1606. const CManualResetSignalState Reset();
  1607. // accessors
  1608. const BOOL FNoWait() const { return m_fSet >= 0; }
  1609. const BOOL FWait() const { return m_fSet < 0; }
  1610. const BOOL FNoWaitAndSet() const { return m_fSet > 0; }
  1611. const BOOL FNoWaitAndNotSet() const { return m_fSet == 0; }
  1612. const BOOL FSet() const { OSSYNCAssert( FNoWait() ); return m_fSet; }
  1613. const int CWait() const { OSSYNCAssert( FWait() ); return -m_cWaitNeg; }
  1614. const CKernelSemaphorePool::IRKSEM Irksem() const { OSSYNCAssert( FWait() ); return CKernelSemaphorePool::IRKSEM( m_irksem ); }
  1615. // debugging support
  1616. void Dump( CDumpContext& dc ) const;
  1617. private:
  1618. // data members
  1619. // transacted state representation (switched on bit 31)
  1620. union
  1621. {
  1622. // Mode 0: no waiters
  1623. volatile long m_fSet; // m_fSet = { 0, 1 }
  1624. // Mode 1: waiters
  1625. struct
  1626. {
  1627. volatile unsigned short m_irksem; // 0 <= m_irksem <= ( 1 << 16 ) - 2
  1628. volatile short m_cWaitNeg; // -( ( 1 << 15 ) - 1 ) <= m_cWaitNeg <= -1
  1629. };
  1630. };
  1631. };
  1632. // ctor
  1633. inline CManualResetSignalState::CManualResetSignalState( const int fSet )
  1634. {
  1635. // set state
  1636. m_fSet = long( fSet );
  1637. }
  1638. // ctor
  1639. inline CManualResetSignalState::CManualResetSignalState( const int cWait, const int irksem )
  1640. {
  1641. // validate IN args
  1642. OSSYNCAssert( cWait > 0 );
  1643. OSSYNCAssert( cWait <= 0x7FFF );
  1644. OSSYNCAssert( irksem >= 0 );
  1645. OSSYNCAssert( irksem <= 0xFFFE );
  1646. // set waiter count
  1647. m_cWaitNeg = short( -cWait );
  1648. // set semaphore
  1649. m_irksem = (unsigned short) irksem;
  1650. }
  1651. // changes the transacted state of the signal using a transacted memory
  1652. // compare/exchange operation, returning fFalse on failure
  1653. inline const BOOL CManualResetSignalState::FChange( const CManualResetSignalState& stateCur, const CManualResetSignalState& stateNew )
  1654. {
  1655. return AtomicCompareExchange( (long*)&m_fSet, stateCur.m_fSet, stateNew.m_fSet ) == stateCur.m_fSet;
  1656. }
  1657. // changes the transacted state of the signal to set using a transacted memory
  1658. // exchange operation and returns the original state of the signal
  1659. inline const CManualResetSignalState CManualResetSignalState::Set()
  1660. {
  1661. const CManualResetSignalState stateNew( 1 );
  1662. return CManualResetSignalState( AtomicExchange( (long*)&m_fSet, stateNew.m_fSet ) );
  1663. }
  1664. // changes the transacted state of the signal to reset using a transacted memory
  1665. // exchange operation and returns the original state of the signal
  1666. inline const CManualResetSignalState CManualResetSignalState::Reset()
  1667. {
  1668. const CManualResetSignalState stateNew( 0 );
  1669. return CManualResetSignalState( AtomicExchange( (long*)&m_fSet, stateNew.m_fSet ) );
  1670. }
  1671. // Manual-Reset Signal
  1672. class CManualResetSignal
  1673. : private CSyncObject,
  1674. private CEnhancedStateContainer< CManualResetSignalState, CSyncStateInitNull, CManualResetSignalInfo, CSyncBasicInfo >
  1675. {
  1676. public:
  1677. // member functions
  1678. // ctors / dtors
  1679. CManualResetSignal( const CSyncBasicInfo& sbi );
  1680. ~CManualResetSignal();
  1681. // manipulators
  1682. void Wait();
  1683. const BOOL FTryWait();
  1684. const BOOL FWait( const int cmsecTimeout );
  1685. void Set();
  1686. void Reset();
  1687. void Pulse();
  1688. // debugging support
  1689. void Dump( CDumpContext& dc ) const;
  1690. private:
  1691. // member functions
  1692. // operators
  1693. CManualResetSignal& operator=( CManualResetSignal& ); // disallowed
  1694. // manipulators
  1695. const BOOL _FWait( const int cmsecTimeout );
  1696. };
  1697. // waits for the signal to be set, forever if necessary
  1698. inline void CManualResetSignal::Wait()
  1699. {
  1700. // we will wait forever, so we should not timeout
  1701. int fWait = FWait( cmsecInfinite );
  1702. OSSYNCAssert( fWait );
  1703. }
  1704. // tests the state of the signal without waiting or spinning, returning fFalse
  1705. // if the signal was not set
  1706. inline const BOOL CManualResetSignal::FTryWait()
  1707. {
  1708. const BOOL fSuccess = State().FNoWaitAndSet();
  1709. // we did not successfully wait for the signal
  1710. if ( !fSuccess )
  1711. {
  1712. // this is a contention
  1713. State().SetContend();
  1714. }
  1715. // we did successfully wait for the signal
  1716. else
  1717. {
  1718. // note that we acquired the signal
  1719. State().SetAcquire();
  1720. }
  1721. return fSuccess;
  1722. }
  1723. // wait for the signal to be set, but only for the specified interval,
  1724. // returning fFalse if the wait timed out before the signal was set
  1725. inline const BOOL CManualResetSignal::FWait( const int cmsecTimeout )
  1726. {
  1727. // first try to quickly pass through the signal. if that doesn't work,
  1728. // retry wait using the full state machine
  1729. return FTryWait() || _FWait( cmsecTimeout );
  1730. }
  1731. // sets the signal, releasing any waiters
  1732. inline void CManualResetSignal::Set()
  1733. {
  1734. // change the signal state to set
  1735. const CManualResetSignalState stateOld = State().Set();
  1736. // there were waiters on the signal
  1737. if ( stateOld.FWait() )
  1738. {
  1739. // release all the waiters
  1740. ksempoolGlobal.Ksem( stateOld.Irksem(), this ).Release( stateOld.CWait() );
  1741. }
  1742. }
  1743. // resets the signal
  1744. inline void CManualResetSignal::Reset()
  1745. {
  1746. // if and only if the signal is in the set state, change it to the reset state
  1747. State().FChange( CManualResetSignalState( 1 ), CManualResetSignalState( 0 ) );
  1748. }
  1749. // resets the signal, releasing any waiters
  1750. inline void CManualResetSignal::Pulse()
  1751. {
  1752. // change the signal state to reset
  1753. const CManualResetSignalState stateOld = State().Reset();
  1754. // there were waiters on the signal
  1755. if ( stateOld.FWait() )
  1756. {
  1757. // release all the waiters
  1758. ksempoolGlobal.Ksem( stateOld.Irksem(), this ).Release( stateOld.CWait() );
  1759. }
  1760. }
  1761. // Lock Object Base Class
  1762. //
  1763. // All Lock Objects are derived from this class
  1764. class CLockObject
  1765. : public CSyncObject
  1766. {
  1767. public:
  1768. // member functions
  1769. // ctors / dtors
  1770. CLockObject() {}
  1771. ~CLockObject() {}
  1772. private:
  1773. // member functions
  1774. // operators
  1775. CLockObject& operator=( CLockObject& ); // disallowed
  1776. };
  1777. // Lock Object Basic Information
  1778. class CLockBasicInfo
  1779. : public CSyncBasicInfo
  1780. {
  1781. public:
  1782. // member functions
  1783. // ctors / dtors
  1784. CLockBasicInfo( const CSyncBasicInfo& sbi, const int rank, const int subrank );
  1785. ~CLockBasicInfo();
  1786. // accessors
  1787. #ifdef SYNC_DEADLOCK_DETECTION
  1788. const int Rank() const { return m_rank; }
  1789. const int SubRank() const { return m_subrank; }
  1790. #endif // SYNC_DEADLOCK_DETECTION
  1791. // debugging support
  1792. void Dump( CDumpContext& dc ) const;
  1793. private:
  1794. // member functions
  1795. // operators
  1796. CLockBasicInfo& operator=( CLockBasicInfo& ); // disallowed
  1797. // data members
  1798. #ifdef SYNC_DEADLOCK_DETECTION
  1799. // Rank and Subrank
  1800. int m_rank;
  1801. int m_subrank;
  1802. #endif // SYNC_DEADLOCK_DETECTION
  1803. };
  1804. // Lock Object Performance: Hold
  1805. class CLockPerfHold
  1806. {
  1807. public:
  1808. // member functions
  1809. // ctors / dtors
  1810. CLockPerfHold();
  1811. ~CLockPerfHold();
  1812. // member functions
  1813. // manipulators
  1814. void StartHold();
  1815. void StopHold();
  1816. // accessors
  1817. #ifdef SYNC_ANALYZE_PERFORMANCE
  1818. QWORD CHoldTotal() const { return m_cHold; }
  1819. double CsecHoldElapsed() const { return (double)(signed __int64)m_qwHRTHoldElapsed /
  1820. (double)(signed __int64)QwOSTimeHRTFreq(); }
  1821. #endif // SYNC_ANALYZE_PERFORMANCE
  1822. // debugging support
  1823. void Dump( CDumpContext& dc ) const;
  1824. private:
  1825. // member functions
  1826. // operators
  1827. CLockPerfHold& operator=( CLockPerfHold& ); // disallowed
  1828. // data members
  1829. #ifdef SYNC_ANALYZE_PERFORMANCE
  1830. // hold count
  1831. volatile QWORD m_cHold;
  1832. // elapsed hold time
  1833. volatile QWORD m_qwHRTHoldElapsed;
  1834. #endif // SYNC_ANALYZE_PERFORMANCE
  1835. };
  1836. // starts the hold timer for the lock object
  1837. inline void CLockPerfHold::StartHold()
  1838. {
  1839. #ifdef SYNC_ANALYZE_PERFORMANCE
  1840. // increment the hold count
  1841. AtomicAdd( (QWORD*)&m_cHold, 1 );
  1842. // subtract the start hold time from the elapsed hold time. this starts
  1843. // an elapsed time computation for this context. StopHold() will later
  1844. // add the end hold time to the elapsed time, causing the following net
  1845. // effect:
  1846. //
  1847. // m_qwHRTHoldElapsed += <end time> - <start time>
  1848. //
  1849. // we simply choose to go ahead and do the subtraction now to save storage
  1850. AtomicAdd( (QWORD*)&m_qwHRTHoldElapsed, QWORD( -__int64( QwOSTimeHRTCount() ) ) );
  1851. #endif // SYNC_ANALYZE_PERFORMANCE
  1852. }
  1853. // stops the hold timer for the lock object
  1854. inline void CLockPerfHold::StopHold()
  1855. {
  1856. #ifdef SYNC_ANALYZE_PERFORMANCE
  1857. // add the end hold time to the elapsed hold time. this completes the
  1858. // computation started in StartHold()
  1859. AtomicAdd( (QWORD*)&m_qwHRTHoldElapsed, QwOSTimeHRTCount() );
  1860. #endif // SYNC_ANALYZE_PERFORMANCE
  1861. }
  1862. // Lock Owner Record
  1863. class CLockDeadlockDetectionInfo;
  1864. class COwner
  1865. {
  1866. public:
  1867. // member functions
  1868. // ctors / dtors
  1869. COwner();
  1870. ~COwner();
  1871. void* operator new( size_t cb ) { return ESMemoryNew( cb ); }
  1872. void operator delete( void* pv ) { ESMemoryDelete( pv ); }
  1873. public:
  1874. // member functions
  1875. // operators
  1876. COwner& operator=( COwner& ); // disallowed
  1877. // data members
  1878. // owning context
  1879. CLS* m_pclsOwner;
  1880. // next context owning this lock
  1881. COwner* m_pownerContextNext;
  1882. // owned lock object
  1883. CLockDeadlockDetectionInfo* m_plddiOwned;
  1884. // next lock owned by this context
  1885. COwner* m_pownerLockNext;
  1886. // owning group for this context and lock
  1887. DWORD m_group;
  1888. };
  1889. // Lock Object Deadlock Detection Information
  1890. class CLockDeadlockDetectionInfo
  1891. {
  1892. public:
  1893. // types
  1894. // subrank used to disable deadlock detection at the subrank level
  1895. enum
  1896. {
  1897. subrankNoDeadlock = INT_MAX
  1898. };
  1899. // member functions
  1900. // ctors / dtors
  1901. CLockDeadlockDetectionInfo( const CLockBasicInfo& lbi );
  1902. ~CLockDeadlockDetectionInfo();
  1903. // member functions
  1904. // manipulators
  1905. void AddAsWaiter( const DWORD group = -1 );
  1906. void RemoveAsWaiter( const DWORD group = -1 );
  1907. void AddAsOwner( const DWORD group = -1 );
  1908. void RemoveAsOwner( const DWORD group = -1 );
  1909. static void OSSYNCAPI NextOwnershipIsNotADeadlock();
  1910. static void OSSYNCAPI DisableOwnershipTracking();
  1911. static void OSSYNCAPI EnableOwnershipTracking();
  1912. // accessors
  1913. const BOOL FOwner( const DWORD group = -1 );
  1914. const BOOL FNotOwner( const DWORD group = -1 );
  1915. const BOOL FOwned();
  1916. const BOOL FNotOwned();
  1917. const BOOL FCanBeWaiter();
  1918. const BOOL FWaiter( const DWORD group = -1 );
  1919. const BOOL FNotWaiter( const DWORD group = -1 );
  1920. #ifdef SYNC_DEADLOCK_DETECTION
  1921. const CLockBasicInfo& Info() { return *m_plbiParent; }
  1922. #endif // SYNC_DEADLOCK_DETECTION
  1923. // debugging support
  1924. void Dump( CDumpContext& dc ) const;
  1925. private:
  1926. // member functions
  1927. // operators
  1928. CLockDeadlockDetectionInfo& operator=( CLockDeadlockDetectionInfo& ); // disallowed
  1929. // data members
  1930. #ifdef SYNC_DEADLOCK_DETECTION
  1931. // parent lock object information
  1932. const CLockBasicInfo* m_plbiParent;
  1933. // semaphore protecting owner list
  1934. CSemaphore m_semOwnerList;
  1935. // owner list head
  1936. COwner m_ownerHead;
  1937. #endif // SYNC_DEADLOCK_DETECTION
  1938. };
  1939. // adds the current context as a waiter for the lock object as a member of the
  1940. // specified group
  1941. inline void CLockDeadlockDetectionInfo::AddAsWaiter( const DWORD group )
  1942. {
  1943. // this context had better not be a waiter for the lock
  1944. OSSYNCAssert( FNotWaiter( group ) );
  1945. #ifdef SYNC_DEADLOCK_DETECTION
  1946. // we had better not already be waiting for something else!
  1947. CLS* const pcls = Pcls();
  1948. OSSYNCAssert( !pcls->plddiLockWait );
  1949. OSSYNCAssert( !pcls->groupLockWait );
  1950. // add this context as a waiter for the lock
  1951. pcls->plddiLockWait = this;
  1952. pcls->groupLockWait = group;
  1953. #endif // SYNC_DEADLOCK_DETECTION
  1954. // this context had better be a waiter for the lock
  1955. OSSYNCAssert( FWaiter( group ) );
  1956. }
  1957. // removes the current context as a waiter for the lock object
  1958. inline void CLockDeadlockDetectionInfo::RemoveAsWaiter( const DWORD group )
  1959. {
  1960. // this context had better be a waiter for the lock
  1961. OSSYNCAssert( FWaiter( group ) );
  1962. #ifdef SYNC_DEADLOCK_DETECTION
  1963. // remove this context as a waiter for the lock
  1964. CLS* const pcls = Pcls();
  1965. pcls->plddiLockWait = NULL;
  1966. pcls->groupLockWait = 0;
  1967. #endif // SYNC_DEADLOCK_DETECTION
  1968. // this context had better not be a waiter for the lock anymore
  1969. OSSYNCAssert( FNotWaiter( group ) );
  1970. }
  1971. // adds the current context as an owner of the lock object as a member of the
  1972. // specified group
  1973. inline void CLockDeadlockDetectionInfo::AddAsOwner( const DWORD group )
  1974. {
  1975. // this context had better not be an owner of the lock
  1976. OSSYNCAssert( FNotOwner( group ) );
  1977. #ifdef SYNC_DEADLOCK_DETECTION
  1978. // add this context as an owner of the lock
  1979. CLS* const pcls = Pcls();
  1980. if ( !pcls->cDisableOwnershipTracking )
  1981. {
  1982. COwner* powner = &m_ownerHead;
  1983. if ( AtomicCompareExchangePointer( (void **)&powner->m_pclsOwner, NULL, pcls ) != NULL )
  1984. {
  1985. powner = new COwner;
  1986. OSSYNCEnforceSz( powner, "Failed to allocate Deadlock Detection Owner Record" );
  1987. m_semOwnerList.Acquire();
  1988. powner->m_pclsOwner = pcls;
  1989. powner->m_pownerContextNext = m_ownerHead.m_pownerContextNext;
  1990. m_ownerHead.m_pownerContextNext = powner;
  1991. m_semOwnerList.Release();
  1992. }
  1993. powner->m_plddiOwned = this;
  1994. powner->m_pownerLockNext = pcls->pownerLockHead;
  1995. pcls->pownerLockHead = powner;
  1996. powner->m_group = group;
  1997. }
  1998. // reset override
  1999. pcls->fOverrideDeadlock = fFalse;
  2000. #endif // SYNC_DEADLOCK_DETECTION
  2001. // this context had better be an owner of the lock
  2002. OSSYNCAssert( FOwner( group ) );
  2003. }
  2004. // removes the current context as an owner of the lock object
  2005. inline void CLockDeadlockDetectionInfo::RemoveAsOwner( const DWORD group )
  2006. {
  2007. // this context had better be an owner of the lock
  2008. OSSYNCAssert( FOwner( group ) );
  2009. #ifdef SYNC_DEADLOCK_DETECTION
  2010. // remove this context as an owner of the lock
  2011. CLS* const pcls = Pcls();
  2012. if ( !pcls->cDisableOwnershipTracking )
  2013. {
  2014. COwner** ppownerLock = &pcls->pownerLockHead;
  2015. while ( (*ppownerLock)->m_plddiOwned != this )
  2016. {
  2017. ppownerLock = &(*ppownerLock)->m_pownerLockNext;
  2018. }
  2019. COwner* pownerLock = *ppownerLock;
  2020. *ppownerLock = pownerLock->m_pownerLockNext;
  2021. pownerLock->m_plddiOwned = NULL;
  2022. pownerLock->m_pownerLockNext = NULL;
  2023. pownerLock->m_group = 0;
  2024. if ( AtomicCompareExchangePointer( (void**) &m_ownerHead.m_pclsOwner, pcls, NULL ) != pcls )
  2025. {
  2026. m_semOwnerList.Acquire();
  2027. COwner** ppownerContext = &m_ownerHead.m_pownerContextNext;
  2028. while ( (*ppownerContext)->m_pclsOwner != pcls )
  2029. {
  2030. ppownerContext = &(*ppownerContext)->m_pownerContextNext;
  2031. }
  2032. COwner* pownerContext = *ppownerContext;
  2033. *ppownerContext = pownerContext->m_pownerContextNext;
  2034. m_semOwnerList.Release();
  2035. delete pownerContext;
  2036. }
  2037. }
  2038. #endif // SYNC_DEADLOCK_DETECTION
  2039. // this context had better not be an owner of the lock anymore
  2040. OSSYNCAssert( FNotOwner( group ) );
  2041. }
  2042. // overrides deadlock detection using ranks for the next ownership
  2043. inline void OSSYNCAPI CLockDeadlockDetectionInfo::NextOwnershipIsNotADeadlock()
  2044. {
  2045. #ifdef SYNC_DEADLOCK_DETECTION
  2046. Pcls()->fOverrideDeadlock = fTrue;
  2047. #endif // SYNC_DEADLOCK_DETECTION
  2048. }
  2049. // disables ownership tracking for this context
  2050. inline void OSSYNCAPI CLockDeadlockDetectionInfo::DisableOwnershipTracking()
  2051. {
  2052. #ifdef SYNC_DEADLOCK_DETECTION
  2053. Pcls()->cDisableOwnershipTracking++;
  2054. #endif // SYNC_DEADLOCK_DETECTION
  2055. }
  2056. // enables ownership tracking for this context
  2057. inline void OSSYNCAPI CLockDeadlockDetectionInfo::EnableOwnershipTracking()
  2058. {
  2059. #ifdef SYNC_DEADLOCK_DETECTION
  2060. Pcls()->cDisableOwnershipTracking--;
  2061. #endif // SYNC_DEADLOCK_DETECTION
  2062. }
  2063. // returns fTrue if the current context is an owner of the lock object
  2064. //
  2065. // NOTE: if deadlock detection is disabled, this function will always return
  2066. // fTrue
  2067. inline const BOOL CLockDeadlockDetectionInfo::FOwner( const DWORD group )
  2068. {
  2069. #ifdef SYNC_DEADLOCK_DETECTION
  2070. COwner* pownerLock = Pcls()->pownerLockHead;
  2071. while ( pownerLock && pownerLock->m_plddiOwned != this )
  2072. {
  2073. pownerLock = pownerLock->m_pownerLockNext;
  2074. }
  2075. return Pcls()->cDisableOwnershipTracking != 0 ||
  2076. pownerLock && pownerLock->m_group == group;
  2077. #else // !SYNC_DEADLOCK_DETECTION
  2078. return fTrue;
  2079. #endif // SYNC_DEADLOCK_DETECTION
  2080. }
  2081. // returns fTrue if the current context is not an owner of the lock object
  2082. //
  2083. // NOTE: if deadlock detection is disabled, this function will always return
  2084. // fTrue
  2085. inline const BOOL CLockDeadlockDetectionInfo::FNotOwner( const DWORD group )
  2086. {
  2087. #ifdef SYNC_DEADLOCK_DETECTION
  2088. return Pcls()->cDisableOwnershipTracking != 0 || !FOwner( group );
  2089. #else // !SYNC_DEADLOCK_DETECTION
  2090. return fTrue;
  2091. #endif // SYNC_DEADLOCK_DETECTION
  2092. }
  2093. // returns fTrue if any context is an owner of the lock object
  2094. //
  2095. // NOTE: if deadlock detection is disabled, this function will always return
  2096. // fTrue
  2097. inline const BOOL CLockDeadlockDetectionInfo::FOwned()
  2098. {
  2099. #ifdef SYNC_DEADLOCK_DETECTION
  2100. return m_ownerHead.m_pclsOwner || m_ownerHead.m_pownerContextNext;
  2101. #else // !SYNC_DEADLOCK_DETECTION
  2102. return fTrue;
  2103. #endif // SYNC_DEADLOCK_DETECTION
  2104. }
  2105. // returns fTrue if no context is an owner of the lock object
  2106. //
  2107. // NOTE: if deadlock detection is disabled, this function will always return
  2108. // fTrue
  2109. inline const BOOL CLockDeadlockDetectionInfo::FNotOwned()
  2110. {
  2111. #ifdef SYNC_DEADLOCK_DETECTION
  2112. return !FOwned();
  2113. #else // !SYNC_DEADLOCK_DETECTION
  2114. return fTrue;
  2115. #endif // SYNC_DEADLOCK_DETECTION
  2116. }
  2117. // returns fTrue if the current context can wait for the lock object without
  2118. // violating any deadlock constraints
  2119. //
  2120. // NOTE: if deadlock detection is disabled, this function will always return
  2121. // fTrue
  2122. inline const BOOL CLockDeadlockDetectionInfo::FCanBeWaiter()
  2123. {
  2124. #ifdef SYNC_DEADLOCK_DETECTION
  2125. // find the minimum rank, subrank of all locks owned by the current context
  2126. CLS* const pcls = Pcls();
  2127. COwner* powner = pcls->pownerLockHead;
  2128. int Rank = INT_MAX;
  2129. int SubRank = INT_MAX;
  2130. while ( powner )
  2131. {
  2132. if ( powner->m_plddiOwned->Info().Rank() < Rank ||
  2133. ( powner->m_plddiOwned->Info().Rank() == Rank &&
  2134. powner->m_plddiOwned->Info().SubRank() < SubRank ) )
  2135. {
  2136. Rank = powner->m_plddiOwned->Info().Rank();
  2137. SubRank = powner->m_plddiOwned->Info().SubRank();
  2138. }
  2139. powner = powner->m_pownerLockNext;
  2140. }
  2141. // test this rank, subrank against our rank, subrank
  2142. return Rank > Info().Rank() ||
  2143. ( Rank == Info().Rank() && SubRank > Info().SubRank() ) ||
  2144. ( Rank == Info().Rank() && SubRank == Info().SubRank() &&
  2145. SubRank == subrankNoDeadlock ) ||
  2146. pcls->fOverrideDeadlock;
  2147. #else // !SYNC_DEADLOCK_DETECTION
  2148. return fTrue;
  2149. #endif // SYNC_DEADLOCK_DETECTION
  2150. }
  2151. // returns fTrue if the current context is a waiter of the lock object
  2152. //
  2153. // NOTE: if deadlock detection is disabled, this function will always return
  2154. // fTrue
  2155. inline const BOOL CLockDeadlockDetectionInfo::FWaiter( const DWORD group )
  2156. {
  2157. #ifdef SYNC_DEADLOCK_DETECTION
  2158. CLS* const pcls = Pcls();
  2159. return pcls->plddiLockWait == this && pcls->groupLockWait == group;
  2160. #else // !SYNC_DEADLOCK_DETECTION
  2161. return fTrue;
  2162. #endif // SYNC_DEADLOCK_DETECTION
  2163. }
  2164. // returns fTrue if the current context is not a waiter of the lock object
  2165. //
  2166. // NOTE: if deadlock detection is disabled, this function will always return
  2167. // fTrue
  2168. inline const BOOL CLockDeadlockDetectionInfo::FNotWaiter( const DWORD group )
  2169. {
  2170. #ifdef SYNC_DEADLOCK_DETECTION
  2171. return !FWaiter( group );
  2172. #else // !SYNC_DEADLOCK_DETECTION
  2173. return fTrue;
  2174. #endif // SYNC_DEADLOCK_DETECTION
  2175. }
  2176. // Critical Section (non-nestable) Information
  2177. class CCriticalSectionInfo
  2178. : public CLockBasicInfo,
  2179. public CLockPerfHold,
  2180. public CLockDeadlockDetectionInfo
  2181. {
  2182. public:
  2183. // member functions
  2184. // ctors / dtors
  2185. CCriticalSectionInfo( const CLockBasicInfo& lbi )
  2186. : CLockBasicInfo( lbi ),
  2187. CLockDeadlockDetectionInfo( (CLockBasicInfo&) *this )
  2188. {
  2189. }
  2190. // debugging support
  2191. void Dump( CDumpContext& dc ) const;
  2192. };
  2193. // Critical Section (non-nestable) State
  2194. class CCriticalSectionState
  2195. {
  2196. public:
  2197. // member functions
  2198. // ctors / dtors
  2199. CCriticalSectionState( const CSyncBasicInfo& sbi );
  2200. ~CCriticalSectionState();
  2201. // accessors
  2202. CSemaphore& Semaphore() { return m_sem; }
  2203. // debugging support
  2204. void Dump( CDumpContext& dc ) const;
  2205. private:
  2206. // member functions
  2207. // operators
  2208. CCriticalSectionState& operator=( CCriticalSectionState& ); // disallowed
  2209. // data members
  2210. // semaphore
  2211. CSemaphore m_sem;
  2212. };
  2213. // Critical Section (non-nestable)
  2214. class CCriticalSection
  2215. : private CLockObject,
  2216. private CEnhancedStateContainer< CCriticalSectionState, CSyncBasicInfo, CCriticalSectionInfo, CLockBasicInfo >
  2217. {
  2218. public:
  2219. // member functions
  2220. // ctors / dtors
  2221. CCriticalSection( const CLockBasicInfo& lbi );
  2222. ~CCriticalSection();
  2223. // manipulators
  2224. void Enter();
  2225. const BOOL FTryEnter();
  2226. const BOOL FEnter( const int cmsecTimeout );
  2227. void Leave();
  2228. // accessors
  2229. const int CWait() { return State().Semaphore().CWait(); }
  2230. const BOOL FOwner() { return State().FOwner(); }
  2231. const BOOL FNotOwner() { return State().FNotOwner(); }
  2232. // debugging support
  2233. void Dump( CDumpContext& dc ) const;
  2234. private:
  2235. // member functions
  2236. // operators
  2237. CCriticalSection& operator=( CCriticalSection& ); // disallowed
  2238. };
  2239. // enter the critical section, waiting forever if someone else is currently the
  2240. // owner. the critical section can not be re-entered until it has been left
  2241. inline void CCriticalSection::Enter()
  2242. {
  2243. // check for deadlock
  2244. OSSYNCAssertSzRTL( State().FCanBeWaiter(), "Potential Deadlock Detected (Rank Violation)" );
  2245. // acquire the semaphore
  2246. State().AddAsWaiter();
  2247. State().Semaphore().Acquire();
  2248. State().RemoveAsWaiter();
  2249. // there had better be no available counts on the semaphore
  2250. OSSYNCAssert( !State().Semaphore().CAvail() );
  2251. // we are now the owner of the critical section
  2252. State().AddAsOwner();
  2253. State().StartHold();
  2254. }
  2255. // try to enter the critical section without waiting or spinning, returning
  2256. // fFalse if someone else currently is the owner. the critical section can not
  2257. // be re-entered until it has been left
  2258. inline const BOOL CCriticalSection::FTryEnter()
  2259. {
  2260. // try to acquire the semaphore without waiting or spinning
  2261. //
  2262. // NOTE: there is no potential for deadlock here, so don't bother to check
  2263. BOOL fAcquire = State().Semaphore().FTryAcquire();
  2264. // we are now the owner of the critical section
  2265. if ( fAcquire )
  2266. {
  2267. // there had better be no available counts on the semaphore
  2268. OSSYNCAssert( !State().Semaphore().CAvail() );
  2269. // add ourself as the owner
  2270. State().AddAsOwner();
  2271. State().StartHold();
  2272. }
  2273. return fAcquire;
  2274. }
  2275. // try to enter the critical section waiting only for the specified interval,
  2276. // returning fFalse if the wait timed out before the critical section could be
  2277. // acquired. the critical section can not be re-entered until it has been left
  2278. inline const BOOL CCriticalSection::FEnter( const int cmsecTimeout )
  2279. {
  2280. // check for deadlock if we are waiting forever
  2281. OSSYNCAssertSzRTL( cmsecTimeout != cmsecInfinite || State().FCanBeWaiter(), "Potential Deadlock Detected (Rank Violation)" );
  2282. // try to acquire the semaphore, timing out as requested
  2283. //
  2284. // NOTE: there is still a potential for deadlock, but that will be detected
  2285. // at the OS level
  2286. State().AddAsWaiter();
  2287. BOOL fAcquire = State().Semaphore().FAcquire( cmsecTimeout );
  2288. State().RemoveAsWaiter();
  2289. // we are now the owner of the critical section
  2290. if ( fAcquire )
  2291. {
  2292. // there had better be no available counts on the semaphore
  2293. OSSYNCAssert( !State().Semaphore().CAvail() );
  2294. // add ourself as the owner
  2295. State().AddAsOwner();
  2296. State().StartHold();
  2297. }
  2298. return fAcquire;
  2299. }
  2300. // leaves the critical section, releasing it for ownership by someone else
  2301. inline void CCriticalSection::Leave()
  2302. {
  2303. // remove ourself as the owner
  2304. State().RemoveAsOwner();
  2305. // we are no longer holding the lock
  2306. State().StopHold();
  2307. // there had better be no available counts on the semaphore
  2308. OSSYNCAssert( !State().Semaphore().CAvail() );
  2309. // release the semaphore
  2310. State().Semaphore().Release();
  2311. }
  2312. // Nestable Critical Section Information
  2313. class CNestableCriticalSectionInfo
  2314. : public CLockBasicInfo,
  2315. public CLockPerfHold,
  2316. public CLockDeadlockDetectionInfo
  2317. {
  2318. public:
  2319. // member functions
  2320. // ctors / dtors
  2321. CNestableCriticalSectionInfo( const CLockBasicInfo& lbi )
  2322. : CLockBasicInfo( lbi ),
  2323. CLockDeadlockDetectionInfo( (CLockBasicInfo&) *this )
  2324. {
  2325. }
  2326. // debugging support
  2327. void Dump( CDumpContext& dc ) const;
  2328. };
  2329. // Nestable Critical Section State
  2330. class CNestableCriticalSectionState
  2331. {
  2332. public:
  2333. // member functions
  2334. // ctors / dtors
  2335. CNestableCriticalSectionState( const CSyncBasicInfo& sbi );
  2336. ~CNestableCriticalSectionState();
  2337. // manipulators
  2338. void SetOwner( CLS* const pcls );
  2339. void Enter();
  2340. void Leave();
  2341. // accessors
  2342. CSemaphore& Semaphore() { return m_sem; }
  2343. CLS* PclsOwner() { return m_pclsOwner; }
  2344. int CEntry() { return m_cEntry; }
  2345. // debugging support
  2346. void Dump( CDumpContext& dc ) const;
  2347. private:
  2348. // member functions
  2349. // operators
  2350. CNestableCriticalSectionState& operator=( CNestableCriticalSectionState& ); // disallowed
  2351. // data members
  2352. // semaphore
  2353. CSemaphore m_sem;
  2354. // owning context (protected by the semaphore)
  2355. CLS* volatile m_pclsOwner;
  2356. // entry count (only valid when the owner id is valid)
  2357. volatile int m_cEntry;
  2358. };
  2359. // set the owner
  2360. inline void CNestableCriticalSectionState::SetOwner( CLS* const pcls )
  2361. {
  2362. // we had either be clearing the owner or setting a new owner. we should
  2363. // never be overwriting another owner
  2364. OSSYNCAssert( !pcls || !m_pclsOwner );
  2365. // set the new owner
  2366. m_pclsOwner = pcls;
  2367. }
  2368. // increment the entry count
  2369. inline void CNestableCriticalSectionState::Enter()
  2370. {
  2371. // we had better have an owner already!
  2372. OSSYNCAssert( m_pclsOwner );
  2373. // we should not overflow the entry count
  2374. OSSYNCAssert( int( m_cEntry + 1 ) >= 1 );
  2375. // increment the entry count
  2376. m_cEntry++;
  2377. }
  2378. // decrement the entry count
  2379. inline void CNestableCriticalSectionState::Leave()
  2380. {
  2381. // we had better have an owner already!
  2382. OSSYNCAssert( m_pclsOwner );
  2383. // decrement the entry count
  2384. m_cEntry--;
  2385. }
  2386. // Nestable Critical Section
  2387. class CNestableCriticalSection
  2388. : private CLockObject,
  2389. private CEnhancedStateContainer< CNestableCriticalSectionState, CSyncBasicInfo, CNestableCriticalSectionInfo, CLockBasicInfo >
  2390. {
  2391. public:
  2392. // member functions
  2393. // ctors / dtors
  2394. CNestableCriticalSection( const CLockBasicInfo& lbi );
  2395. ~CNestableCriticalSection();
  2396. // manipulators
  2397. void Enter();
  2398. const BOOL FTryEnter();
  2399. const BOOL FEnter( const int cmsecTimeout );
  2400. void Leave();
  2401. // accessors
  2402. const int CWait() { return State().Semaphore().CWait(); }
  2403. const BOOL FOwner() { return State().FOwner(); }
  2404. const BOOL FNotOwner() { return State().FNotOwner(); }
  2405. // debugging support
  2406. void Dump( CDumpContext& dc ) const;
  2407. private:
  2408. // member functions
  2409. // operators
  2410. CNestableCriticalSection& operator=( CNestableCriticalSection& ); // disallowed
  2411. };
  2412. // enter the critical section, waiting forever if someone else is currently the
  2413. // owner. the critical section can be reentered without waiting or deadlocking
  2414. inline void CNestableCriticalSection::Enter()
  2415. {
  2416. // get our context
  2417. CLS* const pcls = Pcls();
  2418. // we own the critical section
  2419. if ( State().PclsOwner() == pcls )
  2420. {
  2421. // there had better be no available counts on the semaphore
  2422. OSSYNCAssert( !State().Semaphore().CAvail() );
  2423. // we should have at least one entry count
  2424. OSSYNCAssert( State().CEntry() >= 1 );
  2425. // increment our entry count
  2426. State().Enter();
  2427. }
  2428. // we do not own the critical section
  2429. else
  2430. {
  2431. OSSYNCAssert( State().PclsOwner() != pcls );
  2432. // check for deadlock
  2433. OSSYNCAssertSzRTL( State().FCanBeWaiter(), "Potential Deadlock Detected (Rank Violation)" );
  2434. // acquire the semaphore
  2435. State().AddAsWaiter();
  2436. State().Semaphore().Acquire();
  2437. State().RemoveAsWaiter();
  2438. // there had better be no available counts on the semaphore
  2439. OSSYNCAssert( !State().Semaphore().CAvail() );
  2440. // we are now the owner of the critical section
  2441. State().AddAsOwner();
  2442. State().StartHold();
  2443. // save our context as the owner
  2444. State().SetOwner( pcls );
  2445. // set initial entry count
  2446. State().Enter();
  2447. }
  2448. }
  2449. // try to enter the critical section without waiting or spinning, returning
  2450. // fFalse if someone else currently is the owner. the critical section can be
  2451. // reentered without waiting or deadlocking
  2452. inline const BOOL CNestableCriticalSection::FTryEnter()
  2453. {
  2454. // get our context
  2455. CLS* const pcls = Pcls();
  2456. // we own the critical section
  2457. if ( State().PclsOwner() == pcls )
  2458. {
  2459. // there had better be no available counts on the semaphore
  2460. OSSYNCAssert( !State().Semaphore().CAvail() );
  2461. // we should have at least one entry count
  2462. OSSYNCAssert( State().CEntry() >= 1 );
  2463. // increment our entry count
  2464. State().Enter();
  2465. // return success
  2466. return fTrue;
  2467. }
  2468. // we do not own the critical section
  2469. else
  2470. {
  2471. OSSYNCAssert( State().PclsOwner() != pcls );
  2472. // try to acquire the semaphore without waiting or spinning
  2473. //
  2474. // NOTE: there is no potential for deadlock here, so don't bother to check
  2475. const BOOL fAcquired = State().Semaphore().FTryAcquire();
  2476. // we now own the critical section
  2477. if ( fAcquired )
  2478. {
  2479. // there had better be no available counts on the semaphore
  2480. OSSYNCAssert( !State().Semaphore().CAvail() );
  2481. // add ourself as the owner
  2482. State().AddAsOwner();
  2483. State().StartHold();
  2484. // save our context as the owner
  2485. State().SetOwner( pcls );
  2486. // set initial entry count
  2487. State().Enter();
  2488. }
  2489. // return result
  2490. return fAcquired;
  2491. }
  2492. }
  2493. // try to enter the critical section waiting only for the specified interval,
  2494. // returning fFalse if the wait timed out before the critical section could be
  2495. // acquired. the critical section can be reentered without waiting or
  2496. // deadlocking
  2497. inline const BOOL CNestableCriticalSection::FEnter( const int cmsecTimeout )
  2498. {
  2499. // get our context
  2500. CLS* const pcls = Pcls();
  2501. // we own the critical section
  2502. if ( State().PclsOwner() == pcls )
  2503. {
  2504. // there had better be no available counts on the semaphore
  2505. OSSYNCAssert( !State().Semaphore().CAvail() );
  2506. // we should have at least one entry count
  2507. OSSYNCAssert( State().CEntry() >= 1 );
  2508. // increment our entry count
  2509. State().Enter();
  2510. // return success
  2511. return fTrue;
  2512. }
  2513. // we do not own the critical section
  2514. else
  2515. {
  2516. OSSYNCAssert( State().PclsOwner() != pcls );
  2517. // check for deadlock if we are waiting forever
  2518. OSSYNCAssertSzRTL( cmsecTimeout != cmsecInfinite || State().FCanBeWaiter(), "Potential Deadlock Detected (Rank Violation)" );
  2519. // try to acquire the semaphore, timing out as requested
  2520. //
  2521. // NOTE: there is still a potential for deadlock, but that will be detected
  2522. // at the OS level
  2523. State().AddAsWaiter();
  2524. const BOOL fAcquired = State().Semaphore().FAcquire( cmsecTimeout );
  2525. State().RemoveAsWaiter();
  2526. // we now own the critical section
  2527. if ( fAcquired )
  2528. {
  2529. // there had better be no available counts on the semaphore
  2530. OSSYNCAssert( !State().Semaphore().CAvail() );
  2531. // add ourself as the owner
  2532. State().AddAsOwner();
  2533. State().StartHold();
  2534. // save our context as the owner
  2535. State().SetOwner( pcls );
  2536. // set initial entry count
  2537. State().Enter();
  2538. }
  2539. // return result
  2540. return fAcquired;
  2541. }
  2542. }
  2543. // leave the critical section. if leave has been called for every enter that
  2544. // has completed successfully, the critical section is released for ownership
  2545. // by someone else
  2546. inline void CNestableCriticalSection::Leave()
  2547. {
  2548. // we had better be the current owner
  2549. OSSYNCAssert( State().PclsOwner() == Pcls() );
  2550. // there had better be no available counts on the semaphore
  2551. OSSYNCAssert( !State().Semaphore().CAvail() );
  2552. // there had better be at least one entry count
  2553. OSSYNCAssert( State().CEntry() >= 1 );
  2554. // release one entry count
  2555. State().Leave();
  2556. // we released the last entry count
  2557. if ( !State().CEntry() )
  2558. {
  2559. // reset the owner id
  2560. State().SetOwner( 0 );
  2561. // remove ourself as the owner
  2562. State().RemoveAsOwner();
  2563. // we are no longer holding the lock
  2564. State().StopHold();
  2565. // release the semaphore
  2566. State().Semaphore().Release();
  2567. }
  2568. }
  2569. // Gate Information
  2570. class CGateInfo
  2571. : public CSyncBasicInfo,
  2572. public CSyncPerfWait
  2573. {
  2574. public:
  2575. // member functions
  2576. // ctors / dtors
  2577. CGateInfo( const CSyncBasicInfo& sbi )
  2578. : CSyncBasicInfo( sbi )
  2579. {
  2580. }
  2581. // debugging support
  2582. void Dump( CDumpContext& dc ) const;
  2583. };
  2584. // Gate State
  2585. class CGateState
  2586. {
  2587. public:
  2588. // member functions
  2589. // ctors / dtors
  2590. CGateState( const CSyncStateInitNull& null ) : m_cWait( 0 ), m_irksem( CKernelSemaphorePool::irksemNil ) {}
  2591. CGateState( const int cWait, const int irksem );
  2592. ~CGateState() {}
  2593. // manipulators
  2594. void SetWaitCount( const int cWait );
  2595. void SetIrksem( const CKernelSemaphorePool::IRKSEM irksem );
  2596. // accessors
  2597. const int CWait() const { return m_cWait; }
  2598. const CKernelSemaphorePool::IRKSEM Irksem() const { return CKernelSemaphorePool::IRKSEM( m_irksem ); }
  2599. // debugging support
  2600. void Dump( CDumpContext& dc ) const;
  2601. private:
  2602. // member functions
  2603. // operators
  2604. CGateState& operator=( CGateState& ); // disallowed
  2605. // data members
  2606. // waiter count
  2607. volatile short m_cWait; // 0 <= m_cWait <= ( 1 << 15 ) - 1
  2608. // reference kernel semaphore
  2609. volatile unsigned short m_irksem; // 0 <= m_irksem <= ( 1 << 16 ) - 2
  2610. };
  2611. // sets the wait count for the gate
  2612. inline void CGateState::SetWaitCount( const int cWait )
  2613. {
  2614. // it must be a valid wait count
  2615. OSSYNCAssert( cWait >= 0 );
  2616. OSSYNCAssert( cWait <= 0x7FFF );
  2617. // set the wait count
  2618. m_cWait = (unsigned short) cWait;
  2619. }
  2620. // sets the referenced kernel semaphore for the gate
  2621. inline void CGateState::SetIrksem( const CKernelSemaphorePool::IRKSEM irksem )
  2622. {
  2623. // it must be a valid irksem
  2624. OSSYNCAssert( irksem >= 0 );
  2625. OSSYNCAssert( irksem <= 0xFFFF );
  2626. // set the irksem
  2627. m_irksem = (unsigned short) irksem;
  2628. }
  2629. // Gate
  2630. class CGate
  2631. : private CSyncObject,
  2632. private CEnhancedStateContainer< CGateState, CSyncStateInitNull, CGateInfo, CSyncBasicInfo >
  2633. {
  2634. public:
  2635. // member functions
  2636. // ctors / dtors
  2637. CGate( const CSyncBasicInfo& sbi );
  2638. ~CGate();
  2639. // manipulators
  2640. void Wait( CCriticalSection& crit );
  2641. void Release( CCriticalSection& crit, const int cToRelease = 1 );
  2642. void ReleaseAndHold( CCriticalSection& crit, const int cToRelease = 1 );
  2643. // accessors
  2644. const int CWait() const { return State().CWait(); }
  2645. // debugging support
  2646. void Dump( CDumpContext& dc ) const;
  2647. private:
  2648. // member functions
  2649. // operators
  2650. CGate& operator=( CGate& ); // disallowed
  2651. };
  2652. // Null Lock Object State Initializer
  2653. class CLockStateInitNull
  2654. {
  2655. };
  2656. extern const CLockStateInitNull lockstateNull;
  2657. // Binary Lock Performance Information
  2658. class CBinaryLockPerfInfo
  2659. : public CSyncPerfWait,
  2660. public CSyncPerfAcquire,
  2661. public CLockPerfHold
  2662. {
  2663. public:
  2664. // member functions
  2665. // ctors / dtors
  2666. CBinaryLockPerfInfo()
  2667. {
  2668. }
  2669. // debugging support
  2670. void Dump( CDumpContext& dc ) const;
  2671. };
  2672. // Binary Lock Group Information
  2673. class CBinaryLockGroupInfo
  2674. {
  2675. public:
  2676. // member functions
  2677. // ctors / dtors
  2678. CBinaryLockGroupInfo() {}
  2679. ~CBinaryLockGroupInfo() {}
  2680. // manipulators
  2681. void StartWait( const int iGroup ) { m_rginfo[iGroup].StartWait(); }
  2682. void StopWait( const int iGroup ) { m_rginfo[iGroup].StopWait(); }
  2683. void SetAcquire( const int iGroup ) { m_rginfo[iGroup].SetAcquire(); }
  2684. void SetContend( const int iGroup ) { m_rginfo[iGroup].SetContend(); }
  2685. void StartHold( const int iGroup ) { m_rginfo[iGroup].StartHold(); }
  2686. void StopHold( const int iGroup ) { m_rginfo[iGroup].StopHold(); }
  2687. // accessors
  2688. #ifdef SYNC_ANALYZE_PERFORMANCE
  2689. QWORD CWaitTotal( const int iGroup ) const { return m_rginfo[iGroup].CWaitTotal(); }
  2690. double CsecWaitElapsed( const int iGroup ) const { return m_rginfo[iGroup].CsecWaitElapsed(); }
  2691. QWORD CAcquireTotal( const int iGroup ) const { return m_rginfo[iGroup].CAcquireTotal(); }
  2692. QWORD CContendTotal( const int iGroup ) const { return m_rginfo[iGroup].CContendTotal(); }
  2693. QWORD CHoldTotal( const int iGroup ) const { return m_rginfo[iGroup].CHoldTotal(); }
  2694. double CsecHoldElapsed( const int iGroup ) const { return m_rginfo[iGroup].CsecHoldElapsed(); }
  2695. #endif // SYNC_ANALYZE_PERFORMANCE
  2696. // debugging support
  2697. void Dump( CDumpContext& dc ) const;
  2698. private:
  2699. // member functions
  2700. // operators
  2701. CBinaryLockGroupInfo& operator=( CBinaryLockGroupInfo& ); // disallowed
  2702. // data members
  2703. // performance info for each group
  2704. CBinaryLockPerfInfo m_rginfo[2];
  2705. };
  2706. // Binary Lock Information
  2707. class CBinaryLockInfo
  2708. : public CLockBasicInfo,
  2709. public CBinaryLockGroupInfo,
  2710. public CLockDeadlockDetectionInfo
  2711. {
  2712. public:
  2713. // member functions
  2714. // ctors / dtors
  2715. CBinaryLockInfo( const CLockBasicInfo& lbi )
  2716. : CLockBasicInfo( lbi ),
  2717. CLockDeadlockDetectionInfo( (CLockBasicInfo&) *this )
  2718. {
  2719. }
  2720. // debugging support
  2721. void Dump( CDumpContext& dc ) const;
  2722. };
  2723. // Binary Lock State
  2724. class CBinaryLockState
  2725. {
  2726. public:
  2727. // types
  2728. // control word
  2729. typedef DWORD ControlWord;
  2730. // member functions
  2731. // ctors / dtors
  2732. CBinaryLockState( const CSyncBasicInfo& sbi );
  2733. ~CBinaryLockState();
  2734. // debugging support
  2735. void Dump( CDumpContext& dc ) const;
  2736. // data members
  2737. // control word
  2738. union
  2739. {
  2740. volatile ControlWord m_cw;
  2741. struct
  2742. {
  2743. volatile DWORD m_cOOW1:15;
  2744. volatile DWORD m_fQ1:1;
  2745. volatile DWORD m_cOOW2:15;
  2746. volatile DWORD m_fQ2:1;
  2747. };
  2748. };
  2749. // quiesced owner count
  2750. volatile DWORD m_cOwner;
  2751. // sempahore used by Group 1 to wait for lock ownership
  2752. CSemaphore m_sem1;
  2753. // sempahore used by Group 2 to wait for lock ownership
  2754. CSemaphore m_sem2;
  2755. private:
  2756. // member functions
  2757. // operators
  2758. CBinaryLockState& operator=( CBinaryLockState& ); // disallowed
  2759. };
  2760. // Binary Lock
  2761. class CBinaryLock
  2762. : private CLockObject,
  2763. private CEnhancedStateContainer< CBinaryLockState, CSyncBasicInfo, CBinaryLockInfo, CLockBasicInfo >
  2764. {
  2765. public:
  2766. // types
  2767. // control word
  2768. typedef CBinaryLockState::ControlWord ControlWord;
  2769. // transition reasons for state machine
  2770. enum TransitionReason
  2771. {
  2772. trIllegal = 0,
  2773. trEnter1 = 1,
  2774. trLeave1 = 2,
  2775. trEnter2 = 4,
  2776. trLeave2 = 8,
  2777. };
  2778. // member functions
  2779. // ctors / dtors
  2780. CBinaryLock( const CLockBasicInfo& lbi );
  2781. ~CBinaryLock();
  2782. // manipulators
  2783. void Enter1();
  2784. const BOOL FTryEnter1();
  2785. void Leave1();
  2786. void Enter2();
  2787. const BOOL FTryEnter2();
  2788. void Leave2();
  2789. // accessors
  2790. const BOOL FGroup1Quiesced() { return State().m_cw & 0x00008000; }
  2791. const BOOL FGroup2Quiesced() { return State().m_cw & 0x80000000; }
  2792. const BOOL FMemberOfGroup1() { return State().FOwner( 0 ); }
  2793. const BOOL FNotMemberOfGroup1() { return State().FNotOwner( 0 ); }
  2794. const BOOL FMemberOfGroup2() { return State().FOwner( 1 ); }
  2795. const BOOL FNotMemberOfGroup2() { return State().FNotOwner( 1 ); }
  2796. // debugging support
  2797. void Dump( CDumpContext& dc ) const;
  2798. private:
  2799. // member functions
  2800. // operators
  2801. CBinaryLock& operator=( CBinaryLock& ); // disallowed
  2802. // verification
  2803. int _StateFromControlWord( const ControlWord cw );
  2804. BOOL _FValidStateTransition( const ControlWord cwBI,
  2805. const ControlWord cwAI,
  2806. const TransitionReason tr );
  2807. // manipulators
  2808. void _Enter1( const ControlWord cwBIOld );
  2809. void _Enter2( const ControlWord cwBIOld );
  2810. void _UpdateQuiescedOwnerCountAsGroup1( const DWORD cOwnerDelta );
  2811. void _UpdateQuiescedOwnerCountAsGroup2( const DWORD cOwnerDelta );
  2812. };
  2813. // enters the binary lock as a member of Group 1, waiting forever if necessary
  2814. //
  2815. // NOTE: trying to enter the lock as a member of Group 1 when you already own
  2816. // the lock as a member of Group 2 will cause a deadlock.
  2817. inline void CBinaryLock::Enter1()
  2818. {
  2819. // we had better not already own this lock as either group
  2820. OSSYNCAssert( State().FNotOwner( 0 ) );
  2821. OSSYNCAssert( State().FNotOwner( 1 ) );
  2822. // check for deadlock
  2823. OSSYNCAssertSzRTL( State().FCanBeWaiter(), "Potential Deadlock Detected (Rank Violation)" );
  2824. // try forever until we successfully change the lock state
  2825. OSSYNC_FOREVER
  2826. {
  2827. // read the current state of the control word as our expected before image
  2828. const ControlWord cwBIExpected = State().m_cw;
  2829. // compute the after image of the control word by performing the global
  2830. // transform for the Enter1 state transition
  2831. const ControlWord cwAI = ControlWord( ( ( cwBIExpected & ( ( LONG_PTR( long( cwBIExpected ) ) >> 31 ) |
  2832. 0x0000FFFF ) ) | 0x80000000 ) + 0x00000001 );
  2833. // validate the transaction
  2834. OSSYNCAssert( _FValidStateTransition( cwBIExpected, cwAI, trEnter1 ) );
  2835. // attempt to perform the transacted state transition on the control word
  2836. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  2837. // the transaction failed or Group 1 was quiesced from ownership
  2838. if ( ( cwBI ^ cwBIExpected ) | ( cwBI & 0x00008000 ) )
  2839. {
  2840. // the transaction failed because another context changed the control word
  2841. if ( cwBI != cwBIExpected )
  2842. {
  2843. // try again
  2844. continue;
  2845. }
  2846. // the transaction succeeded but Group 1 was quiesced from ownership
  2847. else
  2848. {
  2849. // this is a contention for Group 1
  2850. State().SetContend( 0 );
  2851. // wait to own the lock as a member of Group 1
  2852. _Enter1( cwBI );
  2853. // we now own the lock, so we're done
  2854. break;
  2855. }
  2856. }
  2857. // the transaction succeeded and Group 1 was not quiesced from ownership
  2858. else
  2859. {
  2860. // we now own the lock, so we're done
  2861. break;
  2862. }
  2863. }
  2864. // we are now an owner of the lock for Group 1
  2865. State().SetAcquire( 0 );
  2866. State().AddAsOwner( 0 );
  2867. State().StartHold( 0 );
  2868. }
  2869. // tries to enter the binary lock as a member of Group 1 without waiting or
  2870. // spinning, returning fFalse if Group 1 is quiesced from ownership
  2871. //
  2872. // NOTE: trying to enter the lock as a member of Group 1 when you already own
  2873. // the lock as a member of Group 2 will cause a deadlock.
  2874. inline const BOOL CBinaryLock::FTryEnter1()
  2875. {
  2876. // we had better not already own this lock as either group
  2877. OSSYNCAssert( State().FNotOwner( 0 ) );
  2878. OSSYNCAssert( State().FNotOwner( 1 ) );
  2879. // try forever until we successfully change the lock state
  2880. OSSYNC_FOREVER
  2881. {
  2882. // read the current state of the control word as our expected before image
  2883. ControlWord cwBIExpected = State().m_cw;
  2884. // change the expected before image so that the transaction will only work if
  2885. // Group 1 ownership is not quiesced
  2886. cwBIExpected = cwBIExpected & 0xFFFF7FFF;
  2887. // compute the after image of the control word by performing the global
  2888. // transform for the Enter1 state transition
  2889. const ControlWord cwAI = ControlWord( ( ( cwBIExpected & ( ( LONG_PTR( long( cwBIExpected ) ) >> 31 ) |
  2890. 0x0000FFFF ) ) | 0x80000000 ) + 0x00000001 );
  2891. // validate the transaction
  2892. OSSYNCAssert( _StateFromControlWord( cwBIExpected ) < 0 ||
  2893. _FValidStateTransition( cwBIExpected, cwAI, trEnter1 ) );
  2894. // attempt to perform the transacted state transition on the control word
  2895. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  2896. // the transaction failed
  2897. if ( cwBI != cwBIExpected )
  2898. {
  2899. // the transaction failed because Group 1 ownership is quiesced
  2900. if ( cwBI & 0x00008000 )
  2901. {
  2902. // return failure
  2903. return fFalse;
  2904. }
  2905. // the transaction failed because another context changed the control word
  2906. else
  2907. {
  2908. // try again
  2909. continue;
  2910. }
  2911. }
  2912. // the transaction succeeded
  2913. else
  2914. {
  2915. // we are now an owner of the lock for Group 1
  2916. State().SetAcquire( 0 );
  2917. State().AddAsOwner( 0 );
  2918. State().StartHold( 0 );
  2919. // return success
  2920. return fTrue;
  2921. }
  2922. }
  2923. }
  2924. // leaves the binary lock as a member of Group 1
  2925. //
  2926. // NOTE: you must leave the lock as a member of the same Group for which you entered
  2927. // the lock or deadlocks may occur
  2928. inline void CBinaryLock::Leave1()
  2929. {
  2930. // we are no longer an owner of the lock
  2931. State().RemoveAsOwner( 0 );
  2932. // we are no longer holding the lock
  2933. State().StopHold( 0 );
  2934. // try forever until we successfully change the lock state
  2935. OSSYNC_FOREVER
  2936. {
  2937. // read the current state of the control word as our expected before image
  2938. ControlWord cwBIExpected = State().m_cw;
  2939. // change the expected before image so that the transaction will only work if
  2940. // Group 1 ownership is not quiesced
  2941. cwBIExpected = cwBIExpected & 0xFFFF7FFF;
  2942. // compute the after image of the control word by performing the transform that
  2943. // will take us either from state 2 to state 0 or state 2 to state 2
  2944. ControlWord cwAI = cwBIExpected + 0xFFFFFFFF;
  2945. cwAI = cwAI - ( ( ( cwAI + 0xFFFFFFFF ) << 16 ) & 0x80000000 );
  2946. // validate the transaction
  2947. OSSYNCAssert( _StateFromControlWord( cwBIExpected ) < 0 ||
  2948. _FValidStateTransition( cwBIExpected, cwAI, trLeave1 ) );
  2949. // attempt to perform the transacted state transition on the control word
  2950. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  2951. // the transaction failed
  2952. if ( cwBI != cwBIExpected )
  2953. {
  2954. // the transaction failed because Group 1 ownership is quiesced
  2955. if ( cwBI & 0x00008000 )
  2956. {
  2957. // leave the lock as a quiesced owner
  2958. _UpdateQuiescedOwnerCountAsGroup1( 0xFFFFFFFF );
  2959. // we're done
  2960. break;
  2961. }
  2962. // the transaction failed because another context changed the control word
  2963. else
  2964. {
  2965. // try again
  2966. continue;
  2967. }
  2968. }
  2969. // the transaction succeeded
  2970. else
  2971. {
  2972. // we're done
  2973. break;
  2974. }
  2975. }
  2976. }
  2977. // enters the binary lock as a member of Group 2, waiting forever if necessary
  2978. //
  2979. // NOTE: trying to enter the lock as a member of Group 2 when you already own
  2980. // the lock as a member of Group 1 will cause a deadlock.
  2981. inline void CBinaryLock::Enter2()
  2982. {
  2983. // we had better not already own this lock as either group
  2984. OSSYNCAssert( State().FNotOwner( 0 ) );
  2985. OSSYNCAssert( State().FNotOwner( 1 ) );
  2986. // check for deadlock
  2987. OSSYNCAssertSzRTL( State().FCanBeWaiter(), "Potential Deadlock Detected (Rank Violation)" );
  2988. // try forever until we successfully change the lock state
  2989. OSSYNC_FOREVER
  2990. {
  2991. // read the current state of the control word as our expected before image
  2992. const ControlWord cwBIExpected = State().m_cw;
  2993. // compute the after image of the control word by performing the global
  2994. // transform for the Enter2 state transition
  2995. const ControlWord cwAI = ControlWord( ( ( cwBIExpected & ( ( LONG_PTR( long( cwBIExpected << 16 ) ) >> 31 ) |
  2996. 0xFFFF0000 ) ) | 0x00008000 ) + 0x00010000 );
  2997. // validate the transaction
  2998. OSSYNCAssert( _FValidStateTransition( cwBIExpected, cwAI, trEnter2 ) );
  2999. // attempt to perform the transacted state transition on the control word
  3000. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  3001. // the transaction failed or Group 2 was quiesced from ownership
  3002. if ( ( cwBI ^ cwBIExpected ) | ( cwBI & 0x80000000 ) )
  3003. {
  3004. // the transaction failed because another context changed the control word
  3005. if ( cwBI != cwBIExpected )
  3006. {
  3007. // try again
  3008. continue;
  3009. }
  3010. // the transaction succeeded but Group 2 was quiesced from ownership
  3011. else
  3012. {
  3013. // this is a contention for Group 2
  3014. State().SetContend( 1 );
  3015. // wait to own the lock as a member of Group 2
  3016. _Enter2( cwBI );
  3017. // we now own the lock, so we're done
  3018. break;
  3019. }
  3020. }
  3021. // the transaction succeeded and Group 2 was not quiesced from ownership
  3022. else
  3023. {
  3024. // we now own the lock, so we're done
  3025. break;
  3026. }
  3027. }
  3028. // we are now an owner of the lock for Group 2
  3029. State().SetAcquire( 1 );
  3030. State().AddAsOwner( 1 );
  3031. State().StartHold( 1 );
  3032. }
  3033. // tries to enter the binary lock as a member of Group 2 without waiting or
  3034. // spinning, returning fFalse if Group 2 is quiesced from ownership
  3035. //
  3036. // NOTE: trying to enter the lock as a member of Group 2 when you already own
  3037. // the lock as a member of Group 1 will cause a deadlock.
  3038. inline const BOOL CBinaryLock::FTryEnter2()
  3039. {
  3040. // we had better not already own this lock as either group
  3041. OSSYNCAssert( State().FNotOwner( 0 ) );
  3042. OSSYNCAssert( State().FNotOwner( 1 ) );
  3043. // try forever until we successfully change the lock state
  3044. OSSYNC_FOREVER
  3045. {
  3046. // read the current state of the control word as our expected before image
  3047. ControlWord cwBIExpected = State().m_cw;
  3048. // change the expected before image so that the transaction will only work if
  3049. // Group 2 ownership is not quiesced
  3050. cwBIExpected = cwBIExpected & 0x7FFFFFFF;
  3051. // compute the after image of the control word by performing the global
  3052. // transform for the Enter2 state transition
  3053. const ControlWord cwAI = ControlWord( ( ( cwBIExpected & ( ( LONG_PTR( long( cwBIExpected << 16 ) ) >> 31 ) |
  3054. 0xFFFF0000 ) ) | 0x00008000 ) + 0x00010000 );
  3055. // validate the transaction
  3056. OSSYNCAssert( _StateFromControlWord( cwBIExpected ) < 0 ||
  3057. _FValidStateTransition( cwBIExpected, cwAI, trEnter2 ) );
  3058. // attempt to perform the transacted state transition on the control word
  3059. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  3060. // the transaction failed
  3061. if ( cwBI != cwBIExpected )
  3062. {
  3063. // the transaction failed because Group 2 ownership is quiesced
  3064. if ( cwBI & 0x80000000 )
  3065. {
  3066. // return failure
  3067. return fFalse;
  3068. }
  3069. // the transaction failed because another context changed the control word
  3070. else
  3071. {
  3072. // try again
  3073. continue;
  3074. }
  3075. }
  3076. // the transaction succeeded
  3077. else
  3078. {
  3079. // we are now an owner of the lock for Group 2
  3080. State().SetAcquire( 1 );
  3081. State().AddAsOwner( 1 );
  3082. State().StartHold( 1 );
  3083. // return success
  3084. return fTrue;
  3085. }
  3086. }
  3087. }
  3088. // leaves the binary lock as a member of Group 2
  3089. //
  3090. // NOTE: you must leave the lock as a member of the same Group for which you entered
  3091. // the lock or deadlocks may occur
  3092. inline void CBinaryLock::Leave2()
  3093. {
  3094. // we are no longer an owner of the lock
  3095. State().RemoveAsOwner( 1 );
  3096. // we are no longer holding the lock
  3097. State().StopHold( 1 );
  3098. // try forever until we successfully change the lock state
  3099. OSSYNC_FOREVER
  3100. {
  3101. // read the current state of the control word as our expected before image
  3102. ControlWord cwBIExpected = State().m_cw;
  3103. // change the expected before image so that the transaction will only work if
  3104. // Group 2 ownership is not quiesced
  3105. cwBIExpected = cwBIExpected & 0x7FFFFFFF;
  3106. // compute the after image of the control word by performing the transform that
  3107. // will take us either from state 1 to state 0 or state 1 to state 1
  3108. ControlWord cwAI = cwBIExpected + 0xFFFF0000;
  3109. cwAI = cwAI - ( ( ( cwAI + 0xFFFF0000 ) >> 16 ) & 0x00008000 );
  3110. // validate the transaction
  3111. OSSYNCAssert( _StateFromControlWord( cwBIExpected ) < 0 ||
  3112. _FValidStateTransition( cwBIExpected, cwAI, trLeave2 ) );
  3113. // attempt to perform the transacted state transition on the control word
  3114. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  3115. // the transaction failed
  3116. if ( cwBI != cwBIExpected )
  3117. {
  3118. // the transaction failed because Group 2 ownership is quiesced
  3119. if ( cwBI & 0x80000000 )
  3120. {
  3121. // leave the lock as a quiesced owner
  3122. _UpdateQuiescedOwnerCountAsGroup2( 0xFFFFFFFF );
  3123. // we're done
  3124. break;
  3125. }
  3126. // the transaction failed because another context changed the control word
  3127. else
  3128. {
  3129. // try again
  3130. continue;
  3131. }
  3132. }
  3133. // the transaction succeeded
  3134. else
  3135. {
  3136. // we're done
  3137. break;
  3138. }
  3139. }
  3140. }
  3141. // Reader / Writer Lock Performance Information
  3142. class CReaderWriterLockPerfInfo
  3143. : public CSyncPerfWait,
  3144. public CSyncPerfAcquire,
  3145. public CLockPerfHold
  3146. {
  3147. public:
  3148. // member functions
  3149. // ctors / dtors
  3150. CReaderWriterLockPerfInfo()
  3151. {
  3152. }
  3153. // debugging support
  3154. void Dump( CDumpContext& dc ) const;
  3155. };
  3156. // Reader / Writer Lock Group Information
  3157. class CReaderWriterLockGroupInfo
  3158. {
  3159. public:
  3160. // member functions
  3161. // ctors / dtors
  3162. CReaderWriterLockGroupInfo() {}
  3163. ~CReaderWriterLockGroupInfo() {}
  3164. // manipulators
  3165. void StartWait( const int iGroup ) { m_rginfo[iGroup].StartWait(); }
  3166. void StopWait( const int iGroup ) { m_rginfo[iGroup].StopWait(); }
  3167. void SetAcquire( const int iGroup ) { m_rginfo[iGroup].SetAcquire(); }
  3168. void SetContend( const int iGroup ) { m_rginfo[iGroup].SetContend(); }
  3169. void StartHold( const int iGroup ) { m_rginfo[iGroup].StartHold(); }
  3170. void StopHold( const int iGroup ) { m_rginfo[iGroup].StopHold(); }
  3171. // accessors
  3172. #ifdef SYNC_ANALYZE_PERFORMANCE
  3173. QWORD CWaitTotal( const int iGroup ) const { return m_rginfo[iGroup].CWaitTotal(); }
  3174. double CsecWaitElapsed( const int iGroup ) const { return m_rginfo[iGroup].CsecWaitElapsed(); }
  3175. QWORD CAcquireTotal( const int iGroup ) const { return m_rginfo[iGroup].CAcquireTotal(); }
  3176. QWORD CContendTotal( const int iGroup ) const { return m_rginfo[iGroup].CContendTotal(); }
  3177. QWORD CHoldTotal( const int iGroup ) const { return m_rginfo[iGroup].CHoldTotal(); }
  3178. double CsecHoldElapsed( const int iGroup ) const { return m_rginfo[iGroup].CsecHoldElapsed(); }
  3179. #endif // SYNC_ANALYZE_PERFORMANCE
  3180. // debugging support
  3181. void Dump( CDumpContext& dc ) const;
  3182. private:
  3183. // member functions
  3184. // operators
  3185. CReaderWriterLockGroupInfo& operator=( CReaderWriterLockGroupInfo& ); // disallowed
  3186. // data members
  3187. // performance info for each group
  3188. CReaderWriterLockPerfInfo m_rginfo[2];
  3189. };
  3190. // Reader / Writer Lock Information
  3191. class CReaderWriterLockInfo
  3192. : public CLockBasicInfo,
  3193. public CReaderWriterLockGroupInfo,
  3194. public CLockDeadlockDetectionInfo
  3195. {
  3196. public:
  3197. // member functions
  3198. // ctors / dtors
  3199. CReaderWriterLockInfo( const CLockBasicInfo& lbi )
  3200. : CLockBasicInfo( lbi ),
  3201. CLockDeadlockDetectionInfo( (CLockBasicInfo&) *this )
  3202. {
  3203. }
  3204. // debugging support
  3205. void Dump( CDumpContext& dc ) const;
  3206. };
  3207. // Reader / Writer Lock State
  3208. class CReaderWriterLockState
  3209. {
  3210. public:
  3211. // types
  3212. // control word
  3213. typedef DWORD ControlWord;
  3214. // member functions
  3215. // ctors / dtors
  3216. CReaderWriterLockState( const CSyncBasicInfo& sbi );
  3217. ~CReaderWriterLockState();
  3218. // debugging support
  3219. void Dump( CDumpContext& dc ) const;
  3220. // data members
  3221. // control word
  3222. union
  3223. {
  3224. volatile ControlWord m_cw;
  3225. struct
  3226. {
  3227. volatile DWORD m_cOAOWW:15;
  3228. volatile DWORD m_fQW:1;
  3229. volatile DWORD m_cOOWR:15;
  3230. volatile DWORD m_fQR:1;
  3231. };
  3232. };
  3233. // quiesced owner count
  3234. volatile DWORD m_cOwner;
  3235. // sempahore used by writers to wait for lock ownership
  3236. CSemaphore m_semWriter;
  3237. // sempahore used by readers to wait for lock ownership
  3238. CSemaphore m_semReader;
  3239. private:
  3240. // member functions
  3241. // operators
  3242. CReaderWriterLockState& operator=( CReaderWriterLockState& ); // disallowed
  3243. };
  3244. // Reader / Writer Lock
  3245. class CReaderWriterLock
  3246. : private CLockObject,
  3247. private CEnhancedStateContainer< CReaderWriterLockState, CSyncBasicInfo, CReaderWriterLockInfo, CLockBasicInfo >
  3248. {
  3249. public:
  3250. // types
  3251. // control word
  3252. typedef CReaderWriterLockState::ControlWord ControlWord;
  3253. // transition reasons for state machine
  3254. enum TransitionReason
  3255. {
  3256. trIllegal = 0,
  3257. trEnterAsWriter = 1,
  3258. trLeaveAsWriter = 2,
  3259. trEnterAsReader = 4,
  3260. trLeaveAsReader = 8,
  3261. };
  3262. // member functions
  3263. // ctors / dtors
  3264. CReaderWriterLock( const CLockBasicInfo& lbi );
  3265. ~CReaderWriterLock();
  3266. // manipulators
  3267. void EnterAsWriter();
  3268. const BOOL FTryEnterAsWriter();
  3269. void LeaveAsWriter();
  3270. void EnterAsReader();
  3271. const BOOL FTryEnterAsReader();
  3272. void LeaveAsReader();
  3273. // accessors
  3274. const BOOL FWritersQuiesced() { return State().m_cw & 0x00008000; }
  3275. const BOOL FReadersQuiesced() { return State().m_cw & 0x80000000; }
  3276. const BOOL FWriter() { return State().FOwner( 0 ); }
  3277. const BOOL FNotWriter() { return State().FNotOwner( 0 ); }
  3278. const BOOL FReader() { return State().FOwner( 1 ); }
  3279. const BOOL FNotReader() { return State().FNotOwner( 1 ); }
  3280. // debugging support
  3281. void Dump( CDumpContext& dc ) const;
  3282. private:
  3283. // member functions
  3284. // operators
  3285. CReaderWriterLock& operator=( CReaderWriterLock& ); // disallowed
  3286. // verification
  3287. int _StateFromControlWord( const ControlWord cw );
  3288. BOOL _FValidStateTransition( const ControlWord cwBI,
  3289. const ControlWord cwAI,
  3290. const TransitionReason tr );
  3291. // manipulators
  3292. void _EnterAsWriter( const ControlWord cwBIOld );
  3293. void _EnterAsReader( const ControlWord cwBIOld );
  3294. void _UpdateQuiescedOwnerCountAsWriter( const DWORD cOwnerDelta );
  3295. void _UpdateQuiescedOwnerCountAsReader( const DWORD cOwnerDelta );
  3296. };
  3297. // enters the reader / writer lock as a writer, waiting forever if necessary
  3298. //
  3299. // NOTE: trying to enter the lock as a writer when you already own the lock
  3300. // as a reader will cause a deadlock.
  3301. inline void CReaderWriterLock::EnterAsWriter()
  3302. {
  3303. // we had better not already own this lock as either a reader or a writer
  3304. OSSYNCAssert( State().FNotOwner( 0 ) );
  3305. OSSYNCAssert( State().FNotOwner( 1 ) );
  3306. // check for deadlock
  3307. OSSYNCAssertSzRTL( State().FCanBeWaiter(), "Potential Deadlock Detected (Rank Violation)");
  3308. // try forever until we successfully change the lock state
  3309. OSSYNC_FOREVER
  3310. {
  3311. // read the current state of the control word as our expected before image
  3312. const ControlWord cwBIExpected = State().m_cw;
  3313. // compute the after image of the control word by performing the global
  3314. // transform for the EnterAsWriter state transition
  3315. const ControlWord cwAI = ControlWord( ( ( cwBIExpected & ( ( LONG_PTR( long( cwBIExpected ) ) >> 31 ) |
  3316. 0x0000FFFF ) ) | 0x80000000 ) + 0x00000001 );
  3317. // validate the transaction
  3318. OSSYNCAssert( _FValidStateTransition( cwBIExpected, cwAI, trEnterAsWriter ) );
  3319. // attempt to perform the transacted state transition on the control word
  3320. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  3321. // the transaction failed or writers are quiesced from ownership or a
  3322. // writer already owns the lock
  3323. if ( ( cwBI ^ cwBIExpected ) | ( cwBI & 0x0000FFFF ) )
  3324. {
  3325. // the transaction failed because another context changed the control word
  3326. if ( cwBI != cwBIExpected )
  3327. {
  3328. // try again
  3329. continue;
  3330. }
  3331. // the transaction succeeded but writers are quiesced from ownership
  3332. // or a writer already owns the lock
  3333. else
  3334. {
  3335. // this is a contention for writers
  3336. State().SetContend( 0 );
  3337. // wait to own the lock as a writer
  3338. _EnterAsWriter( cwBI );
  3339. // we now own the lock, so we're done
  3340. break;
  3341. }
  3342. }
  3343. // the transaction succeeded and writers were not quiesced from ownership
  3344. // and a writer did not already own the lock
  3345. else
  3346. {
  3347. // we now own the lock, so we're done
  3348. break;
  3349. }
  3350. }
  3351. // we are now an owner of the lock for writers
  3352. State().SetAcquire( 0 );
  3353. State().AddAsOwner( 0 );
  3354. State().StartHold( 0 );
  3355. }
  3356. // tries to enter the reader / writer lock as a writer without waiting or
  3357. // spinning, returning fFalse if writers are quiesced from ownership or
  3358. // another writer already owns the lock
  3359. //
  3360. // NOTE: trying to enter the lock as a writer when you already own the lock
  3361. // as a reader will cause a deadlock.
  3362. inline const BOOL CReaderWriterLock::FTryEnterAsWriter()
  3363. {
  3364. // we had better not already own this lock as either a reader or a writer
  3365. OSSYNCAssert( State().FNotOwner( 0 ) );
  3366. OSSYNCAssert( State().FNotOwner( 1 ) );
  3367. // try forever until we successfully change the lock state
  3368. OSSYNC_FOREVER
  3369. {
  3370. // read the current state of the control word as our expected before image
  3371. ControlWord cwBIExpected = State().m_cw;
  3372. // change the expected before image so that the transaction will only work if
  3373. // writers were not quiesced from ownership and another writer doesn't already
  3374. // own the lock
  3375. cwBIExpected = cwBIExpected & 0xFFFF0000;
  3376. // compute the after image of the control word by performing the global
  3377. // transform for the EnterAsWriter state transition
  3378. const ControlWord cwAI = ControlWord( ( ( cwBIExpected & ( ( LONG_PTR( long( cwBIExpected ) ) >> 31 ) |
  3379. 0x0000FFFF ) ) | 0x80000000 ) + 0x00000001 );
  3380. // validate the transaction
  3381. OSSYNCAssert( _StateFromControlWord( cwBIExpected ) < 0 ||
  3382. _FValidStateTransition( cwBIExpected, cwAI, trEnterAsWriter ) );
  3383. // attempt to perform the transacted state transition on the control word
  3384. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  3385. // the transaction failed
  3386. if ( cwBI != cwBIExpected )
  3387. {
  3388. // the transaction failed because writers were quiesced from ownership
  3389. // or another writer already owns the lock
  3390. if ( cwBI & 0x0000FFFF )
  3391. {
  3392. // return failure
  3393. return fFalse;
  3394. }
  3395. // the transaction failed because another context changed the control word
  3396. else
  3397. {
  3398. // try again
  3399. continue;
  3400. }
  3401. }
  3402. // the transaction succeeded
  3403. else
  3404. {
  3405. // we are now an owner of the lock for writers
  3406. State().SetAcquire( 0 );
  3407. State().AddAsOwner( 0 );
  3408. State().StartHold( 0 );
  3409. // return success
  3410. return fTrue;
  3411. }
  3412. }
  3413. }
  3414. // leaves the reader / writer lock as a writer
  3415. //
  3416. // NOTE: you must leave the lock as a member of the same group for which you entered
  3417. // the lock or deadlocks may occur
  3418. inline void CReaderWriterLock::LeaveAsWriter()
  3419. {
  3420. // we are no longer an owner of the lock
  3421. State().RemoveAsOwner( 0 );
  3422. // we are no longer holding the lock
  3423. State().StopHold( 0 );
  3424. // try forever until we successfully change the lock state
  3425. OSSYNC_FOREVER
  3426. {
  3427. // read the current state of the control word as our expected before image
  3428. ControlWord cwBIExpected = State().m_cw;
  3429. // change the expected before image so that the transaction will only work if
  3430. // writers were not quiesced from ownership
  3431. cwBIExpected = cwBIExpected & 0xFFFF7FFF;
  3432. // compute the after image of the control word by performing the transform that
  3433. // will take us either from state 2 to state 0 or state 2 to state 2
  3434. ControlWord cwAI = cwBIExpected + 0xFFFFFFFF;
  3435. cwAI = cwAI - ( ( ( cwAI + 0xFFFFFFFF ) << 16 ) & 0x80000000 );
  3436. // validate the transaction
  3437. OSSYNCAssert( _StateFromControlWord( cwBIExpected ) < 0 ||
  3438. _FValidStateTransition( cwBIExpected, cwAI, trLeaveAsWriter ) );
  3439. // attempt to perform the transacted state transition on the control word
  3440. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  3441. // the transaction failed
  3442. if ( cwBI != cwBIExpected )
  3443. {
  3444. // the transaction failed because writers were quiesced from ownership
  3445. if ( cwBI & 0x00008000 )
  3446. {
  3447. // leave the lock as a quiesced owner
  3448. _UpdateQuiescedOwnerCountAsWriter( 0xFFFFFFFF );
  3449. // we're done
  3450. break;
  3451. }
  3452. // the transaction failed because another context changed the control word
  3453. else
  3454. {
  3455. // try again
  3456. continue;
  3457. }
  3458. }
  3459. // the transaction succeeded
  3460. else
  3461. {
  3462. // there were other writers waiting for ownership of the lock
  3463. if ( cwAI & 0x00007FFF )
  3464. {
  3465. // release the next writer into ownership of the lock
  3466. State().m_semWriter.Release();
  3467. }
  3468. // we're done
  3469. break;
  3470. }
  3471. }
  3472. }
  3473. // enters the reader / writer lock as a reader, waiting forever if necessary
  3474. //
  3475. // NOTE: trying to enter the lock as a reader when you already own the lock
  3476. // as a writer will cause a deadlock.
  3477. inline void CReaderWriterLock::EnterAsReader()
  3478. {
  3479. // we had better not already own this lock as either a reader or a writer
  3480. OSSYNCAssert( State().FNotOwner( 0 ) );
  3481. OSSYNCAssert( State().FNotOwner( 1 ) );
  3482. // check for deadlock
  3483. OSSYNCAssertSzRTL( State().FCanBeWaiter(), "Potential Deadlock Detected (Rank Violation)" );
  3484. // try forever until we successfully change the lock state
  3485. OSSYNC_FOREVER
  3486. {
  3487. // read the current state of the control word as our expected before image
  3488. const ControlWord cwBIExpected = State().m_cw;
  3489. // compute the after image of the control word by performing the global
  3490. // transform for the EnterAsReader state transition
  3491. const ControlWord cwAI = ( cwBIExpected & 0xFFFF7FFF ) +
  3492. ( ( cwBIExpected & 0x80008000 ) == 0x80000000 ?
  3493. 0x00017FFF :
  3494. 0x00018000 );
  3495. // validate the transaction
  3496. OSSYNCAssert( _FValidStateTransition( cwBIExpected, cwAI, trEnterAsReader ) );
  3497. // attempt to perform the transacted state transition on the control word
  3498. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  3499. // the transaction failed or readers were quiesced from ownership
  3500. if ( ( cwBI ^ cwBIExpected ) | ( cwBI & 0x80000000 ) )
  3501. {
  3502. // the transaction failed because another context changed the control word
  3503. if ( cwBI != cwBIExpected )
  3504. {
  3505. // try again
  3506. continue;
  3507. }
  3508. // the transaction succeeded but readers were quiesced from ownership
  3509. else
  3510. {
  3511. // this is a contention for readers
  3512. State().SetContend( 1 );
  3513. // wait to own the lock as a reader
  3514. _EnterAsReader( cwBI );
  3515. // we now own the lock, so we're done
  3516. break;
  3517. }
  3518. }
  3519. // the transaction succeeded and readers were not quiesced from ownership
  3520. else
  3521. {
  3522. // we now own the lock, so we're done
  3523. break;
  3524. }
  3525. }
  3526. // we are now an owner of the lock for readers
  3527. State().SetAcquire( 1 );
  3528. State().AddAsOwner( 1 );
  3529. State().StartHold( 1 );
  3530. }
  3531. // tries to enter the reader / writer lock as a reader without waiting or
  3532. // spinning, returning fFalse if readers are quiesced from ownership
  3533. //
  3534. // NOTE: trying to enter the lock as a reader when you already own the lock
  3535. // as a writer will cause a deadlock.
  3536. inline const BOOL CReaderWriterLock::FTryEnterAsReader()
  3537. {
  3538. // we had better not already own this lock as either a reader or a writer
  3539. OSSYNCAssert( State().FNotOwner( 0 ) );
  3540. OSSYNCAssert( State().FNotOwner( 1 ) );
  3541. // try forever until we successfully change the lock state
  3542. OSSYNC_FOREVER
  3543. {
  3544. // read the current state of the control word as our expected before image
  3545. ControlWord cwBIExpected = State().m_cw;
  3546. // change the expected before image so that the transaction will only work if
  3547. // readers were not quiesced from ownership
  3548. cwBIExpected = cwBIExpected & 0x7FFFFFFF;
  3549. // compute the after image of the control word by performing the global
  3550. // transform for the EnterAsReader state transition
  3551. const ControlWord cwAI = ( cwBIExpected & 0xFFFF7FFF ) +
  3552. ( ( cwBIExpected & 0x80008000 ) == 0x80000000 ?
  3553. 0x00017FFF :
  3554. 0x00018000 );
  3555. // validate the transaction
  3556. OSSYNCAssert( _StateFromControlWord( cwBIExpected ) < 0 ||
  3557. _FValidStateTransition( cwBIExpected, cwAI, trEnterAsReader ) );
  3558. // attempt to perform the transacted state transition on the control word
  3559. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  3560. // the transaction failed
  3561. if ( cwBI != cwBIExpected )
  3562. {
  3563. // the transaction failed because readers were quiesced from ownership
  3564. if ( cwBI & 0x80000000 )
  3565. {
  3566. // return failure
  3567. return fFalse;
  3568. }
  3569. // the transaction failed because another context changed the control word
  3570. else
  3571. {
  3572. // try again
  3573. continue;
  3574. }
  3575. }
  3576. // the transaction succeeded
  3577. else
  3578. {
  3579. // we are now an owner of the lock for readers
  3580. State().SetAcquire( 1 );
  3581. State().AddAsOwner( 1 );
  3582. State().StartHold( 1 );
  3583. // return success
  3584. return fTrue;
  3585. }
  3586. }
  3587. }
  3588. // leaves the reader / writer lock as a reader
  3589. //
  3590. // NOTE: you must leave the lock as a member of the same group for which you entered
  3591. // the lock or deadlocks may occur
  3592. inline void CReaderWriterLock::LeaveAsReader()
  3593. {
  3594. // we are no longer an owner of the lock
  3595. State().RemoveAsOwner( 1 );
  3596. // we are no longer holding the lock
  3597. State().StopHold( 1 );
  3598. // try forever until we successfully change the lock state
  3599. OSSYNC_FOREVER
  3600. {
  3601. // read the current state of the control word as our expected before image
  3602. ControlWord cwBIExpected = State().m_cw;
  3603. // change the expected before image so that the transaction will only work if
  3604. // readers were not quiesced from ownership
  3605. cwBIExpected = cwBIExpected & 0x7FFFFFFF;
  3606. // compute the after image of the control word by performing the transform that
  3607. // will take us either from state 1 to state 0 or state 1 to state 1
  3608. const ControlWord cwAI = ControlWord( cwBIExpected + 0xFFFF0000 +
  3609. ( ( LONG_PTR( long( cwBIExpected + 0xFFFE0000 ) ) >> 31 ) & 0xFFFF8000 ) );
  3610. // validate the transaction
  3611. OSSYNCAssert( _StateFromControlWord( cwBIExpected ) < 0 ||
  3612. _FValidStateTransition( cwBIExpected, cwAI, trLeaveAsReader ) );
  3613. // attempt to perform the transacted state transition on the control word
  3614. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  3615. // the transaction failed
  3616. if ( cwBI != cwBIExpected )
  3617. {
  3618. // the transaction failed because readers were quiesced from ownership
  3619. if ( cwBI & 0x80000000 )
  3620. {
  3621. // leave the lock as a quiesced owner
  3622. _UpdateQuiescedOwnerCountAsReader( 0xFFFFFFFF );
  3623. // we're done
  3624. break;
  3625. }
  3626. // the transaction failed because another context changed the control word
  3627. else
  3628. {
  3629. // try again
  3630. continue;
  3631. }
  3632. }
  3633. // the transaction succeeded
  3634. else
  3635. {
  3636. // we're done
  3637. break;
  3638. }
  3639. }
  3640. }
  3641. // Metered Section
  3642. class CMeteredSection
  3643. : private CSyncObject
  3644. {
  3645. public:
  3646. // types
  3647. // control word
  3648. typedef DWORD ControlWord;
  3649. // callback used to notify the user when a partition of the current
  3650. // group has been completed
  3651. typedef void (*PFNPARTITIONCOMPLETE)( const DWORD_PTR dwCompletionKey );
  3652. // member functions
  3653. // ctors / dtors
  3654. CMeteredSection();
  3655. ~CMeteredSection();
  3656. // manipulators
  3657. int Enter();
  3658. void Leave( const int group );
  3659. void Partition( const PFNPARTITIONCOMPLETE pfnPartitionComplete = NULL,
  3660. const DWORD_PTR dwCompletionKey = NULL );
  3661. // accessors
  3662. int ActiveGroup() { return int( m_groupCurrent ); }
  3663. // debugging support
  3664. void Dump( CDumpContext& dc ) const;
  3665. private:
  3666. // data members
  3667. // partition complete callback
  3668. PFNPARTITIONCOMPLETE m_pfnPartitionComplete;
  3669. DWORD_PTR m_dwPartitionCompleteKey;
  3670. // control word
  3671. union
  3672. {
  3673. volatile ControlWord m_cw;
  3674. struct
  3675. {
  3676. volatile DWORD m_cCurrent:15;
  3677. volatile DWORD m_groupCurrent:1;
  3678. volatile DWORD m_cQuiesced:15;
  3679. volatile DWORD m_groupQuiesced:1;
  3680. };
  3681. };
  3682. // member functions
  3683. // operators
  3684. CMeteredSection& operator=( CMeteredSection& ); // disallowed
  3685. // manipulators
  3686. void _PartitionAsync( const PFNPARTITIONCOMPLETE pfnPartitionComplete,
  3687. const DWORD_PTR dwCompletionKey );
  3688. static void _PartitionSyncComplete( CAutoResetSignal* const pasig );
  3689. };
  3690. // ctor
  3691. inline CMeteredSection::CMeteredSection()
  3692. : m_cw( 0x80000000 ),
  3693. m_pfnPartitionComplete( NULL ),
  3694. m_dwPartitionCompleteKey( NULL )
  3695. {
  3696. }
  3697. // dtor
  3698. inline CMeteredSection::~CMeteredSection()
  3699. {
  3700. }
  3701. // enter the metered section, returning the group id for which the current
  3702. // context has acquired the metered section
  3703. inline int CMeteredSection::Enter()
  3704. {
  3705. // increment the count for the current group
  3706. const DWORD cwDelta = 0x00000001;
  3707. const DWORD cwBI = AtomicExchangeAdd( (long*) &m_cw, (long) cwDelta );
  3708. // there had better not be any overflow!
  3709. OSSYNCAssert( ( cwBI & 0x80008000 ) == ( ( cwBI + cwDelta ) & 0x80008000 ) );
  3710. // return the group we referenced
  3711. return int( ( cwBI >> 15 ) & 1 );
  3712. }
  3713. // leave the metered section using the specified group id. this group id must
  3714. // be the group id returned by the corresponding call to Enter()
  3715. inline void CMeteredSection::Leave( const int group )
  3716. {
  3717. // try forever until we successfully leave
  3718. OSSYNC_FOREVER
  3719. {
  3720. // read the current state of the control word as our expected before image
  3721. const ControlWord cwBIExpected = m_cw;
  3722. // compute the after image of the control word
  3723. const ControlWord cwAI = cwBIExpected - ( ( ( ( cwBIExpected & 0x80008000 ) ^ 0x80008000 ) >> 15 ) ^ ( ( group << 16 ) | group ) );
  3724. // there had better not be any underflow!
  3725. OSSYNCAssert( ( cwBIExpected & 0x80008000 ) == ( cwAI & 0x80008000 ) );
  3726. // attempt to perform the transacted state transition on the control word
  3727. const ControlWord cwBI = AtomicCompareExchange( (long*)&m_cw, cwBIExpected, cwAI );
  3728. // the transaction failed
  3729. if ( cwBI != cwBIExpected )
  3730. {
  3731. // try again
  3732. continue;
  3733. }
  3734. // the transaction succeeded
  3735. else
  3736. {
  3737. // our update resulted in a partition completion
  3738. if ( ( cwBI & 0x7FFF0000 ) + ( cwAI & 0x7FFF0000 ) == 0x00010000 )
  3739. {
  3740. // execute the completion function
  3741. m_pfnPartitionComplete( m_dwPartitionCompleteKey );
  3742. }
  3743. // we're done
  3744. break;
  3745. }
  3746. }
  3747. }
  3748. // partitions all execution contexts entering the metered section into two groups.
  3749. // all contexts entering the section after this call are in a different group than
  3750. // all the contexts that entered the section before this call. when all contexts
  3751. // in the old group have left the metered section, the partition will be completed
  3752. //
  3753. // there are two ways to complete a partition: asynchronously and synchronously.
  3754. // asynchronous operation is selected if a completion function and key are provided.
  3755. // the last thread to leave the metered section for the previous group will
  3756. // execute asynchronous completions
  3757. //
  3758. // NOTE: it is illegal to have multiple concurrent partition requests. any attempt
  3759. // to do so will result in undefined behavior
  3760. inline void CMeteredSection::Partition( const PFNPARTITIONCOMPLETE pfnPartitionComplete,
  3761. const DWORD_PTR dwCompletionKey )
  3762. {
  3763. // this is an async partition request
  3764. if ( pfnPartitionComplete )
  3765. {
  3766. // execute the parititon request
  3767. _PartitionAsync( pfnPartitionComplete, dwCompletionKey );
  3768. }
  3769. // this is a sync partition request
  3770. else
  3771. {
  3772. // create a signal to wait for completion
  3773. CAutoResetSignal asig( CSyncBasicInfo( "CMeteredSection::Partition()::asig" ) );
  3774. // issue an async partition request
  3775. _PartitionAsync( PFNPARTITIONCOMPLETE( _PartitionSyncComplete ),
  3776. DWORD_PTR( &asig ) );
  3777. // wait for the partition to complete
  3778. asig.Wait();
  3779. }
  3780. }
  3781. // performs an async partition request
  3782. inline void CMeteredSection::_PartitionAsync( const PFNPARTITIONCOMPLETE pfnPartitionComplete,
  3783. const DWORD_PTR dwCompletionKey )
  3784. {
  3785. // we should not be calling this if there is already a partition pending
  3786. OSSYNCAssertSz( !( m_cw & 0x7FFF0000 ), "Illegal concurrent use of Partitioning" );
  3787. // save the callback and key for the future completion
  3788. m_pfnPartitionComplete = pfnPartitionComplete;
  3789. m_dwPartitionCompleteKey = dwCompletionKey;
  3790. // try forever until we successfully partition
  3791. OSSYNC_FOREVER
  3792. {
  3793. // read the current state of the control word as our expected before image
  3794. const ControlWord cwBIExpected = m_cw;
  3795. // compute the after image of the control word
  3796. const ControlWord cwAI = ( cwBIExpected >> 16 ) | ( cwBIExpected << 16 );
  3797. // attempt to perform the transacted state transition on the control word
  3798. const ControlWord cwBI = AtomicCompareExchange( (long*)&m_cw, cwBIExpected, cwAI );
  3799. // the transaction failed
  3800. if ( cwBI != cwBIExpected )
  3801. {
  3802. // try again
  3803. continue;
  3804. }
  3805. // the transaction succeeded
  3806. else
  3807. {
  3808. // our update resulted in a partition completion
  3809. if ( !( cwAI & 0x7FFF0000 ) )
  3810. {
  3811. // execute the completion function
  3812. m_pfnPartitionComplete( m_dwPartitionCompleteKey );
  3813. }
  3814. // we're done
  3815. break;
  3816. }
  3817. }
  3818. }
  3819. // partition completion function used for sync partition requests
  3820. inline void CMeteredSection::_PartitionSyncComplete( CAutoResetSignal* const pasig )
  3821. {
  3822. // set the signal
  3823. pasig->Set();
  3824. }
  3825. // S / X / W Latch Performance Information
  3826. class CSXWLatchPerfInfo
  3827. : public CSyncPerfWait,
  3828. public CSyncPerfAcquire,
  3829. public CLockPerfHold
  3830. {
  3831. public:
  3832. // member functions
  3833. // ctors / dtors
  3834. CSXWLatchPerfInfo()
  3835. {
  3836. }
  3837. // debugging support
  3838. void Dump( CDumpContext& dc ) const;
  3839. };
  3840. // S / X / W Latch Group Information
  3841. class CSXWLatchGroupInfo
  3842. {
  3843. public:
  3844. // member functions
  3845. // ctors / dtors
  3846. CSXWLatchGroupInfo() {}
  3847. ~CSXWLatchGroupInfo() {}
  3848. // manipulators
  3849. void StartWait( const int iGroup ) { m_rginfo[iGroup].StartWait(); }
  3850. void StopWait( const int iGroup ) { m_rginfo[iGroup].StopWait(); }
  3851. void SetAcquire( const int iGroup ) { m_rginfo[iGroup].SetAcquire(); }
  3852. void SetContend( const int iGroup ) { m_rginfo[iGroup].SetContend(); }
  3853. void StartHold( const int iGroup ) { m_rginfo[iGroup].StartHold(); }
  3854. void StopHold( const int iGroup ) { m_rginfo[iGroup].StopHold(); }
  3855. // accessors
  3856. #ifdef SYNC_ANALYZE_PERFORMANCE
  3857. QWORD CWaitTotal( const int iGroup ) const { return m_rginfo[iGroup].CWaitTotal(); }
  3858. double CsecWaitElapsed( const int iGroup ) const { return m_rginfo[iGroup].CsecWaitElapsed(); }
  3859. QWORD CAcquireTotal( const int iGroup ) const { return m_rginfo[iGroup].CAcquireTotal(); }
  3860. QWORD CContendTotal( const int iGroup ) const { return m_rginfo[iGroup].CContendTotal(); }
  3861. QWORD CHoldTotal( const int iGroup ) const { return m_rginfo[iGroup].CHoldTotal(); }
  3862. double CsecHoldElapsed( const int iGroup ) const { return m_rginfo[iGroup].CsecHoldElapsed(); }
  3863. #endif // SYNC_ANALYZE_PERFORMANCE
  3864. // debugging support
  3865. void Dump( CDumpContext& dc ) const;
  3866. private:
  3867. // member functions
  3868. // operators
  3869. CSXWLatchGroupInfo& operator=( CSXWLatchGroupInfo& ); // disallowed
  3870. // data members
  3871. // performance info for each group
  3872. CSXWLatchPerfInfo m_rginfo[3];
  3873. };
  3874. // S / X / W Latch Information
  3875. class CSXWLatchInfo
  3876. : public CLockBasicInfo,
  3877. public CSXWLatchGroupInfo,
  3878. public CLockDeadlockDetectionInfo
  3879. {
  3880. public:
  3881. // member functions
  3882. // ctors / dtors
  3883. CSXWLatchInfo( const CLockBasicInfo& lbi )
  3884. : CLockBasicInfo( lbi ),
  3885. CLockDeadlockDetectionInfo( (CLockBasicInfo&) *this )
  3886. {
  3887. }
  3888. // debugging support
  3889. void Dump( CDumpContext& dc ) const;
  3890. };
  3891. // S / X / W Latch State
  3892. class CSXWLatchState
  3893. {
  3894. public:
  3895. // types
  3896. // control word
  3897. typedef DWORD ControlWord;
  3898. // member functions
  3899. // ctors / dtors
  3900. CSXWLatchState( const CSyncBasicInfo& sbi );
  3901. ~CSXWLatchState();
  3902. // debugging support
  3903. void Dump( CDumpContext& dc ) const;
  3904. // data members
  3905. // control word
  3906. union
  3907. {
  3908. volatile ControlWord m_cw;
  3909. struct
  3910. {
  3911. volatile DWORD m_cOOWS:15;
  3912. volatile DWORD m_fQS:1;
  3913. volatile DWORD m_cOAWX:16;
  3914. };
  3915. };
  3916. // quiesced share latch count
  3917. volatile DWORD m_cQS;
  3918. // sempahore used to wait for the shared latch
  3919. CSemaphore m_semS;
  3920. // sempahore used to wait for the exclusive latch
  3921. CSemaphore m_semX;
  3922. // sempahore used to wait for the write latch
  3923. CSemaphore m_semW;
  3924. private:
  3925. // member functions
  3926. // operators
  3927. CSXWLatchState& operator=( CSXWLatchState& ); // disallowed
  3928. };
  3929. // S / X / W Latch
  3930. class CSXWLatch
  3931. : private CLockObject,
  3932. private CEnhancedStateContainer< CSXWLatchState, CSyncBasicInfo, CSXWLatchInfo, CLockBasicInfo >
  3933. {
  3934. public:
  3935. // types
  3936. // control word
  3937. typedef CSXWLatchState::ControlWord ControlWord;
  3938. // API Error Codes
  3939. enum ERR
  3940. {
  3941. errSuccess,
  3942. errWaitForSharedLatch,
  3943. errWaitForExclusiveLatch,
  3944. errWaitForWriteLatch,
  3945. errLatchConflict
  3946. };
  3947. // member functions
  3948. // ctors / dtors
  3949. CSXWLatch( const CLockBasicInfo& lbi );
  3950. ~CSXWLatch();
  3951. // manipulators
  3952. ERR ErrAcquireSharedLatch();
  3953. ERR ErrTryAcquireSharedLatch();
  3954. ERR ErrAcquireExclusiveLatch();
  3955. ERR ErrTryAcquireExclusiveLatch();
  3956. ERR ErrTryAcquireWriteLatch();
  3957. ERR ErrUpgradeSharedLatchToExclusiveLatch();
  3958. ERR ErrUpgradeSharedLatchToWriteLatch();
  3959. ERR ErrUpgradeExclusiveLatchToWriteLatch();
  3960. void DowngradeWriteLatchToExclusiveLatch();
  3961. void DowngradeWriteLatchToSharedLatch();
  3962. void DowngradeExclusiveLatchToSharedLatch();
  3963. void ReleaseWriteLatch();
  3964. void ReleaseExclusiveLatch();
  3965. void ReleaseSharedLatch();
  3966. void WaitForSharedLatch();
  3967. void WaitForExclusiveLatch();
  3968. void WaitForWriteLatch();
  3969. void ClaimOwnership( const DWORD group );
  3970. void ReleaseOwnership( const DWORD group );
  3971. // accessors
  3972. BOOL FOwnSharedLatch() { return State().FOwner( 0 ); }
  3973. BOOL FNotOwnSharedLatch() { return State().FNotOwner( 0 ); }
  3974. BOOL FOwnExclusiveLatch() { return State().FOwner( 1 ); }
  3975. BOOL FNotOwnExclusiveLatch() { return State().FNotOwner( 1 ); }
  3976. BOOL FOwnWriteLatch() { return State().FOwner( 2 ); }
  3977. BOOL FNotOwnWriteLatch() { return State().FNotOwner( 2 ); }
  3978. // debugging support
  3979. void Dump( CDumpContext& dc ) const;
  3980. private:
  3981. // member functions
  3982. // operators
  3983. CSXWLatch& operator=( CSXWLatch& ); // disallowed
  3984. // manipulators
  3985. void _UpdateQuiescedSharedLatchCount( const DWORD cQSDelta );
  3986. };
  3987. // declares the current context as an owner or waiter of a shared latch. if
  3988. // the shared latch is acquired immediately, errSuccess will be returned. if
  3989. // the shared latch is not acquired immediately, errWaitForSharedLatch will be
  3990. // returned and WaitForSharedLatch() must be called to gain ownership of the
  3991. // shared latch
  3992. inline CSXWLatch::ERR CSXWLatch::ErrAcquireSharedLatch()
  3993. {
  3994. // we had better not already have a shared, exclusive, or write latch
  3995. OSSYNCAssert( FNotOwnSharedLatch() );
  3996. OSSYNCAssert( FNotOwnExclusiveLatch() );
  3997. OSSYNCAssert( FNotOwnWriteLatch() );
  3998. // add ourself as an owner or waiter for the shared latch
  3999. const ControlWord cwDelta = 0x00000001;
  4000. const ControlWord cwBI = AtomicExchangeAdd( (long*)&State().m_cw, cwDelta );
  4001. // shared latches are quiesced
  4002. if ( cwBI & 0x00008000 )
  4003. {
  4004. // this is a contention for a shared latch
  4005. State().SetContend( 0 );
  4006. // we are now a waiter for the shared latch
  4007. State().AddAsWaiter( 0 );
  4008. State().StartWait( 0 );
  4009. // we will need to block
  4010. return errWaitForSharedLatch;
  4011. }
  4012. // shared latches are not quiesced
  4013. else
  4014. {
  4015. // we are now an owner of a shared latch
  4016. State().SetAcquire( 0 );
  4017. State().AddAsOwner( 0 );
  4018. State().StartHold( 0 );
  4019. // we now own the shared latch
  4020. return errSuccess;
  4021. }
  4022. }
  4023. // tries to declare the current context as an owner of a shared latch. if
  4024. // the shared latch is acquired immediately, errSuccess will be returned. if
  4025. // the shared latch is not acquired immediately, errLatchConflict will be
  4026. // returned
  4027. inline CSXWLatch::ERR CSXWLatch::ErrTryAcquireSharedLatch()
  4028. {
  4029. // we had better not already have a shared, exclusive, or write latch
  4030. OSSYNCAssert( FNotOwnSharedLatch() );
  4031. OSSYNCAssert( FNotOwnExclusiveLatch() );
  4032. OSSYNCAssert( FNotOwnWriteLatch() );
  4033. // try forever until we successfully change the latch state
  4034. OSSYNC_FOREVER
  4035. {
  4036. // read the current state of the control word as our expected before image
  4037. ControlWord cwBIExpected = State().m_cw;
  4038. // change the expected before image so that the transaction will only work if
  4039. // shared latches are not quiesced
  4040. cwBIExpected = cwBIExpected & 0xFFFF7FFF;
  4041. // compute the after image of the control word by performing the transform
  4042. // that will acquire a shared latch iff shared latches are not quiesced
  4043. const ControlWord cwAI = cwBIExpected + 0x00000001;
  4044. // attempt to perform the transacted state transition on the control word
  4045. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  4046. // the transaction failed
  4047. if ( cwBI != cwBIExpected )
  4048. {
  4049. // the transaction failed because shared latches were quiesced
  4050. if ( cwBI & 0x00008000 )
  4051. {
  4052. // this is a contention for the shared latch
  4053. State().SetContend( 0 );
  4054. // this is a latch conflict
  4055. return errLatchConflict;
  4056. }
  4057. // the transaction failed because another context changed the control
  4058. // word
  4059. else
  4060. {
  4061. // try again
  4062. continue;
  4063. }
  4064. }
  4065. // the transaction succeeded
  4066. else
  4067. {
  4068. // we are now an owner of a shared latch
  4069. State().SetAcquire( 0 );
  4070. State().AddAsOwner( 0 );
  4071. State().StartHold( 0 );
  4072. // we now own the shared latch
  4073. return errSuccess;
  4074. }
  4075. }
  4076. }
  4077. // declares the current context as an owner or waiter of the exclusive latch.
  4078. // if the exclusive latch is acquired immediately, errSuccess will be returned.
  4079. // if the exclusive latch is not acquired immediately, errWaitForExclusiveLatch
  4080. // will be returned and WaitForExclusiveLatch() must be called to gain ownership
  4081. // of the exclusive latch
  4082. inline CSXWLatch::ERR CSXWLatch::ErrAcquireExclusiveLatch()
  4083. {
  4084. // we had better not already have a shared, exclusive, or write latch
  4085. OSSYNCAssert( FNotOwnSharedLatch() );
  4086. OSSYNCAssert( FNotOwnExclusiveLatch() );
  4087. OSSYNCAssert( FNotOwnWriteLatch() );
  4088. // add ourself as an owner or waiter for the exclusive latch
  4089. const ControlWord cwDelta = 0x00010000;
  4090. const ControlWord cwBI = AtomicExchangeAdd( (long*)&State().m_cw, cwDelta );
  4091. // we are not the owner of the exclusive latch
  4092. if ( cwBI & 0xFFFF0000 )
  4093. {
  4094. // this is a contention for the exclusive latch
  4095. State().SetContend( 1 );
  4096. // we are now a waiter for the exclusive latch
  4097. State().AddAsWaiter( 1 );
  4098. State().StartWait( 1 );
  4099. // we will need to block
  4100. return errWaitForExclusiveLatch;
  4101. }
  4102. // we are the owner of the exclusive latch
  4103. else
  4104. {
  4105. // we are now an owner of the exclusive latch
  4106. State().SetAcquire( 1 );
  4107. State().AddAsOwner( 1 );
  4108. State().StartHold( 1 );
  4109. // we now own the exclusive latch
  4110. return errSuccess;
  4111. }
  4112. }
  4113. // tries to declare the current context as an owner of the exclusive latch. if
  4114. // the exclusive latch is acquired immediately, errSuccess will be returned. if
  4115. // the exclusive latch is not acquired immediately, errLatchConflict will be
  4116. // returned
  4117. inline CSXWLatch::ERR CSXWLatch::ErrTryAcquireExclusiveLatch()
  4118. {
  4119. // we had better not already have a shared, exclusive, or write latch
  4120. OSSYNCAssert( FNotOwnSharedLatch() );
  4121. OSSYNCAssert( FNotOwnExclusiveLatch() );
  4122. OSSYNCAssert( FNotOwnWriteLatch() );
  4123. // try forever until we successfully change the latch state
  4124. OSSYNC_FOREVER
  4125. {
  4126. // read the current state of the control word as our expected before image
  4127. ControlWord cwBIExpected = State().m_cw;
  4128. // change the expected before image so that the transaction will only work if
  4129. // the exclusive latch is not already owned
  4130. cwBIExpected = cwBIExpected & 0x0000FFFF;
  4131. // compute the after image of the control word by performing the transform
  4132. // that will acquire the exclusive latch iff it is not already owned
  4133. const ControlWord cwAI = cwBIExpected + 0x00010000;
  4134. // attempt to perform the transacted state transition on the control word
  4135. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  4136. // the transaction failed
  4137. if ( cwBI != cwBIExpected )
  4138. {
  4139. // the transaction failed because the exclusive latch was already
  4140. // owned
  4141. if ( cwBI & 0xFFFF0000 )
  4142. {
  4143. // this is a contention for the exclusive latch
  4144. State().SetContend( 1 );
  4145. // this is a latch conflict
  4146. return errLatchConflict;
  4147. }
  4148. // the transaction failed because another context changed the control
  4149. // word
  4150. else
  4151. {
  4152. // try again
  4153. continue;
  4154. }
  4155. }
  4156. // the transaction succeeded
  4157. else
  4158. {
  4159. // we are now an owner of the exclusive latch
  4160. State().SetAcquire( 1 );
  4161. State().AddAsOwner( 1 );
  4162. State().StartHold( 1 );
  4163. // we now own the exclusive latch
  4164. return errSuccess;
  4165. }
  4166. }
  4167. }
  4168. // tries to declare the current context as an owner of the write latch. if
  4169. // the write latch is acquired immediately, errSuccess will be returned. if
  4170. // the write latch is not acquired immediately, errLatchConflict will be
  4171. // returned. note that a latch conflict will effectively occur if any other
  4172. // context currently owns or is waiting to own any type of latch
  4173. inline CSXWLatch::ERR CSXWLatch::ErrTryAcquireWriteLatch()
  4174. {
  4175. // we had better not already have a shared, exclusive, or write latch
  4176. OSSYNCAssert( FNotOwnSharedLatch() );
  4177. OSSYNCAssert( FNotOwnExclusiveLatch() );
  4178. OSSYNCAssert( FNotOwnWriteLatch() );
  4179. // try forever until we successfully change the latch state
  4180. OSSYNC_FOREVER
  4181. {
  4182. // set the expected before image so that the transaction will only work if
  4183. // no other context currently owns or is waiting to own any type of latch
  4184. const ControlWord cwBIExpected = 0x00000000;
  4185. // set the after image of the control word to a single write latch
  4186. const ControlWord cwAI = 0x00018000;
  4187. // attempt to perform the transacted state transition on the control word
  4188. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  4189. // the transaction failed
  4190. if ( cwBI != cwBIExpected )
  4191. {
  4192. // this is a contention for the write latch
  4193. State().SetContend( 2 );
  4194. // this is a latch conflict
  4195. return errLatchConflict;
  4196. }
  4197. // the transaction succeeded
  4198. else
  4199. {
  4200. // we are now an owner of the write latch
  4201. State().SetAcquire( 2 );
  4202. State().AddAsOwner( 2 );
  4203. State().StartHold( 2 );
  4204. // we now own the write latch
  4205. return errSuccess;
  4206. }
  4207. }
  4208. }
  4209. // attempts to upgrade a shared latch to the exclusive latch. if the exclusive
  4210. // latch is not available, errLatchConflict will be returned. if the exclusive
  4211. // latch is available, it will be acquired and errSuccess will be returned
  4212. inline CSXWLatch::ERR CSXWLatch::ErrUpgradeSharedLatchToExclusiveLatch()
  4213. {
  4214. // we had better already have only a shared latch
  4215. OSSYNCAssert( FOwnSharedLatch() );
  4216. OSSYNCAssert( FNotOwnExclusiveLatch() );
  4217. OSSYNCAssert( FNotOwnWriteLatch() );
  4218. // try forever until we successfully change the latch state
  4219. OSSYNC_FOREVER
  4220. {
  4221. // read the current state of the control word as our expected before image
  4222. ControlWord cwBIExpected = State().m_cw;
  4223. // change the expected before image so that the transaction will only work if
  4224. // the exclusive latch is not already owned
  4225. cwBIExpected = cwBIExpected & 0x0000FFFF;
  4226. // compute the after image of the control word by performing the transform
  4227. // that will set an exclusive latch iff there is no current owner of the
  4228. // exclusive latch and release our shared latch
  4229. const ControlWord cwAI = cwBIExpected + 0x0000FFFF;
  4230. // attempt to perform the transacted state transition on the control word
  4231. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  4232. // the transaction failed
  4233. if ( cwBI != cwBIExpected )
  4234. {
  4235. // the transaction failed because the exclusive latch was already owned
  4236. if ( cwBI & 0xFFFF0000 )
  4237. {
  4238. // this is a contention for the exclusive latch
  4239. State().SetContend( 1 );
  4240. // this is a latch conflict
  4241. return errLatchConflict;
  4242. }
  4243. // the transaction failed because another context changed the control
  4244. // word
  4245. else
  4246. {
  4247. // try again
  4248. continue;
  4249. }
  4250. }
  4251. // the transaction succeeded
  4252. else
  4253. {
  4254. // we are no longer an owner of a shared latch
  4255. State().RemoveAsOwner( 0 );
  4256. State().StopHold( 0 );
  4257. // we are now an owner of the exclusive latch
  4258. State().SetAcquire( 1 );
  4259. State().AddAsOwner( 1 );
  4260. State().StartHold( 1 );
  4261. // we now own the exclusive latch
  4262. return errSuccess;
  4263. }
  4264. }
  4265. }
  4266. // attempts to upgrade a shared latch to the write latch. if the write latch
  4267. // is not available, errLatchConflict will be returned. if the write latch is
  4268. // available, it will be acquired. if the write latch is acquired immediately,
  4269. // errSuccess will be returned. if the write latch is not acquired immediately,
  4270. // errWaitForWriteLatch will be returned and WaitForWriteLatch() must be called
  4271. // to gain ownership of the write latch
  4272. inline CSXWLatch::ERR CSXWLatch::ErrUpgradeSharedLatchToWriteLatch()
  4273. {
  4274. // we had better already have only a shared latch
  4275. OSSYNCAssert( FOwnSharedLatch() );
  4276. OSSYNCAssert( FNotOwnExclusiveLatch() );
  4277. OSSYNCAssert( FNotOwnWriteLatch() );
  4278. // try forever until we successfully change the latch state
  4279. OSSYNC_FOREVER
  4280. {
  4281. // read the current state of the control word as our expected before image
  4282. ControlWord cwBIExpected = State().m_cw;
  4283. // change the expected before image so that the transaction will only work if
  4284. // the exclusive latch is not already owned
  4285. cwBIExpected = cwBIExpected & 0x0000FFFF;
  4286. // compute the after image of the control word by performing the transform
  4287. // that will set a write latch iff there is no current owner of the
  4288. // exclusive latch, quiescing any remaining shared latches
  4289. const ControlWord cwAI = 0x00018000;
  4290. // attempt to perform the transacted state transition on the control word
  4291. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  4292. // the transaction failed
  4293. if ( cwBI != cwBIExpected )
  4294. {
  4295. // the transaction failed because the write latch was already owned
  4296. if ( cwBI & 0xFFFF0000 )
  4297. {
  4298. // this is a contention for the write latch
  4299. State().SetContend( 2 );
  4300. // this is a latch conflict
  4301. return errLatchConflict;
  4302. }
  4303. // the transaction failed because another context changed the control
  4304. // word
  4305. else
  4306. {
  4307. // try again
  4308. continue;
  4309. }
  4310. }
  4311. // the transaction succeeded
  4312. else
  4313. {
  4314. // shared latches were just quiesced
  4315. if ( cwBI != 0x00000001 )
  4316. {
  4317. // we are no longer an owner of a shared latch
  4318. State().RemoveAsOwner( 0 );
  4319. State().StopHold( 0 );
  4320. // update the quiesced shared latch count with the shared latch count
  4321. // that we displaced from the control word, possibly releasing waiters.
  4322. // we update the count as if we we had a shared latch as a write latch
  4323. // (namely ours) can be released. don't forget to deduct our shared
  4324. // latch from this count
  4325. _UpdateQuiescedSharedLatchCount( cwBI - 1 );
  4326. // we are now a waiter for the write latch
  4327. State().AddAsWaiter( 2 );
  4328. State().StartWait( 2 );
  4329. // we will need to block
  4330. return errWaitForWriteLatch;
  4331. }
  4332. // shared latches were not just quiesced
  4333. else
  4334. {
  4335. // we are no longer an owner of a shared latch
  4336. State().RemoveAsOwner( 0 );
  4337. State().StopHold( 0 );
  4338. // we are now an owner of the write latch
  4339. State().SetAcquire( 2 );
  4340. State().AddAsOwner( 2 );
  4341. State().StartHold( 2 );
  4342. // we now own the write latch
  4343. return errSuccess;
  4344. }
  4345. }
  4346. }
  4347. }
  4348. // upgrades the exclusive latch to the write latch. if the write latch is
  4349. // acquired immediately, errSuccess will be returned. if the write latch is
  4350. // not acquired immediately, errWaitForWriteLatch is returned and
  4351. // WaitForWriteLatch() must be called to gain ownership of the write latch
  4352. inline CSXWLatch::ERR CSXWLatch::ErrUpgradeExclusiveLatchToWriteLatch()
  4353. {
  4354. // we had better already have only an exclusive latch
  4355. OSSYNCAssert( FNotOwnSharedLatch() );
  4356. OSSYNCAssert( FOwnExclusiveLatch() );
  4357. OSSYNCAssert( FNotOwnWriteLatch() );
  4358. // we are no longer an owner of the exclusive latch
  4359. State().RemoveAsOwner( 1 );
  4360. State().StopHold( 1 );
  4361. // try forever until we successfully change the latch state
  4362. OSSYNC_FOREVER
  4363. {
  4364. // read the current state of the control word as our expected before image
  4365. const ControlWord cwBIExpected = State().m_cw;
  4366. // compute the after image of the control word by performing the transform that
  4367. // will quiesce shared latches by setting the fQS flag and removing the current
  4368. // shared latch count from the control word
  4369. const ControlWord cwAI = ( cwBIExpected & 0xFFFF0000 ) | 0x00008000;
  4370. // attempt to perform the transacted state transition on the control word
  4371. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  4372. // the transaction failed
  4373. if ( cwBI != cwBIExpected )
  4374. {
  4375. // try again
  4376. continue;
  4377. }
  4378. // the transaction succeeded
  4379. else
  4380. {
  4381. // shared latches were just quiesced
  4382. if ( cwBI & 0x00007FFF )
  4383. {
  4384. // this is a contention for the write latch
  4385. State().SetContend( 2 );
  4386. // update the quiesced shared latch count with the shared latch
  4387. // count that we displaced from the control word, possibly
  4388. // releasing waiters. we update the count as if we we had a
  4389. // shared latch as a write latch (namely ours) can be released
  4390. _UpdateQuiescedSharedLatchCount( cwBI & 0x00007FFF );
  4391. // we are now a waiter for the write latch
  4392. State().AddAsWaiter( 2 );
  4393. State().StartWait( 2 );
  4394. // we will need to block
  4395. return errWaitForWriteLatch;
  4396. }
  4397. // shared latches were not just quiesced
  4398. else
  4399. {
  4400. // we are now an owner of the write latch
  4401. State().SetAcquire( 2 );
  4402. State().AddAsOwner( 2 );
  4403. State().StartHold( 2 );
  4404. // we now own the write latch
  4405. return errSuccess;
  4406. }
  4407. }
  4408. }
  4409. }
  4410. // releases the write latch in exchange for the exclusive latch
  4411. inline void CSXWLatch::DowngradeWriteLatchToExclusiveLatch()
  4412. {
  4413. // we had better already have only a write latch
  4414. OSSYNCAssert( FNotOwnSharedLatch() );
  4415. OSSYNCAssert( FNotOwnExclusiveLatch() );
  4416. OSSYNCAssert( FOwnWriteLatch() );
  4417. // stop quiescing shared latches by resetting the fQS flag
  4418. const ControlWord cwDelta = 0xFFFF8000;
  4419. const ControlWord cwBI = AtomicExchangeAdd( (long*)&State().m_cw, cwDelta );
  4420. // transfer ownership from the write latch to the exclusive latch
  4421. State().RemoveAsOwner( 2 );
  4422. State().StopHold( 2 );
  4423. State().SetAcquire( 1 );
  4424. State().AddAsOwner( 1 );
  4425. State().StartHold( 1 );
  4426. // release any quiesced shared latches
  4427. if ( cwBI & 0x00007FFF )
  4428. {
  4429. State().m_semS.Release( cwBI & 0x00007FFF );
  4430. }
  4431. }
  4432. // releases the write latch in exchange for a shared latch
  4433. inline void CSXWLatch::DowngradeWriteLatchToSharedLatch()
  4434. {
  4435. // we had better already have only a write latch
  4436. OSSYNCAssert( FNotOwnSharedLatch() );
  4437. OSSYNCAssert( FNotOwnExclusiveLatch() );
  4438. OSSYNCAssert( FOwnWriteLatch() );
  4439. // stop quiescing shared latches by resetting the fQS flag, release our
  4440. // exclusive latch, and acquire a shared latch
  4441. const ControlWord cwDelta = 0xFFFE8001;
  4442. const ControlWord cwBI = AtomicExchangeAdd( (long*)&State().m_cw, cwDelta );
  4443. // transfer ownership from the write latch to a shared latch
  4444. State().RemoveAsOwner( 2 );
  4445. State().StopHold( 2 );
  4446. State().SetAcquire( 0 );
  4447. State().AddAsOwner( 0 );
  4448. State().StartHold( 0 );
  4449. // release any quiesced shared latches
  4450. if ( cwBI & 0x00007FFF )
  4451. {
  4452. State().m_semS.Release( cwBI & 0x00007FFF );
  4453. }
  4454. // release a waiter for the exclusive latch, if any
  4455. if ( cwBI >= 0x00020000 )
  4456. {
  4457. State().m_semX.Release();
  4458. }
  4459. }
  4460. // releases the exclusive latch in exchange for a shared latch
  4461. inline void CSXWLatch::DowngradeExclusiveLatchToSharedLatch()
  4462. {
  4463. // we had better already have only an exclusive latch
  4464. OSSYNCAssert( FNotOwnSharedLatch() );
  4465. OSSYNCAssert( FOwnExclusiveLatch() );
  4466. OSSYNCAssert( FNotOwnWriteLatch() );
  4467. // release our exclusive latch and acquire a shared latch
  4468. const ControlWord cwDelta = 0xFFFF0001;
  4469. const ControlWord cwBI = AtomicExchangeAdd( (long*)&State().m_cw, cwDelta );
  4470. // transfer ownership from the exclusive latch to a shared latch
  4471. State().RemoveAsOwner( 1 );
  4472. State().StopHold( 1 );
  4473. State().SetAcquire( 0 );
  4474. State().AddAsOwner( 0 );
  4475. State().StartHold( 0 );
  4476. // release a waiter for the exclusive latch, if any
  4477. if ( cwBI >= 0x00020000 )
  4478. {
  4479. State().m_semX.Release();
  4480. }
  4481. }
  4482. // releases the write latch
  4483. inline void CSXWLatch::ReleaseWriteLatch()
  4484. {
  4485. // we had better already have only a write latch
  4486. OSSYNCAssert( FNotOwnSharedLatch() );
  4487. OSSYNCAssert( FNotOwnExclusiveLatch() );
  4488. OSSYNCAssert( FOwnWriteLatch() );
  4489. // stop quiescing shared latches by resetting the fQS flag and release our
  4490. // exclusive latch
  4491. const ControlWord cwDelta = 0xFFFE8000;
  4492. const ControlWord cwBI = AtomicExchangeAdd( (long*)&State().m_cw, cwDelta );
  4493. // release ownership of the write latch
  4494. State().RemoveAsOwner( 2 );
  4495. State().StopHold( 2 );
  4496. // release any quiesced shared latches
  4497. if ( cwBI & 0x00007FFF )
  4498. {
  4499. State().m_semS.Release( cwBI & 0x00007FFF );
  4500. }
  4501. // release a waiter for the exclusive latch, if any
  4502. if ( cwBI >= 0x00020000 )
  4503. {
  4504. State().m_semX.Release();
  4505. }
  4506. }
  4507. // releases the exclusive latch
  4508. inline void CSXWLatch::ReleaseExclusiveLatch()
  4509. {
  4510. // we had better already have only an exclusive latch
  4511. OSSYNCAssert( FNotOwnSharedLatch() );
  4512. OSSYNCAssert( FOwnExclusiveLatch() );
  4513. OSSYNCAssert( FNotOwnWriteLatch() );
  4514. // release our exclusive latch
  4515. const ControlWord cwDelta = 0xFFFF0000;
  4516. const ControlWord cwBI = AtomicExchangeAdd( (long*)&State().m_cw, cwDelta );
  4517. // release ownership of the exclusive latch
  4518. State().RemoveAsOwner( 1 );
  4519. State().StopHold( 1 );
  4520. // release a waiter for the exclusive latch, if any
  4521. if ( cwBI >= 0x00020000 )
  4522. {
  4523. State().m_semX.Release();
  4524. }
  4525. }
  4526. // releases a shared latch
  4527. inline void CSXWLatch::ReleaseSharedLatch()
  4528. {
  4529. // we had better already have only a shared latch
  4530. OSSYNCAssert( FOwnSharedLatch() );
  4531. OSSYNCAssert( FNotOwnExclusiveLatch() );
  4532. OSSYNCAssert( FNotOwnWriteLatch() );
  4533. // we are no longer an owner of a shared latch
  4534. State().RemoveAsOwner( 0 );
  4535. State().StopHold( 0 );
  4536. // try forever until we successfully change the latch state
  4537. OSSYNC_FOREVER
  4538. {
  4539. // read the current state of the control word as our expected before image
  4540. ControlWord cwBIExpected = State().m_cw;
  4541. // change the expected before image so that the transaction will only work if
  4542. // shared latches are not quiesced
  4543. cwBIExpected = cwBIExpected & 0xFFFF7FFF;
  4544. // compute the after image of the control word by performing the transform that
  4545. // will release our shared latch
  4546. const ControlWord cwAI = cwBIExpected + 0xFFFFFFFF;
  4547. // attempt to perform the transacted state transition on the control word
  4548. const ControlWord cwBI = AtomicCompareExchange( (long*)&State().m_cw, cwBIExpected, cwAI );
  4549. // the transaction failed
  4550. if ( cwBI != cwBIExpected )
  4551. {
  4552. // the transaction failed because shared latches were quiesced
  4553. if ( cwBI & 0x00008000 )
  4554. {
  4555. // leave the latch as a quiesced shared latch
  4556. _UpdateQuiescedSharedLatchCount( 0xFFFFFFFF );
  4557. // we're done
  4558. break;
  4559. }
  4560. // the transaction failed because another context changed the control word
  4561. else
  4562. {
  4563. // try again
  4564. continue;
  4565. }
  4566. }
  4567. // the transaction succeeded
  4568. else
  4569. {
  4570. // we're done
  4571. break;
  4572. }
  4573. }
  4574. }
  4575. // waits for ownership of a shared latch in response to receiving an
  4576. // errWaitForSharedLatch from the API. this function must not be called at any
  4577. // other time
  4578. inline void CSXWLatch::WaitForSharedLatch()
  4579. {
  4580. // check for deadlock
  4581. OSSYNCAssertSzRTL( State().FCanBeWaiter(), "Potential Deadlock Detected (Rank Violation)");
  4582. // we had better already be declared a waiter
  4583. OSSYNCAssert( State().FWaiter( 0 ) );
  4584. // wait for ownership of a shared latch on the shared latch semaphore
  4585. State().m_semS.Acquire();
  4586. State().StopWait( 0 );
  4587. State().RemoveAsWaiter( 0 );
  4588. State().SetAcquire( 0 );
  4589. State().AddAsOwner( 0 );
  4590. State().StartHold( 0 );
  4591. }
  4592. // waits for ownership of the exclusive latch in response to receiving an
  4593. // errWaitForExclusiveLatch from the API. this function must not be called at any
  4594. // other time
  4595. inline void CSXWLatch::WaitForExclusiveLatch()
  4596. {
  4597. // check for deadlock
  4598. OSSYNCAssertSzRTL( State().FCanBeWaiter(), "Potential Deadlock Detected (Rank Violation)");
  4599. // we had better already be declared a waiter
  4600. OSSYNCAssert( State().FWaiter( 1 ) );
  4601. // wait for ownership of the exclusive latch on the exclusive latch semaphore
  4602. State().m_semX.Acquire();
  4603. State().StopWait( 1 );
  4604. State().RemoveAsWaiter( 1 );
  4605. State().SetAcquire( 1 );
  4606. State().AddAsOwner( 1 );
  4607. State().StartHold( 1 );
  4608. }
  4609. // waits for ownership of the write latch in response to receiving an
  4610. // errWaitForWriteLatch from the API. this function must not be called at any
  4611. // other time
  4612. inline void CSXWLatch::WaitForWriteLatch()
  4613. {
  4614. // check for deadlock
  4615. OSSYNCAssertSzRTL( State().FCanBeWaiter(), "Potential Deadlock Detected (Rank Violation)");
  4616. // we had better already be declared a waiter
  4617. OSSYNCAssert( State().FWaiter( 2 ) );
  4618. // wait for ownership of the write latch on the write latch semaphore
  4619. State().m_semW.Acquire();
  4620. State().StopWait( 2 );
  4621. State().RemoveAsWaiter( 2 );
  4622. State().SetAcquire( 2 );
  4623. State().AddAsOwner( 2 );
  4624. State().StartHold( 2 );
  4625. }
  4626. // claims ownership of the latch for the specified group for deadlock detection
  4627. inline void CSXWLatch::ClaimOwnership( const DWORD group )
  4628. {
  4629. State().AddAsOwner( group );
  4630. }
  4631. // releases ownership of the latch for the specified group for deadlock detection
  4632. inline void CSXWLatch::ReleaseOwnership( const DWORD group )
  4633. {
  4634. State().RemoveAsOwner( group );
  4635. }
  4636. // updates the quiesced shared latch count, possibly releasing a waiter for
  4637. // the write latch
  4638. inline void CSXWLatch::_UpdateQuiescedSharedLatchCount( const DWORD cQSDelta )
  4639. {
  4640. // update the quiesced shared latch count using the provided delta
  4641. const DWORD cQSBI = AtomicExchangeAdd( (long*)&State().m_cQS, cQSDelta );
  4642. const DWORD cQSAI = cQSBI + cQSDelta;
  4643. // our update resulted in a zero quiesced shared latch count
  4644. if ( !cQSAI )
  4645. {
  4646. // release the waiter for the write latch
  4647. State().m_semW.Release();
  4648. }
  4649. }
  4650. // init sync subsystem
  4651. const BOOL OSSYNCAPI FOSSyncPreinit();
  4652. // terminate sync subsystem
  4653. void OSSYNCAPI OSSyncPostterm();
  4654. // attach the current context to the sync subsystem
  4655. BOOL OSSYNCAPI FOSSyncAttach();
  4656. // detach the current context from the sync subsystem
  4657. void OSSYNCAPI OSSyncDetach();
  4658. // special init/term API's for Enhanced State only
  4659. const BOOL OSSYNCAPI FOSSyncInitForES();
  4660. void OSSYNCAPI OSSyncTermForES();
  4661. }; // namespace OSSYNC
  4662. using namespace OSSYNC;
  4663. #endif // _SYNC_HXX_INCLUDED