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

4993 lines
155 KiB

  1. /*++
  2. Copyright (c) 1998-2002 Microsoft Corporation
  3. Module Name :
  4. LKRhash.cpp
  5. Abstract:
  6. Implements LKRhash: a fast, scalable, cache- and MP-friendly hash table
  7. Author:
  8. Paul (Per-Ake) Larson, palarson@microsoft.com, July 1997
  9. Murali R. Krishnan (MuraliK)
  10. George V. Reilly (GeorgeRe) 06-Jan-1998
  11. Environment:
  12. Win32 - User Mode
  13. Project:
  14. Internet Information Server RunTime Library
  15. Revision History:
  16. Jan 1998 - Massive cleanup and rewrite. Templatized.
  17. 10/01/1998 - Change name from LKhash to LKRhash
  18. --*/
  19. #include "precomp.hxx"
  20. #define DLL_IMPLEMENTATION
  21. #define IMPLEMENTATION_EXPORT
  22. #include <lkrhash.h>
  23. #ifndef __LKRHASH_NO_NAMESPACE__
  24. #define LKRHASH_NS LKRhash
  25. #else // __LKRHASH_NO_NAMESPACE__
  26. #define LKRHASH_NS
  27. #endif // __LKRHASH_NO_NAMESPACE__
  28. #include "_locks.h"
  29. #ifdef LKRHASH_ALLOCATOR_NEW
  30. # define DECLARE_ALLOCATOR(CLASS) \
  31. CLKRhashAllocator* LKRHASH_NS::CLASS::sm_palloc = NULL
  32. # define DECLARE_ALLOCATOR_LHTSUBCLASS(CLASS) \
  33. CLKRhashAllocator* LKRHASH_NS::CLKRLinearHashTable::CLASS::sm_palloc = NULL
  34. // DECLARE_ALLOCATOR(CLKRLinearHashTable);
  35. // DECLARE_ALLOCATOR(CLKRHashTable);
  36. DECLARE_ALLOCATOR(CNodeClump);
  37. DECLARE_ALLOCATOR(CSmallSegment);
  38. DECLARE_ALLOCATOR(CMediumSegment);
  39. DECLARE_ALLOCATOR(CLargeSegment);
  40. #endif // LKRHASH_ALLOCATOR_NEW
  41. static bool s_fInitialized = false;
  42. static LONG g_nLkrInitCount = 0;
  43. CSimpleLock g_lckLkrInit;
  44. // -------------------------------------------------------------------------
  45. // Initialize per-class allocators
  46. // -------------------------------------------------------------------------
  47. bool
  48. LKRHashTableInit()
  49. {
  50. bool f = true;
  51. #define INIT_ALLOCATOR(CLASS, N) \
  52. LKRHASH_ALLOCATOR_INIT(LKRHASH_NS::CLASS, N, f)
  53. #define INIT_ALLOCATOR_LHTSUBCLASS(CLASS, N) \
  54. LKRHASH_ALLOCATOR_INIT(LKRHASH_NS::CLKRLinearHashTable::CLASS, N, f)
  55. g_lckLkrInit.Enter();
  56. LONG nCount = g_nLkrInitCount;
  57. UNREFERENCED_PARAMETER(nCount);
  58. IRTLTRACE1("LKRHashTableInit, %ld\n", nCount);
  59. if (++g_nLkrInitCount == 1)
  60. {
  61. // INIT_ALLOCATOR(CLKRLinearHashTable, 20);
  62. // INIT_ALLOCATOR(CLKRHashTable, 4);
  63. INIT_ALLOCATOR(CNodeClump, 200);
  64. INIT_ALLOCATOR(CSmallSegment, 5);
  65. INIT_ALLOCATOR(CMediumSegment, 5);
  66. INIT_ALLOCATOR(CLargeSegment, 5);
  67. s_fInitialized = f;
  68. }
  69. g_lckLkrInit.Leave();
  70. return f;
  71. } // LKRHashTableInit
  72. // -------------------------------------------------------------------------
  73. // Destroy per-class allocators
  74. // -------------------------------------------------------------------------
  75. void
  76. LKRHashTableUninit()
  77. {
  78. #define UNINIT_ALLOCATOR(CLASS) \
  79. LKRHASH_ALLOCATOR_UNINIT(LKRHASH_NS::CLASS)
  80. #define UNINIT_ALLOCATOR_LHTSUBCLASS(CLASS) \
  81. LKRHASH_ALLOCATOR_UNINIT(LKRHASH_NS::CLKRLinearHashTable::CLASS)
  82. g_lckLkrInit.Enter();
  83. LONG nCount = g_nLkrInitCount;
  84. UNREFERENCED_PARAMETER(nCount);
  85. if (--g_nLkrInitCount == 0)
  86. {
  87. // UNINIT_ALLOCATOR(CLKRLinearHashTable);
  88. // UNINIT_ALLOCATOR(CLKRHashTable);
  89. UNINIT_ALLOCATOR(CNodeClump);
  90. UNINIT_ALLOCATOR(CSmallSegment);
  91. UNINIT_ALLOCATOR(CMediumSegment);
  92. UNINIT_ALLOCATOR(CLargeSegment);
  93. s_fInitialized = false;
  94. }
  95. g_lckLkrInit.Leave();
  96. IRTLTRACE1("LKRHashTableUninit done, %ld\n", nCount);
  97. } // LKRHashTableUninit
  98. #ifndef __LKRHASH_NO_NAMESPACE__
  99. namespace LKRhash {
  100. #endif // !__LKRHASH_NO_NAMESPACE__
  101. // See if countdown loops are faster than countup loops for traversing
  102. // a CNodeClump
  103. #ifdef LKR_COUNTDOWN
  104. #define FOR_EACH_NODE(x) for (x = NODES_PER_CLUMP; --x >= 0; )
  105. #else // !LKR_COUNTDOWN
  106. #define FOR_EACH_NODE(x) for (x = 0; x < NODES_PER_CLUMP; ++x)
  107. #endif // !LKR_COUNTDOWN
  108. // -------------------------------------------------------------------------
  109. // class static member variables
  110. // -------------------------------------------------------------------------
  111. #ifdef LOCK_INSTRUMENTATION
  112. LONG CBucket::sm_cBuckets = 0;
  113. LONG CLKRLinearHashTable::sm_cTables = 0;
  114. #endif // LOCK_INSTRUMENTATION
  115. #ifndef LKR_NO_GLOBAL_LIST
  116. CLockedDoubleList CLKRLinearHashTable::sm_llGlobalList;
  117. CLockedDoubleList CLKRHashTable::sm_llGlobalList;
  118. #endif // LKR_NO_GLOBAL_LIST
  119. // CLKRLinearHashTable --------------------------------------------------------
  120. // Public Constructor for class CLKRLinearHashTable.
  121. // -------------------------------------------------------------------------
  122. CLKRLinearHashTable::CLKRLinearHashTable(
  123. LPCSTR pszName, // An identifier for debugging
  124. PFnExtractKey pfnExtractKey, // Extract key from record
  125. PFnCalcKeyHash pfnCalcKeyHash, // Calculate hash signature of key
  126. PFnEqualKeys pfnEqualKeys, // Compare two keys
  127. PFnAddRefRecord pfnAddRefRecord,// AddRef in FindKey, etc
  128. double maxload, // Upperbound on the average chain length
  129. DWORD initsize, // Initial size of hash table.
  130. DWORD /*num_subtbls*/, // for compatiblity with CLKRHashTable
  131. bool fMultiKeys // Allow multiple identical keys?
  132. )
  133. :
  134. #ifdef LOCK_INSTRUMENTATION
  135. m_Lock(_LockName()),
  136. #endif // LOCK_INSTRUMENTATION
  137. m_nTableLockType(static_cast<BYTE>(TableLock::LockType())),
  138. m_nBucketLockType(static_cast<BYTE>(BucketLock::LockType())),
  139. m_phtParent(NULL), // directly created, no owning table
  140. m_fMultiKeys(fMultiKeys)
  141. {
  142. #ifndef LOCK_INSTRUMENTATION
  143. STATIC_ASSERT(1 <= LK_DFLT_MAXLOAD && LK_DFLT_MAXLOAD <= NODES_PER_CLUMP);
  144. #endif // !LOCK_INSTRUMENTATION
  145. STATIC_ASSERT(0 <= NODE_BEGIN && NODE_BEGIN < NODES_PER_CLUMP);
  146. STATIC_ASSERT(!(0 <= NODE_END && NODE_END < NODES_PER_CLUMP));
  147. IRTLVERIFY(LK_SUCCESS
  148. == _Initialize(pfnExtractKey, pfnCalcKeyHash, pfnEqualKeys,
  149. pfnAddRefRecord, pszName, maxload, initsize));
  150. _InsertThisIntoGlobalList();
  151. } // CLKRLinearHashTable::CLKRLinearHashTable
  152. // CLKRLinearHashTable --------------------------------------------------------
  153. // Private Constructor for class CLKRLinearHashTable, used by CLKRHashTable.
  154. // -------------------------------------------------------------------------
  155. CLKRLinearHashTable::CLKRLinearHashTable(
  156. LPCSTR pszName, // An identifier for debugging
  157. PFnExtractKey pfnExtractKey, // Extract key from record
  158. PFnCalcKeyHash pfnCalcKeyHash, // Calculate hash signature of key
  159. PFnEqualKeys pfnEqualKeys, // Compare two keys
  160. PFnAddRefRecord pfnAddRefRecord,// AddRef in FindKey, etc
  161. double maxload, // Upperbound on the average chain length
  162. DWORD initsize, // Initial size of hash table.
  163. CLKRHashTable* phtParent, // Owning table.
  164. bool fMultiKeys // Allow multiple identical keys?
  165. )
  166. :
  167. #ifdef LOCK_INSTRUMENTATION
  168. m_Lock(_LockName()),
  169. #endif // LOCK_INSTRUMENTATION
  170. m_nTableLockType(static_cast<BYTE>(TableLock::LockType())),
  171. m_nBucketLockType(static_cast<BYTE>(BucketLock::LockType())),
  172. m_phtParent(phtParent),
  173. m_fMultiKeys(fMultiKeys)
  174. {
  175. IRTLASSERT(m_phtParent != NULL);
  176. IRTLVERIFY(LK_SUCCESS
  177. == _Initialize(pfnExtractKey, pfnCalcKeyHash, pfnEqualKeys,
  178. pfnAddRefRecord, pszName, maxload, initsize));
  179. _InsertThisIntoGlobalList();
  180. } // CLKRLinearHashTable::CLKRLinearHashTable
  181. // _Initialize -------------------------------------------------------------
  182. // Do all the real work of constructing a CLKRLinearHashTable
  183. // -------------------------------------------------------------------------
  184. LK_RETCODE
  185. CLKRLinearHashTable::_Initialize(
  186. PFnExtractKey pfnExtractKey,
  187. PFnCalcKeyHash pfnCalcKeyHash,
  188. PFnEqualKeys pfnEqualKeys,
  189. PFnAddRefRecord pfnAddRefRecord,
  190. LPCSTR pszName,
  191. double maxload,
  192. DWORD initsize)
  193. {
  194. m_dwSignature = SIGNATURE;
  195. m_dwBktAddrMask0 = 0;
  196. m_dwBktAddrMask1 = 0;
  197. m_iExpansionIdx = 0;
  198. m_paDirSegs = NULL;
  199. m_lkts = LK_MEDIUM_TABLESIZE;
  200. m_dwSegBits = 0;
  201. m_dwSegSize = 0;
  202. m_dwSegMask = 0;
  203. m_lkrcState = LK_UNUSABLE;
  204. m_MaxLoad = LK_DFLT_MAXLOAD;
  205. m_nLevel = 0;
  206. m_cDirSegs = 0;
  207. m_cRecords = 0;
  208. m_cActiveBuckets = 0;
  209. m_wBucketLockSpins= LOCK_USE_DEFAULT_SPINS;
  210. m_pfnExtractKey = pfnExtractKey;
  211. m_pfnCalcKeyHash = pfnCalcKeyHash;
  212. m_pfnEqualKeys = pfnEqualKeys;
  213. m_pfnAddRefRecord = pfnAddRefRecord;
  214. strncpy(m_szName, pszName, NAME_SIZE-1);
  215. m_szName[NAME_SIZE-1] = '\0';
  216. IRTLASSERT(m_pfnExtractKey != NULL
  217. && m_pfnCalcKeyHash != NULL
  218. && m_pfnEqualKeys != NULL
  219. && m_pfnAddRefRecord != NULL);
  220. IRTLASSERT(s_fInitialized);
  221. if (!s_fInitialized)
  222. return (m_lkrcState = LK_NOT_INITIALIZED);
  223. if (m_pfnExtractKey == NULL
  224. || m_pfnCalcKeyHash == NULL
  225. || m_pfnEqualKeys == NULL
  226. || m_pfnAddRefRecord == NULL)
  227. return (m_lkrcState = LK_BAD_PARAMETERS);
  228. // TODO: better sanity check for ridiculous values?
  229. m_MaxLoad = (maxload <= 1.0) ? LK_DFLT_MAXLOAD : maxload;
  230. m_MaxLoad = min(m_MaxLoad, 10 * NODES_PER_CLUMP);
  231. // Choose the size of the segments according to the desired "size" of
  232. // the table, small, medium, or large.
  233. LK_TABLESIZE lkts;
  234. if (initsize == LK_SMALL_TABLESIZE)
  235. {
  236. lkts = LK_SMALL_TABLESIZE;
  237. initsize = CSmallSegment::INITSIZE;
  238. }
  239. else if (initsize == LK_MEDIUM_TABLESIZE)
  240. {
  241. lkts = LK_MEDIUM_TABLESIZE;
  242. initsize = CMediumSegment::INITSIZE;
  243. }
  244. else if (initsize == LK_LARGE_TABLESIZE)
  245. {
  246. lkts = LK_LARGE_TABLESIZE;
  247. initsize = CLargeSegment::INITSIZE;
  248. }
  249. // specified an explicit initial size
  250. else
  251. {
  252. // force Small::INITSIZE <= initsize <= MAX_DIRSIZE * Large::INITSIZE
  253. initsize = min(max(initsize, CSmallSegment::INITSIZE),
  254. (MAX_DIRSIZE >> CLargeSegment::SEGBITS)
  255. * CLargeSegment::INITSIZE);
  256. // Guess a table size
  257. if (initsize <= 8 * CSmallSegment::INITSIZE)
  258. lkts = LK_SMALL_TABLESIZE;
  259. else if (initsize >= CLargeSegment::INITSIZE)
  260. lkts = LK_LARGE_TABLESIZE;
  261. else
  262. lkts = LK_MEDIUM_TABLESIZE;
  263. }
  264. return _SetSegVars(lkts, initsize);
  265. } // CLKRLinearHashTable::_Initialize
  266. // CLKRHashTable ----------------------------------------------------------
  267. // Constructor for class CLKRHashTable.
  268. // ---------------------------------------------------------------------
  269. CLKRHashTable::CLKRHashTable(
  270. LPCSTR pszName, // An identifier for debugging
  271. PFnExtractKey pfnExtractKey, // Extract key from record
  272. PFnCalcKeyHash pfnCalcKeyHash, // Calculate hash signature of key
  273. PFnEqualKeys pfnEqualKeys, // Compare two keys
  274. PFnAddRefRecord pfnAddRefRecord,// AddRef in FindKey, etc
  275. double maxload, // Bound on the average chain length
  276. DWORD initsize, // Initial size of hash table.
  277. DWORD num_subtbls, // Number of subordinate hash tables.
  278. bool fMultiKeys // Allow multiple identical keys?
  279. )
  280. : m_dwSignature(SIGNATURE),
  281. m_cSubTables(0),
  282. m_palhtDir(NULL),
  283. m_pfnExtractKey(pfnExtractKey),
  284. m_pfnCalcKeyHash(pfnCalcKeyHash),
  285. m_lkrcState(LK_BAD_PARAMETERS)
  286. {
  287. strncpy(m_szName, pszName, NAME_SIZE-1);
  288. m_szName[NAME_SIZE-1] = '\0';
  289. _InsertThisIntoGlobalList();
  290. IRTLASSERT(pfnExtractKey != NULL
  291. && pfnCalcKeyHash != NULL
  292. && pfnEqualKeys != NULL
  293. && pfnAddRefRecord != NULL);
  294. if (pfnExtractKey == NULL
  295. || pfnCalcKeyHash == NULL
  296. || pfnEqualKeys == NULL
  297. || pfnAddRefRecord == NULL)
  298. return;
  299. if (!s_fInitialized)
  300. {
  301. m_lkrcState = LK_NOT_INITIALIZED;
  302. return;
  303. }
  304. LK_TABLESIZE lkts = NumSubTables(initsize, num_subtbls);
  305. #ifdef IRTLDEBUG
  306. int cBuckets = initsize;
  307. if (initsize == LK_SMALL_TABLESIZE)
  308. cBuckets = CSmallSegment::INITSIZE;
  309. else if (initsize == LK_MEDIUM_TABLESIZE)
  310. cBuckets = CMediumSegment::INITSIZE;
  311. else if (initsize == LK_LARGE_TABLESIZE)
  312. cBuckets = CLargeSegment::INITSIZE;
  313. IRTLTRACE(TEXT("CLKRHashTable: %s, %d subtables, initsize = %d, ")
  314. TEXT("total #buckets = %d\n"),
  315. ((lkts == LK_SMALL_TABLESIZE) ? "small" :
  316. (lkts == LK_MEDIUM_TABLESIZE) ? "medium" : "large"),
  317. num_subtbls, initsize, cBuckets * num_subtbls);
  318. #else // !IRTLDEBUG
  319. UNREFERENCED_PARAMETER(lkts);
  320. #endif // !IRTLDEBUG
  321. m_lkrcState = LK_ALLOC_FAIL;
  322. m_palhtDir = _AllocateSubTableArray(num_subtbls);
  323. if (m_palhtDir == NULL)
  324. return;
  325. else
  326. {
  327. m_cSubTables = num_subtbls;
  328. for (DWORD i = 0; i < m_cSubTables; i++)
  329. m_palhtDir[i] = NULL;
  330. }
  331. for (DWORD i = 0; i < m_cSubTables; i++)
  332. {
  333. m_palhtDir[i] = _AllocateSubTable(pszName, pfnExtractKey,
  334. pfnCalcKeyHash, pfnEqualKeys,
  335. pfnAddRefRecord, maxload,
  336. initsize, this, fMultiKeys);
  337. // Failed to allocate a subtable. Destroy everything allocated so far.
  338. if (m_palhtDir[i] == NULL || !m_palhtDir[i]->IsValid())
  339. {
  340. for (DWORD j = i; j-- > 0; )
  341. _FreeSubTable(m_palhtDir[j]);
  342. _FreeSubTableArray(m_palhtDir);
  343. m_cSubTables = 0;
  344. m_palhtDir = NULL;
  345. return;
  346. }
  347. }
  348. m_nSubTableMask = m_cSubTables - 1;
  349. // power of 2?
  350. if ((m_nSubTableMask & m_cSubTables) != 0)
  351. m_nSubTableMask = -1;
  352. m_lkrcState = LK_SUCCESS; // so IsValid/IsUsable won't fail
  353. } // CLKRHashTable::CLKRHashTable
  354. // ~CLKRLinearHashTable ------------------------------------------------------
  355. // Destructor for class CLKRLinearHashTable
  356. //-------------------------------------------------------------------------
  357. CLKRLinearHashTable::~CLKRLinearHashTable()
  358. {
  359. // must acquire all locks before deleting to make sure
  360. // that no other threads are using the table
  361. WriteLock();
  362. _Clear(false);
  363. WriteUnlock();
  364. _RemoveThisFromGlobalList();
  365. m_dwSignature = SIGNATURE_FREE;
  366. m_lkrcState = LK_UNUSABLE; // so IsUsable will fail
  367. } // CLKRLinearHashTable::~CLKRLinearHashTable
  368. // ~CLKRHashTable ------------------------------------------------------------
  369. // Destructor for class CLKRHashTable
  370. //-------------------------------------------------------------------------
  371. CLKRHashTable::~CLKRHashTable()
  372. {
  373. // Must delete the subtables in forward order (unlike
  374. // delete[], which starts at the end and moves backwards) to
  375. // prevent possibility of deadlock by acquiring the subtable
  376. // locks in a different order from the rest of the code.
  377. for (DWORD i = 0; i < m_cSubTables; ++i)
  378. _FreeSubTable(m_palhtDir[i]);
  379. _FreeSubTableArray(m_palhtDir);
  380. _RemoveThisFromGlobalList();
  381. m_dwSignature = SIGNATURE_FREE;
  382. m_lkrcState = LK_UNUSABLE; // so IsUsable will fail
  383. } // CLKRHashTable::~CLKRHashTable
  384. //------------------------------------------------------------------------
  385. // Function: CLKRLinearHashTable::NumSubTables
  386. // Synopsis:
  387. //------------------------------------------------------------------------
  388. LK_TABLESIZE
  389. CLKRLinearHashTable::NumSubTables(
  390. DWORD&, DWORD&)
  391. {
  392. LK_TABLESIZE lkts = LK_MEDIUM_TABLESIZE;
  393. return lkts;
  394. } // CLKRLinearHashTable::NumSubTables
  395. //------------------------------------------------------------------------
  396. // Function: CLKRHashTable::NumSubTables
  397. // Synopsis:
  398. //------------------------------------------------------------------------
  399. LK_TABLESIZE
  400. CLKRHashTable::NumSubTables(
  401. DWORD& rinitsize,
  402. DWORD& rnum_subtbls)
  403. {
  404. LK_TABLESIZE lkts;
  405. // Establish the table size
  406. if (rinitsize == LK_SMALL_TABLESIZE
  407. || rinitsize == LK_MEDIUM_TABLESIZE
  408. || rinitsize == LK_LARGE_TABLESIZE)
  409. {
  410. lkts = static_cast<LK_TABLESIZE>(rinitsize);
  411. }
  412. else
  413. {
  414. if (rnum_subtbls != LK_DFLT_NUM_SUBTBLS)
  415. {
  416. rinitsize = (rinitsize - 1) / rnum_subtbls + 1;
  417. if (rinitsize <= CSmallSegment::SEGSIZE)
  418. lkts = LK_SMALL_TABLESIZE;
  419. else if (rinitsize >= CLargeSegment::SEGSIZE)
  420. lkts = LK_LARGE_TABLESIZE;
  421. else
  422. lkts = LK_MEDIUM_TABLESIZE;
  423. }
  424. else
  425. {
  426. lkts = LK_MEDIUM_TABLESIZE;
  427. }
  428. }
  429. // Choose a suitable number of subtables
  430. if (rnum_subtbls == LK_DFLT_NUM_SUBTBLS)
  431. {
  432. int nCPUs = NumProcessors();
  433. switch (lkts)
  434. {
  435. case LK_SMALL_TABLESIZE:
  436. rnum_subtbls = max(1, nCPUs);
  437. break;
  438. case LK_MEDIUM_TABLESIZE:
  439. rnum_subtbls = 2 * nCPUs;
  440. break;
  441. case LK_LARGE_TABLESIZE:
  442. rnum_subtbls = 4 * nCPUs;
  443. break;
  444. }
  445. }
  446. rnum_subtbls = min(MAX_SUBTABLES, rnum_subtbls);
  447. return lkts;
  448. } // CLKRHashTable::NumSubTables
  449. //------------------------------------------------------------------------
  450. // Function: CLKRLinearHashTable::_FindBucket
  451. // Synopsis: Find a bucket, given its signature. The bucket is locked
  452. // before returning. Assumes table is already locked, to avoid
  453. // race conditions.
  454. //------------------------------------------------------------------------
  455. LOCK_FORCEINLINE
  456. CBucket*
  457. CLKRLinearHashTable::_FindBucket(
  458. DWORD dwSignature,
  459. bool fLockForWrite) const
  460. {
  461. IRTLASSERT(IsValid());
  462. IRTLASSERT(m_dwBktAddrMask0 > 0);
  463. IRTLASSERT((m_dwBktAddrMask0 & (m_dwBktAddrMask0+1)) == 0); // 00011..111
  464. IRTLASSERT(m_dwBktAddrMask0 == (1U << m_nLevel) - 1);
  465. IRTLASSERT(m_dwBktAddrMask1 == ((m_dwBktAddrMask0 << 1) | 1));
  466. IRTLASSERT((m_dwBktAddrMask1 & (m_dwBktAddrMask1+1)) == 0);
  467. IRTLASSERT(m_iExpansionIdx <= m_dwBktAddrMask0);
  468. IRTLASSERT(2 < m_dwSegBits && m_dwSegBits < 20
  469. && m_dwSegSize == (1U << m_dwSegBits)
  470. && m_dwSegMask == (m_dwSegSize - 1));
  471. IRTLASSERT(IsReadLocked() || IsWriteLocked());
  472. const DWORD dwBktAddr = _BucketAddress(dwSignature);
  473. IRTLASSERT(dwBktAddr < m_cActiveBuckets);
  474. CBucket* const pbkt = _Bucket(dwBktAddr);
  475. IRTLASSERT(pbkt != NULL);
  476. if (fLockForWrite)
  477. pbkt->WriteLock();
  478. else
  479. pbkt->ReadLock();
  480. return pbkt;
  481. } // CLKRLinearHashTable::_FindBucket
  482. //------------------------------------------------------------------------
  483. // Function: CLKRLinearHashTable::_IsNodeCompact
  484. // Synopsis: validates that a node is correctly compacted
  485. //------------------------------------------------------------------------
  486. int
  487. CLKRLinearHashTable::_IsNodeCompact(
  488. CBucket* const pbkt) const
  489. {
  490. CNodeClump* pncCurr;
  491. CNodeClump* pncPrev;
  492. bool fEmpty = pbkt->m_ncFirst.InvalidSignature(NODE_BEGIN);
  493. int cErrors = fEmpty ? !pbkt->m_ncFirst.IsLastClump() : 0;
  494. for (pncCurr = &pbkt->m_ncFirst, pncPrev = NULL;
  495. pncCurr != NULL;
  496. pncPrev = pncCurr, pncCurr = pncCurr->m_pncNext)
  497. {
  498. int i;
  499. FOR_EACH_NODE(i)
  500. {
  501. if (fEmpty)
  502. {
  503. cErrors += (!pncCurr->InvalidSignature(i));
  504. cErrors += (!pncCurr->IsEmptyNode(i));
  505. }
  506. else if (pncCurr->InvalidSignature(i))
  507. {
  508. fEmpty = true;
  509. cErrors += (!pncCurr->IsEmptyNode(i));
  510. cErrors += (!pncCurr->IsLastClump());
  511. }
  512. else // still in non-empty portion
  513. {
  514. cErrors += (pncCurr->InvalidSignature(i));
  515. cErrors += (pncCurr->IsEmptyNode(i));
  516. }
  517. }
  518. }
  519. return cErrors;
  520. } // CLKRLinearHashTable::_IsNodeCompact
  521. //------------------------------------------------------------------------
  522. // Function: CLKRHashTable::_SubTable
  523. // Synopsis:
  524. //------------------------------------------------------------------------
  525. LOCK_FORCEINLINE
  526. CLKRHashTable::SubTable*
  527. CLKRHashTable::_SubTable(
  528. DWORD dwSignature) const
  529. {
  530. IRTLASSERT(m_lkrcState == LK_SUCCESS
  531. && m_palhtDir != NULL && m_cSubTables > 0);
  532. const DWORD PRIME = 1048583UL; // used to scramble the hash sig
  533. DWORD index = dwSignature;
  534. index = (((index * PRIME + 12345) >> 16)
  535. | ((index * 69069 + 1) & 0xffff0000));
  536. if (m_nSubTableMask >= 0)
  537. index &= m_nSubTableMask;
  538. else
  539. index %= m_cSubTables;
  540. return m_palhtDir[index];
  541. } // CLKRHashTable::_SubTable
  542. //------------------------------------------------------------------------
  543. // Function: CLKRHashTable::_SubTableIndex
  544. // Synopsis:
  545. //------------------------------------------------------------------------
  546. int
  547. CLKRHashTable::_SubTableIndex(
  548. CLKRHashTable::SubTable* pst) const
  549. {
  550. int index = -1;
  551. for (int i = 0; i < (int) m_cSubTables; ++i)
  552. {
  553. if (pst == m_palhtDir[i])
  554. {
  555. index = i;
  556. break;
  557. }
  558. }
  559. IRTLASSERT(index >= 0);
  560. return index;
  561. } // CLKRHashTable::_SubTableIndex
  562. //------------------------------------------------------------------------
  563. // Function: CLKRLinearHashTable::_InsertRecord
  564. // Synopsis: Inserts a new record into the hash table. If this causes the
  565. // average chain length to exceed the upper bound, the table is
  566. // expanded by one bucket.
  567. // Output: LK_SUCCESS, if the record was inserted.
  568. // LK_KEY_EXISTS, if the record was not inserted (because a record
  569. // with the same key value already exists in the table, unless
  570. // fOverwrite==true).
  571. // LK_ALLOC_FAIL, if failed to allocate the required space
  572. // LK_UNUSABLE, if hash table not in usable state
  573. // LK_BAD_RECORD, if record is bad.
  574. //
  575. // TODO: honor m_fMultiKeys and allow multiple identical keys.
  576. // This will require keeping all identical signatures contiguously
  577. // within a bucket chain, and keeping all identical keys contigously
  578. // within that set of contigous signatures. With a good hash function,
  579. // there should not be identical signatures without also having
  580. // identical keys. Also, need to modify _DeleteNode. This modification
  581. // is needed for EqualRange and for hash_multiset and hash_multimap
  582. // to work.
  583. //------------------------------------------------------------------------
  584. LK_RETCODE
  585. CLKRLinearHashTable::_InsertRecord(
  586. const void* pvRecord, // Pointer to the record to add to table
  587. DWORD dwSignature,// hash signature
  588. bool fOverwrite // overwrite record if key already present
  589. #ifdef LKR_STL_ITERATORS
  590. , Iterator* piterResult
  591. #endif // LKR_STL_ITERATORS
  592. )
  593. {
  594. IRTLASSERT(IsUsable()
  595. && pvRecord != NULL
  596. && dwSignature != HASH_INVALID_SIGNATURE);
  597. // find the beginning of the correct bucket chain
  598. WriteLock();
  599. // Must call IsValid inside a lock to ensure that none of the state
  600. // variables change while it's being evaluated
  601. IRTLASSERT(IsValid());
  602. #ifdef LKR_STL_ITERATORS
  603. const DWORD dwBktAddr = _BucketAddress(dwSignature);
  604. IRTLASSERT(dwBktAddr < m_cActiveBuckets);
  605. #endif // LKR_STL_ITERATORS
  606. CBucket* const pbkt = _FindBucket(dwSignature, true);
  607. IRTLASSERT(pbkt != NULL);
  608. IRTLASSERT(pbkt->IsWriteLocked());
  609. WriteUnlock();
  610. // check that no record with the same key value exists
  611. // and save a pointer to the last element on the chain
  612. LK_RETCODE lkrc = LK_SUCCESS;
  613. CNodeClump* pncFree = NULL;
  614. int iFreePos = NODE_BEGIN - NODE_STEP;
  615. CNodeClump* pncPrev = NULL;
  616. bool fUpdate = false;
  617. const DWORD_PTR pnKey = _ExtractKey(pvRecord);
  618. // walk down the entire bucket chain, looking for matching hash
  619. // signatures and keys
  620. CNodeClump* pncCurr = &pbkt->m_ncFirst;
  621. do
  622. {
  623. IRTLASSERT(pncCurr != NULL) ;
  624. int i;
  625. FOR_EACH_NODE(i)
  626. {
  627. if (pncCurr->IsEmptySlot(i))
  628. {
  629. IRTLASSERT(pncCurr->IsEmptyAndInvalid(i));
  630. IRTLASSERT(0 == _IsNodeCompact(pbkt));
  631. IRTLASSERT(pncCurr->IsLastClump());
  632. pncFree = pncCurr;
  633. iFreePos = i;
  634. goto insert;
  635. }
  636. if (dwSignature == pncCurr->m_dwKeySigs[i]
  637. && (pvRecord == pncCurr->m_pvNode[i] ||
  638. _EqualKeys(pnKey, _ExtractKey(pncCurr->m_pvNode[i]))))
  639. {
  640. if (fOverwrite)
  641. {
  642. // If we allow overwrites, this is the slot to do it to
  643. fUpdate = true;
  644. pncFree = pncCurr;
  645. iFreePos = i;
  646. goto insert;
  647. }
  648. else
  649. {
  650. // overwrites forbidden: return an error
  651. lkrc = LK_KEY_EXISTS;
  652. goto exit;
  653. }
  654. }
  655. }
  656. pncPrev = pncCurr;
  657. pncCurr = pncCurr->m_pncNext;
  658. } while (pncCurr != NULL);
  659. insert:
  660. if (pncFree != NULL)
  661. {
  662. pncCurr = pncFree;
  663. IRTLASSERT(0 <= iFreePos && iFreePos < NODES_PER_CLUMP);
  664. }
  665. else
  666. {
  667. // No free slots. Attach the new node to the end of the chain
  668. IRTLASSERT(iFreePos == NODE_BEGIN - NODE_STEP);
  669. pncCurr = _AllocateNodeClump();
  670. if (pncCurr == NULL)
  671. {
  672. lkrc = LK_ALLOC_FAIL;
  673. goto exit;
  674. }
  675. IRTLASSERT(pncPrev != NULL && pncPrev->IsLastClump());
  676. pncPrev->m_pncNext = pncCurr;
  677. iFreePos = NODE_BEGIN;
  678. }
  679. // Bump the new record's reference count upwards
  680. _AddRefRecord(pvRecord, +1);
  681. if (fUpdate)
  682. {
  683. // We're overwriting an existing record. Adjust the old record's
  684. // refcount downwards. (Doing ++new, --old in this order ensures
  685. // that the refcount won't briefly go to zero if new and old are
  686. // the same record.)
  687. IRTLASSERT(!pncCurr->IsEmptyAndInvalid(iFreePos));
  688. _AddRefRecord(pncCurr->m_pvNode[iFreePos], -1);
  689. }
  690. else
  691. {
  692. IRTLASSERT(pncCurr->IsEmptyAndInvalid(iFreePos));
  693. InterlockedIncrement(reinterpret_cast<LONG*>(&m_cRecords));
  694. }
  695. pncCurr->m_dwKeySigs[iFreePos] = dwSignature;
  696. pncCurr->m_pvNode[iFreePos] = pvRecord;
  697. exit:
  698. pbkt->WriteUnlock();
  699. if (lkrc == LK_SUCCESS)
  700. {
  701. #ifdef LKR_STL_ITERATORS
  702. // Don't call _Expand() if we're putting the result into an
  703. // iterator, as _Expand() tends to invalidate any other
  704. // iterators that might be in use.
  705. if (piterResult != NULL)
  706. {
  707. piterResult->m_plht = this;
  708. piterResult->m_pnc = pncCurr;
  709. piterResult->m_dwBucketAddr = dwBktAddr;
  710. piterResult->m_iNode = (short) iFreePos;
  711. // Add an extra reference on the record, as the one added by
  712. // _InsertRecord will be lost when the iterator's destructor
  713. // fires or its assignment operator is used
  714. piterResult->_AddRef(+1);
  715. }
  716. else
  717. #endif // LKR_STL_ITERATORS
  718. {
  719. // If the average load factor has grown too high, we grow the
  720. // table one bucket at a time.
  721. while (m_cRecords > m_MaxLoad * m_cActiveBuckets)
  722. {
  723. // If _Expand returns an error code (viz. LK_ALLOC_FAIL), it
  724. // just means that there isn't enough spare memory to expand
  725. // the table by one bucket. This is likely to cause problems
  726. // elsewhere soon, but this hashtable has not been corrupted.
  727. // If the call to _AllocateNodeClump above failed, then we do
  728. // have a real error that must be propagated back to the caller
  729. // because we were unable to insert the element at all.
  730. if (_Expand() != LK_SUCCESS)
  731. break; // expansion failed
  732. }
  733. }
  734. }
  735. return lkrc;
  736. } // CLKRLinearHashTable::_InsertRecord
  737. //------------------------------------------------------------------------
  738. // Function: CLKRHashTable::InsertRecord
  739. // Synopsis: Thin wrapper for the corresponding method in CLKRLinearHashTable
  740. //------------------------------------------------------------------------
  741. LK_RETCODE
  742. CLKRHashTable::InsertRecord(
  743. const void* pvRecord,
  744. bool fOverwrite /*=false*/)
  745. {
  746. if (!IsUsable())
  747. return m_lkrcState;
  748. if (pvRecord == NULL)
  749. return LK_BAD_RECORD;
  750. LKRHASH_GLOBAL_WRITE_LOCK(); // usu. no-op
  751. DWORD hash_val = _CalcKeyHash(_ExtractKey(pvRecord));
  752. SubTable* const pst = _SubTable(hash_val);
  753. LK_RETCODE lk = pst->_InsertRecord(pvRecord, hash_val, fOverwrite);
  754. LKRHASH_GLOBAL_WRITE_UNLOCK(); // usu. no-op
  755. return lk;
  756. } // CLKRHashTable::InsertRecord
  757. //-------------------------------------------------------------------------
  758. // Function: CLKRLinearHashTable::_DeleteKey
  759. // Synopsis: Deletes the record with the given key value from the hash
  760. // table (if it exists).
  761. // Returns: LK_SUCCESS, if record found and deleted.
  762. // LK_NO_SUCH_KEY, if no record with the given key value was found.
  763. // LK_UNUSABLE, if hash table not in usable state
  764. //-------------------------------------------------------------------------
  765. LK_RETCODE
  766. CLKRLinearHashTable::_DeleteKey(
  767. const DWORD_PTR pnKey, // Key value of the record, depends on key type
  768. DWORD dwSignature
  769. )
  770. {
  771. IRTLASSERT(IsUsable());
  772. LK_RETCODE lkrc = LK_NO_SUCH_KEY;
  773. // locate the beginning of the correct bucket chain
  774. WriteLock();
  775. // Must call IsValid inside a lock to ensure that none of the state
  776. // variables change while it's being evaluated
  777. IRTLASSERT(IsValid());
  778. CBucket* const pbkt = _FindBucket(dwSignature, true);
  779. IRTLASSERT(pbkt != NULL);
  780. IRTLASSERT(pbkt->IsWriteLocked());
  781. WriteUnlock();
  782. // scan down the bucket chain, looking for the victim
  783. for (CNodeClump* pncCurr = &pbkt->m_ncFirst, *pncPrev = NULL;
  784. pncCurr != NULL;
  785. pncPrev = pncCurr, pncCurr = pncCurr->m_pncNext)
  786. {
  787. int i;
  788. FOR_EACH_NODE(i)
  789. {
  790. if (pncCurr->IsEmptySlot(i))
  791. {
  792. IRTLASSERT(pncCurr->IsEmptyAndInvalid(i));
  793. IRTLASSERT(0 == _IsNodeCompact(pbkt));
  794. IRTLASSERT(pncCurr->IsLastClump());
  795. goto exit;
  796. }
  797. if (dwSignature != pncCurr->m_dwKeySigs[i])
  798. continue;
  799. const DWORD_PTR pnKey2 = _ExtractKey(pncCurr->m_pvNode[i]);
  800. if (pnKey == pnKey2 || _EqualKeys(pnKey, pnKey2))
  801. {
  802. IRTLVERIFY(_DeleteNode(pbkt, pncCurr, pncPrev, i));
  803. lkrc = LK_SUCCESS;
  804. goto exit;
  805. }
  806. }
  807. }
  808. exit:
  809. pbkt->WriteUnlock();
  810. if (lkrc == LK_SUCCESS)
  811. {
  812. // contract the table if necessary
  813. unsigned nContractedRecords = m_cRecords;
  814. // Hysteresis: add a fudge factor to allow a slightly lower density
  815. // in the subtable. This reduces the frequency of contractions and
  816. // expansions in a subtable that gets a lot of deletions and insertions
  817. nContractedRecords += nContractedRecords >> 4;
  818. // Always want to have at least m_dwSegSize buckets
  819. while (m_cActiveBuckets * m_MaxLoad > nContractedRecords
  820. && m_cActiveBuckets > m_dwSegSize)
  821. {
  822. // If _Contract returns an error code (viz. LK_ALLOC_FAIL), it
  823. // just means that there isn't enough spare memory to contract
  824. // the table by one bucket. This is likely to cause problems
  825. // elsewhere soon, but this hashtable has not been corrupted.
  826. if (_Contract() != LK_SUCCESS)
  827. break;
  828. }
  829. }
  830. return lkrc;
  831. } // CLKRLinearHashTable::_DeleteKey
  832. //------------------------------------------------------------------------
  833. // Function: CLKRHashTable::DeleteKey
  834. // Synopsis: Thin wrapper for the corresponding method in CLKRLinearHashTable
  835. //------------------------------------------------------------------------
  836. LK_RETCODE
  837. CLKRHashTable::DeleteKey(
  838. const DWORD_PTR pnKey)
  839. {
  840. if (!IsUsable())
  841. return m_lkrcState;
  842. LKRHASH_GLOBAL_WRITE_LOCK(); // usu. no-op
  843. DWORD hash_val = _CalcKeyHash(pnKey);
  844. SubTable* const pst = _SubTable(hash_val);
  845. LK_RETCODE lk = pst->_DeleteKey(pnKey, hash_val);
  846. LKRHASH_GLOBAL_WRITE_UNLOCK(); // usu. no-op
  847. return lk;
  848. } // CLKRHashTable::DeleteKey
  849. //-------------------------------------------------------------------------
  850. // Function: CLKRLinearHashTable::_DeleteRecord
  851. // Synopsis: Deletes the specified record from the hash table (if it
  852. // exists). This is not the same thing as calling
  853. // DeleteKey(_ExtractKey(pvRecord)). If _DeleteKey were called for
  854. // a record that doesn't exist in the table, it could delete some
  855. // completely unrelated record that happened to have the same key.
  856. // Returns: LK_SUCCESS, if record found and deleted.
  857. // LK_NO_SUCH_KEY, if the record is not found in the table.
  858. // LK_UNUSABLE, if hash table not in usable state.
  859. //-------------------------------------------------------------------------
  860. LK_RETCODE
  861. CLKRLinearHashTable::_DeleteRecord(
  862. const void* pvRecord, // Pointer to the record to delete from the table
  863. DWORD dwSignature
  864. )
  865. {
  866. IRTLASSERT(IsUsable() && pvRecord != NULL);
  867. LK_RETCODE lkrc = LK_NO_SUCH_KEY;
  868. // locate the beginning of the correct bucket chain
  869. WriteLock();
  870. // Must call IsValid inside a lock to ensure that none of the state
  871. // variables change while it's being evaluated
  872. IRTLASSERT(IsValid());
  873. CBucket* const pbkt = _FindBucket(dwSignature, true);
  874. IRTLASSERT(pbkt != NULL);
  875. IRTLASSERT(pbkt->IsWriteLocked());
  876. WriteUnlock();
  877. const DWORD_PTR pnKey = _ExtractKey(pvRecord);
  878. UNREFERENCED_PARAMETER(pnKey);
  879. IRTLASSERT(dwSignature == _CalcKeyHash(pnKey));
  880. // scan down the bucket chain, looking for the victim
  881. for (CNodeClump* pncCurr = &pbkt->m_ncFirst, *pncPrev = NULL;
  882. pncCurr != NULL;
  883. pncPrev = pncCurr, pncCurr = pncCurr->m_pncNext)
  884. {
  885. int i;
  886. FOR_EACH_NODE(i)
  887. {
  888. if (pncCurr->IsEmptySlot(i))
  889. {
  890. IRTLASSERT(pncCurr->IsEmptyAndInvalid(i));
  891. IRTLASSERT(0 == _IsNodeCompact(pbkt));
  892. IRTLASSERT(pncCurr->IsLastClump());
  893. goto exit;
  894. }
  895. if (pncCurr->m_pvNode[i] == pvRecord)
  896. {
  897. IRTLASSERT(_EqualKeys(pnKey,
  898. _ExtractKey(pncCurr->m_pvNode[i])));
  899. IRTLASSERT(dwSignature == pncCurr->m_dwKeySigs[i]);
  900. IRTLVERIFY(_DeleteNode(pbkt, pncCurr, pncPrev, i));
  901. lkrc = LK_SUCCESS;
  902. goto exit;
  903. }
  904. }
  905. }
  906. exit:
  907. pbkt->WriteUnlock();
  908. if (lkrc == LK_SUCCESS)
  909. {
  910. // contract the table if necessary
  911. unsigned nContractedRecords = m_cRecords;
  912. // Hysteresis: add a fudge factor to allow a slightly lower density
  913. // in the subtable. This reduces the frequency of contractions and
  914. // expansions in a subtable that gets a lot of deletions and insertions
  915. nContractedRecords += nContractedRecords >> 4;
  916. // Always want to have at least m_dwSegSize buckets
  917. while (m_cActiveBuckets * m_MaxLoad > nContractedRecords
  918. && m_cActiveBuckets > m_dwSegSize)
  919. {
  920. // If _Contract returns an error code (viz. LK_ALLOC_FAIL), it
  921. // just means that there isn't enough spare memory to contract
  922. // the table by one bucket. This is likely to cause problems
  923. // elsewhere soon, but this hashtable has not been corrupted.
  924. if (_Contract() != LK_SUCCESS)
  925. break;
  926. }
  927. }
  928. return lkrc;
  929. } // CLKRLinearHashTable::_DeleteRecord
  930. //------------------------------------------------------------------------
  931. // Function: CLKRHashTable::DeleteRecord
  932. // Synopsis: Thin wrapper for the corresponding method in CLKRLinearHashTable
  933. //------------------------------------------------------------------------
  934. LK_RETCODE
  935. CLKRHashTable::DeleteRecord(
  936. const void* pvRecord)
  937. {
  938. if (!IsUsable())
  939. return m_lkrcState;
  940. if (pvRecord == NULL)
  941. return LK_BAD_RECORD;
  942. LKRHASH_GLOBAL_WRITE_LOCK(); // usu. no-op
  943. DWORD hash_val = _CalcKeyHash(_ExtractKey(pvRecord));
  944. SubTable* const pst = _SubTable(hash_val);
  945. LK_RETCODE lk = pst->_DeleteRecord(pvRecord, hash_val);
  946. LKRHASH_GLOBAL_WRITE_UNLOCK(); // usu. no-op
  947. return lk;
  948. } // CLKRHashTable::DeleteRecord
  949. //------------------------------------------------------------------------
  950. // Function: CLKRLinearHashTable::_DeleteNode
  951. // Synopsis: Deletes a node; removes the node clump if empty
  952. // Returns: true if successful
  953. //
  954. // TODO: Is the rpncPrev parameter really necessary?
  955. //------------------------------------------------------------------------
  956. bool
  957. CLKRLinearHashTable::_DeleteNode(
  958. CBucket* pbkt, // bucket chain containing node
  959. CNodeClump*& rpnc, // actual node
  960. CNodeClump*& rpncPrev, // predecessor of actual node, or NULL
  961. int& riNode) // index within node
  962. {
  963. IRTLASSERT(pbkt != NULL && pbkt->IsWriteLocked());
  964. IRTLASSERT(rpnc != NULL);
  965. IRTLASSERT(rpncPrev == NULL || rpncPrev->m_pncNext == rpnc);
  966. IRTLASSERT(0 <= riNode && riNode < NODES_PER_CLUMP);
  967. IRTLASSERT(!rpnc->IsEmptyAndInvalid(riNode));
  968. #ifdef IRTLDEBUG
  969. // Check that the node clump really does belong to the bucket
  970. CNodeClump* pnc1 = &pbkt->m_ncFirst;
  971. while (pnc1 != NULL && pnc1 != rpnc)
  972. pnc1 = pnc1->m_pncNext;
  973. IRTLASSERT(pnc1 == rpnc);
  974. #endif // IRTLDEBUG
  975. // Release the reference to the record
  976. _AddRefRecord(rpnc->m_pvNode[riNode], -1);
  977. IRTLASSERT(0 == _IsNodeCompact(pbkt));
  978. // TODO: honor m_fMultiKeys
  979. // Compact the nodeclump by moving the very last node back to the
  980. // newly freed slot
  981. CNodeClump* pnc2 = rpnc;
  982. int iNode2 = riNode;
  983. // Find the last nodeclump in the chain
  984. while (!pnc2->IsLastClump())
  985. {
  986. pnc2 = pnc2->m_pncNext;
  987. iNode2 = NODE_BEGIN;
  988. }
  989. IRTLASSERT(0 <= iNode2 && iNode2 < NODES_PER_CLUMP);
  990. IRTLASSERT(!pnc2->IsEmptyAndInvalid(iNode2));
  991. // Find the first empty slot in the nodeclump
  992. while (iNode2 != NODE_END && !pnc2->IsEmptySlot(iNode2))
  993. {
  994. iNode2 += NODE_STEP;
  995. }
  996. // Back up to last non-empty slot
  997. iNode2 -= NODE_STEP;
  998. IRTLASSERT(0 <= iNode2 && iNode2 < NODES_PER_CLUMP
  999. && !pnc2->IsEmptyAndInvalid(iNode2));
  1000. IRTLASSERT(iNode2+NODE_STEP == NODE_END
  1001. || pnc2->IsEmptyAndInvalid(iNode2+NODE_STEP));
  1002. #ifdef IRTLDEBUG
  1003. // Check that all the remaining nodes are empty
  1004. IRTLASSERT(pnc2->IsLastClump());
  1005. for (int iNode3 = iNode2 + NODE_STEP;
  1006. iNode3 != NODE_END;
  1007. iNode3 += NODE_STEP)
  1008. {
  1009. IRTLASSERT(pnc2->IsEmptyAndInvalid(iNode3));
  1010. }
  1011. #endif // IRTLDEBUG
  1012. // Move the last node's data back to the current node
  1013. rpnc->m_pvNode[riNode] = pnc2->m_pvNode[iNode2];
  1014. rpnc->m_dwKeySigs[riNode] = pnc2->m_dwKeySigs[iNode2];
  1015. // Blank the old last node.
  1016. // Correct even if (rpnc, riNode) == (pnc2, iNode2).
  1017. pnc2->m_pvNode[iNode2] = NULL;
  1018. pnc2->m_dwKeySigs[iNode2] = HASH_INVALID_SIGNATURE;
  1019. IRTLASSERT(0 == _IsNodeCompact(pbkt));
  1020. // Back up riNode by one, so that the next iteration of the loop
  1021. // calling _DeleteNode will end up pointing to the same spot.
  1022. if (riNode != NODE_BEGIN)
  1023. {
  1024. riNode -= NODE_STEP;
  1025. }
  1026. else
  1027. {
  1028. // rewind rpnc and rpncPrev to previous node
  1029. if (rpnc == &pbkt->m_ncFirst)
  1030. {
  1031. riNode = NODE_BEGIN - NODE_STEP;
  1032. }
  1033. else
  1034. {
  1035. riNode = NODE_END;
  1036. rpnc = rpncPrev;
  1037. if (rpnc == &pbkt->m_ncFirst)
  1038. {
  1039. rpncPrev = NULL;
  1040. }
  1041. else
  1042. {
  1043. for (rpncPrev = &pbkt->m_ncFirst;
  1044. rpncPrev->m_pncNext != rpnc;
  1045. rpncPrev = rpncPrev->m_pncNext)
  1046. {}
  1047. }
  1048. }
  1049. }
  1050. // Is the last node clump now completely empty? Delete, if possible
  1051. if (iNode2 == NODE_BEGIN && pnc2 != &pbkt->m_ncFirst)
  1052. {
  1053. // Find preceding nodeclump
  1054. CNodeClump* pnc3 = &pbkt->m_ncFirst;
  1055. while (pnc3->m_pncNext != pnc2)
  1056. {
  1057. pnc3 = pnc3->m_pncNext;
  1058. IRTLASSERT(pnc3 != NULL);
  1059. }
  1060. pnc3->m_pncNext = NULL;
  1061. #ifdef IRTLDEBUG
  1062. pnc2->m_pncNext = NULL; // or dtor will ASSERT
  1063. #endif // IRTLDEBUG
  1064. _FreeNodeClump(pnc2);
  1065. }
  1066. IRTLASSERT(rpncPrev == NULL || rpncPrev->m_pncNext == rpnc);
  1067. InterlockedDecrement(reinterpret_cast<LONG*>(&m_cRecords));
  1068. return true;
  1069. } // CLKRLinearHashTable::_DeleteNode
  1070. //------------------------------------------------------------------------
  1071. // Function: CLKRLinearHashTable::_FindKey
  1072. // Synopsis: Locate the record associated with the given key value.
  1073. // Returns: Pointer to the record, if it is found.
  1074. // NULL, if the record is not found.
  1075. // Returns: LK_SUCCESS, if record found (record is returned in *ppvRecord)
  1076. // LK_BAD_RECORD, if ppvRecord is invalid
  1077. // LK_NO_SUCH_KEY, if no record with the given key value was found.
  1078. // LK_UNUSABLE, if hash table not in usable state
  1079. // Note: the record is AddRef'd. You must decrement the reference count
  1080. // when you are finished with the record (if you're implementing
  1081. // refcounting semantics).
  1082. //------------------------------------------------------------------------
  1083. LK_RETCODE
  1084. CLKRLinearHashTable::_FindKey(
  1085. const DWORD_PTR pnKey, // Key value of the record, depends on key type
  1086. DWORD dwSignature,// hash signature
  1087. const void** ppvRecord // resultant record
  1088. #ifdef LKR_STL_ITERATORS
  1089. , Iterator* piterResult
  1090. #endif // LKR_STL_ITERATORS
  1091. ) const
  1092. {
  1093. IRTLASSERT(IsUsable() && ppvRecord != NULL);
  1094. *ppvRecord = NULL;
  1095. LK_RETCODE lkrc = LK_NO_SUCH_KEY;
  1096. int iNode = NODE_BEGIN - NODE_STEP;
  1097. // locate the beginning of the correct bucket chain
  1098. bool fReadLocked = _ReadOrWriteLock();
  1099. // Must call IsValid inside a lock to ensure that none of the state
  1100. // variables change while it's being evaluated
  1101. IRTLASSERT(IsValid());
  1102. #ifdef LKR_STL_ITERATORS
  1103. const DWORD dwBktAddr = _BucketAddress(dwSignature);
  1104. IRTLASSERT(dwBktAddr < m_cActiveBuckets);
  1105. #endif // LKR_STL_ITERATORS
  1106. CBucket* const pbkt = _FindBucket(dwSignature, false);
  1107. IRTLASSERT(pbkt != NULL);
  1108. IRTLASSERT(pbkt->IsReadLocked());
  1109. _ReadOrWriteUnlock(fReadLocked);
  1110. // walk down the bucket chain
  1111. for (CNodeClump* pncCurr = &pbkt->m_ncFirst;
  1112. pncCurr != NULL;
  1113. pncCurr = pncCurr->m_pncNext)
  1114. {
  1115. FOR_EACH_NODE(iNode)
  1116. {
  1117. if (pncCurr->IsEmptySlot(iNode))
  1118. {
  1119. IRTLASSERT(pncCurr->IsEmptyAndInvalid(iNode));
  1120. IRTLASSERT(0 == _IsNodeCompact(pbkt));
  1121. IRTLASSERT(pncCurr->IsLastClump());
  1122. goto exit;
  1123. }
  1124. if (dwSignature != pncCurr->m_dwKeySigs[iNode])
  1125. continue;
  1126. const DWORD_PTR pnKey2 = _ExtractKey(pncCurr->m_pvNode[iNode]);
  1127. if (pnKey == pnKey2 || _EqualKeys(pnKey, pnKey2))
  1128. {
  1129. *ppvRecord = pncCurr->m_pvNode[iNode];
  1130. lkrc = LK_SUCCESS;
  1131. // bump the reference count before handing the record
  1132. // back to the user. The user should decrement the
  1133. // reference count when finished with this record.
  1134. _AddRefRecord(*ppvRecord, +1);
  1135. goto exit;
  1136. }
  1137. }
  1138. }
  1139. exit:
  1140. pbkt->ReadUnlock();
  1141. #ifdef LKR_STL_ITERATORS
  1142. if (piterResult != NULL && lkrc == LK_SUCCESS)
  1143. {
  1144. piterResult->m_plht = const_cast<CLKRLinearHashTable*>(this);
  1145. piterResult->m_pnc = pncCurr;
  1146. piterResult->m_dwBucketAddr = dwBktAddr;
  1147. piterResult->m_iNode = (short) iNode;
  1148. }
  1149. #endif // LKR_STL_ITERATORS
  1150. return lkrc;
  1151. } // CLKRLinearHashTable::_FindKey
  1152. //------------------------------------------------------------------------
  1153. // Function: CLKRHashTable::FindKey
  1154. // Synopsis: Thin wrapper for the corresponding method in CLKRLinearHashTable
  1155. //------------------------------------------------------------------------
  1156. LK_RETCODE
  1157. CLKRHashTable::FindKey(
  1158. const DWORD_PTR pnKey,
  1159. const void** ppvRecord) const
  1160. {
  1161. if (!IsUsable())
  1162. return m_lkrcState;
  1163. if (ppvRecord == NULL)
  1164. return LK_BAD_RECORD;
  1165. LKRHASH_GLOBAL_READ_LOCK(); // usu. no-op
  1166. DWORD hash_val = _CalcKeyHash(pnKey);
  1167. SubTable* const pst = _SubTable(hash_val);
  1168. LK_RETCODE lkrc = pst->_FindKey(pnKey, hash_val, ppvRecord);
  1169. LKRHASH_GLOBAL_READ_UNLOCK(); // usu. no-op
  1170. return lkrc;
  1171. } // CLKRHashTable::FindKey
  1172. //------------------------------------------------------------------------
  1173. // Function: CLKRLinearHashTable::_FindRecord
  1174. // Synopsis: Sees if the record is contained in the table
  1175. // Returns: Pointer to the record, if it is found.
  1176. // NULL, if the record is not found.
  1177. // Returns: LK_SUCCESS, if record found
  1178. // LK_BAD_RECORD, if pvRecord is invalid
  1179. // LK_NO_SUCH_KEY, if the record was not found in the table
  1180. // LK_UNUSABLE, if hash table not in usable state
  1181. // Note: The record is *not* AddRef'd.
  1182. //------------------------------------------------------------------------
  1183. LK_RETCODE
  1184. CLKRLinearHashTable::_FindRecord(
  1185. const void* pvRecord, // Pointer to the record to find in the table
  1186. DWORD dwSignature // hash signature
  1187. ) const
  1188. {
  1189. IRTLASSERT(IsUsable() && pvRecord != NULL);
  1190. LK_RETCODE lkrc = LK_NO_SUCH_KEY;
  1191. // locate the beginning of the correct bucket chain
  1192. bool fReadLocked = _ReadOrWriteLock();
  1193. // Must call IsValid inside a lock to ensure that none of the state
  1194. // variables change while it's being evaluated
  1195. IRTLASSERT(IsValid());
  1196. CBucket* const pbkt = _FindBucket(dwSignature, false);
  1197. IRTLASSERT(pbkt != NULL);
  1198. IRTLASSERT(pbkt->IsReadLocked());
  1199. _ReadOrWriteUnlock(fReadLocked);
  1200. const DWORD_PTR pnKey = _ExtractKey(pvRecord);
  1201. UNREFERENCED_PARAMETER(pnKey);
  1202. IRTLASSERT(dwSignature == _CalcKeyHash(pnKey));
  1203. // walk down the bucket chain
  1204. for (CNodeClump* pncCurr = &pbkt->m_ncFirst;
  1205. pncCurr != NULL;
  1206. pncCurr = pncCurr->m_pncNext)
  1207. {
  1208. int i;
  1209. FOR_EACH_NODE(i)
  1210. {
  1211. if (pncCurr->IsEmptySlot(i))
  1212. {
  1213. IRTLASSERT(pncCurr->IsEmptyAndInvalid(i));
  1214. IRTLASSERT(0 == _IsNodeCompact(pbkt));
  1215. IRTLASSERT(pncCurr->IsLastClump());
  1216. goto exit;
  1217. }
  1218. if (pncCurr->m_pvNode[i] == pvRecord)
  1219. {
  1220. IRTLASSERT(dwSignature == pncCurr->m_dwKeySigs[i]);
  1221. IRTLASSERT(_EqualKeys(pnKey,
  1222. _ExtractKey(pncCurr->m_pvNode[i])));
  1223. lkrc = LK_SUCCESS;
  1224. goto exit;
  1225. }
  1226. }
  1227. }
  1228. exit:
  1229. pbkt->ReadUnlock();
  1230. return lkrc;
  1231. } // CLKRLinearHashTable::_FindRecord
  1232. //------------------------------------------------------------------------
  1233. // Function: CLKRHashTable::FindRecord
  1234. // Synopsis: Thin wrapper for the corresponding method in CLKRLinearHashTable
  1235. //------------------------------------------------------------------------
  1236. LK_RETCODE
  1237. CLKRHashTable::FindRecord(
  1238. const void* pvRecord) const
  1239. {
  1240. if (!IsUsable())
  1241. return m_lkrcState;
  1242. if (pvRecord == NULL)
  1243. return LK_BAD_RECORD;
  1244. LKRHASH_GLOBAL_READ_LOCK(); // usu. no-op
  1245. DWORD hash_val = _CalcKeyHash(_ExtractKey(pvRecord));
  1246. SubTable* const pst = _SubTable(hash_val);
  1247. LK_RETCODE lkrc = pst->_FindRecord(pvRecord, hash_val);
  1248. LKRHASH_GLOBAL_READ_UNLOCK(); // usu. no-op
  1249. return lkrc;
  1250. } // CLKRHashTable::FindRecord
  1251. #ifdef LKR_APPLY_IF
  1252. //------------------------------------------------------------------------
  1253. // Function: CLKRLinearHashTable::Apply
  1254. // Synopsis:
  1255. // Returns:
  1256. //------------------------------------------------------------------------
  1257. DWORD
  1258. CLKRLinearHashTable::Apply(
  1259. PFnRecordAction pfnAction,
  1260. void* pvState,
  1261. LK_LOCKTYPE lkl)
  1262. {
  1263. if (!IsUsable())
  1264. return static_cast<DWORD>(LK_UNUSABLE);
  1265. LK_PREDICATE lkp = LKP_PERFORM;
  1266. if (lkl == LKL_WRITELOCK)
  1267. WriteLock();
  1268. else
  1269. ReadLock();
  1270. // Must call IsValid inside a lock to ensure that none of the state
  1271. // variables change while it's being evaluated
  1272. IRTLASSERT(IsValid());
  1273. DWORD dw = _Apply(pfnAction, pvState, lkl, lkp);
  1274. if (lkl == LKL_WRITELOCK)
  1275. WriteUnlock();
  1276. else
  1277. ReadUnlock();
  1278. return dw;
  1279. } // CLKRLinearHashTable::Apply
  1280. //------------------------------------------------------------------------
  1281. // Function: CLKRHashTable::Apply
  1282. // Synopsis:
  1283. // Returns:
  1284. //------------------------------------------------------------------------
  1285. DWORD
  1286. CLKRHashTable::Apply(
  1287. PFnRecordAction pfnAction,
  1288. void* pvState,
  1289. LK_LOCKTYPE lkl)
  1290. {
  1291. if (!IsUsable())
  1292. return static_cast<DWORD>(LK_UNUSABLE);
  1293. DWORD dw = 0;
  1294. LK_PREDICATE lkp = LKP_PERFORM;
  1295. if (lkl == LKL_WRITELOCK)
  1296. WriteLock();
  1297. else
  1298. ReadLock();
  1299. // Must call IsValid inside a lock to ensure that none of the state
  1300. // variables change while it's being evaluated
  1301. IRTLASSERT(IsValid());
  1302. if (IsValid())
  1303. {
  1304. for (DWORD i = 0; i < m_cSubTables; i++)
  1305. {
  1306. dw += m_palhtDir[i]->_Apply(pfnAction, pvState, lkl, lkp);
  1307. if (lkp == LKP_ABORT || lkp == LKP_PERFORM_STOP
  1308. || lkp == LKP_DELETE_STOP)
  1309. break;
  1310. }
  1311. }
  1312. if (lkl == LKL_WRITELOCK)
  1313. WriteUnlock();
  1314. else
  1315. ReadUnlock();
  1316. return dw;
  1317. } // CLKRHashTable::Apply
  1318. //------------------------------------------------------------------------
  1319. // Function: CLKRLinearHashTable::ApplyIf
  1320. // Synopsis:
  1321. // Returns:
  1322. //------------------------------------------------------------------------
  1323. DWORD
  1324. CLKRLinearHashTable::ApplyIf(
  1325. PFnRecordPred pfnPredicate,
  1326. PFnRecordAction pfnAction,
  1327. void* pvState,
  1328. LK_LOCKTYPE lkl)
  1329. {
  1330. if (!IsUsable())
  1331. return static_cast<DWORD>(LK_UNUSABLE);
  1332. DWORD dw = 0;
  1333. LK_PREDICATE lkp = LKP_PERFORM;
  1334. if (lkl == LKL_WRITELOCK)
  1335. WriteLock();
  1336. else
  1337. ReadLock();
  1338. // Must call IsValid inside a lock to ensure that none of the state
  1339. // variables change while it's being evaluated
  1340. IRTLASSERT(IsValid());
  1341. if (IsValid())
  1342. {
  1343. dw = _ApplyIf(pfnPredicate, pfnAction, pvState, lkl, lkp);
  1344. }
  1345. if (lkl == LKL_WRITELOCK)
  1346. WriteUnlock();
  1347. else
  1348. ReadUnlock();
  1349. return dw;
  1350. } // CLKRLinearHashTable::ApplyIf
  1351. //------------------------------------------------------------------------
  1352. // Function: CLKRHashTable::ApplyIf
  1353. // Synopsis:
  1354. // Returns:
  1355. //------------------------------------------------------------------------
  1356. DWORD
  1357. CLKRHashTable::ApplyIf(
  1358. PFnRecordPred pfnPredicate,
  1359. PFnRecordAction pfnAction,
  1360. void* pvState,
  1361. LK_LOCKTYPE lkl)
  1362. {
  1363. if (!IsUsable())
  1364. return static_cast<DWORD>(LK_UNUSABLE);
  1365. DWORD dw = 0;
  1366. LK_PREDICATE lkp = LKP_PERFORM;
  1367. if (lkl == LKL_WRITELOCK)
  1368. WriteLock();
  1369. else
  1370. ReadLock();
  1371. // Must call IsValid inside a lock to ensure that none of the state
  1372. // variables change while it's being evaluated
  1373. IRTLASSERT(IsValid());
  1374. if (IsValid())
  1375. {
  1376. for (DWORD i = 0; i < m_cSubTables; i++)
  1377. {
  1378. dw += m_palhtDir[i]->_ApplyIf(pfnPredicate, pfnAction,
  1379. pvState, lkl, lkp);
  1380. if (lkp == LKP_ABORT || lkp == LKP_PERFORM_STOP
  1381. || lkp == LKP_DELETE_STOP)
  1382. break;
  1383. }
  1384. }
  1385. if (lkl == LKL_WRITELOCK)
  1386. WriteUnlock();
  1387. else
  1388. ReadUnlock();
  1389. return dw;
  1390. } // CLKRHashTable::ApplyIf
  1391. //------------------------------------------------------------------------
  1392. // Function: CLKRLinearHashTable::DeleteIf
  1393. // Synopsis:
  1394. // Returns:
  1395. //------------------------------------------------------------------------
  1396. DWORD
  1397. CLKRLinearHashTable::DeleteIf(
  1398. PFnRecordPred pfnPredicate,
  1399. void* pvState)
  1400. {
  1401. if (!IsUsable())
  1402. return static_cast<DWORD>(LK_UNUSABLE);
  1403. DWORD dw = 0;
  1404. LK_PREDICATE lkp = LKP_PERFORM;
  1405. WriteLock();
  1406. // Must call IsValid inside a lock to ensure that none of the state
  1407. // variables change while it's being evaluated
  1408. IRTLASSERT(IsValid());
  1409. if (IsValid())
  1410. dw = _DeleteIf(pfnPredicate, pvState, lkp);
  1411. WriteUnlock();
  1412. return dw;
  1413. } // CLKRLinearHashTable::DeleteIf
  1414. //------------------------------------------------------------------------
  1415. // Function: CLKRHashTable::DeleteIf
  1416. // Synopsis:
  1417. // Returns:
  1418. //------------------------------------------------------------------------
  1419. DWORD
  1420. CLKRHashTable::DeleteIf(
  1421. PFnRecordPred pfnPredicate,
  1422. void* pvState)
  1423. {
  1424. if (!IsUsable())
  1425. return static_cast<DWORD>(LK_UNUSABLE);
  1426. DWORD dw = 0;
  1427. LK_PREDICATE lkp = LKP_PERFORM;
  1428. WriteLock();
  1429. // Must call IsValid inside a lock to ensure that none of the state
  1430. // variables change while it's being evaluated
  1431. IRTLASSERT(IsValid());
  1432. if (IsValid())
  1433. {
  1434. for (DWORD i = 0; i < m_cSubTables; i++)
  1435. {
  1436. dw += m_palhtDir[i]->_DeleteIf(pfnPredicate, pvState, lkp);
  1437. if (lkp == LKP_ABORT || lkp == LKP_PERFORM_STOP
  1438. || lkp == LKP_DELETE_STOP)
  1439. break;
  1440. }
  1441. }
  1442. WriteUnlock();
  1443. return dw;
  1444. } // CLKRHashTable::DeleteIf
  1445. //------------------------------------------------------------------------
  1446. // Function: CLKRLinearHashTable::_Apply
  1447. // Synopsis:
  1448. // Returns:
  1449. //------------------------------------------------------------------------
  1450. DWORD
  1451. CLKRLinearHashTable::_Apply(
  1452. PFnRecordAction pfnAction,
  1453. void* pvState,
  1454. LK_LOCKTYPE lkl,
  1455. LK_PREDICATE& rlkp)
  1456. {
  1457. if (!IsUsable())
  1458. return static_cast<DWORD>(LK_UNUSABLE);
  1459. IRTLASSERT(lkl == LKL_WRITELOCK ? IsWriteLocked() : IsReadLocked());
  1460. return _ApplyIf(_PredTrue, pfnAction, pvState, lkl, rlkp);
  1461. } // CLKRLinearHashTable::_Apply
  1462. //------------------------------------------------------------------------
  1463. // Function: CLKRLinearHashTable::_ApplyIf
  1464. // Synopsis:
  1465. // Returns: Number of successful actions
  1466. //------------------------------------------------------------------------
  1467. DWORD
  1468. CLKRLinearHashTable::_ApplyIf(
  1469. PFnRecordPred pfnPredicate,
  1470. PFnRecordAction pfnAction,
  1471. void* pvState,
  1472. LK_LOCKTYPE lkl,
  1473. LK_PREDICATE& rlkp)
  1474. {
  1475. if (!IsUsable())
  1476. return static_cast<DWORD>(LK_UNUSABLE);
  1477. IRTLASSERT(lkl == LKL_WRITELOCK ? IsWriteLocked() : IsReadLocked());
  1478. IRTLASSERT(pfnPredicate != NULL && pfnAction != NULL);
  1479. if ((lkl == LKL_WRITELOCK ? !IsWriteLocked() : !IsReadLocked())
  1480. || pfnPredicate == NULL || pfnAction == NULL)
  1481. return 0;
  1482. DWORD cActions = 0;
  1483. for (DWORD iBkt = 0; iBkt < m_cActiveBuckets; ++iBkt)
  1484. {
  1485. CBucket* const pbkt = _Bucket(iBkt);
  1486. IRTLASSERT(pbkt != NULL);
  1487. if (lkl == LKL_WRITELOCK)
  1488. pbkt->WriteLock();
  1489. else
  1490. pbkt->ReadLock();
  1491. for (CNodeClump* pncCurr = &pbkt->m_ncFirst, *pncPrev = NULL;
  1492. pncCurr != NULL;
  1493. pncPrev = pncCurr, pncCurr = pncCurr->m_pncNext)
  1494. {
  1495. int i;
  1496. FOR_EACH_NODE(i)
  1497. {
  1498. if (pncCurr->IsEmptySlot(i))
  1499. {
  1500. IRTLASSERT(pncCurr->IsEmptyAndInvalid(i));
  1501. IRTLASSERT(0 == _IsNodeCompact(pbkt));
  1502. IRTLASSERT(pncCurr->IsLastClump());
  1503. goto unlock;
  1504. }
  1505. else
  1506. {
  1507. rlkp = (*pfnPredicate)(pncCurr->m_pvNode[i], pvState);
  1508. switch (rlkp)
  1509. {
  1510. case LKP_ABORT:
  1511. if (lkl == LKL_WRITELOCK)
  1512. pbkt->WriteUnlock();
  1513. else
  1514. pbkt->ReadUnlock();
  1515. return cActions;
  1516. break;
  1517. case LKP_NO_ACTION:
  1518. // nothing to do
  1519. break;
  1520. case LKP_DELETE:
  1521. case LKP_DELETE_STOP:
  1522. if (lkl != LKL_WRITELOCK)
  1523. {
  1524. pbkt->ReadUnlock();
  1525. return cActions;
  1526. }
  1527. // fall through
  1528. case LKP_PERFORM:
  1529. case LKP_PERFORM_STOP:
  1530. {
  1531. LK_ACTION lka;
  1532. if (rlkp == LKP_DELETE || rlkp == LKP_DELETE_STOP)
  1533. {
  1534. IRTLVERIFY(_DeleteNode(pbkt, pncCurr, pncPrev, i));
  1535. ++cActions;
  1536. lka = LKA_SUCCEEDED;
  1537. }
  1538. else
  1539. {
  1540. lka = (*pfnAction)(pncCurr->m_pvNode[i], pvState);
  1541. switch (lka)
  1542. {
  1543. case LKA_ABORT:
  1544. if (lkl == LKL_WRITELOCK)
  1545. pbkt->WriteUnlock();
  1546. else
  1547. pbkt->ReadUnlock();
  1548. return cActions;
  1549. case LKA_FAILED:
  1550. // nothing to do
  1551. break;
  1552. case LKA_SUCCEEDED:
  1553. ++cActions;
  1554. break;
  1555. default:
  1556. IRTLASSERT(! "Unknown LK_ACTION in ApplyIf");
  1557. break;
  1558. }
  1559. }
  1560. if (rlkp == LKP_PERFORM_STOP
  1561. || rlkp == LKP_DELETE_STOP)
  1562. {
  1563. if (lkl == LKL_WRITELOCK)
  1564. pbkt->WriteUnlock();
  1565. else
  1566. pbkt->ReadUnlock();
  1567. return cActions;
  1568. }
  1569. break;
  1570. }
  1571. default:
  1572. IRTLASSERT(! "Unknown LK_PREDICATE in ApplyIf");
  1573. break;
  1574. }
  1575. }
  1576. }
  1577. }
  1578. unlock:
  1579. if (lkl == LKL_WRITELOCK)
  1580. pbkt->WriteUnlock();
  1581. else
  1582. pbkt->ReadUnlock();
  1583. }
  1584. return cActions;
  1585. } // CLKRLinearHashTable::_ApplyIf
  1586. //------------------------------------------------------------------------
  1587. // Function: CLKRLinearHashTable::_DeleteIf
  1588. // Synopsis: Deletes all records that match the predicate
  1589. // Returns: Count of successful deletions
  1590. //------------------------------------------------------------------------
  1591. DWORD
  1592. CLKRLinearHashTable::_DeleteIf(
  1593. PFnRecordPred pfnPredicate,
  1594. void* pvState,
  1595. LK_PREDICATE& rlkp)
  1596. {
  1597. if (!IsUsable())
  1598. return static_cast<DWORD>(LK_UNUSABLE);
  1599. IRTLASSERT(IsWriteLocked());
  1600. IRTLASSERT(pfnPredicate != NULL);
  1601. if (!IsWriteLocked() || pfnPredicate == NULL)
  1602. return 0;
  1603. DWORD cActions = 0;
  1604. for (DWORD iBkt = 0; iBkt < m_cActiveBuckets; ++iBkt)
  1605. {
  1606. CBucket* const pbkt = _Bucket(iBkt);
  1607. IRTLASSERT(pbkt != NULL);
  1608. pbkt->WriteLock();
  1609. for (CNodeClump* pncCurr = &pbkt->m_ncFirst, *pncPrev = NULL;
  1610. pncCurr != NULL;
  1611. pncPrev = pncCurr, pncCurr = pncCurr->m_pncNext)
  1612. {
  1613. int i;
  1614. FOR_EACH_NODE(i)
  1615. {
  1616. if (pncCurr->IsEmptySlot(i))
  1617. {
  1618. IRTLASSERT(pncCurr->IsEmptyAndInvalid(i));
  1619. IRTLASSERT(0 == _IsNodeCompact(pbkt));
  1620. IRTLASSERT(pncCurr->IsLastClump());
  1621. goto unlock;
  1622. }
  1623. else
  1624. {
  1625. rlkp = (*pfnPredicate)(pncCurr->m_pvNode[i], pvState);
  1626. switch (rlkp)
  1627. {
  1628. case LKP_ABORT:
  1629. pbkt->WriteUnlock();
  1630. return cActions;
  1631. break;
  1632. case LKP_NO_ACTION:
  1633. // nothing to do
  1634. break;
  1635. case LKP_PERFORM:
  1636. case LKP_PERFORM_STOP:
  1637. case LKP_DELETE:
  1638. case LKP_DELETE_STOP:
  1639. {
  1640. IRTLVERIFY(_DeleteNode(pbkt, pncCurr, pncPrev, i));
  1641. ++cActions;
  1642. if (rlkp == LKP_PERFORM_STOP
  1643. || rlkp == LKP_DELETE_STOP)
  1644. {
  1645. pbkt->WriteUnlock();
  1646. return cActions;
  1647. }
  1648. break;
  1649. }
  1650. default:
  1651. IRTLASSERT(! "Unknown LK_PREDICATE in DeleteIf");
  1652. break;
  1653. }
  1654. }
  1655. }
  1656. }
  1657. unlock:
  1658. pbkt->WriteUnlock();
  1659. }
  1660. return cActions;
  1661. } // CLKRLinearHashTable::_DeleteIf
  1662. #endif // LKR_APPLY_IF
  1663. //------------------------------------------------------------------------
  1664. // Function: CLKRLinearHashTable::CheckTable
  1665. // Synopsis: Verify that all records are in the right place and can be located.
  1666. // Returns: 0 => hash table is consistent
  1667. // >0 => that many misplaced records
  1668. // <0 => otherwise invalid
  1669. //------------------------------------------------------------------------
  1670. int
  1671. CLKRLinearHashTable::CheckTable() const
  1672. {
  1673. if (!IsUsable())
  1674. return LK_UNUSABLE;
  1675. bool fReadLocked = _ReadOrWriteLock();
  1676. // Must call IsValid inside a lock to ensure that none of the state
  1677. // variables change while it's being evaluated
  1678. IRTLASSERT(IsValid());
  1679. if (!IsValid())
  1680. {
  1681. _ReadOrWriteUnlock(fReadLocked);
  1682. return LK_UNUSABLE;
  1683. }
  1684. int cMisplaced = 0;
  1685. DWORD cRecords = 0;
  1686. int retcode = 0;
  1687. // Check every bucket
  1688. for (DWORD i = 0; i < m_cActiveBuckets; i++)
  1689. {
  1690. CBucket* const pbkt = _Bucket(i);
  1691. IRTLASSERT(pbkt != NULL);
  1692. retcode += !(pbkt != NULL);
  1693. pbkt->ReadLock();
  1694. IRTLASSERT(0 == _IsNodeCompact(pbkt));
  1695. // Walk the bucket chain
  1696. for (CNodeClump* pncCurr = &pbkt->m_ncFirst, *pncPrev = NULL;
  1697. pncCurr != NULL;
  1698. pncPrev = pncCurr, pncCurr = pncCurr->m_pncNext)
  1699. {
  1700. int j;
  1701. FOR_EACH_NODE(j)
  1702. {
  1703. if (pncCurr->IsEmptySlot(j))
  1704. {
  1705. IRTLASSERT(pncCurr->IsLastClump());
  1706. retcode += !(pncCurr->IsLastClump());
  1707. for (int k = j; k != NODE_END; k += NODE_STEP)
  1708. {
  1709. IRTLASSERT(pncCurr->IsEmptyNode(k));
  1710. retcode += !pncCurr->IsEmptyNode(k);
  1711. IRTLASSERT(pncCurr->InvalidSignature(k));
  1712. retcode += !pncCurr->InvalidSignature(k);
  1713. }
  1714. break;
  1715. }
  1716. if (!pncCurr->IsEmptySlot(j))
  1717. {
  1718. ++cRecords;
  1719. const DWORD_PTR pnKey = _ExtractKey(pncCurr->m_pvNode[j]);
  1720. DWORD dwSignature = _CalcKeyHash(pnKey);
  1721. IRTLASSERT(dwSignature != HASH_INVALID_SIGNATURE);
  1722. retcode += !(dwSignature != HASH_INVALID_SIGNATURE);
  1723. IRTLASSERT(dwSignature == pncCurr->m_dwKeySigs[j]);
  1724. retcode += !(dwSignature == pncCurr->m_dwKeySigs[j]);
  1725. DWORD address = _BucketAddress(dwSignature);
  1726. IRTLASSERT(address == i);
  1727. retcode += !(address == i);
  1728. if (address != i || dwSignature != pncCurr->m_dwKeySigs[j])
  1729. cMisplaced++;
  1730. }
  1731. else // pncCurr->IsEmptySlot(j)
  1732. {
  1733. IRTLASSERT(pncCurr->IsEmptyAndInvalid(j));
  1734. retcode += !pncCurr->IsEmptyAndInvalid(j);
  1735. }
  1736. }
  1737. if (pncPrev != NULL)
  1738. {
  1739. IRTLASSERT(pncPrev->m_pncNext == pncCurr);
  1740. retcode += !(pncPrev->m_pncNext == pncCurr);
  1741. }
  1742. }
  1743. pbkt->ReadUnlock();
  1744. }
  1745. if (cRecords != m_cRecords)
  1746. ++retcode;
  1747. IRTLASSERT(cRecords == m_cRecords);
  1748. retcode += !(cRecords == m_cRecords);
  1749. if (cMisplaced > 0)
  1750. retcode = cMisplaced;
  1751. IRTLASSERT(cMisplaced == 0);
  1752. retcode += !(cMisplaced == 0);
  1753. _ReadOrWriteUnlock(fReadLocked);
  1754. return retcode;
  1755. } // CLKRLinearHashTable::CheckTable
  1756. //------------------------------------------------------------------------
  1757. // Function: CLKRHashTable::CheckTable
  1758. // Synopsis: Verify that all records are in the right place and can be located.
  1759. // Returns: 0 => hash table is consistent
  1760. // >0 => that many misplaced records
  1761. // <0 => otherwise invalid
  1762. //------------------------------------------------------------------------
  1763. int
  1764. CLKRHashTable::CheckTable() const
  1765. {
  1766. if (!IsUsable())
  1767. return LK_UNUSABLE;
  1768. int retcode = 0;
  1769. for (DWORD i = 0; i < m_cSubTables; i++)
  1770. retcode += m_palhtDir[i]->CheckTable();
  1771. return retcode;
  1772. } // CLKRHashTable::CheckTable
  1773. //------------------------------------------------------------------------
  1774. // Function: CLKRLinearHashTable::_Clear
  1775. // Synopsis: Remove all data from the table
  1776. //------------------------------------------------------------------------
  1777. void
  1778. CLKRLinearHashTable::_Clear(
  1779. bool fShrinkDirectory) // Shrink to min size but don't destroy entirely?
  1780. {
  1781. if (!IsUsable())
  1782. return;
  1783. IRTLASSERT(IsWriteLocked());
  1784. // If we're Clear()ing the table AND the table has no records, we
  1785. // can return immediately. The dtor, however, must clean up completely.
  1786. if (fShrinkDirectory && 0 == m_cRecords)
  1787. return;
  1788. #ifdef IRTLDEBUG
  1789. DWORD cDeleted = 0;
  1790. DWORD cOldRecords = m_cRecords;
  1791. #endif // IRTLDEBUG
  1792. for (DWORD iBkt = 0; iBkt < m_cActiveBuckets; ++iBkt)
  1793. {
  1794. CBucket* const pbkt = _Bucket(iBkt);
  1795. IRTLASSERT(pbkt != NULL);
  1796. pbkt->WriteLock();
  1797. IRTLASSERT(0 == _IsNodeCompact(pbkt));
  1798. for (CNodeClump* pncCurr = &pbkt->m_ncFirst, *pncPrev = NULL;
  1799. pncCurr != NULL;
  1800. )
  1801. {
  1802. int i;
  1803. FOR_EACH_NODE(i)
  1804. {
  1805. if (pncCurr->IsEmptySlot(i))
  1806. {
  1807. IRTLASSERT(pncCurr->IsEmptyAndInvalid(i));
  1808. IRTLASSERT(pncCurr->IsLastClump());
  1809. break;
  1810. }
  1811. else
  1812. {
  1813. _AddRefRecord(pncCurr->m_pvNode[i], -1);
  1814. pncCurr->m_pvNode[i] = NULL;
  1815. pncCurr->m_dwKeySigs[i] = HASH_INVALID_SIGNATURE;
  1816. m_cRecords--;
  1817. #ifdef IRTLDEBUG
  1818. ++cDeleted;
  1819. #endif // IRTLDEBUG
  1820. }
  1821. } // for (i ...
  1822. pncPrev = pncCurr;
  1823. pncCurr = pncCurr->m_pncNext;
  1824. pncPrev->m_pncNext = NULL;
  1825. if (pncPrev != &pbkt->m_ncFirst)
  1826. _FreeNodeClump(pncPrev);
  1827. } // for (pncCurr ...
  1828. pbkt->WriteUnlock();
  1829. } // for (iBkt ...
  1830. IRTLASSERT(m_cRecords == 0 && cDeleted == cOldRecords);
  1831. // delete all segments
  1832. for (DWORD iSeg = 0; iSeg < m_cActiveBuckets; iSeg += m_dwSegSize)
  1833. {
  1834. _FreeSegment(_Segment(iSeg));
  1835. _Segment(iSeg) = NULL;
  1836. }
  1837. _FreeSegmentDirectory();
  1838. m_nLevel = m_cActiveBuckets = m_iExpansionIdx = 0;
  1839. m_dwBktAddrMask0 = 1;
  1840. m_dwBktAddrMask1 = (m_dwBktAddrMask0 << 1) | 1;
  1841. // set directory of segments to minimum size
  1842. if (fShrinkDirectory)
  1843. {
  1844. DWORD cInitialBuckets = 0;
  1845. if (LK_SMALL_TABLESIZE == m_lkts)
  1846. cInitialBuckets = CSmallSegment::INITSIZE;
  1847. else if (LK_MEDIUM_TABLESIZE == m_lkts)
  1848. cInitialBuckets = CMediumSegment::INITSIZE;
  1849. else if (LK_LARGE_TABLESIZE == m_lkts)
  1850. cInitialBuckets = CLargeSegment::INITSIZE;
  1851. else
  1852. IRTLASSERT(! "Unknown LK_TABLESIZE");
  1853. _SetSegVars(m_lkts, cInitialBuckets);
  1854. }
  1855. } // CLKRLinearHashTable::_Clear
  1856. //------------------------------------------------------------------------
  1857. // Function: CLKRHashTable::Clear
  1858. // Synopsis: Remove all data from the table
  1859. //------------------------------------------------------------------------
  1860. void
  1861. CLKRHashTable::Clear()
  1862. {
  1863. WriteLock();
  1864. for (DWORD i = 0; i < m_cSubTables; i++)
  1865. m_palhtDir[i]->_Clear(true);
  1866. WriteUnlock();
  1867. } // CLKRHashTable::Clear
  1868. //------------------------------------------------------------------------
  1869. // Function: CLKRLinearHashTable::GetStatistics
  1870. // Synopsis: Gather statistics about the table
  1871. //------------------------------------------------------------------------
  1872. CLKRHashTableStats
  1873. CLKRLinearHashTable::GetStatistics() const
  1874. {
  1875. CLKRHashTableStats stats;
  1876. if (!IsUsable())
  1877. return stats;
  1878. if (m_paDirSegs != NULL)
  1879. {
  1880. stats.RecordCount = m_cRecords;
  1881. stats.TableSize = m_cActiveBuckets;
  1882. stats.SplitFactor = static_cast<double>(m_iExpansionIdx)
  1883. / (1ui64 << m_nLevel);
  1884. stats.DirectorySize = m_cDirSegs;
  1885. stats.NodeClumpSize = NODES_PER_CLUMP;
  1886. stats.CBucketSize = sizeof(CBucket);
  1887. #ifdef LOCK_INSTRUMENTATION
  1888. stats.m_alsBucketsAvg.m_nContentions = 0;
  1889. stats.m_alsBucketsAvg.m_nSleeps = 0;
  1890. stats.m_alsBucketsAvg.m_nContentionSpins = 0;
  1891. stats.m_alsBucketsAvg.m_nAverageSpins = 0;
  1892. stats.m_alsBucketsAvg.m_nReadLocks = 0;
  1893. stats.m_alsBucketsAvg.m_nWriteLocks = 0;
  1894. stats.m_alsBucketsAvg.m_nItems = 0;
  1895. #endif // LOCK_INSTRUMENTATION
  1896. int empty = 0;
  1897. int totacc = 0;
  1898. int low_count = 0;
  1899. int high_count = 0;
  1900. int max_length = 0;
  1901. for (DWORD i = 0; i < m_cActiveBuckets; i++)
  1902. {
  1903. int acc = 0;
  1904. for (CNodeClump* pncCurr = &_Bucket(i)->m_ncFirst;
  1905. pncCurr != NULL;
  1906. pncCurr = pncCurr->m_pncNext)
  1907. {
  1908. int j;
  1909. FOR_EACH_NODE(j)
  1910. {
  1911. if (!pncCurr->IsEmptySlot(j))
  1912. {
  1913. acc++;
  1914. totacc += acc;
  1915. int iBucketIndex = stats.BucketIndex(acc);
  1916. ++stats.m_aBucketLenHistogram[iBucketIndex];
  1917. }
  1918. }
  1919. }
  1920. #ifdef LOCK_INSTRUMENTATION
  1921. CLockStatistics ls = _Bucket(i)->LockStats();
  1922. stats.m_alsBucketsAvg.m_nContentions += ls.m_nContentions;
  1923. stats.m_alsBucketsAvg.m_nSleeps += ls.m_nSleeps;
  1924. stats.m_alsBucketsAvg.m_nContentionSpins += ls.m_nContentionSpins;
  1925. stats.m_alsBucketsAvg.m_nAverageSpins += ls.m_nAverageSpins;
  1926. stats.m_alsBucketsAvg.m_nReadLocks += ls.m_nReadLocks;
  1927. stats.m_alsBucketsAvg.m_nWriteLocks += ls.m_nWriteLocks;
  1928. stats.m_alsBucketsAvg.m_nItems ++;
  1929. #endif // LOCK_INSTRUMENTATION
  1930. max_length = max(max_length, acc);
  1931. if (acc == 0)
  1932. empty++;
  1933. if (_H0(i) < m_iExpansionIdx)
  1934. {
  1935. low_count += acc;
  1936. }
  1937. else
  1938. {
  1939. high_count += acc;
  1940. }
  1941. }
  1942. stats.LongestChain = max_length;
  1943. stats.EmptySlots = empty;
  1944. if (m_cActiveBuckets > 0)
  1945. {
  1946. if (m_cRecords > 0)
  1947. {
  1948. double x=static_cast<double>(m_iExpansionIdx) /(1ui64 << m_nLevel);
  1949. double alpha= static_cast<double>(m_cRecords)/m_cActiveBuckets;
  1950. double low_sl = 0.0;
  1951. double high_sl = 0.0;
  1952. stats.AvgSearchLength= static_cast<double>(totacc) /m_cRecords;
  1953. stats.ExpSearchLength = 1 + alpha * 0.25 * (2 + x - x*x);
  1954. if (m_iExpansionIdx > 0)
  1955. low_sl = static_cast<double>(low_count)
  1956. / (2.0 * m_iExpansionIdx);
  1957. if (m_cActiveBuckets - 2 * m_iExpansionIdx > 0)
  1958. high_sl = static_cast<double>(high_count)
  1959. / (m_cActiveBuckets - 2.0 * m_iExpansionIdx);
  1960. stats.AvgUSearchLength = low_sl * x + high_sl * (1.0 - x);
  1961. stats.ExpUSearchLength = alpha * 0.5 * (2 + x - x*x);
  1962. }
  1963. #ifdef LOCK_INSTRUMENTATION
  1964. stats.m_alsBucketsAvg.m_nContentions /= m_cActiveBuckets;
  1965. stats.m_alsBucketsAvg.m_nSleeps /= m_cActiveBuckets;
  1966. stats.m_alsBucketsAvg.m_nContentionSpins /= m_cActiveBuckets;
  1967. stats.m_alsBucketsAvg.m_nAverageSpins /= m_cActiveBuckets;
  1968. stats.m_alsBucketsAvg.m_nReadLocks /= m_cActiveBuckets;
  1969. stats.m_alsBucketsAvg.m_nWriteLocks /= m_cActiveBuckets;
  1970. #endif // LOCK_INSTRUMENTATION
  1971. }
  1972. else
  1973. {
  1974. stats.AvgSearchLength = 0.0;
  1975. stats.ExpSearchLength = 0.0;
  1976. stats.AvgUSearchLength = 0.0;
  1977. stats.ExpUSearchLength = 0.0;
  1978. }
  1979. }
  1980. #ifdef LOCK_INSTRUMENTATION
  1981. stats.m_gls = TableLock::GlobalStatistics();
  1982. CLockStatistics ls = _LockStats();
  1983. stats.m_alsTable.m_nContentions = ls.m_nContentions;
  1984. stats.m_alsTable.m_nSleeps = ls.m_nSleeps;
  1985. stats.m_alsTable.m_nContentionSpins = ls.m_nContentionSpins;
  1986. stats.m_alsTable.m_nAverageSpins = ls.m_nAverageSpins;
  1987. stats.m_alsTable.m_nReadLocks = ls.m_nReadLocks;
  1988. stats.m_alsTable.m_nWriteLocks = ls.m_nWriteLocks;
  1989. stats.m_alsTable.m_nItems = 1;
  1990. #endif // LOCK_INSTRUMENTATION
  1991. return stats;
  1992. } // CLKRLinearHashTable::GetStatistics
  1993. //------------------------------------------------------------------------
  1994. // Function: CLKRHashTable::GetStatistics
  1995. // Synopsis: Gather statistics about the table
  1996. //------------------------------------------------------------------------
  1997. CLKRHashTableStats
  1998. CLKRHashTable::GetStatistics() const
  1999. {
  2000. CLKRHashTableStats hts;
  2001. if (!IsUsable())
  2002. return hts;
  2003. for (DWORD i = 0; i < m_cSubTables; i++)
  2004. {
  2005. CLKRHashTableStats stats = m_palhtDir[i]->GetStatistics();
  2006. hts.RecordCount += stats.RecordCount;
  2007. hts.TableSize += stats.TableSize;
  2008. hts.DirectorySize += stats.DirectorySize;
  2009. hts.LongestChain = max(hts.LongestChain, stats.LongestChain);
  2010. hts.EmptySlots += stats.EmptySlots;
  2011. hts.SplitFactor += stats.SplitFactor;
  2012. hts.AvgSearchLength += stats.AvgSearchLength;
  2013. hts.ExpSearchLength += stats.ExpSearchLength;
  2014. hts.AvgUSearchLength += stats.AvgUSearchLength;
  2015. hts.ExpUSearchLength += stats.ExpUSearchLength;
  2016. hts.NodeClumpSize = stats.NodeClumpSize;
  2017. hts.CBucketSize = stats.CBucketSize;
  2018. for (int j = 0; j < CLKRHashTableStats::MAX_BUCKETS; ++j)
  2019. hts.m_aBucketLenHistogram[j] += stats.m_aBucketLenHistogram[j];
  2020. #ifdef LOCK_INSTRUMENTATION
  2021. hts.m_alsTable.m_nContentions += stats.m_alsTable.m_nContentions;
  2022. hts.m_alsTable.m_nSleeps += stats.m_alsTable.m_nSleeps;
  2023. hts.m_alsTable.m_nContentionSpins
  2024. += stats.m_alsTable.m_nContentionSpins;
  2025. hts.m_alsTable.m_nAverageSpins += stats.m_alsTable.m_nAverageSpins;
  2026. hts.m_alsTable.m_nReadLocks += stats.m_alsTable.m_nReadLocks;
  2027. hts.m_alsTable.m_nWriteLocks += stats.m_alsTable.m_nWriteLocks;
  2028. hts.m_alsBucketsAvg.m_nContentions
  2029. += stats.m_alsBucketsAvg.m_nContentions;
  2030. hts.m_alsBucketsAvg.m_nSleeps
  2031. += stats.m_alsBucketsAvg.m_nSleeps;
  2032. hts.m_alsBucketsAvg.m_nContentionSpins
  2033. += stats.m_alsBucketsAvg.m_nContentionSpins;
  2034. hts.m_alsBucketsAvg.m_nAverageSpins
  2035. += stats.m_alsBucketsAvg.m_nAverageSpins;
  2036. hts.m_alsBucketsAvg.m_nReadLocks
  2037. += stats.m_alsBucketsAvg.m_nReadLocks;
  2038. hts.m_alsBucketsAvg.m_nWriteLocks
  2039. += stats.m_alsBucketsAvg.m_nWriteLocks;
  2040. hts.m_alsBucketsAvg.m_nItems
  2041. += stats.m_alsBucketsAvg.m_nItems;
  2042. hts.m_gls = stats.m_gls;
  2043. #endif // LOCK_INSTRUMENTATION
  2044. }
  2045. // Average out the subtables statistics. (Does this make sense
  2046. // for all of these fields?)
  2047. hts.DirectorySize /= m_cSubTables;
  2048. hts.SplitFactor /= m_cSubTables;
  2049. hts.AvgSearchLength /= m_cSubTables;
  2050. hts.ExpSearchLength /= m_cSubTables;
  2051. hts.AvgUSearchLength /= m_cSubTables;
  2052. hts.ExpUSearchLength /= m_cSubTables;
  2053. #ifdef LOCK_INSTRUMENTATION
  2054. hts.m_alsTable.m_nContentions /= m_cSubTables;
  2055. hts.m_alsTable.m_nSleeps /= m_cSubTables;
  2056. hts.m_alsTable.m_nContentionSpins /= m_cSubTables;
  2057. hts.m_alsTable.m_nAverageSpins /= m_cSubTables;
  2058. hts.m_alsTable.m_nReadLocks /= m_cSubTables;
  2059. hts.m_alsTable.m_nWriteLocks /= m_cSubTables;
  2060. hts.m_alsTable.m_nItems = m_cSubTables;
  2061. hts.m_alsBucketsAvg.m_nContentions /= m_cSubTables;
  2062. hts.m_alsBucketsAvg.m_nSleeps /= m_cSubTables;
  2063. hts.m_alsBucketsAvg.m_nContentionSpins /= m_cSubTables;
  2064. hts.m_alsBucketsAvg.m_nAverageSpins /= m_cSubTables;
  2065. hts.m_alsBucketsAvg.m_nReadLocks /= m_cSubTables;
  2066. hts.m_alsBucketsAvg.m_nWriteLocks /= m_cSubTables;
  2067. #endif // LOCK_INSTRUMENTATION
  2068. return hts;
  2069. } // CLKRHashTable::GetStatistics
  2070. //-----------------------------------------------------------------------
  2071. // Function: CLKRLinearHashTable::_SetSegVars
  2072. // Synopsis: sets the size-specific segment variables
  2073. //-----------------------------------------------------------------------
  2074. LK_RETCODE
  2075. CLKRLinearHashTable::_SetSegVars(
  2076. LK_TABLESIZE lkts,
  2077. DWORD cInitialBuckets)
  2078. {
  2079. switch (lkts)
  2080. {
  2081. case LK_SMALL_TABLESIZE:
  2082. {
  2083. m_lkts = LK_SMALL_TABLESIZE;
  2084. m_dwSegBits = CSmallSegment::SEGBITS;
  2085. m_dwSegSize = CSmallSegment::SEGSIZE;
  2086. m_dwSegMask = CSmallSegment::SEGMASK;
  2087. STATIC_ASSERT(CSmallSegment::SEGSIZE == (1U<<CSmallSegment::SEGBITS));
  2088. STATIC_ASSERT(CSmallSegment::SEGMASK == (CSmallSegment::SEGSIZE-1));
  2089. break;
  2090. }
  2091. default:
  2092. IRTLASSERT(! "Unknown LK_TABLESIZE");
  2093. // fall-through
  2094. case LK_MEDIUM_TABLESIZE:
  2095. {
  2096. m_lkts = LK_MEDIUM_TABLESIZE;
  2097. m_dwSegBits = CMediumSegment::SEGBITS;
  2098. m_dwSegSize = CMediumSegment::SEGSIZE;
  2099. m_dwSegMask = CMediumSegment::SEGMASK;
  2100. STATIC_ASSERT(CMediumSegment::SEGSIZE ==(1U<<CMediumSegment::SEGBITS));
  2101. STATIC_ASSERT(CMediumSegment::SEGMASK == (CMediumSegment::SEGSIZE-1));
  2102. break;
  2103. }
  2104. case LK_LARGE_TABLESIZE:
  2105. {
  2106. m_lkts = LK_LARGE_TABLESIZE;
  2107. m_dwSegBits = CLargeSegment::SEGBITS;
  2108. m_dwSegSize = CLargeSegment::SEGSIZE;
  2109. m_dwSegMask = CLargeSegment::SEGMASK;
  2110. STATIC_ASSERT(CLargeSegment::SEGSIZE == (1U<<CLargeSegment::SEGBITS));
  2111. STATIC_ASSERT(CLargeSegment::SEGMASK == (CLargeSegment::SEGSIZE-1));
  2112. break;
  2113. }
  2114. }
  2115. m_dwBktAddrMask0 = m_dwSegMask;
  2116. m_dwBktAddrMask1 = (m_dwBktAddrMask0 << 1) | 1;
  2117. m_nLevel = m_dwSegBits;
  2118. m_cActiveBuckets = cInitialBuckets;
  2119. IRTLASSERT(m_cActiveBuckets > 0);
  2120. IRTLASSERT(m_nLevel == m_dwSegBits);
  2121. IRTLASSERT(m_dwBktAddrMask0 == (1U << m_nLevel) - 1);
  2122. IRTLASSERT(m_dwBktAddrMask1 == ((m_dwBktAddrMask0 << 1) | 1));
  2123. IRTLASSERT(m_dwSegBits > 0);
  2124. IRTLASSERT(m_dwSegSize == (1U << m_dwSegBits));
  2125. IRTLASSERT(m_dwSegMask == (m_dwSegSize - 1));
  2126. IRTLASSERT(m_dwBktAddrMask0 == m_dwSegMask);
  2127. // adjust m_dwBktAddrMask0 (== m_dwSegMask) to make it large
  2128. // enough to distribute the buckets across the address space
  2129. for (DWORD tmp = m_cActiveBuckets >> m_dwSegBits; tmp > 1; tmp >>= 1)
  2130. {
  2131. ++m_nLevel;
  2132. m_dwBktAddrMask0 = (m_dwBktAddrMask0 << 1) | 1;
  2133. }
  2134. m_dwBktAddrMask1 = (m_dwBktAddrMask0 << 1) | 1;
  2135. IRTLASSERT(_H1(m_cActiveBuckets) == m_cActiveBuckets);
  2136. m_iExpansionIdx = m_cActiveBuckets & m_dwBktAddrMask0;
  2137. // create and clear directory of segments
  2138. DWORD cDirSegs = MIN_DIRSIZE;
  2139. while (cDirSegs < (m_cActiveBuckets >> m_dwSegBits))
  2140. cDirSegs <<= 1;
  2141. cDirSegs = min(cDirSegs, MAX_DIRSIZE);
  2142. IRTLASSERT((cDirSegs << m_dwSegBits) >= m_cActiveBuckets);
  2143. m_lkrcState = LK_ALLOC_FAIL;
  2144. m_paDirSegs = _AllocateSegmentDirectory(cDirSegs);
  2145. if (m_paDirSegs != NULL)
  2146. {
  2147. m_cDirSegs = cDirSegs;
  2148. IRTLASSERT(m_cDirSegs >= MIN_DIRSIZE
  2149. && (m_cDirSegs & (m_cDirSegs-1)) == 0); // == (1 << N)
  2150. // create and initialize only the required segments
  2151. DWORD dwMaxSegs = (m_cActiveBuckets + m_dwSegSize - 1) >> m_dwSegBits;
  2152. IRTLASSERT(dwMaxSegs <= m_cDirSegs);
  2153. IRTLTRACE(TEXT("InitSegDir: m_lkts = %d, m_cActiveBuckets = %lu, ")
  2154. TEXT("m_dwSegSize = %lu, bits = %lu\n")
  2155. TEXT("m_cDirSegs = %lu, dwMaxSegs = %lu, ")
  2156. TEXT("segment total size = %lu bytes\n"),
  2157. m_lkts, m_cActiveBuckets,
  2158. m_dwSegSize, m_dwSegBits,
  2159. m_cDirSegs, dwMaxSegs,
  2160. m_dwSegSize * sizeof(CBucket));
  2161. m_lkrcState = LK_SUCCESS; // so IsValid/IsUsable won't fail
  2162. for (DWORD i = 0; i < dwMaxSegs; i++)
  2163. {
  2164. CSegment* pSeg = _AllocateSegment();
  2165. if (pSeg != NULL)
  2166. m_paDirSegs[i].m_pseg = pSeg;
  2167. else
  2168. {
  2169. // problem: deallocate everything
  2170. m_lkrcState = LK_ALLOC_FAIL;
  2171. for (DWORD j = i; j-- > 0; )
  2172. {
  2173. _FreeSegment(m_paDirSegs[j].m_pseg);
  2174. m_paDirSegs[j].m_pseg = NULL;
  2175. }
  2176. _FreeSegmentDirectory();
  2177. break;
  2178. }
  2179. }
  2180. }
  2181. if (m_lkrcState != LK_SUCCESS)
  2182. {
  2183. m_paDirSegs = NULL;
  2184. m_cDirSegs = m_cActiveBuckets = m_iExpansionIdx = 0;
  2185. // Propagate error back up to parent (if it exists). This ensures
  2186. // that all of the parent's public methods will start failing.
  2187. if (NULL != m_phtParent)
  2188. m_phtParent->m_lkrcState = m_lkrcState;
  2189. }
  2190. return m_lkrcState;
  2191. } // CLKRLinearHashTable::_SetSegVars
  2192. #include <stdlib.h>
  2193. LONG g_cAllocDirEntry = 0;
  2194. LONG g_cAllocNodeClump = 0;
  2195. LONG g_cAllocSmallSegment = 0;
  2196. LONG g_cAllocMediumSegment = 0;
  2197. LONG g_cAllocLargeSegment = 0;
  2198. extern "C"
  2199. __declspec(dllexport)
  2200. bool
  2201. GetAllocCounters()
  2202. {
  2203. return true;
  2204. }
  2205. // #define LKR_RANDOM_MEMORY_FAILURES 1000 // 1..RAND_MAX (32767)
  2206. // Memory allocation wrappers to allow us to simulate allocation
  2207. // failures during testing
  2208. //------------------------------------------------------------------------
  2209. // Function: CLKRLinearHashTable::_AllocateSegmentDirectory
  2210. // Synopsis:
  2211. //------------------------------------------------------------------------
  2212. CDirEntry* const
  2213. CLKRLinearHashTable::_AllocateSegmentDirectory(
  2214. size_t n)
  2215. {
  2216. #ifdef LKR_RANDOM_MEMORY_FAILURES
  2217. if (rand() < LKR_RANDOM_MEMORY_FAILURES)
  2218. return NULL;
  2219. #endif // LKR_RANDOM_MEMORY_FAILURES
  2220. // InterlockedIncrement(&g_cAllocDirEntry);
  2221. CDirEntry* const paDirSegs = new CDirEntry [n];
  2222. #ifdef IRTLDEBUG
  2223. for (size_t i = 0; i < n; ++i)
  2224. IRTLASSERT(paDirSegs[i].m_pseg == NULL);
  2225. #endif // IRTLDEBUG
  2226. return paDirSegs;
  2227. } // CLKRLinearHashTable::_AllocateSegmentDirectory
  2228. //------------------------------------------------------------------------
  2229. // Function: CLKRLinearHashTable::_FreeSegmentDirectory
  2230. // Synopsis:
  2231. //------------------------------------------------------------------------
  2232. bool
  2233. CLKRLinearHashTable::_FreeSegmentDirectory()
  2234. {
  2235. #ifdef IRTLDEBUG
  2236. for (size_t i = 0; i < m_cDirSegs; ++i)
  2237. IRTLASSERT(m_paDirSegs[i].m_pseg == NULL);
  2238. #endif // IRTLDEBUG
  2239. delete [] m_paDirSegs;
  2240. m_paDirSegs = NULL;
  2241. m_cDirSegs = 0;
  2242. return true;
  2243. } // CLKRLinearHashTable::_FreeSegmentDirectory
  2244. //------------------------------------------------------------------------
  2245. // Function: CLKRLinearHashTable::_AllocateNodeClump
  2246. // Synopsis:
  2247. //------------------------------------------------------------------------
  2248. CNodeClump* const
  2249. CLKRLinearHashTable::_AllocateNodeClump()
  2250. {
  2251. #ifdef LKR_RANDOM_MEMORY_FAILURES
  2252. if (rand() < LKR_RANDOM_MEMORY_FAILURES)
  2253. return NULL;
  2254. #endif // LKR_RANDOM_MEMORY_FAILURES
  2255. // InterlockedIncrement(&g_cAllocNodeClump);
  2256. return new CNodeClump;
  2257. } // CLKRLinearHashTable::_AllocateNodeClump
  2258. //------------------------------------------------------------------------
  2259. // Function: CLKRLinearHashTable::_FreeNodeClump
  2260. // Synopsis:
  2261. //------------------------------------------------------------------------
  2262. bool
  2263. CLKRLinearHashTable::_FreeNodeClump(
  2264. CNodeClump* pnc)
  2265. {
  2266. delete pnc;
  2267. return true;
  2268. } // CLKRLinearHashTable::_FreeNodeClump
  2269. //-----------------------------------------------------------------------
  2270. // Function: CLKRLinearHashTable::_AllocateSegment
  2271. // Synopsis: creates a new segment of the approriate size
  2272. // Output: pointer to the new segment; NULL => failure
  2273. //-----------------------------------------------------------------------
  2274. CSegment* const
  2275. CLKRLinearHashTable::_AllocateSegment(
  2276. ) const
  2277. {
  2278. #ifdef LKR_RANDOM_MEMORY_FAILURES
  2279. if (rand() < LKR_RANDOM_MEMORY_FAILURES)
  2280. return NULL;
  2281. #endif // LKR_RANDOM_MEMORY_FAILURES
  2282. STATIC_ASSERT(offsetof(CSegment, m_bktSlots) + sizeof(CBucket)
  2283. == offsetof(CSmallSegment, m_bktSlots2));
  2284. STATIC_ASSERT(offsetof(CSegment, m_bktSlots) + sizeof(CBucket)
  2285. == offsetof(CMediumSegment, m_bktSlots2));
  2286. STATIC_ASSERT(offsetof(CSegment, m_bktSlots) + sizeof(CBucket)
  2287. == offsetof(CLargeSegment, m_bktSlots2));
  2288. CSegment* pseg = NULL;
  2289. switch (m_lkts)
  2290. {
  2291. case LK_SMALL_TABLESIZE:
  2292. #ifdef LKRHASH_ALLOCATOR_NEW
  2293. IRTLASSERT(CSmallSegment::sm_palloc != NULL);
  2294. #endif // LKRHASH_ALLOCATOR_NEW
  2295. // InterlockedIncrement(&g_cAllocSmallSegment);
  2296. pseg = new CSmallSegment;
  2297. break;
  2298. default:
  2299. IRTLASSERT(! "Unknown LK_TABLESIZE");
  2300. // fall-through
  2301. case LK_MEDIUM_TABLESIZE:
  2302. #ifdef LKRHASH_ALLOCATOR_NEW
  2303. IRTLASSERT(CMediumSegment::sm_palloc != NULL);
  2304. #endif // LKRHASH_ALLOCATOR_NEW
  2305. // InterlockedIncrement(&g_cAllocMediumSegment);
  2306. pseg = new CMediumSegment;
  2307. break;
  2308. case LK_LARGE_TABLESIZE:
  2309. #ifdef LKRHASH_ALLOCATOR_NEW
  2310. IRTLASSERT(CLargeSegment::sm_palloc != NULL);
  2311. #endif // LKRHASH_ALLOCATOR_NEW
  2312. // InterlockedIncrement(&g_cAllocLargeSegment);
  2313. pseg = new CLargeSegment;
  2314. break;
  2315. }
  2316. IRTLASSERT(pseg != NULL);
  2317. if (pseg != NULL && BucketLock::PerLockSpin() == LOCK_INDIVIDUAL_SPIN)
  2318. {
  2319. for (DWORD i = 0; i < m_dwSegSize; ++i)
  2320. pseg->Slot(i).SetSpinCount(m_wBucketLockSpins);
  2321. }
  2322. return pseg;
  2323. } // CLKRLinearHashTable::_AllocateSegment
  2324. //------------------------------------------------------------------------
  2325. // Function: CLKRLinearHashTable::_FreeSegment
  2326. // Synopsis:
  2327. //------------------------------------------------------------------------
  2328. bool
  2329. CLKRLinearHashTable::_FreeSegment(
  2330. CSegment* pseg) const
  2331. {
  2332. switch (m_lkts)
  2333. {
  2334. case LK_SMALL_TABLESIZE:
  2335. delete static_cast<CSmallSegment*>(pseg);
  2336. break;
  2337. default:
  2338. IRTLASSERT(! "Unknown LK_TABLESIZE");
  2339. // fall-through
  2340. case LK_MEDIUM_TABLESIZE:
  2341. delete static_cast<CMediumSegment*>(pseg);
  2342. break;
  2343. case LK_LARGE_TABLESIZE:
  2344. delete static_cast<CLargeSegment*>(pseg);
  2345. break;
  2346. }
  2347. return true;
  2348. } // CLKRLinearHashTable::_FreeSegment
  2349. //------------------------------------------------------------------------
  2350. // Function: CLKRHashTable::_AllocateSubTableArray
  2351. // Synopsis:
  2352. //------------------------------------------------------------------------
  2353. CLKRHashTable::SubTable** const
  2354. CLKRHashTable::_AllocateSubTableArray(
  2355. size_t n)
  2356. {
  2357. #ifdef LKR_RANDOM_MEMORY_FAILURES
  2358. if (rand() < LKR_RANDOM_MEMORY_FAILURES)
  2359. return NULL;
  2360. #endif // LKR_RANDOM_MEMORY_FAILURES
  2361. return new SubTable* [n];
  2362. } // CLKRHashTable::_AllocateSubTableArray
  2363. //------------------------------------------------------------------------
  2364. // Function: CLKRHashTable::_FreeSubTableArray
  2365. // Synopsis:
  2366. //------------------------------------------------------------------------
  2367. bool
  2368. CLKRHashTable::_FreeSubTableArray(
  2369. CLKRHashTable::SubTable** palht)
  2370. {
  2371. delete [] palht;
  2372. return true;
  2373. } // CLKRHashTable::_FreeSubTableArray
  2374. //------------------------------------------------------------------------
  2375. // Function: CLKRHashTable::_AllocateSubTable
  2376. // Synopsis:
  2377. //------------------------------------------------------------------------
  2378. CLKRHashTable::SubTable* const
  2379. CLKRHashTable::_AllocateSubTable(
  2380. LPCSTR pszName, // An identifier for debugging
  2381. PFnExtractKey pfnExtractKey, // Extract key from record
  2382. PFnCalcKeyHash pfnCalcKeyHash, // Calculate hash signature of key
  2383. PFnEqualKeys pfnEqualKeys, // Compare two keys
  2384. PFnAddRefRecord pfnAddRefRecord,// AddRef in FindKey, etc
  2385. double maxload, // Upperbound on average chain length
  2386. DWORD initsize, // Initial size of hash table.
  2387. CLKRHashTable* phtParent, // Owning table.
  2388. bool fMultiKeys // Allow multiple identical keys?
  2389. )
  2390. {
  2391. #ifdef LKR_RANDOM_MEMORY_FAILURES
  2392. if (rand() < LKR_RANDOM_MEMORY_FAILURES)
  2393. return NULL;
  2394. #endif // LKR_RANDOM_MEMORY_FAILURES
  2395. return new SubTable(pszName, pfnExtractKey, pfnCalcKeyHash,
  2396. pfnEqualKeys, pfnAddRefRecord,
  2397. maxload, initsize, phtParent, fMultiKeys);
  2398. } // CLKRHashTable::_AllocateSubTable
  2399. //------------------------------------------------------------------------
  2400. // Function: CLKRHashTable::_FreeSubTable
  2401. // Synopsis:
  2402. //------------------------------------------------------------------------
  2403. bool
  2404. CLKRHashTable::_FreeSubTable(
  2405. CLKRHashTable::SubTable* plht)
  2406. {
  2407. delete plht;
  2408. return true;
  2409. } // CLKRHashTable::_FreeSubTable
  2410. //-----------------------------------------------------------------------
  2411. // Function: CLKRLinearHashTable::_Expand
  2412. // Synopsis: Expands the table by one bucket. Done by splitting the
  2413. // bucket pointed to by m_iExpansionIdx.
  2414. // Output: LK_SUCCESS, if expansion was successful.
  2415. // LK_ALLOC_FAIL, if expansion failed due to lack of memory.
  2416. //-----------------------------------------------------------------------
  2417. LK_RETCODE
  2418. CLKRLinearHashTable::_Expand()
  2419. {
  2420. if (m_cActiveBuckets >= MAX_DIRSIZE * m_dwSegSize - 1)
  2421. return LK_ALLOC_FAIL; // table is not allowed to grow any more
  2422. WriteLock();
  2423. // double segment directory size if necessary
  2424. if (m_cActiveBuckets >= m_cDirSegs * m_dwSegSize)
  2425. {
  2426. IRTLASSERT(m_cDirSegs < MAX_DIRSIZE);
  2427. DWORD cDirSegsNew = (m_cDirSegs == 0) ? MIN_DIRSIZE : m_cDirSegs << 1;
  2428. CDirEntry* paDirSegsNew = _AllocateSegmentDirectory(cDirSegsNew);
  2429. if (paDirSegsNew != NULL)
  2430. {
  2431. for (DWORD j = 0; j < m_cDirSegs; j++)
  2432. {
  2433. paDirSegsNew[j] = m_paDirSegs[j];
  2434. m_paDirSegs[j].m_pseg = NULL;
  2435. }
  2436. _FreeSegmentDirectory();
  2437. m_paDirSegs = paDirSegsNew;
  2438. m_cDirSegs = cDirSegsNew;
  2439. }
  2440. else
  2441. {
  2442. WriteUnlock();
  2443. return LK_ALLOC_FAIL; // expansion failed
  2444. }
  2445. }
  2446. // locate the new bucket, creating a new segment if necessary
  2447. ++m_cActiveBuckets;
  2448. DWORD dwOldBkt = m_iExpansionIdx;
  2449. DWORD dwNewBkt = (1 << m_nLevel) | dwOldBkt;
  2450. IRTLASSERT(dwOldBkt < m_cActiveBuckets);
  2451. IRTLASSERT(dwNewBkt < m_cActiveBuckets);
  2452. IRTLASSERT(_Segment(dwOldBkt) != NULL);
  2453. CSegment* psegNew = _Segment(dwNewBkt);
  2454. if (psegNew == NULL)
  2455. {
  2456. psegNew = _AllocateSegment();
  2457. if (psegNew == NULL)
  2458. {
  2459. --m_cActiveBuckets;
  2460. WriteUnlock();
  2461. return LK_ALLOC_FAIL; // expansion failed
  2462. }
  2463. _Segment(dwNewBkt) = psegNew;
  2464. }
  2465. // prepare to relocate records to the new bucket
  2466. CBucket* pbktOld = _Bucket(dwOldBkt);
  2467. CBucket* pbktNew = _Bucket(dwNewBkt);
  2468. // get locks on the two buckets involved
  2469. pbktOld->WriteLock();
  2470. pbktNew->WriteLock();
  2471. // Now work out if we need to allocate any extra CNodeClumps. We do
  2472. // this up front, before calling _SplitRecordSet, as it's hard to
  2473. // gracefully recover from the depths of that routine should we run
  2474. // out of memory.
  2475. CNodeClump* pncFreeList = NULL;
  2476. LK_RETCODE lkrc = LK_SUCCESS;
  2477. // If the old bucket has more than one CNodeClump, there's a chance that
  2478. // we'll need extra CNodeClumps in the new bucket too. If it doesn't,
  2479. // we definitely won't. One CNodeClump is enough to prime the freelist.
  2480. if (!pbktOld->m_ncFirst.IsLastClump())
  2481. {
  2482. pncFreeList = _AllocateNodeClump();
  2483. if (pncFreeList == NULL)
  2484. {
  2485. lkrc = LK_ALLOC_FAIL;
  2486. --m_cActiveBuckets;
  2487. }
  2488. }
  2489. // adjust expansion pointer, level, and mask
  2490. if (lkrc == LK_SUCCESS)
  2491. {
  2492. if (++m_iExpansionIdx == (1U << m_nLevel))
  2493. {
  2494. ++m_nLevel;
  2495. m_iExpansionIdx = 0;
  2496. m_dwBktAddrMask0 = (m_dwBktAddrMask0 << 1) | 1;
  2497. // m_dwBktAddrMask0 = 00011..111
  2498. IRTLASSERT((m_dwBktAddrMask0 & (m_dwBktAddrMask0+1)) == 0);
  2499. m_dwBktAddrMask1 = (m_dwBktAddrMask0 << 1) | 1;
  2500. IRTLASSERT((m_dwBktAddrMask1 & (m_dwBktAddrMask1+1)) == 0);
  2501. }
  2502. }
  2503. DWORD iExpansionIdx = m_iExpansionIdx; // save to avoid race conditions
  2504. DWORD dwBktAddrMask = m_dwBktAddrMask0; // ditto
  2505. // Release the table lock before doing the actual relocation
  2506. WriteUnlock();
  2507. if (lkrc == LK_SUCCESS)
  2508. {
  2509. lkrc = _SplitRecordSet(&pbktOld->m_ncFirst, &pbktNew->m_ncFirst,
  2510. iExpansionIdx, dwBktAddrMask,
  2511. dwNewBkt, pncFreeList);
  2512. }
  2513. pbktNew->WriteUnlock();
  2514. pbktOld->WriteUnlock();
  2515. return lkrc;
  2516. } // CLKRLinearHashTable::_Expand
  2517. //------------------------------------------------------------------------
  2518. // Function: CLKRLinearHashTable::_SplitRecordSet
  2519. // Synopsis: Split records between the old and new buckets.
  2520. //------------------------------------------------------------------------
  2521. LK_RETCODE
  2522. CLKRLinearHashTable::_SplitRecordSet(
  2523. CNodeClump* pncOldTarget,
  2524. CNodeClump* pncNewTarget,
  2525. DWORD iExpansionIdx,
  2526. DWORD dwBktAddrMask,
  2527. DWORD dwNewBkt,
  2528. CNodeClump* pncFreeList // list of free nodes available for reuse
  2529. )
  2530. {
  2531. CNodeClump ncFirst = *pncOldTarget; // save head of old target chain
  2532. CNodeClump* pncOldList = &ncFirst;
  2533. CNodeClump* pncTmp;
  2534. int iOldSlot = NODE_BEGIN;
  2535. int iNewSlot = NODE_BEGIN;
  2536. // clear target buckets
  2537. pncOldTarget->Clear();
  2538. pncNewTarget->Clear();
  2539. // scan through the old bucket chain and decide where to move each record
  2540. while (pncOldList != NULL)
  2541. {
  2542. int i;
  2543. FOR_EACH_NODE(i)
  2544. {
  2545. // node already empty?
  2546. if (pncOldList->IsEmptySlot(i))
  2547. {
  2548. IRTLASSERT(pncOldList->IsEmptyAndInvalid(i));
  2549. continue;
  2550. }
  2551. // calculate bucket address of this node
  2552. DWORD dwBkt = _H0(pncOldList->m_dwKeySigs[i], dwBktAddrMask);
  2553. if (dwBkt < iExpansionIdx)
  2554. dwBkt = _H1(pncOldList->m_dwKeySigs[i], dwBktAddrMask);
  2555. // record to be moved to the new address?
  2556. if (dwBkt == dwNewBkt)
  2557. {
  2558. // node in new bucket chain full?
  2559. if (iNewSlot == NODE_END)
  2560. {
  2561. // the calling routine has passed in a FreeList adequate
  2562. // for all needs
  2563. IRTLASSERT(pncFreeList != NULL);
  2564. pncTmp = pncFreeList;
  2565. pncFreeList = pncFreeList->m_pncNext;
  2566. pncTmp->Clear();
  2567. pncNewTarget->m_pncNext = pncTmp;
  2568. pncNewTarget = pncTmp;
  2569. iNewSlot = NODE_BEGIN;
  2570. }
  2571. pncNewTarget->m_dwKeySigs[iNewSlot]
  2572. = pncOldList->m_dwKeySigs[i];
  2573. pncNewTarget->m_pvNode[iNewSlot]
  2574. = pncOldList->m_pvNode[i];
  2575. iNewSlot += NODE_STEP;
  2576. }
  2577. // no, record stays in its current bucket chain
  2578. else
  2579. {
  2580. // node in old bucket chain full?
  2581. if (iOldSlot == NODE_END)
  2582. {
  2583. // the calling routine has passed in a FreeList adequate
  2584. // for all needs
  2585. IRTLASSERT(pncFreeList != NULL);
  2586. pncTmp = pncFreeList;
  2587. pncFreeList = pncFreeList->m_pncNext;
  2588. pncTmp->Clear();
  2589. pncOldTarget->m_pncNext = pncTmp;
  2590. pncOldTarget = pncTmp;
  2591. iOldSlot = NODE_BEGIN;
  2592. }
  2593. pncOldTarget->m_dwKeySigs[iOldSlot]
  2594. = pncOldList->m_dwKeySigs[i];
  2595. pncOldTarget->m_pvNode[iOldSlot]
  2596. = pncOldList->m_pvNode[i];
  2597. iOldSlot += NODE_STEP;
  2598. }
  2599. // clear old slot
  2600. pncOldList->m_dwKeySigs[i] = HASH_INVALID_SIGNATURE;
  2601. pncOldList->m_pvNode[i] = NULL;
  2602. }
  2603. // keep walking down the original bucket chain
  2604. pncTmp = pncOldList;
  2605. pncOldList = pncOldList->m_pncNext;
  2606. // ncFirst is a stack variable, not allocated on the heap
  2607. if (pncTmp != &ncFirst)
  2608. {
  2609. pncTmp->m_pncNext = pncFreeList;
  2610. pncFreeList = pncTmp;
  2611. }
  2612. }
  2613. // delete any leftover nodes
  2614. while (pncFreeList != NULL)
  2615. {
  2616. pncTmp = pncFreeList;
  2617. pncFreeList = pncFreeList->m_pncNext;
  2618. #ifdef IRTLDEBUG
  2619. pncTmp->m_pncNext = NULL; // or ~CNodeClump will ASSERT
  2620. #endif // IRTLDEBUG
  2621. _FreeNodeClump(pncTmp);
  2622. }
  2623. #ifdef IRTLDEBUG
  2624. ncFirst.m_pncNext = NULL; // or ~CNodeClump will ASSERT
  2625. #endif // IRTLDEBUG
  2626. return LK_SUCCESS;
  2627. } // CLKRLinearHashTable::_SplitRecordSet
  2628. //------------------------------------------------------------------------
  2629. // Function: CLKRLinearHashTable::_Contract
  2630. // Synopsis: Contract the table by deleting the last bucket in the active
  2631. // address space. Return the records to the "buddy" of the
  2632. // deleted bucket.
  2633. //------------------------------------------------------------------------
  2634. LK_RETCODE
  2635. CLKRLinearHashTable::_Contract()
  2636. {
  2637. WriteLock();
  2638. IRTLASSERT(m_cActiveBuckets >= m_dwSegSize);
  2639. // Always keep at least m_dwSegSize buckets in the table;
  2640. // i.e., one segment's worth.
  2641. if (m_cActiveBuckets <= m_dwSegSize)
  2642. {
  2643. WriteUnlock();
  2644. return LK_ALLOC_FAIL;
  2645. }
  2646. // update the state variables (expansion ptr, level and mask)
  2647. if (m_iExpansionIdx > 0)
  2648. --m_iExpansionIdx;
  2649. else
  2650. {
  2651. --m_nLevel;
  2652. m_iExpansionIdx = (1 << m_nLevel) - 1;
  2653. IRTLASSERT(m_nLevel > 0 && m_iExpansionIdx > 0);
  2654. m_dwBktAddrMask0 >>= 1;
  2655. IRTLASSERT((m_dwBktAddrMask0 & (m_dwBktAddrMask0+1)) == 0); // 00011..111
  2656. m_dwBktAddrMask1 >>= 1;
  2657. IRTLASSERT(m_dwBktAddrMask1 == ((m_dwBktAddrMask0 << 1) | 1));
  2658. IRTLASSERT((m_dwBktAddrMask1 & (m_dwBktAddrMask1+1)) == 0);
  2659. }
  2660. // The last bucket is the one that will be emptied
  2661. CBucket* pbktLast = _Bucket(m_cActiveBuckets - 1);
  2662. pbktLast->WriteLock();
  2663. // Decrement after calculating pbktLast, or _Bucket() will assert.
  2664. --m_cActiveBuckets;
  2665. // Where the nodes from pbktLast will end up
  2666. CBucket* pbktNew = _Bucket(m_iExpansionIdx);
  2667. pbktNew->WriteLock();
  2668. // Now we work out if we need to allocate any extra CNodeClumps. We do
  2669. // this up front, before calling _MergeRecordSets, as it's hard to
  2670. // gracefully recover from the depths of that routine should we run
  2671. // out of memory.
  2672. CNodeClump* pnc;
  2673. int c = 0;
  2674. // First, count the number of items in the old bucket
  2675. for (pnc = &pbktLast->m_ncFirst; pnc != NULL; pnc = pnc->m_pncNext)
  2676. {
  2677. int i;
  2678. FOR_EACH_NODE(i)
  2679. {
  2680. if (!pnc->IsEmptySlot(i))
  2681. {
  2682. IRTLASSERT(!pnc->IsEmptyAndInvalid(i));
  2683. c++;
  2684. }
  2685. }
  2686. }
  2687. // Then, subtract off the number of empty slots in the new bucket
  2688. for (pnc = &pbktNew->m_ncFirst; pnc != NULL; pnc = pnc->m_pncNext)
  2689. {
  2690. int i;
  2691. FOR_EACH_NODE(i)
  2692. {
  2693. if (pnc->IsEmptySlot(i))
  2694. {
  2695. IRTLASSERT(pnc->IsEmptyAndInvalid(i));
  2696. c--;
  2697. }
  2698. }
  2699. }
  2700. CNodeClump* pncFreeList = NULL; // list of nodes available for reuse
  2701. LK_RETCODE lkrc = LK_SUCCESS;
  2702. // Do we need to allocate CNodeClumps to accommodate the surplus items?
  2703. if (c > 0)
  2704. {
  2705. pncFreeList = _AllocateNodeClump();
  2706. if (pncFreeList == NULL)
  2707. lkrc = LK_ALLOC_FAIL;
  2708. else if (c > NODES_PER_CLUMP)
  2709. {
  2710. // In the worst case, we need a 2-element freelist for
  2711. // _MergeRecordSets. Two CNodeClumps always suffice since the
  2712. // freelist will be augmented by the CNodeClumps from the old
  2713. // bucket as they are processed.
  2714. pnc = _AllocateNodeClump();
  2715. if (pnc == NULL)
  2716. {
  2717. _FreeNodeClump(pncFreeList);
  2718. lkrc = LK_ALLOC_FAIL;
  2719. }
  2720. else
  2721. pncFreeList->m_pncNext = pnc;
  2722. }
  2723. }
  2724. // Abort if we couldn't allocate enough CNodeClumps
  2725. if (lkrc != LK_SUCCESS)
  2726. {
  2727. // undo the changes to the state variables
  2728. if (++m_iExpansionIdx == (1U << m_nLevel))
  2729. {
  2730. ++m_nLevel;
  2731. m_iExpansionIdx = 0;
  2732. m_dwBktAddrMask0 = (m_dwBktAddrMask0 << 1) | 1;
  2733. m_dwBktAddrMask1 = (m_dwBktAddrMask0 << 1) | 1;
  2734. }
  2735. ++m_cActiveBuckets;
  2736. // Unlock the buckets and the table
  2737. pbktLast->WriteUnlock();
  2738. pbktNew->WriteUnlock();
  2739. WriteUnlock();
  2740. return lkrc;
  2741. }
  2742. // Copy the chain of records from pbktLast
  2743. CNodeClump ncOldFirst = pbktLast->m_ncFirst;
  2744. // destroy pbktLast
  2745. pbktLast->m_ncFirst.Clear();
  2746. pbktLast->WriteUnlock();
  2747. // remove segment, if empty
  2748. if (_SegIndex(m_cActiveBuckets) == 0)
  2749. {
  2750. #ifdef IRTLDEBUG
  2751. // double-check that the supposedly empty segment is really empty
  2752. IRTLASSERT(_Segment(m_cActiveBuckets) != NULL);
  2753. for (DWORD i = 0; i < m_dwSegSize; ++i)
  2754. {
  2755. CBucket* pbkt = &_Segment(m_cActiveBuckets)->Slot(i);
  2756. IRTLASSERT(pbkt->IsWriteUnlocked() && pbkt->IsReadUnlocked());
  2757. IRTLASSERT(pbkt->m_ncFirst.IsLastClump());
  2758. int j;
  2759. FOR_EACH_NODE(j)
  2760. {
  2761. IRTLASSERT(pbkt->m_ncFirst.IsEmptyAndInvalid(j));
  2762. }
  2763. }
  2764. #endif // IRTLDEBUG
  2765. _FreeSegment(_Segment(m_cActiveBuckets));
  2766. _Segment(m_cActiveBuckets) = NULL;
  2767. }
  2768. // reduce directory of segments if possible
  2769. if (m_cActiveBuckets <= (m_cDirSegs * m_dwSegSize) >> 1
  2770. && m_cDirSegs > MIN_DIRSIZE)
  2771. {
  2772. DWORD cDirSegsNew = m_cDirSegs >> 1;
  2773. CDirEntry* paDirSegsNew = _AllocateSegmentDirectory(cDirSegsNew);
  2774. // Memory allocation failure here does not require us to abort; it
  2775. // just means that the directory of segments is larger than we'd like.
  2776. if (paDirSegsNew != NULL)
  2777. {
  2778. for (DWORD j = 0; j < cDirSegsNew; j++)
  2779. paDirSegsNew[j] = m_paDirSegs[j];
  2780. for (j = 0; j < m_cDirSegs; j++)
  2781. m_paDirSegs[j].m_pseg = NULL;
  2782. _FreeSegmentDirectory();
  2783. m_paDirSegs = paDirSegsNew;
  2784. m_cDirSegs = cDirSegsNew;
  2785. }
  2786. }
  2787. // release the table lock before doing the reorg
  2788. WriteUnlock();
  2789. lkrc = _MergeRecordSets(pbktNew, &ncOldFirst, pncFreeList);
  2790. pbktNew->WriteUnlock();
  2791. #ifdef IRTLDEBUG
  2792. ncOldFirst.m_pncNext = NULL; // or ~CNodeClump will ASSERT
  2793. #endif // IRTLDEBUG
  2794. return lkrc;
  2795. } // CLKRLinearHashTable::_Contract
  2796. //------------------------------------------------------------------------
  2797. // Function: CLKRLinearHashTable::_MergeRecordSets
  2798. // Synopsis: Merge two record sets. Copy the contents of pncOldList
  2799. // into pbktNewTarget.
  2800. //------------------------------------------------------------------------
  2801. LK_RETCODE
  2802. CLKRLinearHashTable::_MergeRecordSets(
  2803. CBucket* pbktNewTarget,
  2804. CNodeClump* pncOldList,
  2805. CNodeClump* pncFreeList
  2806. )
  2807. {
  2808. IRTLASSERT(pbktNewTarget != NULL && pncOldList != NULL);
  2809. CNodeClump* pncTmp = NULL;
  2810. CNodeClump* const pncOldFirst = pncOldList;
  2811. CNodeClump* pncNewTarget = &pbktNewTarget->m_ncFirst;
  2812. int iNewSlot;
  2813. // find the first nodeclump in the new target bucket with an empty slot
  2814. while (!pncNewTarget->IsLastClump())
  2815. {
  2816. FOR_EACH_NODE(iNewSlot)
  2817. {
  2818. if (pncNewTarget->IsEmptySlot(iNewSlot))
  2819. break;
  2820. }
  2821. if (iNewSlot == NODE_END)
  2822. pncNewTarget = pncNewTarget->m_pncNext;
  2823. else
  2824. break;
  2825. }
  2826. IRTLASSERT(pncNewTarget != NULL);
  2827. // find the first empty slot in pncNewTarget;
  2828. // if none, iNewSlot == NODE_END
  2829. FOR_EACH_NODE(iNewSlot)
  2830. {
  2831. if (pncNewTarget->IsEmptySlot(iNewSlot))
  2832. {
  2833. break;
  2834. }
  2835. }
  2836. while (pncOldList != NULL)
  2837. {
  2838. int i;
  2839. FOR_EACH_NODE(i)
  2840. {
  2841. if (!pncOldList->IsEmptySlot(i))
  2842. {
  2843. // any empty slots left in pncNewTarget?
  2844. if (iNewSlot == NODE_END)
  2845. {
  2846. // no, so walk down pncNewTarget until we find another
  2847. // empty slot
  2848. while (!pncNewTarget->IsLastClump())
  2849. {
  2850. pncNewTarget = pncNewTarget->m_pncNext;
  2851. FOR_EACH_NODE(iNewSlot)
  2852. {
  2853. if (pncNewTarget->IsEmptySlot(iNewSlot))
  2854. goto found_slot;
  2855. }
  2856. }
  2857. // Oops, reached the last nodeclump in pncNewTarget
  2858. // and it's full. Get a new nodeclump off the free
  2859. // list, which is big enough to handle all needs.
  2860. IRTLASSERT(pncNewTarget != NULL);
  2861. IRTLASSERT(pncFreeList != NULL);
  2862. pncTmp = pncFreeList;
  2863. pncFreeList = pncFreeList->m_pncNext;
  2864. pncTmp->Clear();
  2865. pncNewTarget->m_pncNext = pncTmp;
  2866. pncNewTarget = pncTmp;
  2867. iNewSlot = NODE_BEGIN;
  2868. }
  2869. found_slot:
  2870. // We have an empty slot in pncNewTarget
  2871. IRTLASSERT(0 <= iNewSlot && iNewSlot < NODES_PER_CLUMP
  2872. && pncNewTarget != NULL
  2873. && pncNewTarget->IsEmptyAndInvalid(iNewSlot));
  2874. // Let's copy the node from pncOldList
  2875. pncNewTarget->m_dwKeySigs[iNewSlot]
  2876. = pncOldList->m_dwKeySigs[i];
  2877. pncNewTarget->m_pvNode[iNewSlot]
  2878. = pncOldList->m_pvNode[i];
  2879. // Clear old slot
  2880. pncOldList->m_dwKeySigs[i] = HASH_INVALID_SIGNATURE;
  2881. pncOldList->m_pvNode[i] = NULL;
  2882. // find the next free slot in pncNewTarget
  2883. while ((iNewSlot += NODE_STEP) != NODE_END)
  2884. {
  2885. if (pncNewTarget->IsEmptySlot(iNewSlot))
  2886. {
  2887. break;
  2888. }
  2889. }
  2890. }
  2891. else // iNewSlot != NODE_END
  2892. {
  2893. IRTLASSERT(pncOldList->IsEmptyAndInvalid(i));
  2894. }
  2895. }
  2896. // Move into the next nodeclump in pncOldList
  2897. pncTmp = pncOldList;
  2898. pncOldList = pncOldList->m_pncNext;
  2899. // Append to the free list. Don't put the first node of
  2900. // pncOldList on the free list, as it's a stack variable.
  2901. if (pncTmp != pncOldFirst)
  2902. {
  2903. pncTmp->m_pncNext = pncFreeList;
  2904. pncFreeList = pncTmp;
  2905. }
  2906. }
  2907. // delete any leftover nodes
  2908. while (pncFreeList != NULL)
  2909. {
  2910. pncTmp = pncFreeList;
  2911. pncFreeList = pncFreeList->m_pncNext;
  2912. #ifdef IRTLDEBUG
  2913. pncTmp->m_pncNext = NULL; // or ~CNodeClump will ASSERT
  2914. #endif // IRTLDEBUG
  2915. _FreeNodeClump(pncTmp);
  2916. }
  2917. return LK_SUCCESS;
  2918. } // CLKRLinearHashTable::_MergeRecordSets
  2919. #ifdef LKR_DEPRECATED_ITERATORS
  2920. //------------------------------------------------------------------------
  2921. // Function: CLKRLinearHashTable::_InitializeIterator
  2922. // Synopsis: Make the iterator point to the first record in the hash table.
  2923. //------------------------------------------------------------------------
  2924. LK_RETCODE
  2925. CLKRLinearHashTable::_InitializeIterator(
  2926. CIterator* piter)
  2927. {
  2928. if (!IsUsable())
  2929. return LK_UNUSABLE;
  2930. IRTLASSERT(piter != NULL);
  2931. IRTLASSERT(piter->m_lkl == LKL_WRITELOCK
  2932. ? IsWriteLocked()
  2933. : IsReadLocked());
  2934. if (piter == NULL || piter->m_plht != NULL)
  2935. return LK_BAD_ITERATOR;
  2936. piter->m_plht = this;
  2937. piter->m_dwBucketAddr = 0;
  2938. CBucket* pbkt = _Bucket(piter->m_dwBucketAddr);
  2939. IRTLASSERT(pbkt != NULL);
  2940. if (piter->m_lkl == LKL_WRITELOCK)
  2941. pbkt->WriteLock();
  2942. else
  2943. pbkt->ReadLock();
  2944. piter->m_pnc = &pbkt->m_ncFirst;
  2945. piter->m_iNode = NODE_BEGIN - NODE_STEP;
  2946. // Let IncrementIterator do the hard work of finding the first
  2947. // slot in use.
  2948. return IncrementIterator(piter);
  2949. } // CLKRLinearHashTable::_InitializeIterator
  2950. //------------------------------------------------------------------------
  2951. // Function: CLKRHashTable::InitializeIterator
  2952. // Synopsis: make the iterator point to the first record in the hash table
  2953. //------------------------------------------------------------------------
  2954. LK_RETCODE
  2955. CLKRHashTable::InitializeIterator(
  2956. CIterator* piter)
  2957. {
  2958. if (!IsUsable())
  2959. return LK_UNUSABLE;
  2960. IRTLASSERT(piter != NULL && piter->m_pht == NULL);
  2961. if (piter == NULL || piter->m_pht != NULL)
  2962. return LK_BAD_ITERATOR;
  2963. // First, lock all the subtables
  2964. if (piter->m_lkl == LKL_WRITELOCK)
  2965. WriteLock();
  2966. else
  2967. ReadLock();
  2968. // Must call IsValid inside a lock to ensure that none of the state
  2969. // variables change while it's being evaluated
  2970. IRTLASSERT(IsValid());
  2971. if (!IsValid())
  2972. return LK_UNUSABLE;
  2973. piter->m_pht = this;
  2974. piter->m_ist = -1;
  2975. piter->m_plht = NULL;
  2976. // Let IncrementIterator do the hard work of finding the first
  2977. // valid node in the subtables.
  2978. return IncrementIterator(piter);
  2979. } // CLKRHashTable::InitializeIterator
  2980. //------------------------------------------------------------------------
  2981. // Function: CLKRLinearHashTable::IncrementIterator
  2982. // Synopsis: move the iterator on to the next record in the hash table
  2983. //------------------------------------------------------------------------
  2984. LK_RETCODE
  2985. CLKRLinearHashTable::IncrementIterator(
  2986. CIterator* piter)
  2987. {
  2988. if (!IsUsable())
  2989. return LK_UNUSABLE;
  2990. IRTLASSERT(piter != NULL);
  2991. IRTLASSERT(piter->m_plht == this);
  2992. IRTLASSERT(piter->m_lkl == LKL_WRITELOCK
  2993. ? IsWriteLocked()
  2994. : IsReadLocked());
  2995. IRTLASSERT(piter->m_dwBucketAddr < m_cActiveBuckets);
  2996. IRTLASSERT(piter->m_pnc != NULL);
  2997. IRTLASSERT((0 <= piter->m_iNode && piter->m_iNode < NODES_PER_CLUMP)
  2998. || (NODE_BEGIN - NODE_STEP == piter->m_iNode));
  2999. if (piter == NULL || piter->m_plht != this)
  3000. return LK_BAD_ITERATOR;
  3001. const void* pvRecord = NULL;
  3002. if (piter->m_iNode != NODE_BEGIN - NODE_STEP)
  3003. {
  3004. // Release the reference acquired in the previous call to
  3005. // IncrementIterator
  3006. pvRecord = piter->m_pnc->m_pvNode[piter->m_iNode];
  3007. _AddRefRecord(pvRecord, -1);
  3008. }
  3009. do
  3010. {
  3011. do
  3012. {
  3013. // find the next slot in the nodeclump that's in use
  3014. while ((piter->m_iNode += NODE_STEP) != NODE_END)
  3015. {
  3016. pvRecord = piter->m_pnc->m_pvNode[piter->m_iNode];
  3017. if (pvRecord != NULL)
  3018. {
  3019. // Add a new reference
  3020. _AddRefRecord(pvRecord, +1);
  3021. return LK_SUCCESS;
  3022. }
  3023. else // pvRecord == NULL
  3024. {
  3025. #ifdef IRTLDEBUG
  3026. // Check that all the remaining nodes are empty
  3027. IRTLASSERT(piter->m_pnc->IsLastClump());
  3028. for (int i = piter->m_iNode;
  3029. i != NODE_END;
  3030. i += NODE_STEP)
  3031. {
  3032. IRTLASSERT(piter->m_pnc->IsEmptyAndInvalid(i));
  3033. }
  3034. #endif // IRTLDEBUG
  3035. break; // rest of nodeclump is empty
  3036. }
  3037. }
  3038. // try the next nodeclump in the bucket chain
  3039. piter->m_iNode = NODE_BEGIN - NODE_STEP;
  3040. piter->m_pnc = piter->m_pnc->m_pncNext;
  3041. } while (piter->m_pnc != NULL);
  3042. // Exhausted this bucket chain. Unlock it.
  3043. CBucket* pbkt = _Bucket(piter->m_dwBucketAddr);
  3044. IRTLASSERT(pbkt != NULL);
  3045. IRTLASSERT(piter->m_lkl == LKL_WRITELOCK
  3046. ? pbkt->IsWriteLocked()
  3047. : pbkt->IsReadLocked());
  3048. if (piter->m_lkl == LKL_WRITELOCK)
  3049. pbkt->WriteUnlock();
  3050. else
  3051. pbkt->ReadUnlock();
  3052. // Try the next bucket, if there is one
  3053. if (++piter->m_dwBucketAddr < m_cActiveBuckets)
  3054. {
  3055. pbkt = _Bucket(piter->m_dwBucketAddr);
  3056. IRTLASSERT(pbkt != NULL);
  3057. if (piter->m_lkl == LKL_WRITELOCK)
  3058. pbkt->WriteLock();
  3059. else
  3060. pbkt->ReadLock();
  3061. piter->m_pnc = &pbkt->m_ncFirst;
  3062. }
  3063. } while (piter->m_dwBucketAddr < m_cActiveBuckets);
  3064. // We have fallen off the end of the hashtable
  3065. piter->m_iNode = NODE_BEGIN - NODE_STEP;
  3066. piter->m_pnc = NULL;
  3067. return LK_NO_MORE_ELEMENTS;
  3068. } // CLKRLinearHashTable::IncrementIterator
  3069. //------------------------------------------------------------------------
  3070. // Function: CLKRHashTable::IncrementIterator
  3071. // Synopsis: move the iterator on to the next record in the hash table
  3072. //------------------------------------------------------------------------
  3073. LK_RETCODE
  3074. CLKRHashTable::IncrementIterator(
  3075. CIterator* piter)
  3076. {
  3077. if (!IsUsable())
  3078. return LK_UNUSABLE;
  3079. IRTLASSERT(piter != NULL);
  3080. IRTLASSERT(piter->m_pht == this);
  3081. IRTLASSERT(-1 <= piter->m_ist
  3082. && piter->m_ist < static_cast<int>(m_cSubTables));
  3083. if (piter == NULL || piter->m_pht != this)
  3084. return LK_BAD_ITERATOR;
  3085. // Table is already locked
  3086. if (!IsValid())
  3087. return LK_UNUSABLE;
  3088. LK_RETCODE lkrc;
  3089. CLHTIterator* pBaseIter = static_cast<CLHTIterator*>(piter);
  3090. for (;;)
  3091. {
  3092. // Do we have a valid iterator into a subtable? If not, get one.
  3093. while (piter->m_plht == NULL)
  3094. {
  3095. while (++piter->m_ist < static_cast<int>(m_cSubTables))
  3096. {
  3097. lkrc = m_palhtDir[piter->m_ist]->_InitializeIterator(piter);
  3098. if (lkrc == LK_SUCCESS)
  3099. {
  3100. IRTLASSERT(m_palhtDir[piter->m_ist] == piter->m_plht);
  3101. return lkrc;
  3102. }
  3103. else if (lkrc == LK_NO_MORE_ELEMENTS)
  3104. lkrc = piter->m_plht->_CloseIterator(pBaseIter);
  3105. if (lkrc != LK_SUCCESS)
  3106. return lkrc;
  3107. }
  3108. // There are no more subtables left.
  3109. return LK_NO_MORE_ELEMENTS;
  3110. }
  3111. // We already have a valid iterator into a subtable. Increment it.
  3112. lkrc = piter->m_plht->IncrementIterator(pBaseIter);
  3113. if (lkrc == LK_SUCCESS)
  3114. return lkrc;
  3115. // We've exhausted that subtable. Move on.
  3116. if (lkrc == LK_NO_MORE_ELEMENTS)
  3117. lkrc = piter->m_plht->_CloseIterator(pBaseIter);
  3118. if (lkrc != LK_SUCCESS)
  3119. return lkrc;
  3120. }
  3121. } // CLKRHashTable::IncrementIterator
  3122. //------------------------------------------------------------------------
  3123. // Function: CLKRLinearHashTable::_CloseIterator
  3124. // Synopsis: release the resources held by the iterator
  3125. //------------------------------------------------------------------------
  3126. LK_RETCODE
  3127. CLKRLinearHashTable::_CloseIterator(
  3128. CIterator* piter)
  3129. {
  3130. if (!IsUsable())
  3131. return LK_UNUSABLE;
  3132. IRTLASSERT(piter != NULL);
  3133. IRTLASSERT(piter->m_plht == this);
  3134. IRTLASSERT(piter->m_lkl == LKL_WRITELOCK
  3135. ? IsWriteLocked()
  3136. : IsReadLocked());
  3137. IRTLASSERT(piter->m_dwBucketAddr <= m_cActiveBuckets);
  3138. IRTLASSERT((0 <= piter->m_iNode && piter->m_iNode < NODES_PER_CLUMP)
  3139. || (NODE_BEGIN - NODE_STEP == piter->m_iNode));
  3140. if (piter == NULL || piter->m_plht != this)
  3141. return LK_BAD_ITERATOR;
  3142. // Are we abandoning the iterator before the end of the table?
  3143. // If so, need to unlock the bucket.
  3144. if (piter->m_dwBucketAddr < m_cActiveBuckets)
  3145. {
  3146. CBucket* pbkt = _Bucket(piter->m_dwBucketAddr);
  3147. IRTLASSERT(pbkt != NULL);
  3148. IRTLASSERT(piter->m_lkl == LKL_WRITELOCK
  3149. ? pbkt->IsWriteLocked()
  3150. : pbkt->IsReadLocked());
  3151. if (0 <= piter->m_iNode && piter->m_iNode < NODES_PER_CLUMP)
  3152. {
  3153. IRTLASSERT(piter->m_pnc != NULL);
  3154. const void* pvRecord = piter->m_pnc->m_pvNode[piter->m_iNode];
  3155. _AddRefRecord(pvRecord, -1);
  3156. }
  3157. if (piter->m_lkl == LKL_WRITELOCK)
  3158. pbkt->WriteUnlock();
  3159. else
  3160. pbkt->ReadUnlock();
  3161. }
  3162. piter->m_plht = NULL;
  3163. piter->m_pnc = NULL;
  3164. return LK_SUCCESS;
  3165. } // CLKRLinearHashTable::_CloseIterator
  3166. //------------------------------------------------------------------------
  3167. // Function: CLKRHashTable::CloseIterator
  3168. // Synopsis: release the resources held by the iterator
  3169. //------------------------------------------------------------------------
  3170. LK_RETCODE
  3171. CLKRHashTable::CloseIterator(
  3172. CIterator* piter)
  3173. {
  3174. if (!IsUsable())
  3175. return LK_UNUSABLE;
  3176. IRTLASSERT(piter != NULL);
  3177. IRTLASSERT(piter->m_pht == this);
  3178. IRTLASSERT(-1 <= piter->m_ist
  3179. && piter->m_ist <= static_cast<int>(m_cSubTables));
  3180. if (piter == NULL || piter->m_pht != this)
  3181. return LK_BAD_ITERATOR;
  3182. LK_RETCODE lkrc = LK_SUCCESS;
  3183. if (!IsValid())
  3184. lkrc = LK_UNUSABLE;
  3185. else
  3186. {
  3187. // Are we abandoning the iterator before we've reached the end?
  3188. // If so, close the subtable iterator.
  3189. if (piter->m_plht != NULL)
  3190. {
  3191. IRTLASSERT(piter->m_ist < static_cast<int>(m_cSubTables));
  3192. CLHTIterator* pBaseIter = static_cast<CLHTIterator*>(piter);
  3193. piter->m_plht->_CloseIterator(pBaseIter);
  3194. }
  3195. }
  3196. // Unlock all the subtables
  3197. if (piter->m_lkl == LKL_WRITELOCK)
  3198. WriteUnlock();
  3199. else
  3200. ReadUnlock();
  3201. piter->m_plht = NULL;
  3202. piter->m_pht = NULL;
  3203. piter->m_ist = -1;
  3204. return lkrc;
  3205. } // CLKRHashTable::CloseIterator
  3206. #endif // LKR_DEPRECATED_ITERATORS
  3207. #ifdef LKR_STL_ITERATORS
  3208. //------------------------------------------------------------------------
  3209. // Function: CLKRLinearHashTable::Begin
  3210. // Synopsis: Make the iterator point to the first record in the hash table.
  3211. //------------------------------------------------------------------------
  3212. CLKRLinearHashTable::Iterator
  3213. CLKRLinearHashTable::Begin()
  3214. {
  3215. Iterator iter(this, &_Bucket(0)->m_ncFirst, 0, NODE_BEGIN - NODE_STEP);
  3216. LKR_ITER_TRACE(_TEXT(" LKLH:Begin(it=%p, plht=%p)\n"), &iter, this);
  3217. // Let Increment do the hard work of finding the first slot in use.
  3218. iter._Increment(false);
  3219. IRTLASSERT(iter.m_iNode != NODE_BEGIN - NODE_STEP);
  3220. IRTLASSERT(iter == End() || _IsValidIterator(iter));
  3221. return iter;
  3222. } // CLKRLinearHashTable::Begin
  3223. //------------------------------------------------------------------------
  3224. // Function: CLKRLinearHashTable_Iterator::Increment()
  3225. // Synopsis: move iterator to next valid record in table
  3226. //------------------------------------------------------------------------
  3227. bool
  3228. CLKRLinearHashTable_Iterator::_Increment(
  3229. bool fDecrementOldValue)
  3230. {
  3231. IRTLASSERT(m_plht != NULL);
  3232. IRTLASSERT(m_dwBucketAddr < m_plht->m_cActiveBuckets);
  3233. IRTLASSERT(m_pnc != NULL);
  3234. IRTLASSERT((0 <= m_iNode && m_iNode < NODES_PER_CLUMP)
  3235. || (NODE_BEGIN - NODE_STEP == m_iNode));
  3236. // Release the reference acquired in the previous call to _Increment
  3237. if (fDecrementOldValue)
  3238. _AddRef(-1);
  3239. do
  3240. {
  3241. do
  3242. {
  3243. // find the next slot in the nodeclump that's in use
  3244. while ((m_iNode += NODE_STEP) != NODE_END)
  3245. {
  3246. const void* pvRecord = m_pnc->m_pvNode[m_iNode];
  3247. if (pvRecord != NULL)
  3248. {
  3249. IRTLASSERT(!m_pnc->InvalidSignature(m_iNode));
  3250. // Add a new reference
  3251. _AddRef(+1);
  3252. LKR_ITER_TRACE(_TEXT(" LKLH:++(this=%p, plht=%p, NC=%p, ")
  3253. _TEXT("BA=%u, IN=%d, Rec=%p)\n"),
  3254. this, m_plht, m_pnc,
  3255. m_dwBucketAddr, m_iNode, pvRecord);
  3256. return true;
  3257. }
  3258. else // pvRecord == NULL
  3259. {
  3260. #if 0 //// #ifdef IRTLDEBUG
  3261. // Check that all the remaining nodes are empty
  3262. IRTLASSERT(m_pnc->IsLastClump());
  3263. for (int i = m_iNode; i != NODE_END; i += NODE_STEP)
  3264. {
  3265. IRTLASSERT(m_pnc->IsEmptyAndInvalid(i));
  3266. }
  3267. #endif // IRTLDEBUG
  3268. break; // rest of nodeclump is empty
  3269. }
  3270. }
  3271. // try the next nodeclump in the bucket chain
  3272. m_iNode = NODE_BEGIN - NODE_STEP;
  3273. m_pnc = m_pnc->m_pncNext;
  3274. } while (m_pnc != NULL);
  3275. // Try the next bucket, if there is one
  3276. if (++m_dwBucketAddr < m_plht->m_cActiveBuckets)
  3277. {
  3278. CBucket* pbkt = m_plht->_Bucket(m_dwBucketAddr);
  3279. IRTLASSERT(pbkt != NULL);
  3280. m_pnc = &pbkt->m_ncFirst;
  3281. }
  3282. } while (m_dwBucketAddr < m_plht->m_cActiveBuckets);
  3283. // We have fallen off the end of the hashtable. Set iterator equal
  3284. // to end(), the empty iterator.
  3285. LKR_ITER_TRACE(_TEXT(" LKLH:End(this=%p, plht=%p)\n"), this, m_plht);
  3286. m_plht = NULL;
  3287. m_pnc = NULL;
  3288. m_dwBucketAddr = 0;
  3289. m_iNode = 0;
  3290. //// IRTLASSERT(this->operator==(Iterator())); // == end()
  3291. return false;
  3292. } // CLKRLinearHashTable_Iterator::_Increment()
  3293. //------------------------------------------------------------------------
  3294. // Function: CLKRLinearHashTable::Insert
  3295. // Synopsis:
  3296. //------------------------------------------------------------------------
  3297. bool
  3298. CLKRLinearHashTable::Insert(
  3299. const void* pvRecord,
  3300. Iterator& riterResult,
  3301. bool fOverwrite)
  3302. {
  3303. riterResult = End();
  3304. if (!IsUsable() || pvRecord == NULL)
  3305. return false;
  3306. bool fSuccess = (_InsertRecord(pvRecord,
  3307. _CalcKeyHash(_ExtractKey(pvRecord)),
  3308. fOverwrite,
  3309. &riterResult)
  3310. == LK_SUCCESS);
  3311. IRTLASSERT(riterResult.m_iNode != NODE_BEGIN - NODE_STEP);
  3312. IRTLASSERT(fSuccess
  3313. ? _IsValidIterator(riterResult)
  3314. : riterResult == End());
  3315. return fSuccess;
  3316. } // CLKRLinearHashTable::Insert()
  3317. //------------------------------------------------------------------------
  3318. // Function: CLKRLinearHashTable::_Erase
  3319. // Synopsis:
  3320. //------------------------------------------------------------------------
  3321. bool
  3322. CLKRLinearHashTable::_Erase(
  3323. Iterator& riter,
  3324. DWORD dwSignature)
  3325. {
  3326. CNodeClump* pncCurr, *pncPrev;
  3327. CBucket* const pbkt = riter.m_plht->_Bucket(riter.m_dwBucketAddr);
  3328. LKR_ITER_TRACE(_TEXT(" LKLH:_Erase:pre(iter=%p, plht=%p, NC=%p, ")
  3329. _TEXT("BA=%u, IN=%d, Sig=%x, Rec=%p)\n"),
  3330. &riter, riter.m_plht, riter.m_pnc,
  3331. riter.m_dwBucketAddr, riter.m_iNode, dwSignature,
  3332. riter.m_pnc ? riter.m_pnc->m_pvNode[riter.m_iNode] : NULL);
  3333. pbkt->WriteLock();
  3334. for (pncCurr = &pbkt->m_ncFirst, pncPrev = NULL;
  3335. pncCurr != NULL;
  3336. pncPrev = pncCurr, pncCurr = pncCurr->m_pncNext)
  3337. {
  3338. if (pncCurr == riter.m_pnc)
  3339. break;
  3340. }
  3341. IRTLASSERT(pncCurr != NULL);
  3342. // Release the iterator's reference on the record
  3343. const void* pvRecord = riter.m_pnc->m_pvNode[riter.m_iNode];
  3344. IRTLASSERT(pvRecord != NULL);
  3345. _AddRefRecord(pvRecord, -1);
  3346. // _DeleteNode will leave iterator members pointing to the
  3347. // preceding record
  3348. int iNode = riter.m_iNode;
  3349. IRTLVERIFY(_DeleteNode(pbkt, riter.m_pnc, pncPrev, iNode));
  3350. if (iNode == NODE_END)
  3351. {
  3352. LKR_ITER_TRACE(_TEXT("\t_Erase(BKT=%p, PNC=%p, PREV=%p, INODE=%d)\n"),
  3353. pbkt, riter.m_pnc, pncPrev, iNode);
  3354. }
  3355. riter.m_iNode = (short) ((iNode == NODE_END) ? NODE_END-NODE_STEP : iNode);
  3356. pbkt->WriteUnlock();
  3357. // Don't contract the table. Likely to invalidate the iterator,
  3358. // if iterator is being used in a loop
  3359. return true;
  3360. } // CLKRLinearHashTable::_Erase()
  3361. //------------------------------------------------------------------------
  3362. // Function: CLKRLinearHashTable::Erase
  3363. // Synopsis:
  3364. //------------------------------------------------------------------------
  3365. bool
  3366. CLKRLinearHashTable::Erase(
  3367. Iterator& riter)
  3368. {
  3369. if (!IsUsable() || !_IsValidIterator(riter))
  3370. return false;
  3371. DWORD dwSignature = _CalcKeyHash(_ExtractKey(riter.Record()));
  3372. LKR_ITER_TRACE(_TEXT(" LKLH:Erase:pre(iter=%p, plht=%p, NC=%p, BA=%u, ")
  3373. _TEXT("IN=%d, Sig=%x, Rec=%p)\n"),
  3374. &riter, riter.m_plht, riter.m_pnc, riter.m_dwBucketAddr,
  3375. riter.m_iNode, dwSignature,
  3376. riter.m_pnc ? riter.m_pnc->m_pvNode[riter.m_iNode] : NULL);
  3377. bool fSuccess = _Erase(riter, dwSignature);
  3378. bool fIncrement = false;
  3379. LKR_ITER_TRACE(_TEXT(" LKLH:Erase:post(iter=%p, plht=%p, NC=%p, BA=%u, ")
  3380. _TEXT("IN=%d, Sig=%x, Rec=%p, Success=%s)\n"),
  3381. &riter, riter.m_plht, riter.m_pnc, riter.m_dwBucketAddr,
  3382. riter.m_iNode, dwSignature,
  3383. riter.m_pnc ? riter.m_pnc->m_pvNode[riter.m_iNode] : NULL,
  3384. (fSuccess ? "true" : "false"));
  3385. // _Erase left riter pointing to the preceding record.
  3386. // Move to next record.
  3387. if (fSuccess)
  3388. fIncrement = riter._Increment(false);
  3389. IRTLASSERT(riter.m_iNode != NODE_BEGIN - NODE_STEP);
  3390. IRTLASSERT(fIncrement ? _IsValidIterator(riter) : riter == End());
  3391. LKR_ITER_TRACE(_TEXT(" LKLH:Erase:post++(iter=%p, plht=%p, NC=%p, ")
  3392. _TEXT("BA=%u, IN=%d, Sig=%x, Rec=%p)\n"),
  3393. &riter, riter.m_plht, riter.m_pnc,
  3394. riter.m_dwBucketAddr, riter.m_iNode, dwSignature,
  3395. riter.m_pnc ? riter.m_pnc->m_pvNode[riter.m_iNode] : NULL);
  3396. return fSuccess;
  3397. } // CLKRLinearHashTable::Erase
  3398. //------------------------------------------------------------------------
  3399. // Function: CLKRLinearHashTable::Erase
  3400. // Synopsis:
  3401. //------------------------------------------------------------------------
  3402. bool
  3403. CLKRLinearHashTable::Erase(
  3404. Iterator& riterFirst,
  3405. Iterator& riterLast)
  3406. {
  3407. LKR_ITER_TRACE(_TEXT(" LKHT:Erase2(%p, %p)\n"), &riterFirst, &riterLast);
  3408. bool fSuccess;
  3409. int cRecords = 0;
  3410. do
  3411. {
  3412. LKR_ITER_TRACE(_TEXT("\n LKLH:Erase2(%d, %p)\n"),
  3413. ++cRecords, &riterFirst);
  3414. fSuccess = Erase(riterFirst);
  3415. } while (fSuccess && riterFirst != End() && riterFirst != riterLast);
  3416. LKR_ITER_TRACE(_TEXT(" LKLH:Erase2: fSuccess = %s\n"),
  3417. (fSuccess ? "true" : "false"));
  3418. return fSuccess;
  3419. } // CLKRLinearHashTable::Erase
  3420. //------------------------------------------------------------------------
  3421. // Function: CLKRLinearHashTable::Find
  3422. // Synopsis:
  3423. //------------------------------------------------------------------------
  3424. bool
  3425. CLKRLinearHashTable::Find(
  3426. DWORD_PTR pnKey,
  3427. Iterator& riterResult)
  3428. {
  3429. riterResult = End();
  3430. if (!IsUsable())
  3431. return false;
  3432. const void* pvRecord = NULL;
  3433. DWORD hash_val = _CalcKeyHash(pnKey);
  3434. bool fFound = (_FindKey(pnKey, hash_val, &pvRecord, &riterResult)
  3435. == LK_SUCCESS);
  3436. IRTLASSERT(fFound
  3437. ? _IsValidIterator(riterResult) && riterResult.Key() == pnKey
  3438. : riterResult == End());
  3439. IRTLASSERT(riterResult.m_iNode != NODE_BEGIN - NODE_STEP);
  3440. return fFound;
  3441. } // CLKRLinearHashTable::Find
  3442. //------------------------------------------------------------------------
  3443. // Function: CLKRLinearHashTable::EqualRange
  3444. // Synopsis:
  3445. //------------------------------------------------------------------------
  3446. bool
  3447. CLKRLinearHashTable::EqualRange(
  3448. DWORD_PTR pnKey,
  3449. Iterator& riterFirst,
  3450. Iterator& riterLast)
  3451. {
  3452. LKR_ITER_TRACE(_TEXT(" LKLH:EqualRange: Key=%p)\n"), (void*) pnKey);
  3453. riterLast = End();
  3454. bool fFound = Find(pnKey, riterFirst);
  3455. if (fFound)
  3456. {
  3457. riterLast = riterFirst;
  3458. IRTLASSERT(riterLast != End());
  3459. do
  3460. {
  3461. riterLast._Increment();
  3462. } while (riterLast != End() && riterLast.Key() == pnKey);
  3463. }
  3464. IRTLASSERT(riterFirst.m_iNode != NODE_BEGIN - NODE_STEP);
  3465. IRTLASSERT(fFound ? _IsValidIterator(riterFirst) : riterFirst == End());
  3466. IRTLASSERT(riterLast.m_iNode != NODE_BEGIN - NODE_STEP);
  3467. IRTLASSERT(fFound || riterLast == End());
  3468. return fFound;
  3469. } // CLKRLinearHashTable::EqualRange
  3470. //------------------------------------------------------------------------
  3471. // Function: CLKRHashTable::Begin
  3472. // Synopsis: Make the iterator point to the first record in the hash table.
  3473. //------------------------------------------------------------------------
  3474. CLKRHashTable::Iterator
  3475. CLKRHashTable::Begin()
  3476. {
  3477. Iterator iter(this, -1);
  3478. LKR_ITER_TRACE(_TEXT(" LKHT:Begin(it=%p, pht=%p)\n"), &iter, this);
  3479. // Let Increment do the hard work of finding the first slot in use.
  3480. iter._Increment(false);
  3481. IRTLASSERT(iter.m_ist != -1);
  3482. IRTLASSERT(iter == End() || _IsValidIterator(iter));
  3483. return iter;
  3484. } // CLKRHashTable::Begin
  3485. //------------------------------------------------------------------------
  3486. // Function: CLKRHashTable_Iterator::_Increment()
  3487. // Synopsis: move iterator to next valid record in table
  3488. //------------------------------------------------------------------------
  3489. bool
  3490. CLKRHashTable_Iterator::_Increment(
  3491. bool fDecrementOldValue)
  3492. {
  3493. IRTLASSERT(m_pht != NULL);
  3494. IRTLASSERT(-1 <= m_ist
  3495. && m_ist < static_cast<int>(m_pht->m_cSubTables));
  3496. for (;;)
  3497. {
  3498. // Do we have a valid iterator into a subtable? If not, get one.
  3499. while (m_subiter.m_plht == NULL)
  3500. {
  3501. while (++m_ist < static_cast<int>(m_pht->m_cSubTables))
  3502. {
  3503. LKR_ITER_TRACE(_TEXT(" LKHT:++IST=%d\n"), m_ist);
  3504. m_subiter = m_pht->m_palhtDir[m_ist]->Begin();
  3505. if (m_subiter.m_plht != NULL)
  3506. {
  3507. LKR_ITER_TRACE(_TEXT(" LKHT:++(this=%p, pht=%p, IST=%d, ")
  3508. _TEXT("LHT=%p, NC=%p, ")
  3509. _TEXT("BA=%u, IN=%d, Rec=%p)\n"),
  3510. this, m_pht, m_ist,
  3511. m_subiter.m_plht, m_subiter.m_pnc,
  3512. m_subiter.m_dwBucketAddr, m_subiter.m_iNode,
  3513. m_subiter.m_pnc->m_pvNode[m_subiter.m_iNode]
  3514. );
  3515. return true;
  3516. }
  3517. }
  3518. // There are no more subtables left.
  3519. LKR_ITER_TRACE(_TEXT(" LKHT:End(this=%p, pht=%p)\n"), this, m_pht);
  3520. m_pht = NULL;
  3521. m_ist = 0;
  3522. //// IRTLASSERT(this->operator==(Iterator())); // == end()
  3523. return false;
  3524. }
  3525. // We already have a valid iterator into a subtable. Increment it.
  3526. m_subiter._Increment(fDecrementOldValue);
  3527. if (m_subiter.m_plht != NULL)
  3528. {
  3529. LKR_ITER_TRACE(_TEXT(" LKHT:++(this=%p, pht=%p, IST=%d, ")
  3530. _TEXT("LHT=%p, NC=%p, BA=%u, IN=%d, Rec=%p)\n"),
  3531. this, m_pht, m_ist,
  3532. m_subiter.m_plht, m_subiter.m_pnc,
  3533. m_subiter.m_dwBucketAddr, m_subiter.m_iNode,
  3534. m_subiter.m_pnc->m_pvNode[m_subiter.m_iNode]);
  3535. return true;
  3536. }
  3537. }
  3538. } // CLKRHashTable_Iterator::_Increment()
  3539. //------------------------------------------------------------------------
  3540. // Function: CLKRHashTable::Insert
  3541. // Synopsis:
  3542. //------------------------------------------------------------------------
  3543. bool
  3544. CLKRHashTable::Insert(
  3545. const void* pvRecord,
  3546. Iterator& riterResult,
  3547. bool fOverwrite)
  3548. {
  3549. riterResult = End();
  3550. if (!IsUsable() || pvRecord == NULL)
  3551. return false;
  3552. DWORD hash_val = _CalcKeyHash(_ExtractKey(pvRecord));
  3553. SubTable* const pst = _SubTable(hash_val);
  3554. bool f = (pst->_InsertRecord(pvRecord, hash_val, fOverwrite,
  3555. &riterResult.m_subiter)
  3556. == LK_SUCCESS);
  3557. if (f)
  3558. {
  3559. riterResult.m_pht = this;
  3560. riterResult.m_ist = (short) _SubTableIndex(pst);
  3561. }
  3562. IRTLASSERT(riterResult.m_ist != -1);
  3563. IRTLASSERT(f ? _IsValidIterator(riterResult) : riterResult == End());
  3564. return f;
  3565. } // CLKRHashTable::Insert
  3566. //------------------------------------------------------------------------
  3567. // Function: CLKRHashTable::Erase
  3568. // Synopsis:
  3569. //------------------------------------------------------------------------
  3570. bool
  3571. CLKRHashTable::Erase(
  3572. Iterator& riter)
  3573. {
  3574. if (!IsUsable() || !_IsValidIterator(riter))
  3575. return false;
  3576. DWORD dwSignature = _CalcKeyHash(_ExtractKey(riter.Record()));
  3577. SubTable* const pst = _SubTable(dwSignature);
  3578. IRTLASSERT(pst == riter.m_subiter.m_plht);
  3579. if (pst != riter.m_subiter.m_plht)
  3580. return false;
  3581. LKR_ITER_TRACE(_TEXT(" LKHT:Erase:pre(iter=%p, pht=%p, ist=%d, plht=%p, ")
  3582. _TEXT("NC=%p, BA=%u, IN=%d, Sig=%x, Rec=%p)\n"),
  3583. &riter, riter.m_pht, riter.m_ist,
  3584. riter.m_subiter.m_plht, riter.m_subiter.m_pnc,
  3585. riter.m_subiter.m_dwBucketAddr, riter.m_subiter.m_iNode,
  3586. dwSignature,
  3587. (riter.m_subiter.m_pnc ? riter.Record() : NULL));
  3588. // _Erase left riter pointing to the preceding record. Move to
  3589. // next record.
  3590. bool fSuccess = pst->_Erase(riter.m_subiter, dwSignature);
  3591. bool fIncrement = false;
  3592. LKR_ITER_TRACE(_TEXT(" LKHT:Erase:post(iter=%p, pht=%p, ist=%d, plht=%p, ")
  3593. _TEXT("NC=%p, BA=%u, IN=%d, Sig=%x, Rec=%p, Success=%s)\n"),
  3594. &riter, riter.m_pht, riter.m_ist,
  3595. riter.m_subiter.m_plht, riter.m_subiter.m_pnc,
  3596. riter.m_subiter.m_dwBucketAddr, riter.m_subiter.m_iNode,
  3597. dwSignature,
  3598. ((riter.m_subiter.m_pnc && riter.m_subiter.m_iNode >= 0)
  3599. ? riter.Record() : NULL),
  3600. (fSuccess ? "true" : "false"));
  3601. if (fSuccess)
  3602. fIncrement = riter._Increment(false);
  3603. IRTLASSERT(riter.m_ist != -1);
  3604. IRTLASSERT(fIncrement ? _IsValidIterator(riter) : riter == End());
  3605. LKR_ITER_TRACE(_TEXT(" LKHT:Erase:post++(iter=%p, pht=%p, ist=%d, ")
  3606. _TEXT("plht=%p, NC=%p, ")
  3607. _TEXT("BA=%u, IN=%d, Sig=%x, Rec=%p)\n"),
  3608. &riter, riter.m_pht, riter.m_ist,
  3609. riter.m_subiter.m_plht, riter.m_subiter.m_pnc,
  3610. riter.m_subiter.m_dwBucketAddr, riter.m_subiter.m_iNode,
  3611. dwSignature,
  3612. (riter.m_subiter.m_pnc ? riter.Record() : NULL));
  3613. return fSuccess;
  3614. } // CLKRHashTable::Erase
  3615. //------------------------------------------------------------------------
  3616. // Function: CLKRHashTable::Erase
  3617. // Synopsis:
  3618. //------------------------------------------------------------------------
  3619. bool
  3620. CLKRHashTable::Erase(
  3621. Iterator& riterFirst,
  3622. Iterator& riterLast)
  3623. {
  3624. LKR_ITER_TRACE(_TEXT(" LKHT:Erase2(%p, %p)\n"), &riterFirst, &riterLast);
  3625. bool fSuccess;
  3626. int cRecords = 0;
  3627. do
  3628. {
  3629. LKR_ITER_TRACE(_TEXT("\n LKHT:Erase2(%d, %p)\n"),
  3630. ++cRecords, &riterFirst);
  3631. fSuccess = Erase(riterFirst);
  3632. } while (fSuccess && riterFirst != End() && riterFirst != riterLast);
  3633. LKR_ITER_TRACE(_TEXT(" LKHT:Erase2: fSuccess = %s\n"),
  3634. (fSuccess ? "true" : "false"));
  3635. return fSuccess;
  3636. } // CLKRHashTable::Erase
  3637. //------------------------------------------------------------------------
  3638. // Function: CLKRHashTable::Find
  3639. // Synopsis:
  3640. //------------------------------------------------------------------------
  3641. bool
  3642. CLKRHashTable::Find(
  3643. DWORD_PTR pnKey,
  3644. Iterator& riterResult)
  3645. {
  3646. riterResult = End();
  3647. if (!IsUsable())
  3648. return false;
  3649. const void* pvRecord = NULL;
  3650. DWORD hash_val = _CalcKeyHash(pnKey);
  3651. SubTable* const pst = _SubTable(hash_val);
  3652. bool fFound = (pst->_FindKey(pnKey, hash_val, &pvRecord,
  3653. &riterResult.m_subiter)
  3654. == LK_SUCCESS);
  3655. if (fFound)
  3656. {
  3657. riterResult.m_pht = this;
  3658. riterResult.m_ist = (short) _SubTableIndex(pst);
  3659. }
  3660. IRTLASSERT(riterResult.m_ist != -1);
  3661. IRTLASSERT(fFound
  3662. ? _IsValidIterator(riterResult) && riterResult.Key() == pnKey
  3663. : riterResult == End());
  3664. return fFound;
  3665. } // CLKRHashTable::Find
  3666. //------------------------------------------------------------------------
  3667. // Function: CLKRHashTable::EqualRange
  3668. // Synopsis:
  3669. //------------------------------------------------------------------------
  3670. bool
  3671. CLKRHashTable::EqualRange(
  3672. DWORD_PTR pnKey,
  3673. Iterator& riterFirst,
  3674. Iterator& riterLast)
  3675. {
  3676. LKR_ITER_TRACE(_TEXT(" LKHT:EqualRange: Key=%p)\n"), (void*) pnKey);
  3677. riterLast = End();
  3678. bool fFound = Find(pnKey, riterFirst);
  3679. if (fFound)
  3680. {
  3681. riterLast = riterFirst;
  3682. IRTLASSERT(riterLast != End());
  3683. do
  3684. {
  3685. riterLast._Increment();
  3686. } while (riterLast != End() && riterLast.Key() == pnKey);
  3687. }
  3688. IRTLASSERT(riterFirst.m_ist != -1);
  3689. IRTLASSERT(fFound ? _IsValidIterator(riterFirst) : riterFirst == End());
  3690. IRTLASSERT(riterLast.m_ist != -1);
  3691. IRTLASSERT(fFound || riterLast == End());
  3692. return fFound;
  3693. } // CLKRHashTable::EqualRange
  3694. #endif // LKR_STL_ITERATORS
  3695. //------------------------------------------------------------------------
  3696. // Function: CLKRHashTable::WriteLock
  3697. // Synopsis: Lock all subtables for writing
  3698. //------------------------------------------------------------------------
  3699. void
  3700. CLKRHashTable::WriteLock()
  3701. {
  3702. for (DWORD i = 0; i < m_cSubTables; i++)
  3703. {
  3704. m_palhtDir[i]->WriteLock();
  3705. IRTLASSERT(m_palhtDir[i]->IsWriteLocked());
  3706. }
  3707. } // CLKRHashTable::WriteLock
  3708. //------------------------------------------------------------------------
  3709. // Function: CLKRHashTable::ReadLock
  3710. // Synopsis: Lock all subtables for reading
  3711. //------------------------------------------------------------------------
  3712. void
  3713. CLKRHashTable::ReadLock() const
  3714. {
  3715. for (DWORD i = 0; i < m_cSubTables; i++)
  3716. {
  3717. m_palhtDir[i]->ReadLock();
  3718. IRTLASSERT(m_palhtDir[i]->IsReadLocked());
  3719. }
  3720. } // CLKRHashTable::ReadLock
  3721. //------------------------------------------------------------------------
  3722. // Function: CLKRHashTable::WriteUnlock
  3723. // Synopsis: Unlock all subtables
  3724. //------------------------------------------------------------------------
  3725. void
  3726. CLKRHashTable::WriteUnlock() const
  3727. {
  3728. // unlock in reverse order: LIFO
  3729. for (DWORD i = m_cSubTables; i-- > 0; )
  3730. {
  3731. IRTLASSERT(m_palhtDir[i]->IsWriteLocked());
  3732. m_palhtDir[i]->WriteUnlock();
  3733. IRTLASSERT(m_palhtDir[i]->IsWriteUnlocked());
  3734. }
  3735. } // CLKRHashTable::WriteUnlock
  3736. //------------------------------------------------------------------------
  3737. // Function: CLKRHashTable::ReadUnlock
  3738. // Synopsis: Unlock all subtables
  3739. //------------------------------------------------------------------------
  3740. void
  3741. CLKRHashTable::ReadUnlock() const
  3742. {
  3743. // unlock in reverse order: LIFO
  3744. for (DWORD i = m_cSubTables; i-- > 0; )
  3745. {
  3746. IRTLASSERT(m_palhtDir[i]->IsReadLocked());
  3747. m_palhtDir[i]->ReadUnlock();
  3748. IRTLASSERT(m_palhtDir[i]->IsReadUnlocked());
  3749. }
  3750. } // CLKRHashTable::ReadUnlock
  3751. //------------------------------------------------------------------------
  3752. // Function: CLKRHashTable::IsWriteLocked
  3753. // Synopsis: Are all subtables write-locked?
  3754. //------------------------------------------------------------------------
  3755. bool
  3756. CLKRHashTable::IsWriteLocked() const
  3757. {
  3758. bool fLocked = (m_cSubTables > 0);
  3759. for (DWORD i = 0; i < m_cSubTables; i++)
  3760. {
  3761. fLocked = fLocked && m_palhtDir[i]->IsWriteLocked();
  3762. }
  3763. return fLocked;
  3764. } // CLKRHashTable::IsWriteLocked
  3765. //------------------------------------------------------------------------
  3766. // Function: CLKRHashTable::IsReadLocked
  3767. // Synopsis: Are all subtables read-locked?
  3768. //------------------------------------------------------------------------
  3769. bool
  3770. CLKRHashTable::IsReadLocked() const
  3771. {
  3772. bool fLocked = (m_cSubTables > 0);
  3773. for (DWORD i = 0; i < m_cSubTables; i++)
  3774. {
  3775. fLocked = fLocked && m_palhtDir[i]->IsReadLocked();
  3776. }
  3777. return fLocked;
  3778. } // CLKRHashTable::IsReadLocked
  3779. //------------------------------------------------------------------------
  3780. // Function: CLKRHashTable::IsWriteUnlocked
  3781. // Synopsis: Are all subtables write-unlocked?
  3782. //------------------------------------------------------------------------
  3783. bool
  3784. CLKRHashTable::IsWriteUnlocked() const
  3785. {
  3786. bool fUnlocked = (m_cSubTables > 0);
  3787. for (DWORD i = 0; i < m_cSubTables; i++)
  3788. {
  3789. fUnlocked = fUnlocked && m_palhtDir[i]->IsWriteUnlocked();
  3790. }
  3791. return fUnlocked;
  3792. } // CLKRHashTable::IsWriteUnlocked
  3793. //------------------------------------------------------------------------
  3794. // Function: CLKRHashTable::IsReadUnlocked
  3795. // Synopsis: Are all subtables read-unlocked?
  3796. //------------------------------------------------------------------------
  3797. bool
  3798. CLKRHashTable::IsReadUnlocked() const
  3799. {
  3800. bool fUnlocked = (m_cSubTables > 0);
  3801. for (DWORD i = 0; i < m_cSubTables; i++)
  3802. {
  3803. fUnlocked = fUnlocked && m_palhtDir[i]->IsReadUnlocked();
  3804. }
  3805. return fUnlocked;
  3806. } // CLKRHashTable::IsReadUnlocked
  3807. //------------------------------------------------------------------------
  3808. // Function: CLKRHashTable::ConvertSharedToExclusive
  3809. // Synopsis: Convert the read lock to a write lock
  3810. //------------------------------------------------------------------------
  3811. void
  3812. CLKRHashTable::ConvertSharedToExclusive() const
  3813. {
  3814. for (DWORD i = 0; i < m_cSubTables; i++)
  3815. {
  3816. m_palhtDir[i]->ConvertSharedToExclusive();
  3817. IRTLASSERT(m_palhtDir[i]->IsWriteLocked());
  3818. }
  3819. } // CLKRHashTable::ConvertSharedToExclusive
  3820. //------------------------------------------------------------------------
  3821. // Function: CLKRHashTable::ConvertExclusiveToShared
  3822. // Synopsis: Convert the write lock to a read lock
  3823. //------------------------------------------------------------------------
  3824. void
  3825. CLKRHashTable::ConvertExclusiveToShared() const
  3826. {
  3827. for (DWORD i = 0; i < m_cSubTables; i++)
  3828. {
  3829. m_palhtDir[i]->ConvertExclusiveToShared();
  3830. IRTLASSERT(m_palhtDir[i]->IsReadLocked());
  3831. }
  3832. } // CLKRHashTable::ConvertExclusiveToShared
  3833. //------------------------------------------------------------------------
  3834. // Function: CLKRHashTable::Size
  3835. // Synopsis: Number of elements in the table
  3836. //------------------------------------------------------------------------
  3837. DWORD
  3838. CLKRHashTable::Size() const
  3839. {
  3840. DWORD cSize = 0;
  3841. for (DWORD i = 0; i < m_cSubTables; i++)
  3842. cSize += m_palhtDir[i]->Size();
  3843. return cSize;
  3844. } // CLKRHashTable::Size
  3845. //------------------------------------------------------------------------
  3846. // Function: CLKRHashTable::MaxSize
  3847. // Synopsis: Maximum possible number of elements in the table
  3848. //------------------------------------------------------------------------
  3849. DWORD
  3850. CLKRHashTable::MaxSize() const
  3851. {
  3852. return (m_cSubTables == 0) ? 0 : m_cSubTables * m_palhtDir[0]->MaxSize();
  3853. } // CLKRHashTable::MaxSize
  3854. //------------------------------------------------------------------------
  3855. // Function: CLKRHashTable::IsValid
  3856. // Synopsis: is the table valid?
  3857. //------------------------------------------------------------------------
  3858. bool
  3859. CLKRHashTable::IsValid() const
  3860. {
  3861. bool f = (m_lkrcState == LK_SUCCESS // serious internal failure?
  3862. && (m_palhtDir != NULL && m_cSubTables > 0)
  3863. && ValidSignature());
  3864. for (DWORD i = 0; f && i < m_cSubTables; i++)
  3865. f = f && m_palhtDir[i]->IsValid();
  3866. if (!f)
  3867. m_lkrcState = LK_UNUSABLE;
  3868. return f;
  3869. } // CLKRHashTable::IsValid
  3870. //------------------------------------------------------------------------
  3871. // Function: CLKRHashTable::SetBucketLockSpinCount
  3872. // Synopsis:
  3873. //------------------------------------------------------------------------
  3874. void
  3875. CLKRLinearHashTable::SetBucketLockSpinCount(
  3876. WORD wSpins)
  3877. {
  3878. m_wBucketLockSpins = wSpins;
  3879. if (BucketLock::PerLockSpin() != LOCK_INDIVIDUAL_SPIN)
  3880. return;
  3881. for (DWORD i = 0; i < m_cDirSegs; i++)
  3882. {
  3883. CSegment* pseg = m_paDirSegs[i].m_pseg;
  3884. if (pseg != NULL)
  3885. {
  3886. for (DWORD j = 0; j < m_dwSegSize; ++j)
  3887. {
  3888. pseg->Slot(j).SetSpinCount(wSpins);
  3889. }
  3890. }
  3891. }
  3892. } // CLKRLinearHashTable::SetBucketLockSpinCount
  3893. //------------------------------------------------------------------------
  3894. // Function: CLKRHashTable::SetBucketLockSpinCount
  3895. // Synopsis:
  3896. //------------------------------------------------------------------------
  3897. WORD
  3898. CLKRLinearHashTable::GetBucketLockSpinCount() const
  3899. {
  3900. return m_wBucketLockSpins;
  3901. } // CLKRLinearHashTable::GetBucketLockSpinCount
  3902. //------------------------------------------------------------------------
  3903. // Function: CLKRHashTable::SetTableLockSpinCount
  3904. // Synopsis:
  3905. //------------------------------------------------------------------------
  3906. void
  3907. CLKRHashTable::SetTableLockSpinCount(
  3908. WORD wSpins)
  3909. {
  3910. for (DWORD i = 0; i < m_cSubTables; i++)
  3911. m_palhtDir[i]->SetTableLockSpinCount(wSpins);
  3912. } // CLKRHashTable::SetTableLockSpinCount
  3913. //------------------------------------------------------------------------
  3914. // Function: CLKRHashTable::GetTableLockSpinCount
  3915. // Synopsis:
  3916. //------------------------------------------------------------------------
  3917. WORD
  3918. CLKRHashTable::GetTableLockSpinCount() const
  3919. {
  3920. return ((m_cSubTables == 0)
  3921. ? (WORD) LOCK_DEFAULT_SPINS
  3922. : m_palhtDir[0]->GetTableLockSpinCount());
  3923. } // CLKRHashTable::GetTableLockSpinCount
  3924. //------------------------------------------------------------------------
  3925. // Function: CLKRHashTable::SetBucketLockSpinCount
  3926. // Synopsis:
  3927. //------------------------------------------------------------------------
  3928. void
  3929. CLKRHashTable::SetBucketLockSpinCount(
  3930. WORD wSpins)
  3931. {
  3932. for (DWORD i = 0; i < m_cSubTables; i++)
  3933. m_palhtDir[i]->SetBucketLockSpinCount(wSpins);
  3934. } // CLKRHashTable::SetBucketLockSpinCount
  3935. //------------------------------------------------------------------------
  3936. // Function: CLKRHashTable::GetBucketLockSpinCount
  3937. // Synopsis:
  3938. //------------------------------------------------------------------------
  3939. WORD
  3940. CLKRHashTable::GetBucketLockSpinCount() const
  3941. {
  3942. return ((m_cSubTables == 0)
  3943. ? (WORD) LOCK_DEFAULT_SPINS
  3944. : m_palhtDir[0]->GetBucketLockSpinCount());
  3945. } // CLKRHashTable::GetBucketLockSpinCount
  3946. //------------------------------------------------------------------------
  3947. // Function: CLKRHashTable::MultiKeys
  3948. // Synopsis:
  3949. //------------------------------------------------------------------------
  3950. bool
  3951. CLKRHashTable::MultiKeys() const
  3952. {
  3953. return ((m_cSubTables == 0)
  3954. ? false
  3955. : m_palhtDir[0]->MultiKeys());
  3956. } // CLKRHashTable::MultiKeys
  3957. #ifndef __LKRHASH_NO_NAMESPACE__
  3958. }
  3959. #endif // !__LKRHASH_NO_NAMESPACE__