HeapBlockMap.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "CommonMemoryPch.h"
  6. // The VS2013 linker treats this as a redefinition of an already
  7. // defined constant and complains. So skip the declaration if we're compiling
  8. // with VS2013 or below.
  9. #if !defined(_MSC_VER) || _MSC_VER >= 1900
  10. const uint Memory::HeapBlockMap32::L1Count;
  11. const uint Memory::HeapBlockMap32::L2Count;
  12. #endif
  13. #if defined(TARGET_64)
  14. HeapBlockMap32::HeapBlockMap32(__in char * startAddress) :
  15. startAddress(startAddress),
  16. #else
  17. HeapBlockMap32::HeapBlockMap32() :
  18. #endif
  19. count(0)
  20. {
  21. memset(map, 0, sizeof(map));
  22. #if defined(TARGET_64)
  23. Assert(((size_t)startAddress) % TotalSize == 0);
  24. #endif
  25. }
  26. HeapBlockMap32::~HeapBlockMap32()
  27. {
  28. for (uint i = 0; i < _countof(map); i++)
  29. {
  30. L2MapChunk * chunk = map[i];
  31. if (chunk)
  32. {
  33. NoMemProtectHeapDelete(chunk);
  34. }
  35. }
  36. }
  37. HeapBlock *
  38. HeapBlockMap32::GetHeapBlock(void * address)
  39. {
  40. uint id1 = GetLevel1Id(address);
  41. L2MapChunk * l2map = map[id1];
  42. if (l2map == nullptr)
  43. {
  44. return nullptr;
  45. }
  46. return l2map->Get(address);
  47. }
  48. bool
  49. HeapBlockMap32::EnsureHeapBlock(void * address, uint pageCount)
  50. {
  51. uint id1 = GetLevel1Id(address);
  52. uint id2 = GetLevel2Id(address);
  53. uint currentPageCount = min(pageCount, L2Count - id2);
  54. while (true)
  55. {
  56. if (map[id1] == nullptr)
  57. {
  58. L2MapChunk * newChunk = NoMemProtectHeapNewNoThrowZ(L2MapChunk);
  59. if (newChunk == nullptr)
  60. {
  61. // Leave any previously allocated L2MapChunks in place --
  62. // the concurrent thread may have already accessed them.
  63. // These will be cleaned up in the Cleanup method, after Sweep is complete.
  64. return false;
  65. }
  66. map[id1] = newChunk;
  67. count++;
  68. }
  69. pageCount -= currentPageCount;
  70. if (pageCount == 0)
  71. {
  72. break;
  73. }
  74. id2 = 0;
  75. id1++;
  76. currentPageCount = min(pageCount, L2Count);
  77. }
  78. return true;
  79. }
  80. void
  81. HeapBlockMap32::SetHeapBlockNoCheck(void * address, uint pageCount, HeapBlock * heapBlock, HeapBlock::HeapBlockType blockType, byte bucketIndex)
  82. {
  83. uint id1 = GetLevel1Id(address);
  84. uint id2 = GetLevel2Id(address);
  85. uint currentPageCount = min(pageCount, L2Count - id2);
  86. while (true)
  87. {
  88. Assert(map[id1] != nullptr);
  89. map[id1]->Set(id2, currentPageCount, heapBlock, blockType, bucketIndex);
  90. pageCount -= currentPageCount;
  91. if (pageCount == 0)
  92. {
  93. return;
  94. }
  95. id2 = 0;
  96. id1++;
  97. currentPageCount = min(pageCount, Memory::HeapBlockMap32::L2Count);
  98. }
  99. }
  100. bool
  101. HeapBlockMap32::SetHeapBlock(void * address, uint pageCount, HeapBlock * heapBlock, HeapBlock::HeapBlockType blockType, byte bucketIndex)
  102. {
  103. // First, make sure we have all the necessary L2MapChunks we'll need.
  104. // This ensures that in case of failure, the concurrent thread won't see an inconsistent state.
  105. if (!EnsureHeapBlock(address, pageCount))
  106. {
  107. return false;
  108. }
  109. // Now, do the actual set, which cannot fail.
  110. SetHeapBlockNoCheck(address, pageCount, heapBlock, blockType, bucketIndex);
  111. return true;
  112. }
  113. void
  114. HeapBlockMap32::ClearHeapBlock(void * address, uint pageCount)
  115. {
  116. uint id1 = GetLevel1Id(address);
  117. uint id2 = GetLevel2Id(address);
  118. uint currentPageCount = min(pageCount, L2Count - id2);
  119. while (true)
  120. {
  121. Assert(map[id1] != nullptr);
  122. map[id1]->Clear(id2, currentPageCount);
  123. pageCount -= currentPageCount;
  124. if (pageCount == 0)
  125. {
  126. return;
  127. }
  128. id2 = 0;
  129. id1++;
  130. currentPageCount = min(pageCount, L2Count);
  131. }
  132. }
  133. HeapBlockMap32::PageMarkBitVector *
  134. HeapBlockMap32::GetPageMarkBitVector(void * address)
  135. {
  136. uint id1 = GetLevel1Id(address);
  137. L2MapChunk * l2map = map[id1];
  138. if (l2map == nullptr)
  139. {
  140. return nullptr;
  141. }
  142. return l2map->GetPageMarkBitVector(address);
  143. }
  144. template <size_t BitCount>
  145. BVStatic<BitCount>*
  146. HeapBlockMap32::GetMarkBitVectorForPages(void * address)
  147. {
  148. uint id1 = GetLevel1Id(address);
  149. L2MapChunk * l2map = map[id1];
  150. if (l2map == nullptr)
  151. {
  152. return nullptr;
  153. }
  154. return l2map->GetMarkBitVectorForPages<BitCount>(address);
  155. }
  156. template BVStatic<SmallAllocationBlockAttributes::BitVectorCount>* HeapBlockMap32::GetMarkBitVectorForPages<SmallAllocationBlockAttributes::BitVectorCount>(void * address);
  157. template BVStatic<MediumAllocationBlockAttributes::BitVectorCount>* HeapBlockMap32::GetMarkBitVectorForPages<MediumAllocationBlockAttributes::BitVectorCount>(void * address);
  158. uint
  159. HeapBlockMap32::GetMarkCount(void * address, uint pageCount)
  160. {
  161. uint markCount = 0;
  162. ForEachChunkInAddressRange(address, pageCount, [&](L2MapChunk* l2Map, uint chunkId)
  163. {
  164. markCount += l2Map->GetPageMarkBitVector(chunkId /* pageIndex */)->Count();
  165. });
  166. return markCount;
  167. }
  168. template <class Fn>
  169. void
  170. HeapBlockMap32::ForEachChunkInAddressRange(void * address, size_t pageCount, Fn fn)
  171. {
  172. uint id1 = GetLevel1Id(address);
  173. uint id2 = GetLevel2Id(address);
  174. while (true)
  175. {
  176. L2MapChunk * l2map = map[id1];
  177. Assert(l2map != nullptr);
  178. if (l2map != nullptr)
  179. {
  180. while (id2 < L2Count)
  181. {
  182. fn(l2map, id2);
  183. id2++;
  184. pageCount--;
  185. if (pageCount == 0)
  186. {
  187. return;
  188. }
  189. }
  190. id2 = 0;
  191. id1++;
  192. }
  193. }
  194. }
  195. bool
  196. HeapBlockMap32::IsMarked(void * address) const
  197. {
  198. uint id1 = GetLevel1Id(address);
  199. L2MapChunk * chunk = map[id1];
  200. Assert(chunk != nullptr);
  201. return chunk->IsMarked(address);
  202. }
  203. void
  204. HeapBlockMap32::SetMark(void * address)
  205. {
  206. uint id1 = GetLevel1Id(address);
  207. L2MapChunk * chunk = map[id1];
  208. Assert(chunk != nullptr);
  209. return chunk->SetMark(address);
  210. }
  211. bool
  212. HeapBlockMap32::TestAndSetMark(void * address)
  213. {
  214. uint id1 = GetLevel1Id(address);
  215. L2MapChunk * chunk = map[id1];
  216. if (chunk == nullptr)
  217. {
  218. // False reference
  219. return false;
  220. }
  221. uint bitIndex = chunk->GetMarkBitIndex(address);
  222. return (chunk->markBits.TestAndSet(bitIndex) != 0);
  223. }
  224. void
  225. HeapBlockMap32::ResetMarks()
  226. {
  227. for (uint i = 0; i < L1Count; i++)
  228. {
  229. L2MapChunk * chunk = map[i];
  230. if (chunk == nullptr)
  231. {
  232. continue;
  233. }
  234. chunk->markBits.ClearAll();
  235. #ifdef RECYCLER_VERIFY_MARK
  236. chunk->isNewChunk = false;
  237. #endif
  238. #if DBG
  239. for (uint j = 0; j < L2Count; j++)
  240. {
  241. chunk->pageMarkCount[j] = 0;
  242. }
  243. #endif
  244. }
  245. }
  246. #if DBG
  247. ushort
  248. HeapBlockMap32::GetPageMarkCount(void * address) const
  249. {
  250. uint id1 = GetLevel1Id(address);
  251. L2MapChunk * l2map = map[id1];
  252. Assert(l2map != nullptr);
  253. uint id2 = GetLevel2Id(address);
  254. return l2map->pageMarkCount[id2];
  255. }
  256. void
  257. HeapBlockMap32::SetPageMarkCount(void * address, ushort markCount)
  258. {
  259. uint id1 = GetLevel1Id(address);
  260. L2MapChunk * l2map = map[id1];
  261. Assert(l2map != nullptr);
  262. uint id2 = GetLevel2Id(address);
  263. // Callers should already have updated the mark bits by the time they call this,
  264. // so check that the new count is correct for the current mark bits.
  265. // Not true right now, will be true...
  266. #if ENABLE_ALLOCATIONS_DURING_CONCURRENT_SWEEP
  267. DebugOnly(HeapBlock * heapBlock = this->GetHeapBlock(address));
  268. Assert(l2map->GetPageMarkBitVector(id2)->Count() == markCount || heapBlock->WasAllocatedFromDuringSweep());
  269. #else
  270. Assert(l2map->GetPageMarkBitVector(id2)->Count() == markCount);
  271. #endif
  272. l2map->pageMarkCount[id2] = markCount;
  273. }
  274. template void HeapBlockMap32::VerifyMarkCountForPages<SmallAllocationBlockAttributes::BitVectorCount>(void* address, uint pageCount);
  275. template void HeapBlockMap32::VerifyMarkCountForPages<MediumAllocationBlockAttributes::BitVectorCount>(void* address, uint pageCount);
  276. template <uint BitVectorCount>
  277. void
  278. HeapBlockMap32::VerifyMarkCountForPages(void * address, uint pageCount)
  279. {
  280. uint id1 = GetLevel1Id(address);
  281. L2MapChunk * l2map = map[id1];
  282. Assert(l2map != nullptr);
  283. uint id2 = GetLevel2Id(address);
  284. Assert(id2 + pageCount <= L2Count);
  285. for (uint i = id2; i < pageCount + id2; i++)
  286. {
  287. uint markCountForPage = l2map->GetPageMarkBitVector(i)->Count();
  288. #if ENABLE_ALLOCATIONS_DURING_CONCURRENT_SWEEP
  289. DebugOnly(HeapBlock * heapBlock = this->GetHeapBlock(address));
  290. Assert(markCountForPage == l2map->pageMarkCount[i] || heapBlock->WasAllocatedFromDuringSweep());
  291. #else
  292. Assert(markCountForPage == l2map->pageMarkCount[i]);
  293. #endif
  294. }
  295. }
  296. #endif
  297. HeapBlockMap32::L2MapChunk::L2MapChunk()
  298. {
  299. // We are zero-initialized so don't need to actually init.
  300. // Mark bits should be cleared by default
  301. Assert(markBits.Count() == 0);
  302. #ifdef RECYCLER_VERIFY_MARK
  303. this->isNewChunk = true;
  304. #endif
  305. #if DBG
  306. for (uint i = 0; i < L2Count; i++)
  307. {
  308. Assert(pageMarkCount[i] == 0);
  309. }
  310. #endif
  311. }
  312. HeapBlockMap32::L2MapChunk::~L2MapChunk()
  313. {
  314. // In debug builds, we guarantee that the heap block is clear on shutdown.
  315. // In free builds, we skip this to save time.
  316. // So this assert is only true in debug builds.
  317. Assert(IsEmpty());
  318. }
  319. HeapBlock *
  320. HeapBlockMap32::L2MapChunk::Get(void * address)
  321. {
  322. uint id2 = GetLevel2Id(address);
  323. Assert(id2 < L2Count);
  324. __analysis_assume(id2 < L2Count);
  325. return map[id2];
  326. }
  327. void
  328. HeapBlockMap32::L2MapChunk::Set(uint id2, uint pageCount, HeapBlock * heapBlock, HeapBlock::HeapBlockType blockType, byte bucketIndex)
  329. {
  330. uint id2End = id2 + pageCount;
  331. Assert(id2 < L2Count);
  332. Assert(id2End <= L2Count);
  333. for (uint i = id2; i < id2End; i++)
  334. {
  335. __analysis_assume(i < L2Count);
  336. Assert(map[i] == nullptr);
  337. Assert(blockInfo[i].blockType == HeapBlock::HeapBlockType::FreeBlockType);
  338. // Set the blockType last, because we will test this first during marking.
  339. // If it's not FreeBlock, then we expect bucketIndex and heapBlock to be valid.
  340. map[i] = heapBlock;
  341. blockInfo[i].bucketIndex = bucketIndex;
  342. // We need memory barrier here for ARM to ensure that the blockType is set last.
  343. #if defined(_M_ARM32_OR_ARM64)
  344. MemoryBarrier();
  345. #endif
  346. blockInfo[i].blockType = blockType;
  347. }
  348. }
  349. void
  350. HeapBlockMap32::L2MapChunk::Clear(uint id2, uint pageCount)
  351. {
  352. uint id2End = id2 + pageCount;
  353. Assert(id2 < L2Count);
  354. Assert(id2End <= L2Count);
  355. for (uint i = id2; i < id2End; i++)
  356. {
  357. __analysis_assume(i < L2Count);
  358. Assert(map[i] != nullptr);
  359. Assert(blockInfo[i].blockType != HeapBlock::HeapBlockType::FreeBlockType);
  360. // This shouldn't be called when concurrent marking is happening, so order does not matter.
  361. // Regardless, set the blockType first just to be internally consistent.
  362. // We don't actually clear the bucketIndex because it doesn't matter if the blockType is FreeBlock.
  363. blockInfo[i].blockType = HeapBlock::HeapBlockType::FreeBlockType;
  364. map[i] = nullptr;
  365. }
  366. }
  367. bool
  368. HeapBlockMap32::L2MapChunk::IsEmpty() const
  369. {
  370. for (uint i = 0; i < L2Count; i++)
  371. {
  372. if (map[i] != nullptr)
  373. {
  374. return false;
  375. }
  376. }
  377. return true;
  378. }
  379. HeapBlockMap32::PageMarkBitVector *
  380. HeapBlockMap32::L2MapChunk::GetPageMarkBitVector(void * address)
  381. {
  382. uint id2 = GetLevel2Id(address);
  383. Assert(id2 < L2Count);
  384. __analysis_assume(id2 < L2Count);
  385. return GetPageMarkBitVector(id2);
  386. }
  387. HeapBlockMap32::PageMarkBitVector *
  388. HeapBlockMap32::L2MapChunk::GetPageMarkBitVector(uint pageIndex)
  389. {
  390. return markBits.GetRange<PageMarkBitCount>(pageIndex * PageMarkBitCount);
  391. }
  392. template <size_t BitCount>
  393. BVStatic<BitCount> *
  394. HeapBlockMap32::L2MapChunk::GetMarkBitVectorForPages(void * address)
  395. {
  396. uint id2 = GetLevel2Id(address);
  397. Assert(id2 < L2Count);
  398. __analysis_assume(id2 < L2Count);
  399. return GetMarkBitVectorForPages<BitCount>(id2);
  400. }
  401. template <size_t BitCount>
  402. BVStatic<BitCount> *
  403. HeapBlockMap32::L2MapChunk::GetMarkBitVectorForPages(uint pageIndex)
  404. {
  405. return markBits.GetRange<BitCount>(pageIndex * PageMarkBitCount);
  406. }
  407. bool
  408. HeapBlockMap32::L2MapChunk::IsMarked(void * address) const
  409. {
  410. return markBits.Test(GetMarkBitIndex(address)) == TRUE;
  411. }
  412. void
  413. HeapBlockMap32::L2MapChunk::SetMark(void * address)
  414. {
  415. markBits.Set(GetMarkBitIndex(address));
  416. }
  417. #ifdef RECYCLER_STRESS
  418. void
  419. HeapBlockMap32::InduceFalsePositives(Recycler * recycler)
  420. {
  421. for (uint i = 0; i < L1Count; i++)
  422. {
  423. L2MapChunk * chunk = map[i];
  424. if (chunk == nullptr)
  425. {
  426. continue;
  427. }
  428. for (uint j = 0; j < L2Count; j++)
  429. {
  430. HeapBlock * block = chunk->map[j];
  431. if (block == nullptr)
  432. {
  433. // Unallocated block. Try to mark the first offset, in case
  434. // we are simultaneously allocating this block on the main thread.
  435. recycler->TryMarkNonInterior((void *)GetAddressFromIds(i, j), nullptr);
  436. }
  437. else if (!block->IsLargeHeapBlock())
  438. {
  439. ((SmallHeapBlock *)block)->InduceFalsePositive(recycler);
  440. }
  441. }
  442. }
  443. }
  444. #endif
  445. #ifdef RECYCLER_VERIFY_MARK
  446. bool
  447. HeapBlockMap32::IsAddressInNewChunk(void * address)
  448. {
  449. uint id1 = GetLevel1Id(address);
  450. L2MapChunk * l2map = map[id1];
  451. Assert(l2map != nullptr);
  452. return l2map->isNewChunk;
  453. }
  454. #endif
  455. template <class Fn>
  456. void
  457. HeapBlockMap32::ForEachSegment(Recycler * recycler, Fn func)
  458. {
  459. Segment * currentSegment = nullptr;
  460. for (uint i = 0; i < L1Count; i++)
  461. {
  462. L2MapChunk * chunk = map[i];
  463. if (chunk == nullptr)
  464. {
  465. continue;
  466. }
  467. for (uint j = 0; j < L2Count; j++)
  468. {
  469. HeapBlock * block = chunk->map[j];
  470. if (block == nullptr)
  471. {
  472. continue;
  473. }
  474. Assert(block->GetSegment() != nullptr);
  475. if (block->GetSegment() == currentSegment)
  476. {
  477. Assert(currentSegment != nullptr);
  478. Assert(currentSegment->IsInSegment(block->GetAddress()));
  479. continue;
  480. }
  481. // New segment.
  482. Assert(currentSegment == nullptr || !currentSegment->IsInSegment(block->GetAddress()));
  483. currentSegment = block->GetSegment();
  484. AnalysisAssert(currentSegment != nullptr);
  485. char * segmentStart = currentSegment->GetAddress();
  486. size_t segmentLength = currentSegment->GetPageCount() * PageSize;
  487. PageAllocator* segmentPageAllocator = (PageAllocator*)currentSegment->GetAllocator();
  488. Assert(segmentPageAllocator == block->GetPageAllocator(block->GetHeapInfo()));
  489. #if defined(TARGET_64)
  490. // On 64 bit, the segment may span multiple HeapBlockMap32 structures.
  491. // Limit the processing to the portion of the segment in this HeapBlockMap32.
  492. // We'll process other portions when we visit the other HeapBlockMap32 structures.
  493. if (segmentStart < this->startAddress)
  494. {
  495. Assert(segmentLength > (size_t)(this->startAddress - segmentStart));
  496. segmentLength -= (this->startAddress - segmentStart);
  497. segmentStart = this->startAddress;
  498. }
  499. if ((segmentStart - this->startAddress) + segmentLength > HeapBlockMap32::TotalSize)
  500. {
  501. segmentLength = HeapBlockMap32::TotalSize - (segmentStart - this->startAddress);
  502. }
  503. #endif
  504. func(segmentStart, segmentLength, currentSegment, segmentPageAllocator);
  505. }
  506. }
  507. }
  508. #if ENABLE_CONCURRENT_GC
  509. void
  510. HeapBlockMap32::ResetDirtyPages(Recycler * recycler)
  511. {
  512. this->ForEachSegment(recycler, [=](char * segmentStart, size_t segmentLength, Segment * segment, PageAllocator * segmentPageAllocator) {
  513. Assert(segmentLength % AutoSystemInfo::PageSize == 0);
  514. #ifdef RECYCLER_WRITE_WATCH
  515. if (!CONFIG_FLAG(ForceSoftwareWriteBarrier))
  516. {
  517. if (segmentPageAllocator->IsWriteWatchEnabled())
  518. {
  519. // Call ResetWriteWatch for Small non-leaf and Large segments.
  520. UINT ret = ::ResetWriteWatch(segmentStart, segmentLength);
  521. Assert(ret == 0);
  522. }
  523. }
  524. #endif
  525. #ifdef RECYCLER_WRITE_BARRIER
  526. #if defined(TARGET_64)
  527. if (segment->IsWriteBarrierEnabled())
  528. #endif
  529. {
  530. // Reset software write barrier for barrier segments.
  531. RecyclerWriteBarrierManager::ResetWriteBarrier(segmentStart, segmentLength / AutoSystemInfo::PageSize);
  532. }
  533. #endif
  534. });
  535. }
  536. #endif
  537. bool
  538. HeapBlockMap32::RescanPage(void * dirtyPage, bool* anyObjectsMarkedOnPage, Recycler * recycler)
  539. {
  540. uint id1 = GetLevel1Id(dirtyPage);
  541. L2MapChunk * chunk = map[id1];
  542. if (chunk != nullptr)
  543. {
  544. uint id2 = GetLevel2Id(dirtyPage);
  545. HeapBlock::HeapBlockType blockType = chunk->blockInfo[id2].blockType;
  546. // Determine block type and process as appropriate
  547. switch (blockType)
  548. {
  549. case HeapBlock::HeapBlockType::FreeBlockType:
  550. // We had a false reference to a free block. Do nothing.
  551. break;
  552. case HeapBlock::HeapBlockType::SmallNormalBlockType:
  553. #ifdef RECYCLER_WRITE_BARRIER
  554. case HeapBlock::HeapBlockType::SmallNormalBlockWithBarrierType:
  555. #endif
  556. return RescanHeapBlock<SmallNormalHeapBlock>(dirtyPage, blockType, chunk, id2, anyObjectsMarkedOnPage, recycler);
  557. case HeapBlock::HeapBlockType::SmallFinalizableBlockType:
  558. #ifdef RECYCLER_WRITE_BARRIER
  559. case HeapBlock::HeapBlockType::SmallFinalizableBlockWithBarrierType:
  560. #endif
  561. return RescanHeapBlock<SmallFinalizableHeapBlock>(dirtyPage, blockType, chunk, id2, anyObjectsMarkedOnPage, recycler);
  562. #ifdef RECYCLER_VISITED_HOST
  563. case HeapBlock::HeapBlockType::SmallRecyclerVisitedHostBlockType:
  564. return RescanHeapBlock<SmallRecyclerVisitedHostHeapBlock>(dirtyPage, blockType, chunk, id2, anyObjectsMarkedOnPage, recycler);
  565. #endif
  566. case HeapBlock::HeapBlockType::MediumNormalBlockType:
  567. #ifdef RECYCLER_WRITE_BARRIER
  568. case HeapBlock::HeapBlockType::MediumNormalBlockWithBarrierType:
  569. #endif
  570. return RescanHeapBlock<MediumNormalHeapBlock>(dirtyPage, blockType, chunk, id2, anyObjectsMarkedOnPage, recycler);
  571. case HeapBlock::HeapBlockType::MediumFinalizableBlockType:
  572. #ifdef RECYCLER_WRITE_BARRIER
  573. case HeapBlock::HeapBlockType::MediumFinalizableBlockWithBarrierType:
  574. #endif
  575. return RescanHeapBlock<MediumFinalizableHeapBlock>(dirtyPage, blockType, chunk, id2, anyObjectsMarkedOnPage, recycler);
  576. #ifdef RECYCLER_VISITED_HOST
  577. case HeapBlock::HeapBlockType::MediumRecyclerVisitedHostBlockType:
  578. return RescanHeapBlock<MediumRecyclerVisitedHostHeapBlock>(dirtyPage, blockType, chunk, id2, anyObjectsMarkedOnPage, recycler);
  579. #endif
  580. default:
  581. // Shouldn't be here -- leaf blocks aren't rescanned, and large blocks are handled separately
  582. Assert(false);
  583. break;
  584. }
  585. }
  586. return false;
  587. }
  588. template bool HeapBlockMap32::RescanHeapBlock<SmallNormalHeapBlock>(void * dirtyPage, HeapBlock::HeapBlockType blockType, L2MapChunk* chunk, uint id2, bool* anyObjectsMarkedOnPage, Recycler * recycler);
  589. template bool HeapBlockMap32::RescanHeapBlock<SmallFinalizableHeapBlock>(void * dirtyPage, HeapBlock::HeapBlockType blockType, L2MapChunk* chunk, uint id2, bool* anyObjectsMarkedOnPage, Recycler * recycler);
  590. template bool HeapBlockMap32::RescanHeapBlock<MediumNormalHeapBlock>(void * dirtyPage, HeapBlock::HeapBlockType blockType, L2MapChunk* chunk, uint id2, bool* anyObjectsMarkedOnPage, Recycler * recycler);
  591. template bool HeapBlockMap32::RescanHeapBlock<MediumFinalizableHeapBlock>(void * dirtyPage, HeapBlock::HeapBlockType blockType, L2MapChunk* chunk, uint id2, bool* anyObjectsMarkedOnPage, Recycler * recycler);
  592. template <class TBlockType>
  593. bool
  594. HeapBlockMap32::RescanHeapBlock(void * dirtyPage, HeapBlock::HeapBlockType blockType, L2MapChunk* chunk, uint id2, bool* anyObjectsMarkedOnPage, Recycler * recycler)
  595. {
  596. Assert(chunk != nullptr);
  597. char* heapBlockPageAddress = TBlockType::GetBlockStartAddress((char*) dirtyPage);
  598. typedef typename TBlockType::HeapBlockAttributes TBlockAttributes;
  599. // We need to check the entire mark bit vector here. It's not sufficient to just check the page's
  600. // mark bit vector because the object that's dirty on the page could have started on an earlier page
  601. auto markBits = chunk->GetMarkBitVectorForPages<TBlockAttributes::BitVectorCount>(heapBlockPageAddress);
  602. if (!markBits->IsAllClear())
  603. {
  604. Assert(chunk->map[id2]->GetHeapBlockType() == blockType);
  605. // Small finalizable heap blocks require the HeapBlock * (to look up object attributes).
  606. // For others, this is null
  607. TBlockType* block = GetHeapBlockForRescan<TBlockType>(chunk, id2);
  608. uint bucketIndex = chunk->blockInfo[id2].bucketIndex;
  609. if (!SmallNormalHeapBucketBase<TBlockType>::RescanObjectsOnPage(block,
  610. (char *)dirtyPage, heapBlockPageAddress, markBits, HeapInfo::GetObjectSizeForBucketIndex<TBlockAttributes>(bucketIndex), bucketIndex, anyObjectsMarkedOnPage, recycler))
  611. {
  612. // Failed due to OOM
  613. ((TBlockType*) chunk->map[id2])->SetNeedOOMRescan(recycler);
  614. return false;
  615. }
  616. return true;
  617. }
  618. // Didn't actually rescan the block.
  619. return false;
  620. }
  621. template <typename TBlockType>
  622. TBlockType*
  623. HeapBlockMap32::GetHeapBlockForRescan(HeapBlockMap32::L2MapChunk* chunk, uint id2) const
  624. {
  625. return nullptr;
  626. }
  627. template <>
  628. SmallFinalizableHeapBlock*
  629. HeapBlockMap32::GetHeapBlockForRescan(HeapBlockMap32::L2MapChunk* chunk, uint id2) const
  630. {
  631. return (SmallFinalizableHeapBlock*) chunk->map[id2];
  632. }
  633. template <>
  634. MediumFinalizableHeapBlock*
  635. HeapBlockMap32::GetHeapBlockForRescan(HeapBlockMap32::L2MapChunk* chunk, uint id2) const
  636. {
  637. return (MediumFinalizableHeapBlock*)chunk->map[id2];
  638. }
  639. #ifdef RECYCLER_VISITED_HOST
  640. template <>
  641. SmallRecyclerVisitedHostHeapBlock*
  642. HeapBlockMap32::GetHeapBlockForRescan(HeapBlockMap32::L2MapChunk* chunk, uint id2) const
  643. {
  644. return (SmallRecyclerVisitedHostHeapBlock*) chunk->map[id2];
  645. }
  646. #endif
  647. #ifdef RECYCLER_VISITED_HOST
  648. template <>
  649. MediumRecyclerVisitedHostHeapBlock*
  650. HeapBlockMap32::GetHeapBlockForRescan(HeapBlockMap32::L2MapChunk* chunk, uint id2) const
  651. {
  652. return (MediumRecyclerVisitedHostHeapBlock*)chunk->map[id2];
  653. }
  654. #endif
  655. void
  656. HeapBlockMap32::MakeAllPagesReadOnly(Recycler* recycler)
  657. {
  658. this->ChangeProtectionLevel(recycler, PAGE_READONLY, PAGE_READWRITE);
  659. }
  660. void
  661. HeapBlockMap32::MakeAllPagesReadWrite(Recycler* recycler)
  662. {
  663. this->ChangeProtectionLevel(recycler, PAGE_READWRITE, PAGE_READONLY);
  664. }
  665. void
  666. HeapBlockMap32::ChangeProtectionLevel(Recycler* recycler, DWORD protectFlags, DWORD expectedOldFlags)
  667. {
  668. this->ForEachSegment(recycler, [&](char* segmentStart, size_t segmentLength, Segment* currentSegment, PageAllocator* segmentPageAllocator)
  669. {
  670. // Ideally, we shouldn't to exclude LargeBlocks here but guest arenas are allocated
  671. // from this allocator and we touch them during marking if they're pending delete
  672. if (!recycler->autoHeap.IsRecyclerLeafPageAllocator(segmentPageAllocator)
  673. && !recycler->autoHeap.IsRecyclerLargeBlockPageAllocator(segmentPageAllocator))
  674. {
  675. Assert(currentSegment->IsPageSegment());
  676. ((PageSegment*)currentSegment)->ChangeSegmentProtection(protectFlags, expectedOldFlags);
  677. }
  678. });
  679. }
  680. #if ENABLE_CONCURRENT_GC
  681. #ifdef RECYCLER_WRITE_WATCH
  682. ///
  683. /// The GetWriteWatch API can fail under low-mem situations if called to retrieve write-watch for a large number of pages
  684. /// (On Win10, > 255 pages). This helper is to handle the failure case. In the case of failure, we degrade to retrieving
  685. /// the write-watch one page at a time since that's expected to succeed
  686. ///
  687. UINT
  688. HeapBlockMap32::GetWriteWatchHelper(Recycler * recycler, DWORD writeWatchFlags, void* baseAddress, size_t regionSize,
  689. void** addresses, ULONG_PTR* count, LPDWORD granularity)
  690. {
  691. UINT ret = 0;
  692. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  693. if (recycler->GetRecyclerFlagsTable().ForceGetWriteWatchOOM)
  694. {
  695. if (regionSize != AutoSystemInfo::PageSize)
  696. {
  697. ret = (UINT) -1;
  698. }
  699. }
  700. else
  701. #endif
  702. {
  703. ret = ::GetWriteWatch(writeWatchFlags, baseAddress, regionSize, addresses, count, granularity);
  704. }
  705. if (ret != 0 && regionSize != AutoSystemInfo::PageSize)
  706. {
  707. ret = GetWriteWatchHelperOnOOM(writeWatchFlags, baseAddress, regionSize, addresses, count, granularity);
  708. }
  709. Assert(ret == 0);
  710. return ret;
  711. }
  712. // OOM codepath- Retrieve write-watch one page at a time
  713. // It's slow, but we are okay with that during OOM
  714. // Factored into its own function to help the compiler inline the parent
  715. UINT
  716. HeapBlockMap32::GetWriteWatchHelperOnOOM(DWORD writeWatchFlags, _In_ void* baseAddress, size_t regionSize,
  717. _Out_writes_(*count) void** addresses, _Inout_ ULONG_PTR* count, LPDWORD granularity)
  718. {
  719. const size_t pageCount = (regionSize / AutoSystemInfo::PageSize);
  720. // Ensure target buffer
  721. AnalysisAssertMsg(*count >= pageCount, "Not enough space in the buffer to store the write watch state for the given region size");
  722. void* result = nullptr;
  723. size_t dirtyCount = 0;
  724. for (size_t i = 0; i < pageCount; i++)
  725. {
  726. result = nullptr;
  727. char* pageAddress = ((char*)baseAddress) + (i * AutoSystemInfo::PageSize);
  728. ULONG_PTR resultBufferCount = 1;
  729. DWORD r = ::GetWriteWatch(writeWatchFlags, pageAddress, AutoSystemInfo::PageSize, &result, &resultBufferCount, granularity);
  730. Assert(r == 0);
  731. Assert(resultBufferCount <= 1);
  732. AnalysisAssert(dirtyCount < pageCount);
  733. // The requested page was dirty
  734. if (resultBufferCount == 1)
  735. {
  736. Assert(result == pageAddress);
  737. #pragma prefast(suppress:22102)
  738. addresses[dirtyCount] = pageAddress;
  739. dirtyCount++;
  740. }
  741. }
  742. Assert(dirtyCount <= *count);
  743. *count = dirtyCount;
  744. return 0;
  745. }
  746. #endif
  747. #endif
  748. #if ENABLE_CONCURRENT_GC
  749. uint
  750. HeapBlockMap32::Rescan(Recycler * recycler, bool resetWriteWatch)
  751. {
  752. // Loop through segments and find dirty pages.
  753. uint scannedPageCount = 0;
  754. bool anyObjectsScannedOnPage = false;
  755. this->ForEachSegment(recycler, [&](char * segmentStart, size_t segmentLength, Segment * currentSegment, PageAllocator * segmentPageAllocator)
  756. {
  757. Assert(segmentLength % AutoSystemInfo::PageSize == 0);
  758. #ifdef RECYCLER_WRITE_WATCH
  759. if (!CONFIG_FLAG(ForceSoftwareWriteBarrier))
  760. {
  761. // Call GetWriteWatch for Small non-leaf segments.
  762. // Large blocks have their own separate write watch handling.
  763. if (recycler->autoHeap.IsRecyclerPageAllocator(segmentPageAllocator))
  764. {
  765. Assert(segmentLength <= MaxGetWriteWatchPages * PageSize);
  766. void * dirtyPageAddresses[MaxGetWriteWatchPages];
  767. ULONG_PTR pageCount = MaxGetWriteWatchPages;
  768. DWORD pageSize = PageSize;
  769. const DWORD writeWatchFlags = (resetWriteWatch ? WRITE_WATCH_FLAG_RESET : 0);
  770. UINT ret = HeapBlockMap32::GetWriteWatchHelper(recycler, writeWatchFlags, segmentStart, segmentLength, dirtyPageAddresses, &pageCount, &pageSize);
  771. Assert(ret == 0);
  772. Assert(pageSize == PageSize);
  773. Assert(pageCount <= MaxGetWriteWatchPages);
  774. // Process results:
  775. // Loop through reported dirty pages and set their write watch bit.
  776. for (uint i = 0; i < pageCount; i++)
  777. {
  778. char * dirtyPage = (char *)dirtyPageAddresses[i];
  779. Assert((((size_t)dirtyPage) % PageSize) == 0);
  780. Assert(dirtyPage >= segmentStart);
  781. Assert(dirtyPage < segmentStart + segmentLength);
  782. #if defined(TARGET_64)
  783. Assert(HeapBlockMap64::GetNodeStartAddress(dirtyPage) == this->startAddress);
  784. #endif
  785. if (RescanPage(dirtyPage, &anyObjectsScannedOnPage, recycler) && anyObjectsScannedOnPage)
  786. {
  787. scannedPageCount++;
  788. }
  789. }
  790. return;
  791. }
  792. }
  793. #endif
  794. #ifdef RECYCLER_WRITE_BARRIER
  795. if (recycler->autoHeap.IsRecyclerWithBarrierPageAllocator(segmentPageAllocator))
  796. {
  797. // Loop through pages for this segment and check write barrier.
  798. size_t pageCount = segmentLength / AutoSystemInfo::PageSize;
  799. for (size_t i = 0; i < pageCount; i++)
  800. {
  801. char * pageAddress = segmentStart + (i * AutoSystemInfo::PageSize);
  802. Assert((size_t)(pageAddress - segmentStart) < segmentLength);
  803. #if defined(TARGET_64)
  804. Assert(HeapBlockMap64::GetNodeStartAddress(pageAddress) == this->startAddress);
  805. #endif
  806. // TODO: We are not resetting the write barrier here when RescanFlags_ResetWriteWatch is passed.
  807. // We never have previously, but it still seems like we should.
  808. BYTE writeBarrierByte = RecyclerWriteBarrierManager::GetWriteBarrier(pageAddress);
  809. SwbVerboseTrace(recycler->GetRecyclerFlagsTable(), _u("Address: 0x%p, Write Barrier value: %u\n"), pageAddress, writeBarrierByte);
  810. bool isDirty = (writeBarrierByte & DIRTYBIT);
  811. if (isDirty)
  812. {
  813. if (RescanPage(pageAddress, &anyObjectsScannedOnPage, recycler) && anyObjectsScannedOnPage)
  814. {
  815. scannedPageCount++;
  816. }
  817. }
  818. }
  819. return;
  820. }
  821. #endif
  822. Assert(recycler->autoHeap.IsRecyclerLeafPageAllocator(segmentPageAllocator) ||
  823. recycler->autoHeap.IsRecyclerLargeBlockPageAllocator(segmentPageAllocator));
  824. });
  825. return scannedPageCount;
  826. }
  827. #endif
  828. bool
  829. HeapBlockMap32::OOMRescan(Recycler * recycler)
  830. {
  831. this->anyHeapBlockRescannedDuringOOM = false;
  832. bool noHeapBlockNeedsRescan = true;
  833. // Loop through segments and find pages that need OOM Rescan.
  834. this->ForEachSegment(recycler, [=, &noHeapBlockNeedsRescan] (char * segmentStart, size_t segmentLength, Segment * currentSegment, PageAllocator * segmentPageAllocator) {
  835. Assert(segmentLength % AutoSystemInfo::PageSize == 0);
  836. // Process Small non-leaf segments (including write barrier blocks).
  837. // Large blocks have their own separate write watch handling.
  838. if (recycler->autoHeap.IsRecyclerPageAllocator(segmentPageAllocator)
  839. #ifdef RECYCLER_WRITE_BARRIER
  840. || recycler->autoHeap.IsRecyclerWithBarrierPageAllocator(segmentPageAllocator)
  841. #endif
  842. )
  843. {
  844. if (recycler->NeedOOMRescan())
  845. {
  846. // We hit OOM again. Don't try to process any more blocks, leave them for the next OOM pass.
  847. return;
  848. }
  849. // Loop through pages for this segment and check OOM flag.
  850. size_t pageCount = segmentLength / AutoSystemInfo::PageSize;
  851. for (size_t i = 0; i < pageCount; i++)
  852. {
  853. char * pageAddress = segmentStart + (i * AutoSystemInfo::PageSize);
  854. Assert((size_t)(pageAddress - segmentStart) < segmentLength);
  855. #if defined(TARGET_64)
  856. Assert(HeapBlockMap64::GetNodeStartAddress(pageAddress) == this->startAddress);
  857. #endif
  858. uint id1 = GetLevel1Id(pageAddress);
  859. L2MapChunk * chunk = map[id1];
  860. if (chunk != nullptr)
  861. {
  862. uint id2 = GetLevel2Id(pageAddress);
  863. HeapBlock * heapBlock = chunk->map[id2];
  864. if (heapBlock != nullptr && heapBlock->GetAddress() == pageAddress)
  865. {
  866. if (heapBlock->GetAndClearNeedOOMRescan())
  867. {
  868. noHeapBlockNeedsRescan = false;
  869. HeapBlock::HeapBlockType blockType = chunk->blockInfo[id2].blockType;
  870. // Determine block type and process as appropriate
  871. switch (blockType)
  872. {
  873. case HeapBlock::HeapBlockType::FreeBlockType:
  874. // Can't have a free block that has OOMRescan flag set
  875. Assert(false);
  876. break;
  877. case HeapBlock::HeapBlockType::SmallNormalBlockType:
  878. #ifdef RECYCLER_WRITE_BARRIER
  879. case HeapBlock::HeapBlockType::SmallNormalBlockWithBarrierType:
  880. #endif
  881. if (!RescanHeapBlockOnOOM<SmallNormalHeapBlock>((SmallNormalHeapBlock*)heapBlock, pageAddress, blockType, chunk->blockInfo[id2].bucketIndex, chunk, recycler))
  882. {
  883. return;
  884. }
  885. break;
  886. case HeapBlock::HeapBlockType::SmallFinalizableBlockType:
  887. #ifdef RECYCLER_WRITE_BARRIER
  888. case HeapBlock::HeapBlockType::SmallFinalizableBlockWithBarrierType:
  889. #endif
  890. if (!RescanHeapBlockOnOOM<SmallFinalizableHeapBlock>((SmallFinalizableHeapBlock*) heapBlock, pageAddress, blockType, chunk->blockInfo[id2].bucketIndex, chunk, recycler))
  891. {
  892. return;
  893. }
  894. break;
  895. #ifdef RECYCLER_VISITED_HOST
  896. case HeapBlock::HeapBlockType::SmallRecyclerVisitedHostBlockType:
  897. if (!RescanHeapBlockOnOOM<SmallRecyclerVisitedHostHeapBlock>((SmallRecyclerVisitedHostHeapBlock*) heapBlock, pageAddress, blockType, chunk->blockInfo[id2].bucketIndex, chunk, recycler))
  898. {
  899. return;
  900. }
  901. break;
  902. #endif
  903. case HeapBlock::HeapBlockType::MediumNormalBlockType:
  904. #ifdef RECYCLER_WRITE_BARRIER
  905. case HeapBlock::HeapBlockType::MediumNormalBlockWithBarrierType:
  906. #endif
  907. if (!RescanHeapBlockOnOOM<MediumNormalHeapBlock>((MediumNormalHeapBlock*)heapBlock, pageAddress, blockType, chunk->blockInfo[id2].bucketIndex, chunk, recycler))
  908. {
  909. return;
  910. }
  911. break;
  912. case HeapBlock::HeapBlockType::MediumFinalizableBlockType:
  913. #ifdef RECYCLER_WRITE_BARRIER
  914. case HeapBlock::HeapBlockType::MediumFinalizableBlockWithBarrierType:
  915. #endif
  916. if (!RescanHeapBlockOnOOM<MediumFinalizableHeapBlock>((MediumFinalizableHeapBlock*) heapBlock, pageAddress, blockType, chunk->blockInfo[id2].bucketIndex, chunk, recycler))
  917. {
  918. return;
  919. }
  920. break;
  921. #ifdef RECYCLER_VISITED_HOST
  922. case HeapBlock::HeapBlockType::MediumRecyclerVisitedHostBlockType:
  923. if (!RescanHeapBlockOnOOM<MediumRecyclerVisitedHostHeapBlock>((MediumRecyclerVisitedHostHeapBlock*) heapBlock, pageAddress, blockType, chunk->blockInfo[id2].bucketIndex, chunk, recycler))
  924. {
  925. return;
  926. }
  927. break;
  928. #endif
  929. default:
  930. // Shouldn't be here -- leaf blocks aren't rescanned, and large blocks are handled separately
  931. Assert(false);
  932. break;
  933. }
  934. }
  935. }
  936. }
  937. }
  938. }
  939. else
  940. {
  941. Assert(recycler->autoHeap.IsRecyclerLeafPageAllocator(segmentPageAllocator) ||
  942. recycler->autoHeap.IsRecyclerLargeBlockPageAllocator(segmentPageAllocator));
  943. }
  944. });
  945. // TODO: Enable this assert post-Win10
  946. // Assert(this->anyHeapBlockRescannedDuringOOM);
  947. // Success if:
  948. // No heap block needs OOM rescan OR
  949. // A single heap block was rescanned
  950. return noHeapBlockNeedsRescan || this->anyHeapBlockRescannedDuringOOM;
  951. }
  952. template bool HeapBlockMap32::RescanHeapBlockOnOOM<SmallNormalHeapBlock>(SmallNormalHeapBlock* heapBlock, char* pageAddress, HeapBlock::HeapBlockType blockType, uint bucketIndex, L2MapChunk * chunk, Recycler * recycler);
  953. template bool HeapBlockMap32::RescanHeapBlockOnOOM<SmallFinalizableHeapBlock>(SmallFinalizableHeapBlock* heapBlock, char* pageAddress, HeapBlock::HeapBlockType blockType, uint bucketIndex, L2MapChunk * chunk, Recycler * recycler);
  954. template bool HeapBlockMap32::RescanHeapBlockOnOOM<MediumNormalHeapBlock>(MediumNormalHeapBlock* heapBlock, char* pageAddress, HeapBlock::HeapBlockType blockType, uint bucketIndex, L2MapChunk * chunk, Recycler * recycler);
  955. template bool HeapBlockMap32::RescanHeapBlockOnOOM<MediumFinalizableHeapBlock>(MediumFinalizableHeapBlock* heapBlock, char* pageAddress, HeapBlock::HeapBlockType blockType, uint bucketIndex, L2MapChunk * chunk, Recycler * recycler);
  956. template <class TBlockType>
  957. bool
  958. HeapBlockMap32::RescanHeapBlockOnOOM(TBlockType* heapBlock, char* pageAddress, HeapBlock::HeapBlockType blockType, uint bucketIndex, L2MapChunk * chunk, Recycler * recycler)
  959. {
  960. // In the OOM codepath, we expect the heap block to be dereferenced since perf is not critical
  961. Assert(heapBlock != nullptr);
  962. Assert(heapBlock->GetHeapBlockType() == blockType);
  963. auto markBits = this->GetMarkBitVectorForPages<TBlockType::HeapBlockAttributes::BitVectorCount>(heapBlock->GetAddress());
  964. char* blockStartAddress = TBlockType::GetBlockStartAddress(pageAddress);
  965. // Rescan all pages in this block
  966. // The following assert makes sure that this method is called only once per heap block
  967. Assert(blockStartAddress == pageAddress);
  968. int inUsePageCount = heapBlock->GetPageCount() - heapBlock->GetUnusablePageCount();
  969. for (int i = 0; i < inUsePageCount; i++)
  970. {
  971. char* pageAddressToScan = blockStartAddress + (i * AutoSystemInfo::PageSize);
  972. if (!SmallNormalHeapBucketBase<TBlockType>::RescanObjectsOnPage(heapBlock,
  973. pageAddressToScan, blockStartAddress, markBits, HeapInfo::template GetObjectSizeForBucketIndex<typename TBlockType::HeapBlockAttributes>(bucketIndex), bucketIndex, nullptr, recycler))
  974. {
  975. // Failed due to OOM
  976. ((TBlockType*)heapBlock)->SetNeedOOMRescan(recycler);
  977. }
  978. if (recycler->NeedOOMRescan())
  979. {
  980. // We hit OOM again. Don't try to process any more blocks, leave them for the next OOM pass.
  981. return false;
  982. }
  983. }
  984. this->anyHeapBlockRescannedDuringOOM = true;
  985. return true;
  986. }
  987. // This function is called in-thread after Sweep, to find empty L2 Maps and release them.
  988. void
  989. HeapBlockMap32::Cleanup(bool concurrentFindImplicitRoot)
  990. {
  991. for (uint id1 = 0; id1 < L1Count; id1++)
  992. {
  993. L2MapChunk * l2map = map[id1];
  994. if (l2map != nullptr && l2map->IsEmpty())
  995. {
  996. // Concurrent searches for implicit roots will never see empty L2 maps.
  997. map[id1] = nullptr;
  998. NoMemProtectHeapDelete(l2map);
  999. Assert(count > 0);
  1000. count--;
  1001. }
  1002. }
  1003. }
  1004. #if defined(TARGET_64)
  1005. HeapBlockMap64::HeapBlockMap64():
  1006. list(nullptr)
  1007. {
  1008. }
  1009. HeapBlockMap64::~HeapBlockMap64()
  1010. {
  1011. Node * node = list;
  1012. list = nullptr;
  1013. while (node != nullptr)
  1014. {
  1015. Node * next = node->next;
  1016. NoMemProtectHeapDelete(node);
  1017. node = next;
  1018. }
  1019. }
  1020. bool
  1021. HeapBlockMap64::EnsureHeapBlock(void * address, size_t pageCount)
  1022. {
  1023. uint lowerBitsAddress = ::Math::PointerCastToIntegralTruncate<uint>(address);
  1024. size_t pageCountLeft = pageCount;
  1025. uint nodePages = HeapBlockMap64::PagesPer4GB - lowerBitsAddress / AutoSystemInfo::PageSize;
  1026. if (pageCountLeft < nodePages)
  1027. {
  1028. nodePages = (uint)pageCountLeft;
  1029. }
  1030. do
  1031. {
  1032. Node * node = FindOrInsertNode(address);
  1033. if (node == nullptr || !node->map.EnsureHeapBlock(address, nodePages))
  1034. {
  1035. return false;
  1036. }
  1037. pageCountLeft -= nodePages;
  1038. if (pageCountLeft == 0)
  1039. {
  1040. return true;
  1041. }
  1042. address = (void *)((size_t)address + ((size_t)nodePages * AutoSystemInfo::PageSize));
  1043. nodePages = HeapBlockMap64::PagesPer4GB;
  1044. if (pageCountLeft < HeapBlockMap64::PagesPer4GB)
  1045. {
  1046. nodePages = (uint)pageCountLeft;
  1047. }
  1048. }
  1049. while (true);
  1050. }
  1051. void
  1052. HeapBlockMap64::SetHeapBlockNoCheck(void * address, size_t pageCount, HeapBlock * heapBlock, HeapBlock::HeapBlockType blockType, byte bucketIndex)
  1053. {
  1054. ForEachNodeInAddressRange(address, pageCount, [&](Node * node, void * address, uint nodePages)
  1055. {
  1056. Assert(node != nullptr);
  1057. node->map.SetHeapBlockNoCheck(address, nodePages, heapBlock, blockType, bucketIndex);
  1058. });
  1059. }
  1060. bool
  1061. HeapBlockMap64::SetHeapBlock(void * address, size_t pageCount, HeapBlock * heapBlock, HeapBlock::HeapBlockType blockType, byte bucketIndex)
  1062. {
  1063. if (!EnsureHeapBlock(address, pageCount))
  1064. {
  1065. return false;
  1066. }
  1067. SetHeapBlockNoCheck(address, pageCount, heapBlock, blockType, bucketIndex);
  1068. return true;
  1069. }
  1070. void HeapBlockMap64::ClearHeapBlock(void * address, size_t pageCount)
  1071. {
  1072. ForEachNodeInAddressRange(address, pageCount, [&](Node* node, void* address, uint nodePages)
  1073. {
  1074. Assert(node != nullptr);
  1075. node->map.ClearHeapBlock(address, nodePages);
  1076. });
  1077. }
  1078. template <class Fn>
  1079. void HeapBlockMap64::ForEachNodeInAddressRange(void * address, size_t pageCount, Fn fn)
  1080. {
  1081. uint lowerBitsAddress = ::Math::PointerCastToIntegralTruncate<uint>(address);
  1082. uint nodePages = HeapBlockMap64::PagesPer4GB - lowerBitsAddress / AutoSystemInfo::PageSize;
  1083. if (pageCount < nodePages)
  1084. {
  1085. nodePages = (uint)pageCount;
  1086. }
  1087. // TODO: the loop is no longer needed as we are limiting the recycler object to be less than 2GB
  1088. do
  1089. {
  1090. Node * node = FindNode(address);
  1091. fn(node, address, nodePages);
  1092. pageCount -= nodePages;
  1093. if (pageCount == 0)
  1094. {
  1095. break;
  1096. }
  1097. address = (void *)((size_t)address + ((size_t)nodePages * AutoSystemInfo::PageSize));
  1098. nodePages = HeapBlockMap64::PagesPer4GB;
  1099. if (pageCount < HeapBlockMap64::PagesPer4GB)
  1100. {
  1101. nodePages = (uint)pageCount;
  1102. }
  1103. } while (true);
  1104. }
  1105. HeapBlock *
  1106. HeapBlockMap64::GetHeapBlock(void * address)
  1107. {
  1108. Node * node = FindNode(address);
  1109. if (node == nullptr)
  1110. {
  1111. return nullptr;
  1112. }
  1113. return node->map.GetHeapBlock(address);
  1114. }
  1115. HeapBlockMap32::PageMarkBitVector *
  1116. HeapBlockMap64::GetPageMarkBitVector(void * address)
  1117. {
  1118. Node * node = FindNode(address);
  1119. Assert(node != nullptr);
  1120. return node->map.GetPageMarkBitVector(address);
  1121. }
  1122. template <size_t BitCount>
  1123. BVStatic<BitCount>* HeapBlockMap64::GetMarkBitVectorForPages(void * address)
  1124. {
  1125. Node * node = FindNode(address);
  1126. Assert(node != nullptr);
  1127. return node->map.GetMarkBitVectorForPages<BitCount>(address);
  1128. }
  1129. template BVStatic<SmallAllocationBlockAttributes::BitVectorCount>* HeapBlockMap64::GetMarkBitVectorForPages<SmallAllocationBlockAttributes::BitVectorCount>(void * address);
  1130. template BVStatic<MediumAllocationBlockAttributes::BitVectorCount>* HeapBlockMap64::GetMarkBitVectorForPages<MediumAllocationBlockAttributes::BitVectorCount>(void * address);
  1131. uint
  1132. HeapBlockMap64::GetMarkCount(void * address, uint pageCount)
  1133. {
  1134. uint markCount = 0;
  1135. ForEachNodeInAddressRange(address, pageCount, [&](Node* node, void* address, uint nodePageCount)
  1136. {
  1137. Assert(node != nullptr);
  1138. markCount += node->map.GetMarkCount(address, nodePageCount);
  1139. });
  1140. return markCount;
  1141. }
  1142. bool
  1143. HeapBlockMap64::IsMarked(void * address) const
  1144. {
  1145. Node * node = FindNode(address);
  1146. if (node != nullptr)
  1147. {
  1148. return node->map.IsMarked(address);
  1149. }
  1150. return false;
  1151. }
  1152. void
  1153. HeapBlockMap64::SetMark(void * address)
  1154. {
  1155. Node * node = FindNode(address);
  1156. if (node != nullptr)
  1157. {
  1158. node->map.SetMark(address);
  1159. }
  1160. }
  1161. bool
  1162. HeapBlockMap64::TestAndSetMark(void * address)
  1163. {
  1164. Node * node = FindNode(address);
  1165. if (node == nullptr)
  1166. {
  1167. return false;
  1168. }
  1169. return node->map.TestAndSetMark(address);
  1170. }
  1171. HeapBlockMap64::Node *
  1172. HeapBlockMap64::FindOrInsertNode(void * address)
  1173. {
  1174. Node * node = FindNode(address);
  1175. if (node == nullptr)
  1176. {
  1177. node = NoMemProtectHeapNewNoThrowZ(Node, GetNodeStartAddress(address));
  1178. if (node != nullptr)
  1179. {
  1180. node->nodeIndex = GetNodeIndex(address);
  1181. node->next = list;
  1182. #ifdef _M_ARM64
  1183. // For ARM we need to make sure that the list remains traversable during this insert.
  1184. MemoryBarrier();
  1185. #endif
  1186. list = node;
  1187. }
  1188. }
  1189. return node;
  1190. }
  1191. HeapBlockMap64::Node *
  1192. HeapBlockMap64::FindNode(void * address) const
  1193. {
  1194. uint index = GetNodeIndex(address);
  1195. Node * node = list;
  1196. while (node != nullptr)
  1197. {
  1198. if (node->nodeIndex == index)
  1199. {
  1200. return node;
  1201. }
  1202. node = node->next;
  1203. }
  1204. return nullptr;
  1205. }
  1206. void
  1207. HeapBlockMap64::ResetMarks()
  1208. {
  1209. Node * node = this->list;
  1210. while (node != nullptr)
  1211. {
  1212. node->map.ResetMarks();
  1213. node = node->next;
  1214. }
  1215. }
  1216. bool
  1217. HeapBlockMap64::OOMRescan(Recycler * recycler)
  1218. {
  1219. Node * node = this->list;
  1220. while (node != nullptr)
  1221. {
  1222. if (!node->map.OOMRescan(recycler))
  1223. {
  1224. return false;
  1225. }
  1226. node = node->next;
  1227. }
  1228. return true;
  1229. }
  1230. #if ENABLE_CONCURRENT_GC
  1231. void
  1232. HeapBlockMap64::ResetDirtyPages(Recycler * recycler)
  1233. {
  1234. Node * node = this->list;
  1235. while (node != nullptr)
  1236. {
  1237. node->map.ResetDirtyPages(recycler);
  1238. node = node->next;
  1239. }
  1240. }
  1241. #endif
  1242. void
  1243. HeapBlockMap64::MakeAllPagesReadOnly(Recycler* recycler)
  1244. {
  1245. Node * node = this->list;
  1246. while (node != nullptr)
  1247. {
  1248. node->map.MakeAllPagesReadOnly(recycler);
  1249. node = node->next;
  1250. }
  1251. }
  1252. void
  1253. HeapBlockMap64::MakeAllPagesReadWrite(Recycler* recycler)
  1254. {
  1255. Node * node = this->list;
  1256. while (node != nullptr)
  1257. {
  1258. node->map.MakeAllPagesReadWrite(recycler);
  1259. node = node->next;
  1260. }
  1261. }
  1262. #if ENABLE_CONCURRENT_GC
  1263. uint
  1264. HeapBlockMap64::Rescan(Recycler * recycler, bool resetWriteWatch)
  1265. {
  1266. uint scannedPageCount = 0;
  1267. Node * node = this->list;
  1268. while (node != nullptr)
  1269. {
  1270. scannedPageCount += node->map.Rescan(recycler, resetWriteWatch);
  1271. node = node->next;
  1272. }
  1273. return scannedPageCount;
  1274. }
  1275. #endif
  1276. void
  1277. HeapBlockMap64::Cleanup(bool concurrentFindImplicitRoot)
  1278. {
  1279. Node ** prevnext = &this->list;
  1280. Node * node = *prevnext;
  1281. while (node != nullptr)
  1282. {
  1283. node->map.Cleanup(concurrentFindImplicitRoot);
  1284. Node * nextNode = node->next;
  1285. if (!concurrentFindImplicitRoot && node->map.Empty())
  1286. {
  1287. // Concurrent traversals of the node list would result in a race and possible UAF.
  1288. // Currently we simply defer node free for the lifetime of the heap (only affects MemProtect).
  1289. *prevnext = node->next;
  1290. NoMemProtectHeapDelete(node);
  1291. }
  1292. else
  1293. {
  1294. prevnext = &node->next;
  1295. }
  1296. node = nextNode;
  1297. }
  1298. }
  1299. #if DBG
  1300. ushort
  1301. HeapBlockMap64::GetPageMarkCount(void * address) const
  1302. {
  1303. Node * node = FindNode(address);
  1304. Assert(node != nullptr);
  1305. return node->map.GetPageMarkCount(address);
  1306. }
  1307. void
  1308. HeapBlockMap64::SetPageMarkCount(void * address, ushort markCount)
  1309. {
  1310. Node * node = FindNode(address);
  1311. Assert(node != nullptr);
  1312. node->map.SetPageMarkCount(address, markCount);
  1313. }
  1314. template void HeapBlockMap64::VerifyMarkCountForPages<SmallAllocationBlockAttributes::BitVectorCount>(void* address, uint pageCount);
  1315. template void HeapBlockMap64::VerifyMarkCountForPages<MediumAllocationBlockAttributes::BitVectorCount>(void* address, uint pageCount);
  1316. template <uint BitVectorCount>
  1317. void
  1318. HeapBlockMap64::VerifyMarkCountForPages(void * address, uint pageCount)
  1319. {
  1320. Node * node = FindNode(address);
  1321. Assert(node != nullptr);
  1322. node->map.VerifyMarkCountForPages<BitVectorCount>(address, pageCount);
  1323. }
  1324. #endif
  1325. #ifdef RECYCLER_STRESS
  1326. void
  1327. HeapBlockMap64::InduceFalsePositives(Recycler * recycler)
  1328. {
  1329. Node * node = this->list;
  1330. while (node != nullptr)
  1331. {
  1332. node->map.InduceFalsePositives(recycler);
  1333. node = node->next;
  1334. }
  1335. }
  1336. #endif
  1337. #ifdef RECYCLER_VERIFY_MARK
  1338. bool
  1339. HeapBlockMap64::IsAddressInNewChunk(void * address)
  1340. {
  1341. Node * node = FindNode(address);
  1342. Assert(node != nullptr);
  1343. return node->map.IsAddressInNewChunk(address);
  1344. }
  1345. #endif
  1346. #endif