PageAllocator.cpp 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558
  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. #define UpdateMinimum(dst, src) if (dst > src) { dst = src; }
  7. //=============================================================================================================
  8. // Segment
  9. //=============================================================================================================
  10. template<typename T>
  11. SegmentBase<T>::SegmentBase(PageAllocatorBase<T> * allocator, size_t pageCount) :
  12. allocator(allocator),
  13. address(nullptr),
  14. trailingGuardPageCount(0),
  15. leadingGuardPageCount(0),
  16. secondaryAllocPageCount(allocator->secondaryAllocPageCount),
  17. secondaryAllocator(nullptr)
  18. #if defined(_M_X64_OR_ARM64) && defined(RECYCLER_WRITE_BARRIER)
  19. , isWriteBarrierAllowed(false)
  20. #endif
  21. {
  22. this->segmentPageCount = pageCount + secondaryAllocPageCount;
  23. }
  24. template<typename T>
  25. SegmentBase<T>::~SegmentBase()
  26. {
  27. Assert(this->allocator != nullptr);
  28. if (this->address)
  29. {
  30. char* originalAddress = this->address - (leadingGuardPageCount * AutoSystemInfo::PageSize);
  31. allocator->GetVirtualAllocator()->Free(originalAddress, GetPageCount() * AutoSystemInfo::PageSize, MEM_RELEASE);
  32. allocator->ReportFree(this->segmentPageCount * AutoSystemInfo::PageSize); //Note: We reported the guard pages free when we decommitted them during segment initialization
  33. #if defined(_M_X64_OR_ARM64) && defined(RECYCLER_WRITE_BARRIER_BYTE)
  34. RecyclerWriteBarrierManager::OnSegmentFree(this->address, this->segmentPageCount);
  35. #endif
  36. }
  37. if(this->secondaryAllocator)
  38. {
  39. this->secondaryAllocator->Delete();
  40. this->secondaryAllocator = nullptr;
  41. }
  42. }
  43. template<typename T>
  44. bool SegmentBase<T>::IsInPreReservedHeapPageAllocator() const
  45. {
  46. return this->allocator->GetVirtualAllocator() != nullptr;
  47. }
  48. template<typename T>
  49. bool
  50. SegmentBase<T>::Initialize(DWORD allocFlags, bool excludeGuardPages)
  51. {
  52. Assert(this->address == nullptr);
  53. char* originalAddress = nullptr;
  54. bool addGuardPages = false;
  55. if (!excludeGuardPages)
  56. {
  57. addGuardPages = (this->segmentPageCount * AutoSystemInfo::PageSize) > VirtualAllocThreshold;
  58. #if _M_IX86_OR_ARM32
  59. unsigned int randomNumber = static_cast<unsigned int>(Math::Rand());
  60. addGuardPages = addGuardPages && (randomNumber % 4 == 1);
  61. #endif
  62. #if DEBUG
  63. addGuardPages = addGuardPages || Js::Configuration::Global.flags.ForceGuardPages;
  64. #endif
  65. if (addGuardPages)
  66. {
  67. unsigned int randomNumber = static_cast<unsigned int>(Math::Rand());
  68. this->leadingGuardPageCount = randomNumber % maxGuardPages + minGuardPages;
  69. this->trailingGuardPageCount = minGuardPages;
  70. }
  71. }
  72. // We can only allocate with this granularity using VirtualAlloc
  73. size_t totalPages = Math::Align<size_t>(this->segmentPageCount + leadingGuardPageCount + trailingGuardPageCount, AutoSystemInfo::Data.GetAllocationGranularityPageCount());
  74. this->segmentPageCount = totalPages - (leadingGuardPageCount + trailingGuardPageCount);
  75. #ifdef FAULT_INJECTION
  76. if(Js::FaultInjection::Global.ShouldInjectFault(Js::FaultInjection::Global.NoThrow))
  77. {
  78. this->address = nullptr;
  79. return(address != nullptr);
  80. }
  81. #endif
  82. if (!this->allocator->RequestAlloc(totalPages * AutoSystemInfo::PageSize))
  83. {
  84. return nullptr;
  85. }
  86. this->address = (char *) GetAllocator()->GetVirtualAllocator()->Alloc(NULL, totalPages * AutoSystemInfo::PageSize, MEM_RESERVE | allocFlags, PAGE_READWRITE, this->IsInCustomHeapAllocator());
  87. originalAddress = this->address;
  88. if (originalAddress != nullptr)
  89. {
  90. if (addGuardPages)
  91. {
  92. #if DBG_DUMP
  93. GUARD_PAGE_TRACE(L"Number of Leading Guard Pages: %d\n", leadingGuardPageCount);
  94. GUARD_PAGE_TRACE(L"Starting address of Leading Guard Pages: 0x%p\n", address);
  95. GUARD_PAGE_TRACE(L"Offset of Segment Start address: 0x%p\n", this->address + (leadingGuardPageCount*AutoSystemInfo::PageSize));
  96. GUARD_PAGE_TRACE(L"Starting address of Trailing Guard Pages: 0x%p\n", address + ((leadingGuardPageCount + this->segmentPageCount)*AutoSystemInfo::PageSize));
  97. #endif
  98. #pragma warning(suppress: 6250)
  99. GetAllocator()->GetVirtualAllocator()->Free(address, leadingGuardPageCount*AutoSystemInfo::PageSize, MEM_DECOMMIT);
  100. #pragma warning(suppress: 6250)
  101. GetAllocator()->GetVirtualAllocator()->Free(address + ((leadingGuardPageCount + this->segmentPageCount)*AutoSystemInfo::PageSize), trailingGuardPageCount*AutoSystemInfo::PageSize, MEM_DECOMMIT);
  102. this->allocator->ReportFree((leadingGuardPageCount + trailingGuardPageCount)*AutoSystemInfo::PageSize);
  103. this->address = this->address + (leadingGuardPageCount*AutoSystemInfo::PageSize);
  104. }
  105. if (!allocator->CreateSecondaryAllocator(this, &this->secondaryAllocator))
  106. {
  107. GetAllocator()->GetVirtualAllocator()->Free(originalAddress, GetPageCount() * AutoSystemInfo::PageSize, MEM_RELEASE);
  108. this->allocator->ReportFree(totalPages * AutoSystemInfo::PageSize);
  109. this->address = nullptr;
  110. }
  111. #if defined(_M_X64_OR_ARM64) && defined(RECYCLER_WRITE_BARRIER_BYTE)
  112. else if (!RecyclerWriteBarrierManager::OnSegmentAlloc(this->address, this->segmentPageCount))
  113. {
  114. GetAllocator()->GetVirtualAllocator()->Free(originalAddress, GetPageCount() * AutoSystemInfo::PageSize, MEM_RELEASE);
  115. this->allocator->ReportFree(totalPages * AutoSystemInfo::PageSize);
  116. this->address = nullptr;
  117. }
  118. else
  119. {
  120. this->isWriteBarrierAllowed = true;
  121. }
  122. #endif
  123. }
  124. if (this->address == nullptr)
  125. {
  126. this->allocator->ReportFailure(totalPages * AutoSystemInfo::PageSize);
  127. }
  128. return (this->address != nullptr);
  129. }
  130. //=============================================================================================================
  131. // PageSegment
  132. //=============================================================================================================
  133. template<typename T>
  134. PageSegmentBase<T>::PageSegmentBase(PageAllocatorBase<T> * allocator, bool external) :
  135. SegmentBase(allocator, allocator->maxAllocPageCount), decommitPageCount(0)
  136. {
  137. Assert(this->segmentPageCount == allocator->maxAllocPageCount + allocator->secondaryAllocPageCount);
  138. if (external)
  139. {
  140. this->freePageCount = 0;
  141. this->ClearAllInFreePagesBitVector();
  142. }
  143. else
  144. {
  145. this->freePageCount = this->GetAvailablePageCount();
  146. uint maxPageCount = GetMaxPageCount();
  147. this->SetRangeInFreePagesBitVector(0, this->freePageCount);
  148. if (this->freePageCount != maxPageCount)
  149. {
  150. this->ClearRangeInFreePagesBitVector(this->freePageCount, (maxPageCount - this->freePageCount));
  151. }
  152. Assert(this->GetCountOfFreePages() == this->freePageCount);
  153. }
  154. }
  155. #ifdef PAGEALLOCATOR_PROTECT_FREEPAGE
  156. template<typename T>
  157. bool
  158. PageSegmentBase<T>::Initialize(DWORD allocFlags, bool excludeGuardPages)
  159. {
  160. Assert(freePageCount + allocator->secondaryAllocPageCount == this->segmentPageCount || freePageCount == 0);
  161. if (__super::Initialize(allocFlags, excludeGuardPages))
  162. {
  163. if (freePageCount != 0)
  164. {
  165. DWORD oldProtect;
  166. BOOL vpresult = ::VirtualProtect(this->address, this->GetAvailablePageCount() * AutoSystemInfo::PageSize, PAGE_NOACCESS, &oldProtect);
  167. Assert(vpresult && oldProtect == PAGE_READWRITE);
  168. }
  169. return true;
  170. }
  171. return false;
  172. }
  173. #endif
  174. template<typename T>
  175. void
  176. PageSegmentBase<T>::Prime()
  177. {
  178. #ifndef PAGEALLOCATOR_PROTECT_FREEPAGE
  179. for (uint i = 0; i < this->GetAvailablePageCount(); i++)
  180. {
  181. this->address[i * AutoSystemInfo::PageSize] = NULL;
  182. }
  183. #endif
  184. }
  185. template<typename T>
  186. bool
  187. PageSegmentBase<T>::IsAllocationPageAligned(__in char* address, size_t pageCount, PageHeapMode pageHeapFlags)
  188. {
  189. #ifdef RECYCLER_PAGE_HEAP
  190. if (pageHeapFlags != PageHeapMode::PageHeapModeOff)
  191. {
  192. // In PageHeap mode, we should ensure that if the guard page
  193. // is in the front, the page after the guard page is aligned
  194. if ((pageHeapFlags == PageHeapMode::PageHeapModeBlockStart))
  195. {
  196. address += AutoSystemInfo::PageSize;
  197. }
  198. // We don't care about whether the guard pages themselves are aligned
  199. // or fit in the chunk, so don't count the guard page for the purposes
  200. // of alignment
  201. pageCount--;
  202. }
  203. #endif
  204. // Require that allocations are aligned at a boundary
  205. // corresponding to the page count
  206. // REVIEW: This might actually lead to additional address space fragmentation
  207. // because of the leading guard pages feature in the page allocator
  208. // We can restrict the guard pages to be an even number to improve the chances
  209. // of having the first allocation be aligned but that reduces the effectiveness
  210. // of having a random number of guard pages
  211. uintptr_t mask = (pageCount * AutoSystemInfo::PageSize) - 1;
  212. if ((reinterpret_cast<uintptr_t>(address)& mask) == 0)
  213. {
  214. return true;
  215. }
  216. return false;
  217. }
  218. template<typename T>
  219. template <bool notPageAligned>
  220. char *
  221. PageSegmentBase<T>::AllocPages(uint pageCount, PageHeapMode pageHeapFlags)
  222. {
  223. Assert(freePageCount != 0);
  224. Assert(freePageCount == (uint)this->GetCountOfFreePages());
  225. if (freePageCount < pageCount)
  226. {
  227. return nullptr;
  228. }
  229. Assert(!IsFull());
  230. #pragma prefast(push)
  231. #pragma prefast(suppress:__WARNING_LOOP_INDEX_UNDERFLOW, "Prefast about overflow when multiplying index.")
  232. uint index = this->GetNextBitInFreePagesBitVector(0);
  233. while (index != -1)
  234. {
  235. Assert(index < allocator->GetMaxAllocPageCount());
  236. if (GetAvailablePageCount() - index < pageCount)
  237. {
  238. break;
  239. }
  240. if (pageCount == 1 || this->TestRangeInFreePagesBitVector(index, pageCount))
  241. {
  242. char * allocAddress = this->address + index * AutoSystemInfo::PageSize;
  243. if (pageCount > 1 && !notPageAligned)
  244. {
  245. if (!IsAllocationPageAligned(allocAddress, pageCount, pageHeapFlags))
  246. {
  247. index = this->freePages.GetNextBit(index + 1);
  248. continue;
  249. }
  250. }
  251. this->ClearRangeInFreePagesBitVector(index, pageCount);
  252. freePageCount -= pageCount;
  253. Assert(freePageCount == (uint)this->GetCountOfFreePages());
  254. #ifdef PAGEALLOCATOR_PROTECT_FREEPAGE
  255. DWORD oldProtect;
  256. BOOL vpresult = ::VirtualProtect(allocAddress, pageCount * AutoSystemInfo::PageSize, PAGE_READWRITE, &oldProtect);
  257. Assert(vpresult && oldProtect == PAGE_NOACCESS);
  258. #endif
  259. return allocAddress;
  260. }
  261. index = this->GetNextBitInFreePagesBitVector(index + 1);
  262. }
  263. #pragma prefast(pop)
  264. return nullptr;
  265. }
  266. #pragma prefast(push)
  267. #pragma prefast(suppress:__WARNING_LOOP_INDEX_UNDERFLOW, "Prefast about overflow when multiplying index.")
  268. template<typename TVirtualAlloc>
  269. template<typename T, bool notPageAligned>
  270. char *
  271. PageSegmentBase<TVirtualAlloc>::AllocDecommitPages(uint pageCount, T freePages, T decommitPages, PageHeapMode pageHeapFlags)
  272. {
  273. Assert(freePageCount == (uint)this->GetCountOfFreePages());
  274. Assert(decommitPageCount == (uint)this->GetCountOfDecommitPages());
  275. Assert(decommitPageCount != 0);
  276. if (freePageCount + decommitPageCount < pageCount)
  277. {
  278. return nullptr;
  279. }
  280. Assert(secondaryAllocator == nullptr || secondaryAllocator->CanAllocate());
  281. T freeAndDecommitPages = freePages;
  282. freeAndDecommitPages.Or(&decommitPages);
  283. uint oldFreePageCount = freePageCount;
  284. uint index = freeAndDecommitPages.GetNextBit(0);
  285. while (index != -1)
  286. {
  287. Assert(index < allocator->GetMaxAllocPageCount());
  288. if (GetAvailablePageCount() - index < pageCount)
  289. {
  290. break;
  291. }
  292. if (pageCount == 1 || freeAndDecommitPages.TestRange(index, pageCount))
  293. {
  294. char * pages = this->address + index * AutoSystemInfo::PageSize;
  295. if (!notPageAligned)
  296. {
  297. if (!IsAllocationPageAligned(pages, pageCount, pageHeapFlags))
  298. {
  299. index = freeAndDecommitPages.GetNextBit(index + 1);
  300. continue;
  301. }
  302. }
  303. void * ret = GetAllocator()->GetVirtualAllocator()->Alloc(pages, pageCount * AutoSystemInfo::PageSize, MEM_COMMIT, PAGE_READWRITE, this->IsInCustomHeapAllocator());
  304. if (ret != nullptr)
  305. {
  306. Assert(ret == pages);
  307. this->ClearRangeInFreePagesBitVector(index, pageCount);
  308. this->ClearRangeInDecommitPagesBitVector(index, pageCount);
  309. uint newFreePageCount = this->GetCountOfFreePages();
  310. freePageCount = freePageCount - oldFreePageCount + newFreePageCount;
  311. decommitPageCount -= pageCount - (oldFreePageCount - newFreePageCount);
  312. Assert(freePageCount == (uint)this->GetCountOfFreePages());
  313. Assert(decommitPageCount == (uint)this->GetCountOfDecommitPages());
  314. return pages;
  315. }
  316. else if (pageCount == 1)
  317. {
  318. // if we failed to commit one page, we should just give up.
  319. return nullptr;
  320. }
  321. }
  322. index = freeAndDecommitPages.GetNextBit(index + 1);
  323. }
  324. return nullptr;
  325. }
  326. #pragma prefast(pop)
  327. template<typename T>
  328. void
  329. PageSegmentBase<T>::ReleasePages(__in void * address, uint pageCount)
  330. {
  331. Assert(address >= this->address);
  332. Assert(pageCount <= allocator->maxAllocPageCount);
  333. Assert(((uint)(((char *)address) - this->address)) <= (allocator->maxAllocPageCount - pageCount) * AutoSystemInfo::PageSize);
  334. Assert(!IsFreeOrDecommitted(address, pageCount));
  335. uint base = this->GetBitRangeBase(address);
  336. this->SetRangeInFreePagesBitVector(base, pageCount);
  337. this->freePageCount += pageCount;
  338. Assert(freePageCount == (uint)this->GetCountOfFreePages());
  339. #ifdef PAGEALLOCATOR_PROTECT_FREEPAGE
  340. DWORD oldProtect;
  341. BOOL vpresult = ::VirtualProtect(address, pageCount * AutoSystemInfo::PageSize, PAGE_NOACCESS, &oldProtect);
  342. Assert(vpresult && oldProtect == PAGE_READWRITE);
  343. #endif
  344. }
  345. template<typename T>
  346. void
  347. PageSegmentBase<T>::ChangeSegmentProtection(DWORD protectFlags, DWORD expectedOldProtectFlags)
  348. {
  349. // TODO: There is a discrepancy in PageSegmentBase
  350. // The segment page count is initialized in PageSegmentBase::Initialize. It takes into account
  351. // the guard pages + any additional pages for alignment.
  352. // However, the free page count is calculated for the segment before initialize is called.
  353. // In practice, what happens is the following. The initial segment page count is 256. This
  354. // ends up being the free page count too. When initialize is called, we allocate the guard
  355. // pages and the alignment pages, which causes the total page count to be 272. The segment
  356. // page count is then calculated as total - guard, which means 256 <= segmentPageCount < totalPageCount
  357. // The code in PageSegment's constructor will mark the pages between 256 and 272 as in use,
  358. // which is why it generally works. However, it breaks in the case where we want to know the end
  359. // address of the page. It should really be address + 256 * 4k but this->GetEndAddress will return
  360. // a value greater than that. Need to do a pass through the counts and make sure that it's rational.
  361. // For now, simply calculate the end address from the allocator's page count
  362. char* segmentEndAddress = this->address + (this->allocator->GetMaxAllocPageCount() * AutoSystemInfo::PageSize);
  363. for (char* address = this->address; address < segmentEndAddress; address += AutoSystemInfo::PageSize)
  364. {
  365. if (!IsFreeOrDecommitted(address))
  366. {
  367. char* endAddress = address;
  368. do
  369. {
  370. endAddress += AutoSystemInfo::PageSize;
  371. } while (endAddress < segmentEndAddress && !IsFreeOrDecommitted(endAddress));
  372. Assert(((uintptr_t)(endAddress - address)) < UINT_MAX);
  373. DWORD regionSize = (DWORD) (endAddress - address);
  374. DWORD oldProtect = 0;
  375. #if DBG
  376. MEMORY_BASIC_INFORMATION info = { 0 };
  377. ::VirtualQuery(address, &info, sizeof(MEMORY_BASIC_INFORMATION));
  378. Assert(info.Protect == expectedOldProtectFlags);
  379. #endif
  380. BOOL fSuccess = ::VirtualProtect(address, regionSize, protectFlags, &oldProtect);
  381. Assert(fSuccess == TRUE);
  382. Assert(oldProtect == expectedOldProtectFlags);
  383. address = endAddress;
  384. }
  385. }
  386. }
  387. template<typename T>
  388. template <bool onlyUpdateState>
  389. void
  390. PageSegmentBase<T>::DecommitPages(__in void * address, uint pageCount)
  391. {
  392. Assert(address >= this->address);
  393. Assert(pageCount <= allocator->maxAllocPageCount);
  394. Assert(((uint)(((char *)address) - this->address)) <= (allocator->maxAllocPageCount - pageCount) * AutoSystemInfo::PageSize);
  395. Assert(!IsFreeOrDecommitted(address, pageCount));
  396. uint base = this->GetBitRangeBase(address);
  397. this->SetRangeInDecommitPagesBitVector(base, pageCount);
  398. this->decommitPageCount += pageCount;
  399. if (!onlyUpdateState)
  400. {
  401. #pragma warning(suppress: 6250)
  402. GetAllocator()->GetVirtualAllocator()->Free(address, pageCount * AutoSystemInfo::PageSize, MEM_DECOMMIT);
  403. }
  404. Assert(decommitPageCount == (uint)this->GetCountOfDecommitPages());
  405. }
  406. template<typename T>
  407. size_t
  408. PageSegmentBase<T>::DecommitFreePages(size_t pageToDecommit)
  409. {
  410. Assert(pageToDecommit != 0);
  411. char * currentAddress = this->address;
  412. uint decommitCount = 0;
  413. for (uint i = 0; i < this->GetAvailablePageCount(); i++)
  414. {
  415. if (this->TestInFreePagesBitVector(i))
  416. {
  417. this->ClearBitInFreePagesBitVector(i);
  418. this->SetBitInDecommitPagesBitVector(i);
  419. #pragma warning(suppress: 6250)
  420. GetAllocator()->GetVirtualAllocator()->Free(currentAddress, AutoSystemInfo::PageSize, MEM_DECOMMIT);
  421. decommitCount++;
  422. }
  423. currentAddress += AutoSystemInfo::PageSize;
  424. if (decommitCount == pageToDecommit)
  425. {
  426. break;
  427. }
  428. }
  429. Assert(decommitCount <= this->freePageCount);
  430. this->decommitPageCount += decommitCount;
  431. this->freePageCount -= decommitCount;
  432. return decommitCount;
  433. }
  434. //=============================================================================================================
  435. // PageAllocator
  436. //=============================================================================================================
  437. #if DBG
  438. #define ASSERT_THREAD() AssertMsg(ValidThreadAccess(), "Page allocation should only be used by a single thread");
  439. #else
  440. #define ASSERT_THREAD()
  441. #endif
  442. /*
  443. * Global counter to keep track of the total used bytes by the page allocator
  444. * per process for performance tooling. This is reported through the
  445. * JSCRIPT_PAGE_ALLOCATOR_USED_SIZE ETW event.
  446. */
  447. static size_t totalUsedBytes = 0;
  448. static size_t maxUsedBytes = 0;
  449. template<typename T>
  450. size_t PageAllocatorBase<T>::GetAndResetMaxUsedBytes()
  451. {
  452. size_t value = maxUsedBytes;
  453. maxUsedBytes = 0;
  454. return value;
  455. }
  456. template<typename T>
  457. size_t
  458. PageAllocatorBase<T>::GetProcessUsedBytes()
  459. {
  460. return totalUsedBytes;
  461. }
  462. template<typename T>
  463. PageAllocatorBase<T>::BackgroundPageQueue::BackgroundPageQueue()
  464. {
  465. ::InitializeSListHead(&freePageList);
  466. DebugOnly(this->isZeroPageQueue = false);
  467. }
  468. template<typename T>
  469. PageAllocatorBase<T>::ZeroPageQueue::ZeroPageQueue()
  470. {
  471. ::InitializeSListHead(&pendingZeroPageList);
  472. DebugOnly(this->isZeroPageQueue = true);
  473. }
  474. template<typename T>
  475. uint
  476. PageAllocatorBase<T>::GetMaxAllocPageCount()
  477. {
  478. return maxAllocPageCount;
  479. }
  480. template<typename T>
  481. PageAllocatorBase<T>::PageAllocatorBase(AllocationPolicyManager * policyManager,
  482. #ifndef JD_PRIVATE
  483. Js::ConfigFlagsTable& flagTable,
  484. #endif
  485. PageAllocatorType type,
  486. uint maxFreePageCount, bool zeroPages, BackgroundPageQueue * backgroundPageQueue, uint maxAllocPageCount, uint secondaryAllocPageCount,
  487. bool stopAllocationOnOutOfMemory, bool excludeGuardPages) :
  488. policyManager(policyManager),
  489. #ifndef JD_PRIVATE
  490. pageAllocatorFlagTable(flagTable),
  491. #endif
  492. maxFreePageCount(maxFreePageCount),
  493. freePageCount(0),
  494. allocFlags(0),
  495. zeroPages(zeroPages),
  496. queueZeroPages(false),
  497. hasZeroQueuedPages(false),
  498. backgroundPageQueue(backgroundPageQueue),
  499. minFreePageCount(0),
  500. isUsed(false),
  501. idleDecommitEnterCount(1),
  502. isClosed(false),
  503. stopAllocationOnOutOfMemory(stopAllocationOnOutOfMemory),
  504. disableAllocationOutOfMemory(false),
  505. secondaryAllocPageCount(secondaryAllocPageCount),
  506. excludeGuardPages(excludeGuardPages),
  507. virtualAllocator(nullptr),
  508. type(type)
  509. , reservedBytes(0)
  510. , committedBytes(0)
  511. , usedBytes(0)
  512. , numberOfSegments(0)
  513. {
  514. AssertMsg(Math::IsPow2(maxAllocPageCount + secondaryAllocPageCount), "Illegal maxAllocPageCount: Why is this not a power of 2 aligned?");
  515. this->maxAllocPageCount = maxAllocPageCount;
  516. #if DBG
  517. // By default, a page allocator is not associated with any thread context
  518. // Any host which wishes to associate it with a thread context must do so explicitly
  519. this->threadContextHandle = NULL;
  520. this->concurrentThreadId = (DWORD)-1;
  521. #endif
  522. #if DBG
  523. this->disableThreadAccessCheck = false;
  524. this->debugMinFreePageCount = 0;
  525. #endif
  526. #if DBG_DUMP
  527. this->decommitPageCount = 0;
  528. this->debugName = nullptr;
  529. #endif
  530. #ifdef RECYCLER_MEMORY_VERIFY
  531. this->verifyEnabled = false;
  532. this->disablePageReuse = false;
  533. #endif
  534. #ifdef PROFILE_MEM
  535. this->memoryData = MemoryProfiler::GetPageMemoryData(type);
  536. #endif
  537. PageTracking::PageAllocatorCreated((PageAllocator*)this);
  538. }
  539. template<typename T>
  540. PageAllocatorBase<T>::~PageAllocatorBase()
  541. {
  542. AssertMsg(this->ValidThreadAccess(), "Page allocator tear-down should only happen on the owning thread");
  543. #if DBG
  544. Assert(!HasMultiThreadAccess());
  545. #endif
  546. SubUsedBytes(usedBytes);
  547. SubCommittedBytes(committedBytes);
  548. SubReservedBytes(reservedBytes);
  549. ReleaseSegmentList(&segments);
  550. ReleaseSegmentList(&fullSegments);
  551. ReleaseSegmentList(&emptySegments);
  552. ReleaseSegmentList(&decommitSegments);
  553. ReleaseSegmentList(&largeSegments);
  554. PageTracking::PageAllocatorDestroyed((PageAllocator*)this);
  555. }
  556. template<typename T>
  557. void
  558. PageAllocatorBase<T>::StartQueueZeroPage()
  559. {
  560. Assert(HasZeroPageQueue());
  561. Assert(!queueZeroPages);
  562. queueZeroPages = true;
  563. }
  564. template<typename T>
  565. void
  566. PageAllocatorBase<T>::StopQueueZeroPage()
  567. {
  568. Assert(HasZeroPageQueue());
  569. Assert(queueZeroPages);
  570. queueZeroPages = false;
  571. }
  572. template<typename T>
  573. bool
  574. PageAllocatorBase<T>::HasZeroPageQueue() const
  575. {
  576. bool hasZeroPageQueue = (ZeroPages() && this->backgroundPageQueue != nullptr);
  577. Assert(backgroundPageQueue == nullptr || hasZeroPageQueue == backgroundPageQueue->isZeroPageQueue);
  578. return hasZeroPageQueue;
  579. }
  580. #if DBG
  581. template<typename T>
  582. bool
  583. PageAllocatorBase<T>::HasZeroQueuedPages() const
  584. {
  585. Assert(!HasZeroPageQueue() || hasZeroQueuedPages ||
  586. ::QueryDepthSList(&(((ZeroPageQueue *)this->backgroundPageQueue)->pendingZeroPageList)) == 0);
  587. return hasZeroQueuedPages;
  588. }
  589. #endif
  590. template<typename T>
  591. PageAllocation *
  592. PageAllocatorBase<T>::AllocPagesForBytes(size_t requestBytes)
  593. {
  594. Assert(!isClosed);
  595. ASSERT_THREAD();
  596. uint pageSize = AutoSystemInfo::PageSize;
  597. uint addSize = sizeof(PageAllocation) + pageSize - 1; // this shouldn't overflow
  598. // overflow check
  599. size_t allocSize = AllocSizeMath::Add(requestBytes, addSize);
  600. if (allocSize == (size_t)-1)
  601. {
  602. return nullptr;
  603. }
  604. size_t pages = allocSize / pageSize;
  605. return this->AllocAllocation(pages);
  606. }
  607. template<typename T>
  608. PageSegmentBase<T> *
  609. PageAllocatorBase<T>::AllocPageSegment(DListBase<PageSegmentBase<T>>& segmentList, PageAllocatorBase<T> * pageAllocator, bool external)
  610. {
  611. PageSegmentBase<T> * segment = segmentList.PrependNode(&NoThrowNoMemProtectHeapAllocator::Instance, pageAllocator, external);
  612. if (segment == nullptr)
  613. {
  614. return nullptr;
  615. }
  616. if (!segment->Initialize((external ? 0 : MEM_COMMIT) | pageAllocator->allocFlags, pageAllocator->excludeGuardPages))
  617. {
  618. segmentList.RemoveHead(&NoThrowNoMemProtectHeapAllocator::Instance);
  619. return nullptr;
  620. }
  621. return segment;
  622. }
  623. template<typename T>
  624. PageSegmentBase<T> *
  625. PageAllocatorBase<T>::AddPageSegment(DListBase<PageSegmentBase<T>>& segmentList)
  626. {
  627. Assert(!HasMultiThreadAccess());
  628. PageSegmentBase<T> * segment = AllocPageSegment(segmentList, this, false);
  629. if (segment != nullptr)
  630. {
  631. LogAllocSegment(segment);
  632. this->AddFreePageCount(maxAllocPageCount);
  633. }
  634. return segment;
  635. }
  636. template<>
  637. char *
  638. HeapPageAllocator<PreReservedVirtualAllocWrapper>::InitPageSegment()
  639. {
  640. Assert(virtualAllocator);
  641. PageSegmentBase<PreReservedVirtualAllocWrapper> * firstPreReservedSegment = AddPageSegment(emptySegments);
  642. if (firstPreReservedSegment == nullptr)
  643. {
  644. return nullptr;
  645. }
  646. return firstPreReservedSegment->GetAddress();
  647. }
  648. template<>
  649. char *
  650. HeapPageAllocator<VirtualAllocWrapper>::InitPageSegment()
  651. {
  652. Assert(false);
  653. return nullptr;
  654. }
  655. template<typename T>
  656. PageSegmentBase<T> *
  657. HeapPageAllocator<T>::AddPageSegment(DListBase<PageSegmentBase<T>>& segmentList)
  658. {
  659. Assert(!HasMultiThreadAccess());
  660. PageSegmentBase<T> * segment = AllocPageSegment(segmentList, this, false);
  661. if (segment != nullptr)
  662. {
  663. LogAllocSegment(segment);
  664. this->AddFreePageCount(maxAllocPageCount);
  665. }
  666. return segment;
  667. }
  668. template<typename T>
  669. template <bool notPageAligned>
  670. char *
  671. PageAllocatorBase<T>::TryAllocFreePages(uint pageCount, PageSegmentBase<T> ** pageSegment, PageHeapMode pageHeapFlags)
  672. {
  673. Assert(!HasMultiThreadAccess());
  674. if (this->freePageCount < pageCount)
  675. {
  676. return nullptr;
  677. }
  678. FAULTINJECT_MEMORY_NOTHROW(this->debugName, pageCount*4096);
  679. DListBase<PageSegmentBase<T>>::EditingIterator i(&segments);
  680. while (i.Next())
  681. {
  682. PageSegmentBase<T> * freeSegment = &i.Data();
  683. char * pages = freeSegment->AllocPages<notPageAligned>(pageCount, pageHeapFlags);
  684. if (pages != nullptr)
  685. {
  686. LogAllocPages(pageCount);
  687. if (freeSegment->GetFreePageCount() == 0)
  688. {
  689. i.MoveCurrentTo(&fullSegments);
  690. }
  691. this->freePageCount -= pageCount;
  692. *pageSegment = freeSegment;
  693. #if DBG
  694. UpdateMinimum(this->debugMinFreePageCount, this->freePageCount);
  695. #endif
  696. this->FillAllocPages(pages, pageCount);
  697. return pages;
  698. }
  699. }
  700. if (pageCount == 1 && backgroundPageQueue != nullptr)
  701. {
  702. FreePageEntry * freePage = (FreePageEntry *)::InterlockedPopEntrySList(&backgroundPageQueue->freePageList);
  703. if (freePage != nullptr)
  704. {
  705. #if DBG
  706. UpdateMinimum(this->debugMinFreePageCount, this->freePageCount);
  707. #endif
  708. *pageSegment = freePage->segment;
  709. char * pages;
  710. if (freePage->pageCount != 1)
  711. {
  712. uint pageIndex = --freePage->pageCount;
  713. ::InterlockedPushEntrySList(&backgroundPageQueue->freePageList, freePage);
  714. pages = (char *)freePage + pageIndex * AutoSystemInfo::PageSize;
  715. }
  716. else
  717. {
  718. pages = (char *)freePage;
  719. memset(pages, 0, sizeof(FreePageEntry));
  720. }
  721. this->FillAllocPages(pages, pageCount);
  722. return (char *)pages;
  723. }
  724. }
  725. return nullptr;
  726. }
  727. template<typename T>
  728. void
  729. PageAllocatorBase<T>::FillAllocPages(__in void * address, uint pageCount)
  730. {
  731. #if DBG
  732. #ifdef RECYCLER_ZERO_MEM_CHECK
  733. for (size_t i = 0; i < AutoSystemInfo::PageSize * pageCount; i++)
  734. {
  735. // new pages are filled with zeros, old pages are filled with DbgMemFill
  736. Assert(((byte *)address)[i] == 0 || ((byte *)address)[i] == DbgMemFill);
  737. }
  738. #endif
  739. #endif
  740. #ifdef RECYCLER_MEMORY_VERIFY
  741. if (verifyEnabled)
  742. {
  743. memset(address, Recycler::VerifyMemFill, AutoSystemInfo::PageSize * pageCount);
  744. return;
  745. }
  746. #endif
  747. #if DBG
  748. if (ZeroPages())
  749. {
  750. // for release build, the page is zeroed in ReleasePages
  751. memset(address, 0, AutoSystemInfo::PageSize * pageCount);
  752. }
  753. #endif
  754. }
  755. template<typename T>
  756. void
  757. PageAllocatorBase<T>::FillFreePages(__in void * address, uint pageCount)
  758. {
  759. #if DBG
  760. memset(address, DbgMemFill, AutoSystemInfo::PageSize * pageCount);
  761. #else
  762. #ifdef RECYCLER_MEMORY_VERIFY
  763. if (verifyEnabled)
  764. {
  765. return;
  766. }
  767. #endif
  768. if (ZeroPages())
  769. {
  770. memset(address, 0, AutoSystemInfo::PageSize * pageCount);
  771. }
  772. #endif
  773. }
  774. template<typename T>
  775. template <bool notPageAligned>
  776. char *
  777. PageAllocatorBase<T>::TryAllocDecommitedPages(uint pageCount, PageSegmentBase<T> ** pageSegment, PageHeapMode pageHeapFlags)
  778. {
  779. Assert(!HasMultiThreadAccess());
  780. DListBase<PageSegmentBase<T>>::EditingIterator i(&decommitSegments);
  781. while (i.Next())
  782. {
  783. PageSegmentBase<T> * freeSegment = &i.Data();
  784. uint oldFreePageCount = freeSegment->GetFreePageCount();
  785. uint oldDecommitPageCount = freeSegment->GetDecommitPageCount();
  786. char * pages = freeSegment->DoAllocDecommitPages<notPageAligned>(pageCount, pageHeapFlags);
  787. if (pages != nullptr)
  788. {
  789. this->freePageCount = this->freePageCount - oldFreePageCount + freeSegment->GetFreePageCount();
  790. #if DBG_DUMP
  791. this->decommitPageCount = this->decommitPageCount - oldDecommitPageCount + freeSegment->GetDecommitPageCount();
  792. #endif
  793. #if DBG
  794. UpdateMinimum(this->debugMinFreePageCount, this->freePageCount);
  795. #endif
  796. uint recommitPageCount = pageCount - (oldFreePageCount - freeSegment->GetFreePageCount());
  797. LogRecommitPages(recommitPageCount);
  798. LogAllocPages(pageCount);
  799. if (freeSegment->GetDecommitPageCount() == 0)
  800. {
  801. auto toList = GetSegmentList(freeSegment);
  802. i.MoveCurrentTo(toList);
  803. }
  804. *pageSegment = freeSegment;
  805. return pages;
  806. }
  807. }
  808. return nullptr;
  809. }
  810. template<typename T>
  811. PageAllocation *
  812. PageAllocatorBase<T>::AllocAllocation(size_t pageCount)
  813. {
  814. PageAllocation * pageAllocation;
  815. SegmentBase<T> * segment;
  816. if (pageCount > this->maxAllocPageCount)
  817. {
  818. // We need some space reserved for secondary allocations
  819. segment = AllocSegment(pageCount);
  820. if (segment == nullptr)
  821. {
  822. return nullptr;
  823. }
  824. pageAllocation = (PageAllocation *)segment->GetAddress();
  825. pageAllocation->pageCount = segment->GetAvailablePageCount();
  826. }
  827. else
  828. {
  829. Assert(pageCount <= UINT_MAX);
  830. pageAllocation = (PageAllocation *)AllocPages((uint)pageCount, (PageSegmentBase<T> **)&segment);
  831. if (pageAllocation == nullptr)
  832. {
  833. return nullptr;
  834. }
  835. pageAllocation->pageCount = pageCount;
  836. }
  837. pageAllocation->segment = segment;
  838. return pageAllocation;
  839. }
  840. template<typename T>
  841. SegmentBase<T> *
  842. PageAllocatorBase<T>::AllocSegment(size_t pageCount)
  843. {
  844. Assert(!isClosed);
  845. ASSERT_THREAD();
  846. // Even though we don't idle decommit large segments, we still need to consider these allocations
  847. // as using the page allocator
  848. this->isUsed = true;
  849. SegmentBase<T> * segment = largeSegments.PrependNode(&NoThrowNoMemProtectHeapAllocator::Instance, this, pageCount);
  850. if (segment == nullptr)
  851. {
  852. return nullptr;
  853. }
  854. if (!segment->Initialize(MEM_COMMIT | allocFlags, excludeGuardPages))
  855. {
  856. largeSegments.RemoveHead(&NoThrowNoMemProtectHeapAllocator::Instance);
  857. return nullptr;
  858. }
  859. LogAllocSegment(segment);
  860. LogAllocPages(segment->GetPageCount());
  861. PageTracking::ReportAllocation((PageAllocator*)this, segment->GetAddress(), AutoSystemInfo::PageSize * segment->GetPageCount());
  862. #ifdef RECYCLER_MEMORY_VERIFY
  863. if (verifyEnabled)
  864. {
  865. memset(segment->GetAddress(), Recycler::VerifyMemFill, AutoSystemInfo::PageSize * segment->GetPageCount());
  866. }
  867. #endif
  868. return segment;
  869. }
  870. char *
  871. PageAllocatorBase<VirtualAllocWrapper>::Alloc(size_t * pageCount, SegmentBase<VirtualAllocWrapper> ** segment)
  872. {
  873. Assert(virtualAllocator == nullptr);
  874. return AllocInternal<false>(pageCount, segment);
  875. }
  876. char *
  877. PageAllocatorBase<PreReservedVirtualAllocWrapper>::Alloc(size_t * pageCount, SegmentBase<PreReservedVirtualAllocWrapper> ** segment)
  878. {
  879. Assert(virtualAllocator);
  880. if (virtualAllocator->IsPreReservedRegionPresent())
  881. {
  882. return AllocInternal<false>(pageCount, segment);
  883. }
  884. else
  885. {
  886. return nullptr;
  887. }
  888. }
  889. template<typename T>
  890. template <bool doPageAlign>
  891. char *
  892. PageAllocatorBase<T>::AllocInternal(size_t * pageCount, SegmentBase<T> ** segment)
  893. {
  894. char * addr = nullptr;
  895. if (*pageCount > this->maxAllocPageCount)
  896. {
  897. // Don't bother trying to do single chunk allocation here
  898. // We're allocating a new segment. If the segment size is
  899. // within a single chunk, great, otherwise, doesn't matter
  900. // We need some space reserved for secondary allocations
  901. SegmentBase<T> * newSegment = this->AllocSegment(*pageCount);
  902. if (newSegment != nullptr)
  903. {
  904. addr = newSegment->GetAddress();
  905. *pageCount = newSegment->GetAvailablePageCount();
  906. *segment = newSegment;
  907. }
  908. }
  909. else
  910. {
  911. Assert(*pageCount <= UINT_MAX);
  912. PageSegmentBase<T> * pageSegment;
  913. if (doPageAlign)
  914. {
  915. // TODO: Remove this entire codepath since doPageAlign is not being used anymore
  916. addr = this->AllocPagesPageAligned((uint)*pageCount, &pageSegment, PageHeapMode::PageHeapModeOff);
  917. }
  918. else
  919. {
  920. addr = this->AllocPages((uint) *pageCount, &pageSegment);
  921. }
  922. if (addr != nullptr)
  923. {
  924. *segment = pageSegment;
  925. }
  926. }
  927. return addr;
  928. }
  929. template<typename T>
  930. void PageAllocatorBase<T>::UpdateMinFreePageCount()
  931. {
  932. UpdateMinimum(minFreePageCount, freePageCount);
  933. Assert(debugMinFreePageCount == minFreePageCount);
  934. }
  935. template<typename T>
  936. void PageAllocatorBase<T>::ResetMinFreePageCount()
  937. {
  938. minFreePageCount = freePageCount;
  939. #if DBG
  940. debugMinFreePageCount = freePageCount;
  941. #endif
  942. }
  943. template<typename T>
  944. void PageAllocatorBase<T>::ClearMinFreePageCount()
  945. {
  946. minFreePageCount = 0;
  947. #if DBG
  948. debugMinFreePageCount = 0;
  949. #endif
  950. }
  951. template<>
  952. char *
  953. PageAllocatorBase<VirtualAllocWrapper>::AllocPages(uint pageCount, PageSegmentBase<VirtualAllocWrapper> ** pageSegment)
  954. {
  955. Assert(virtualAllocator == nullptr);
  956. return AllocPagesInternal<true /* noPageAligned */>(pageCount, pageSegment);
  957. }
  958. template<>
  959. char *
  960. PageAllocatorBase<PreReservedVirtualAllocWrapper>::AllocPages(uint pageCount, PageSegmentBase<PreReservedVirtualAllocWrapper> ** pageSegment)
  961. {
  962. Assert(virtualAllocator);
  963. if (virtualAllocator->IsPreReservedRegionPresent())
  964. {
  965. return AllocPagesInternal<true /* noPageAligned */>(pageCount, pageSegment);
  966. }
  967. else
  968. {
  969. return nullptr;
  970. }
  971. }
  972. template<typename T>
  973. char *
  974. PageAllocatorBase<T>::AllocPagesPageAligned(uint pageCount, PageSegmentBase<T> ** pageSegment, PageHeapMode pageHeapFlags)
  975. {
  976. return AllocPagesInternal<false /* noPageAligned */>(pageCount, pageSegment, pageHeapFlags);
  977. }
  978. template<typename T>
  979. template <bool notPageAligned>
  980. char *
  981. PageAllocatorBase<T>::AllocPagesInternal(uint pageCount, PageSegmentBase<T> ** pageSegment, PageHeapMode pageHeapModeFlags)
  982. {
  983. Assert(!isClosed);
  984. ASSERT_THREAD();
  985. Assert(pageCount <= this->maxAllocPageCount);
  986. this->isUsed = true;
  987. SuspendIdleDecommit();
  988. char * allocation = TryAllocFreePages<notPageAligned>(pageCount, pageSegment, pageHeapModeFlags);
  989. if (allocation == nullptr)
  990. {
  991. allocation = SnailAllocPages<notPageAligned>(pageCount, pageSegment, pageHeapModeFlags);
  992. }
  993. ResumeIdleDecommit();
  994. PageTracking::ReportAllocation((PageAllocator*)this, allocation, AutoSystemInfo::PageSize * pageCount);
  995. return allocation;
  996. }
  997. template<typename T>
  998. void
  999. PageAllocatorBase<T>::OnAllocFromNewSegment(uint pageCount, __in void* pages, SegmentBase<T>* newSegment)
  1000. {
  1001. DListBase<PageSegmentBase<T>>* targetSegmentList = (pageCount == maxAllocPageCount) ? &fullSegments : &segments;
  1002. LogAllocPages(pageCount);
  1003. this->FillAllocPages(pages, pageCount);
  1004. this->freePageCount -= pageCount;
  1005. #if DBG
  1006. UpdateMinimum(this->debugMinFreePageCount, this->freePageCount);
  1007. #endif
  1008. Assert(targetSegmentList != nullptr);
  1009. emptySegments.MoveHeadTo(targetSegmentList);
  1010. }
  1011. template<typename T>
  1012. template <bool notPageAligned>
  1013. char *
  1014. PageAllocatorBase<T>::SnailAllocPages(uint pageCount, PageSegmentBase<T> ** pageSegment, PageHeapMode pageHeapFlags)
  1015. {
  1016. Assert(!HasMultiThreadAccess());
  1017. char * pages = nullptr;
  1018. PageSegmentBase<T> * newSegment = nullptr;
  1019. if (!emptySegments.Empty())
  1020. {
  1021. newSegment = &emptySegments.Head();
  1022. if (!notPageAligned && !PageSegmentBase<T>::IsAllocationPageAligned(newSegment->GetAddress(), pageCount, pageHeapFlags))
  1023. {
  1024. newSegment = nullptr;
  1025. // Scan through the empty segments for a segment that can fit this allocation
  1026. FOREACH_DLISTBASE_ENTRY_EDITING(PageSegmentBase<T>, emptySegment, &this->emptySegments, iter)
  1027. {
  1028. if (PageSegmentBase<T>::IsAllocationPageAligned(emptySegment.GetAddress(), pageCount, pageHeapFlags))
  1029. {
  1030. iter.MoveCurrentTo(&this->emptySegments);
  1031. newSegment = &emptySegment;
  1032. break;
  1033. }
  1034. }
  1035. NEXT_DLISTBASE_ENTRY_EDITING
  1036. }
  1037. if (newSegment != nullptr)
  1038. {
  1039. pages = newSegment->AllocPages<notPageAligned>(pageCount, pageHeapFlags);
  1040. if (pages != nullptr)
  1041. {
  1042. OnAllocFromNewSegment(pageCount, pages, newSegment);
  1043. *pageSegment = newSegment;
  1044. return pages;
  1045. }
  1046. }
  1047. }
  1048. pages = TryAllocDecommitedPages<notPageAligned>(pageCount, pageSegment, pageHeapFlags);
  1049. if (pages != nullptr)
  1050. {
  1051. // TryAllocDecommitedPages may give out a mix of free pages and decommitted pages.
  1052. // Free pages are filled with 0xFE in debug build, so we need to zero them
  1053. // out before giving it out. In release build, free page is already zeroed
  1054. // in ReleasePages
  1055. this->FillAllocPages(pages, pageCount);
  1056. return pages;
  1057. }
  1058. Assert(pages == nullptr);
  1059. // At this point, we haven't been able to allocate either from the
  1060. // decommitted pages, or from the empty segment list, so we'll
  1061. // try allocating a segment. In a page allocator with a pre-reserved segment,
  1062. // we're not allowed to allocate additional segments so return here.
  1063. // Otherwise, add a new segment and allocate from it
  1064. newSegment = AddPageSegment(emptySegments);
  1065. if (newSegment == nullptr)
  1066. {
  1067. return nullptr;
  1068. }
  1069. pages = newSegment->AllocPages<notPageAligned>(pageCount, pageHeapFlags);
  1070. if (notPageAligned)
  1071. {
  1072. // REVIEW: Is this true for single-chunk allocations too? Are new segments guaranteed to
  1073. // allow for single-chunk allocations to succeed?
  1074. Assert(pages != nullptr);
  1075. }
  1076. if (pages != nullptr)
  1077. {
  1078. OnAllocFromNewSegment(pageCount, pages, newSegment);
  1079. *pageSegment = newSegment;
  1080. }
  1081. return pages;
  1082. }
  1083. template<typename T>
  1084. DListBase<PageSegmentBase<T>> *
  1085. PageAllocatorBase<T>::GetSegmentList(PageSegmentBase<T> * segment)
  1086. {
  1087. Assert(!HasMultiThreadAccess());
  1088. return
  1089. (segment->IsAllDecommitted()) ? nullptr :
  1090. (segment->IsFull()) ? &fullSegments :
  1091. (segment->ShouldBeInDecommittedList()) ? &decommitSegments :
  1092. (segment->IsEmpty()) ? &emptySegments :
  1093. &segments;
  1094. }
  1095. template<typename T>
  1096. void
  1097. PageAllocatorBase<T>::ReleaseAllocation(PageAllocation * allocation)
  1098. {
  1099. SuspendIdleDecommit();
  1100. ReleaseAllocationNoSuspend(allocation);
  1101. ResumeIdleDecommit();
  1102. }
  1103. template<typename T>
  1104. void
  1105. PageAllocatorBase<T>::ReleaseAllocationNoSuspend(PageAllocation * allocation)
  1106. {
  1107. this->Release((char *)allocation, allocation->pageCount, allocation->segment);
  1108. }
  1109. template<typename T>
  1110. void
  1111. PageAllocatorBase<T>::Release(void * address, size_t pageCount, void * segmentParam)
  1112. {
  1113. SegmentBase<T> * segment = (SegmentBase<T>*)segmentParam;
  1114. Assert(!HasMultiThreadAccess());
  1115. Assert(segment->GetAllocator() == this);
  1116. if (pageCount > this->maxAllocPageCount)
  1117. {
  1118. Assert(address == segment->GetAddress());
  1119. Assert(pageCount == segment->GetAvailablePageCount());
  1120. this->ReleaseSegment(segment);
  1121. }
  1122. else
  1123. {
  1124. Assert(pageCount <= UINT_MAX);
  1125. this->ReleasePages(address, static_cast<uint>(pageCount), (PageSegmentBase<T> *)segment);
  1126. }
  1127. }
  1128. template<typename T>
  1129. void
  1130. PageAllocatorBase<T>::ReleaseSegment(SegmentBase<T> * segment)
  1131. {
  1132. ASSERT_THREAD();
  1133. #if defined(RECYCLER_MEMORY_VERIFY) || defined(ARENA_MEMORY_VERIFY)
  1134. if (disablePageReuse)
  1135. {
  1136. DWORD oldProtect;
  1137. BOOL vpresult = ::VirtualProtect(segment->GetAddress(), segment->GetPageCount() * AutoSystemInfo::PageSize, PAGE_NOACCESS, &oldProtect);
  1138. Assert(vpresult && oldProtect == PAGE_READWRITE);
  1139. return;
  1140. }
  1141. #endif
  1142. PageTracking::ReportFree((PageAllocator*)this, segment->GetAddress(), AutoSystemInfo::PageSize * segment->GetPageCount());
  1143. LogFreePages(segment->GetPageCount());
  1144. LogFreeSegment(segment);
  1145. largeSegments.RemoveElement(&NoThrowNoMemProtectHeapAllocator::Instance, segment);
  1146. }
  1147. template<typename T>
  1148. void
  1149. PageAllocatorBase<T>::AddFreePageCount(uint pageCount)
  1150. {
  1151. // minFreePageCount is only updated on release of a page or before decommit
  1152. // so that we don't have to update it on every page allocation.
  1153. UpdateMinFreePageCount();
  1154. this->freePageCount += pageCount;
  1155. }
  1156. template<typename T>
  1157. void
  1158. PageAllocatorBase<T>::ReleasePages(__in void * address, uint pageCount, __in void * segmentParam)
  1159. {
  1160. Assert(pageCount <= this->maxAllocPageCount);
  1161. PageSegmentBase<T> * segment = (PageSegmentBase<T>*) segmentParam;
  1162. ASSERT_THREAD();
  1163. Assert(!HasMultiThreadAccess());
  1164. #if defined(RECYCLER_MEMORY_VERIFY) || defined(ARENA_MEMORY_VERIFY)
  1165. if (disablePageReuse)
  1166. {
  1167. DWORD oldProtect;
  1168. BOOL vpresult = ::VirtualProtect(address, pageCount * AutoSystemInfo::PageSize, PAGE_NOACCESS, &oldProtect);
  1169. Assert(vpresult && oldProtect == PAGE_READWRITE);
  1170. return;
  1171. }
  1172. #endif
  1173. PageTracking::ReportFree((PageAllocator*)this, address, AutoSystemInfo::PageSize * pageCount);
  1174. DListBase<PageSegmentBase<T>> * fromSegmentList = GetSegmentList(segment);
  1175. Assert(fromSegmentList != nullptr);
  1176. /**
  1177. * The logic here is as follows:
  1178. * - If we have sufficient pages already, such that the newly free pages are going
  1179. * to cause us to exceed the threshold of free pages we want:
  1180. * - First check and see if we have empty segments. If we do, just release that
  1181. * entire segment back to the operating system, and add the current segments
  1182. * free pages to our free page pool
  1183. * - Otherwise, if there are no empty segments (i.e our memory is fragmented),
  1184. * decommit the pages that are being released so that they don't count towards
  1185. * our working set
  1186. * - If we don't have enough pages:
  1187. * - If we're in the free page queuing mode where we have a "pages to zero out" queue
  1188. * put it in that queue and we're done
  1189. * - Otherwise, zero it out, and add it to the free page pool
  1190. * Now that we've either decommited or freed the pages in the segment,
  1191. * move the segment to the right segment list
  1192. */
  1193. if (this->freePageCount + pageCount > maxFreePageCount)
  1194. {
  1195. // Release a whole segment if possible to reduce the number of VirtualFree and fragmentation
  1196. if (!ZeroPages() && !emptySegments.Empty())
  1197. {
  1198. Assert(emptySegments.Head().GetDecommitPageCount() == 0);
  1199. LogFreeSegment(&emptySegments.Head());
  1200. emptySegments.RemoveHead(&NoThrowNoMemProtectHeapAllocator::Instance);
  1201. this->freePageCount -= maxAllocPageCount;
  1202. #if DBG
  1203. UpdateMinimum(this->debugMinFreePageCount, this->freePageCount);
  1204. memset(address, DbgMemFill, AutoSystemInfo::PageSize * pageCount);
  1205. #endif
  1206. segment->ReleasePages(address, pageCount);
  1207. LogFreePages(pageCount);
  1208. this->AddFreePageCount(pageCount);
  1209. }
  1210. else
  1211. {
  1212. segment->DecommitPages<false>(address, pageCount);
  1213. LogFreePages(pageCount);
  1214. LogDecommitPages(pageCount);
  1215. #if DBG_DUMP
  1216. this->decommitPageCount += pageCount;
  1217. #endif
  1218. }
  1219. }
  1220. else
  1221. {
  1222. if (QueueZeroPages())
  1223. {
  1224. Assert(HasZeroPageQueue());
  1225. AddPageToZeroQueue(address, pageCount, segment);
  1226. return;
  1227. }
  1228. this->FillFreePages((char *)address, pageCount);
  1229. segment->ReleasePages(address, pageCount);
  1230. LogFreePages(pageCount);
  1231. this->AddFreePageCount(pageCount);
  1232. }
  1233. TransferSegment(segment, fromSegmentList);
  1234. }
  1235. template<class T>
  1236. typename PageAllocatorBase<T>::FreePageEntry *
  1237. PageAllocatorBase<T>::PopPendingZeroPage()
  1238. {
  1239. Assert(HasZeroPageQueue());
  1240. return (PageAllocatorBase<T>::FreePageEntry *)::InterlockedPopEntrySList(&(((PageAllocatorBase<T>::ZeroPageQueue *) backgroundPageQueue)->pendingZeroPageList));
  1241. }
  1242. template<typename T>
  1243. void
  1244. PageAllocatorBase<T>::AddPageToZeroQueue(__in void * address, uint pageCount, __in PageSegmentBase<T> * pageSegment)
  1245. {
  1246. Assert(HasZeroPageQueue());
  1247. Assert(pageSegment->GetAllocator() == this);
  1248. FreePageEntry * entry = (FreePageEntry *)address;
  1249. entry->segment = pageSegment;
  1250. entry->pageCount = pageCount;
  1251. ::InterlockedPushEntrySList(&(((ZeroPageQueue *)backgroundPageQueue)->pendingZeroPageList), entry);
  1252. this->hasZeroQueuedPages = true;
  1253. }
  1254. template<typename T>
  1255. void
  1256. PageAllocatorBase<T>::TransferSegment(PageSegmentBase<T> * segment, DListBase<PageSegmentBase<T>> * fromSegmentList)
  1257. {
  1258. DListBase<PageSegmentBase<T>> * toSegmentList = GetSegmentList(segment);
  1259. if (fromSegmentList != toSegmentList)
  1260. {
  1261. if (toSegmentList)
  1262. {
  1263. AssertMsg(segment->GetSecondaryAllocator() == nullptr || fromSegmentList != &fullSegments || segment->GetSecondaryAllocator()->CanAllocate(),
  1264. "If it's being moved from a full segment it should be able to do secondary allocations");
  1265. fromSegmentList->MoveElementTo(segment, toSegmentList);
  1266. }
  1267. else
  1268. {
  1269. LogFreePartiallyDecommitedPageSegment(segment);
  1270. fromSegmentList->RemoveElement(&NoThrowNoMemProtectHeapAllocator::Instance, segment);
  1271. #if DBG_DUMP
  1272. this->decommitPageCount -= maxAllocPageCount;
  1273. #endif
  1274. }
  1275. }
  1276. }
  1277. template<typename T>
  1278. void
  1279. PageAllocatorBase<T>::BackgroundZeroQueuedPages()
  1280. {
  1281. Assert(HasZeroPageQueue());
  1282. AutoCriticalSection autocs(&backgroundPageQueue->backgroundPageQueueCriticalSection);
  1283. ZeroQueuedPages();
  1284. }
  1285. template<typename T>
  1286. void
  1287. PageAllocatorBase<T>::ZeroQueuedPages()
  1288. {
  1289. Assert(HasZeroPageQueue());
  1290. while (true)
  1291. {
  1292. FreePageEntry * freePageEntry = PopPendingZeroPage();
  1293. if (freePageEntry == nullptr)
  1294. {
  1295. break;
  1296. }
  1297. PageSegmentBase<T> * segment = freePageEntry->segment;
  1298. uint pageCount = freePageEntry->pageCount;
  1299. memset(freePageEntry, 0, pageCount * AutoSystemInfo::PageSize);
  1300. QueuePages(freePageEntry, pageCount, segment);
  1301. }
  1302. this->hasZeroQueuedPages = false;
  1303. }
  1304. template<typename T>
  1305. void
  1306. PageAllocatorBase<T>::BackgroundReleasePages(void * address, uint pageCount, PageSegmentBase<T> * segment)
  1307. {
  1308. FillFreePages(address, pageCount);
  1309. QueuePages(address, pageCount, segment);
  1310. }
  1311. template<typename T>
  1312. void
  1313. PageAllocatorBase<T>::QueuePages(void * address, uint pageCount, PageSegmentBase<T> * segment)
  1314. {
  1315. Assert(backgroundPageQueue);
  1316. FreePageEntry * freePageEntry = (FreePageEntry *)address;
  1317. freePageEntry->segment = segment;
  1318. freePageEntry->pageCount = pageCount;
  1319. ::InterlockedPushEntrySList(&backgroundPageQueue->freePageList, freePageEntry);
  1320. }
  1321. template<typename T>
  1322. void
  1323. PageAllocatorBase<T>::FlushBackgroundPages()
  1324. {
  1325. Assert(!HasMultiThreadAccess());
  1326. Assert(backgroundPageQueue);
  1327. // We can have additional pages queued up to be zeroed out here
  1328. // and that's okay since they'll eventually be zeroed out before being flushed
  1329. uint newFreePages = 0;
  1330. while (true)
  1331. {
  1332. FreePageEntry * freePageEntry = (FreePageEntry *)::InterlockedPopEntrySList(&backgroundPageQueue->freePageList);
  1333. if (freePageEntry == nullptr)
  1334. {
  1335. break;
  1336. }
  1337. PageSegmentBase<T> * segment = freePageEntry->segment;
  1338. uint pageCount = freePageEntry->pageCount;
  1339. DListBase<PageSegmentBase<T>> * fromSegmentList = GetSegmentList(segment);
  1340. Assert(fromSegmentList != nullptr);
  1341. memset(freePageEntry, 0, sizeof(FreePageEntry));
  1342. segment->ReleasePages(freePageEntry, pageCount);
  1343. newFreePages += pageCount;
  1344. TransferSegment(segment, fromSegmentList);
  1345. }
  1346. LogFreePages(newFreePages);
  1347. PAGE_ALLOC_VERBOSE_TRACE(L"New free pages: %d\n", newFreePages);
  1348. this->AddFreePageCount(newFreePages);
  1349. }
  1350. template<typename T>
  1351. void
  1352. PageAllocatorBase<T>::SuspendIdleDecommit()
  1353. {
  1354. #ifdef IDLE_DECOMMIT_ENABLED
  1355. if (this->idleDecommitEnterCount != 0)
  1356. {
  1357. return;
  1358. }
  1359. Assert(this->IsIdleDecommitPageAllocator());
  1360. ((IdleDecommitPageAllocator *)this)->cs.Enter();
  1361. PAGE_ALLOC_VERBOSE_TRACE(L"SuspendIdleDecommit");
  1362. #endif
  1363. }
  1364. template<typename T>
  1365. void
  1366. PageAllocatorBase<T>::ResumeIdleDecommit()
  1367. {
  1368. #ifdef IDLE_DECOMMIT_ENABLED
  1369. if (this->idleDecommitEnterCount != 0)
  1370. {
  1371. return;
  1372. }
  1373. Assert(this->IsIdleDecommitPageAllocator());
  1374. PAGE_ALLOC_VERBOSE_TRACE(L"ResumeIdleDecommit");
  1375. ((IdleDecommitPageAllocator *)this)->cs.Leave();
  1376. #endif
  1377. }
  1378. template<typename T>
  1379. void
  1380. PageAllocatorBase<T>::DecommitNow(bool all)
  1381. {
  1382. Assert(!HasMultiThreadAccess());
  1383. #if DBG_DUMP
  1384. size_t deleteCount = 0;
  1385. #endif
  1386. // First, drain the zero page queue.
  1387. // This will cause the free page count to be accurate
  1388. if (HasZeroPageQueue())
  1389. {
  1390. int numZeroPagesFreed = 0;
  1391. // There might be queued zero pages. Drain them first
  1392. while (true)
  1393. {
  1394. FreePageEntry * freePageEntry = PopPendingZeroPage();
  1395. if (freePageEntry == nullptr)
  1396. {
  1397. break;
  1398. }
  1399. PAGE_ALLOC_TRACE_AND_STATS(L"Freeing page from zero queue");
  1400. PageSegmentBase<T> * segment = freePageEntry->segment;
  1401. uint pageCount = freePageEntry->pageCount;
  1402. numZeroPagesFreed += pageCount;
  1403. DListBase<PageSegmentBase<T>> * fromSegmentList = GetSegmentList(segment);
  1404. Assert(fromSegmentList != nullptr);
  1405. // Check for all here, since the actual free page count can't be determined
  1406. // until we've flushed the zeroed page queue
  1407. if (all)
  1408. {
  1409. // Decommit them immediately if we are decommitting all pages.
  1410. segment->DecommitPages<false>(freePageEntry, pageCount);
  1411. LogFreePages(pageCount);
  1412. LogDecommitPages(pageCount);
  1413. if (segment->IsAllDecommitted())
  1414. {
  1415. LogFreePartiallyDecommitedPageSegment(segment);
  1416. fromSegmentList->RemoveElement(&NoThrowNoMemProtectHeapAllocator::Instance, segment);
  1417. #if DBG_DUMP
  1418. deleteCount += maxAllocPageCount;
  1419. #endif
  1420. continue;
  1421. }
  1422. }
  1423. else
  1424. {
  1425. // Zero them and release them in case we don't decommit them.
  1426. memset(freePageEntry, 0, pageCount * AutoSystemInfo::PageSize);
  1427. segment->ReleasePages(freePageEntry, pageCount);
  1428. LogFreePages(pageCount);
  1429. }
  1430. TransferSegment(segment, fromSegmentList);
  1431. }
  1432. // Take the lock to make sure the recycler thread has finished zeroing out the pages after
  1433. // we drained the queue
  1434. backgroundPageQueue->backgroundPageQueueCriticalSection.Enter();
  1435. this->hasZeroQueuedPages = false;
  1436. Assert(!this->HasZeroQueuedPages());
  1437. backgroundPageQueue->backgroundPageQueueCriticalSection.Leave();
  1438. FlushBackgroundPages();
  1439. }
  1440. if (this->freePageCount == 0)
  1441. {
  1442. Assert(debugMinFreePageCount == 0);
  1443. return;
  1444. }
  1445. PAGE_ALLOC_TRACE_AND_STATS(L"Decommit now");
  1446. // minFreePageCount is not updated on every page allocate,
  1447. // so we have to do a final update here.
  1448. UpdateMinFreePageCount();
  1449. size_t newFreePageCount;
  1450. if (all)
  1451. {
  1452. newFreePageCount = this->GetFreePageLimit();
  1453. PAGE_ALLOC_TRACE_AND_STATS(L"Full decommit");
  1454. }
  1455. else
  1456. {
  1457. // Decommit half the min free page count since last partial decommit
  1458. Assert(this->minFreePageCount <= this->freePageCount);
  1459. newFreePageCount = this->freePageCount - (this->minFreePageCount / 2);
  1460. // Ensure we don't decommit down to fewer than our partial decommit minimum
  1461. newFreePageCount = max(newFreePageCount, static_cast<size_t>(MinPartialDecommitFreePageCount));
  1462. PAGE_ALLOC_TRACE_AND_STATS(L"Partial decommit");
  1463. }
  1464. if (newFreePageCount >= this->freePageCount)
  1465. {
  1466. PAGE_ALLOC_TRACE_AND_STATS(L"No pages to decommit");
  1467. return;
  1468. }
  1469. size_t pageToDecommit = this->freePageCount - newFreePageCount;
  1470. PAGE_ALLOC_TRACE_AND_STATS(L"Decommit page count = %d", pageToDecommit);
  1471. PAGE_ALLOC_TRACE_AND_STATS(L"Free page count = %d", this->freePageCount);
  1472. PAGE_ALLOC_TRACE_AND_STATS(L"New free page count = %d", newFreePageCount);
  1473. #if DBG_DUMP
  1474. size_t decommitCount = 0;
  1475. #endif
  1476. // decommit from page that already has other decommitted page already
  1477. {
  1478. DListBase<PageSegmentBase<T>>::EditingIterator i(&decommitSegments);
  1479. while (pageToDecommit > 0 && i.Next())
  1480. {
  1481. size_t pageDecommited = i.Data().DecommitFreePages(pageToDecommit);
  1482. LogDecommitPages(pageDecommited);
  1483. #if DBG_DUMP
  1484. decommitCount += pageDecommited;
  1485. #endif
  1486. if (i.Data().GetDecommitPageCount() == maxAllocPageCount)
  1487. {
  1488. LogFreePartiallyDecommitedPageSegment(&i.Data());
  1489. i.RemoveCurrent(&NoThrowNoMemProtectHeapAllocator::Instance);
  1490. #if DBG_DUMP
  1491. deleteCount += maxAllocPageCount;
  1492. #endif
  1493. }
  1494. pageToDecommit -= pageDecommited;
  1495. }
  1496. }
  1497. // decommit pages that are empty
  1498. while (pageToDecommit > 0 && !emptySegments.Empty())
  1499. {
  1500. if (pageToDecommit >= maxAllocPageCount)
  1501. {
  1502. Assert(emptySegments.Head().GetDecommitPageCount() == 0);
  1503. LogFreeSegment(&emptySegments.Head());
  1504. emptySegments.RemoveHead(&NoThrowNoMemProtectHeapAllocator::Instance);
  1505. pageToDecommit -= maxAllocPageCount;
  1506. #if DBG_DUMP
  1507. decommitCount += maxAllocPageCount;
  1508. deleteCount += maxAllocPageCount;
  1509. #endif
  1510. }
  1511. else
  1512. {
  1513. size_t pageDecommited = emptySegments.Head().DecommitFreePages(pageToDecommit);
  1514. LogDecommitPages(pageDecommited);
  1515. #if DBG_DUMP
  1516. decommitCount += pageDecommited;
  1517. #endif
  1518. Assert(pageDecommited == pageToDecommit);
  1519. emptySegments.MoveHeadTo(&decommitSegments);
  1520. pageToDecommit = 0;
  1521. }
  1522. }
  1523. {
  1524. DListBase<PageSegmentBase<T>>::EditingIterator i(&segments);
  1525. while (pageToDecommit > 0 && i.Next())
  1526. {
  1527. size_t pageDecommited = i.Data().DecommitFreePages(pageToDecommit);
  1528. LogDecommitPages(pageDecommited);
  1529. #if DBG_DUMP
  1530. decommitCount += pageDecommited;
  1531. #endif
  1532. Assert(i.Data().GetDecommitPageCount() != 0);
  1533. Assert(i.Data().GetDecommitPageCount() <= maxAllocPageCount);
  1534. i.MoveCurrentTo(&decommitSegments);
  1535. pageToDecommit -= pageDecommited;
  1536. }
  1537. }
  1538. Assert(pageToDecommit == 0);
  1539. #if DBG_DUMP
  1540. Assert(this->freePageCount == newFreePageCount + decommitCount);
  1541. #endif
  1542. this->freePageCount = newFreePageCount;
  1543. #if DBG
  1544. UpdateMinimum(this->debugMinFreePageCount, this->freePageCount);
  1545. Check();
  1546. #endif
  1547. #if DBG_DUMP
  1548. this->decommitPageCount += (decommitCount - deleteCount);
  1549. if (CUSTOM_PHASE_TRACE1(this->pageAllocatorFlagTable, Js::PageAllocatorPhase))
  1550. {
  1551. if (CUSTOM_PHASE_STATS1(this->pageAllocatorFlagTable, Js::PageAllocatorPhase))
  1552. {
  1553. Output::Print(L" After decommit now:\n");
  1554. this->DumpStats();
  1555. }
  1556. Output::Flush();
  1557. }
  1558. #endif
  1559. }
  1560. template<typename T>
  1561. void
  1562. PageAllocatorBase<T>::AddReservedBytes(size_t bytes)
  1563. {
  1564. reservedBytes += bytes;
  1565. #ifdef PERF_COUNTERS
  1566. GetReservedSizeCounter() += bytes;
  1567. GetTotalReservedSizeCounter() += bytes;
  1568. #endif
  1569. }
  1570. template<typename T>
  1571. void
  1572. PageAllocatorBase<T>::SubReservedBytes(size_t bytes)
  1573. {
  1574. reservedBytes -= bytes;
  1575. #ifdef PERF_COUNTERS
  1576. GetReservedSizeCounter() -= bytes;
  1577. GetTotalReservedSizeCounter() -= bytes;
  1578. #endif
  1579. }
  1580. template<typename T>
  1581. void
  1582. PageAllocatorBase<T>::AddCommittedBytes(size_t bytes)
  1583. {
  1584. committedBytes += bytes;
  1585. #ifdef PERF_COUNTERS
  1586. GetCommittedSizeCounter() += bytes;
  1587. GetTotalCommittedSizeCounter() += bytes;
  1588. #endif
  1589. }
  1590. template<typename T>
  1591. void
  1592. PageAllocatorBase<T>::SubCommittedBytes(size_t bytes)
  1593. {
  1594. committedBytes -= bytes;
  1595. #ifdef PERF_COUNTERS
  1596. GetCommittedSizeCounter() -= bytes;
  1597. GetTotalCommittedSizeCounter() -= bytes;
  1598. #endif
  1599. }
  1600. template<typename T>
  1601. void
  1602. PageAllocatorBase<T>::AddUsedBytes(size_t bytes)
  1603. {
  1604. usedBytes += bytes;
  1605. #if defined(_M_X64_OR_ARM64)
  1606. size_t lastTotalUsedBytes = ::InterlockedExchangeAdd64((volatile LONG64 *)&totalUsedBytes, bytes);
  1607. #else
  1608. DWORD lastTotalUsedBytes = ::InterlockedExchangeAdd(&totalUsedBytes, bytes);
  1609. #endif
  1610. if (totalUsedBytes > maxUsedBytes)
  1611. {
  1612. maxUsedBytes = totalUsedBytes;
  1613. }
  1614. // ETW events from different threads may be reported out of order, producing an
  1615. // incorrect representation of current used bytes in the process. We've determined that this is an
  1616. // acceptable issue, which will be mitigated at the level of the application consuming the event.
  1617. JS_ETW(EventWriteJSCRIPT_PAGE_ALLOCATOR_USED_SIZE(lastTotalUsedBytes + bytes));
  1618. #ifndef ENABLE_JS_ETW
  1619. Unused(lastTotalUsedBytes);
  1620. #endif
  1621. #ifdef PERF_COUNTERS
  1622. GetUsedSizeCounter() += bytes;
  1623. GetTotalUsedSizeCounter() += bytes;
  1624. #endif
  1625. }
  1626. template<typename T>
  1627. void
  1628. PageAllocatorBase<T>::SubUsedBytes(size_t bytes)
  1629. {
  1630. Assert(bytes <= usedBytes);
  1631. Assert(bytes <= totalUsedBytes);
  1632. usedBytes -= bytes;
  1633. #if defined(_M_X64_OR_ARM64)
  1634. size_t lastTotalUsedBytes = ::InterlockedExchangeAdd64((volatile LONG64 *)&totalUsedBytes, -(LONG64)bytes);
  1635. #else
  1636. DWORD lastTotalUsedBytes = ::InterlockedExchangeSubtract(&totalUsedBytes, bytes);
  1637. #endif
  1638. // ETW events from different threads may be reported out of order, producing an
  1639. // incorrect representation of current used bytes in the process. We've determined that this is an
  1640. // acceptable issue, which will be mitigated at the level of the application consuming the event.
  1641. JS_ETW(EventWriteJSCRIPT_PAGE_ALLOCATOR_USED_SIZE(lastTotalUsedBytes - bytes));
  1642. #ifndef ENABLE_JS_ETW
  1643. Unused(lastTotalUsedBytes);
  1644. #endif
  1645. #ifdef PERF_COUNTERS
  1646. GetUsedSizeCounter() -= bytes;
  1647. GetTotalUsedSizeCounter() -= bytes;
  1648. #endif
  1649. }
  1650. template<typename T>
  1651. void
  1652. PageAllocatorBase<T>::AddNumberOfSegments(size_t segmentCount)
  1653. {
  1654. numberOfSegments += segmentCount;
  1655. }
  1656. template<typename T>
  1657. void
  1658. PageAllocatorBase<T>::SubNumberOfSegments(size_t segmentCount)
  1659. {
  1660. numberOfSegments -= segmentCount;
  1661. }
  1662. template<typename T>
  1663. void
  1664. PageAllocatorBase<T>::IntegrateSegments(DListBase<PageSegmentBase<T>>& segmentList, uint segmentCount, size_t pageCount)
  1665. {
  1666. #if DBG
  1667. size_t debugPageCount = 0;
  1668. uint debugSegmentCount = 0;
  1669. DListBase<PageSegmentBase<T>>::Iterator i(&segmentList);
  1670. while (i.Next())
  1671. {
  1672. Assert(i.Data().GetAllocator() == this);
  1673. debugSegmentCount++;
  1674. debugPageCount += i.Data().GetPageCount();
  1675. }
  1676. Assert(debugSegmentCount == segmentCount);
  1677. Assert(debugPageCount == pageCount);
  1678. #endif
  1679. LogAllocSegment(segmentCount, pageCount);
  1680. LogAllocPages(pageCount);
  1681. this->SuspendIdleDecommit();
  1682. segmentList.MoveTo(&this->fullSegments);
  1683. this->ResumeIdleDecommit();
  1684. }
  1685. template<typename T>
  1686. void
  1687. PageAllocatorBase<T>::LogAllocSegment(SegmentBase<T> * segment)
  1688. {
  1689. LogAllocSegment(1, segment->GetPageCount());
  1690. }
  1691. template<typename T>
  1692. void
  1693. PageAllocatorBase<T>::LogAllocSegment(uint segmentCount, size_t pageCount)
  1694. {
  1695. size_t bytes = pageCount * AutoSystemInfo::PageSize;
  1696. AddReservedBytes(bytes);
  1697. AddCommittedBytes(bytes);
  1698. AddNumberOfSegments(segmentCount);
  1699. #ifdef PROFILE_MEM
  1700. if (this->memoryData)
  1701. {
  1702. this->memoryData->allocSegmentCount += segmentCount;
  1703. this->memoryData->allocSegmentBytes += pageCount * AutoSystemInfo::PageSize;
  1704. this->memoryData->currentCommittedPageCount += pageCount;
  1705. this->memoryData->peakCommittedPageCount = max(this->memoryData->peakCommittedPageCount, this->memoryData->currentCommittedPageCount);
  1706. }
  1707. #endif
  1708. }
  1709. template<typename T>
  1710. void
  1711. PageAllocatorBase<T>::LogFreeSegment(SegmentBase<T> * segment)
  1712. {
  1713. size_t bytes = segment->GetPageCount() * AutoSystemInfo::PageSize;
  1714. SubCommittedBytes(bytes);
  1715. SubReservedBytes(bytes);
  1716. SubNumberOfSegments(1);
  1717. #ifdef PROFILE_MEM
  1718. if (this->memoryData)
  1719. {
  1720. this->memoryData->releaseSegmentCount++;
  1721. this->memoryData->releaseSegmentBytes += segment->GetPageCount() * AutoSystemInfo::PageSize;
  1722. this->memoryData->currentCommittedPageCount -= segment->GetPageCount();
  1723. }
  1724. #endif
  1725. }
  1726. template<typename T>
  1727. void
  1728. PageAllocatorBase<T>::LogFreeDecommittedSegment(SegmentBase<T> * segment)
  1729. {
  1730. SubReservedBytes(segment->GetPageCount() * AutoSystemInfo::PageSize);
  1731. SubNumberOfSegments(1);
  1732. #ifdef PROFILE_MEM
  1733. if (this->memoryData)
  1734. {
  1735. this->memoryData->releaseSegmentCount++;
  1736. this->memoryData->releaseSegmentBytes += segment->GetPageCount() * AutoSystemInfo::PageSize;
  1737. }
  1738. #endif
  1739. }
  1740. template<typename T>
  1741. void
  1742. PageAllocatorBase<T>::LogFreePages(size_t pageCount)
  1743. {
  1744. SubUsedBytes(pageCount * AutoSystemInfo::PageSize);
  1745. #ifdef PROFILE_MEM
  1746. if (this->memoryData)
  1747. {
  1748. this->memoryData->releasePageCount += pageCount;
  1749. }
  1750. #endif
  1751. }
  1752. template<typename T>
  1753. void
  1754. PageAllocatorBase<T>::LogFreePartiallyDecommitedPageSegment(PageSegmentBase<T> * pageSegment)
  1755. {
  1756. AddCommittedBytes(pageSegment->GetDecommitPageCount() * AutoSystemInfo::PageSize);
  1757. #ifdef PROFILE_MEM
  1758. if (this->memoryData)
  1759. {
  1760. this->memoryData->currentCommittedPageCount += pageSegment->GetDecommitPageCount();
  1761. }
  1762. #endif
  1763. LogFreeSegment(pageSegment);
  1764. }
  1765. template<typename T>
  1766. void
  1767. PageAllocatorBase<T>::LogAllocPages(size_t pageCount)
  1768. {
  1769. AddUsedBytes(pageCount * AutoSystemInfo::PageSize);
  1770. #ifdef PROFILE_MEM
  1771. if (this->memoryData)
  1772. {
  1773. this->memoryData->allocPageCount += pageCount;
  1774. }
  1775. #endif
  1776. }
  1777. template<typename T>
  1778. void
  1779. PageAllocatorBase<T>::LogRecommitPages(size_t pageCount)
  1780. {
  1781. #ifdef PROFILE_MEM
  1782. if (this->memoryData)
  1783. {
  1784. this->memoryData->recommitPageCount += pageCount;
  1785. }
  1786. #endif
  1787. LogCommitPages(pageCount);
  1788. }
  1789. template<typename T>
  1790. void
  1791. PageAllocatorBase<T>::LogCommitPages(size_t pageCount)
  1792. {
  1793. AddCommittedBytes(pageCount * AutoSystemInfo::PageSize);
  1794. #ifdef PROFILE_MEM
  1795. if (this->memoryData)
  1796. {
  1797. this->memoryData->currentCommittedPageCount += pageCount;
  1798. this->memoryData->peakCommittedPageCount = max(this->memoryData->peakCommittedPageCount, this->memoryData->currentCommittedPageCount);
  1799. }
  1800. #endif
  1801. }
  1802. template<typename T>
  1803. void
  1804. PageAllocatorBase<T>::LogDecommitPages(size_t pageCount)
  1805. {
  1806. SubCommittedBytes(pageCount * AutoSystemInfo::PageSize);
  1807. #ifdef PROFILE_MEM
  1808. if (this->memoryData)
  1809. {
  1810. this->memoryData->decommitPageCount += pageCount;
  1811. this->memoryData->currentCommittedPageCount -= pageCount;
  1812. }
  1813. #endif
  1814. }
  1815. #if DBG_DUMP
  1816. template<typename T>
  1817. void
  1818. PageAllocatorBase<T>::DumpStats() const
  1819. {
  1820. Output::Print(L" Full/Partial/Empty/Decommit/Large Segments: %4d %4d %4d %4d %4d\n",
  1821. fullSegments.Count(), segments.Count(), emptySegments.Count(), decommitSegments.Count(), largeSegments.Count());
  1822. Output::Print(L" Free/Decommit/Min Free Pages : %4d %4d %4d\n",
  1823. this->freePageCount, this->decommitPageCount, this->minFreePageCount);
  1824. }
  1825. #endif
  1826. #if DBG
  1827. template<typename T>
  1828. void
  1829. PageAllocatorBase<T>::Check()
  1830. {
  1831. Assert(!this->HasZeroQueuedPages());
  1832. size_t currentFreePageCount = 0;
  1833. DListBase<PageSegmentBase<T>>::Iterator segmentsIterator(&segments);
  1834. while (segmentsIterator.Next())
  1835. {
  1836. currentFreePageCount += segmentsIterator.Data().GetFreePageCount();
  1837. }
  1838. DListBase<PageSegmentBase<T>>::Iterator fullSegmentsIterator(&fullSegments);
  1839. while (fullSegmentsIterator.Next())
  1840. {
  1841. currentFreePageCount += fullSegmentsIterator.Data().GetFreePageCount();
  1842. }
  1843. DListBase<PageSegmentBase<T>>::Iterator emptySegmentsIterator(&emptySegments);
  1844. while (emptySegmentsIterator.Next())
  1845. {
  1846. currentFreePageCount += emptySegmentsIterator.Data().GetFreePageCount();
  1847. }
  1848. DListBase<PageSegmentBase<T>>::Iterator decommitSegmentsIterator(&decommitSegments);
  1849. while (decommitSegmentsIterator.Next())
  1850. {
  1851. currentFreePageCount += decommitSegmentsIterator.Data().GetFreePageCount();
  1852. }
  1853. Assert(freePageCount == currentFreePageCount);
  1854. }
  1855. #endif
  1856. template<typename T>
  1857. HeapPageAllocator<T>::HeapPageAllocator(AllocationPolicyManager * policyManager, bool allocXdata, bool excludeGuardPages) :
  1858. PageAllocatorBase(policyManager,
  1859. Js::Configuration::Global.flags,
  1860. PageAllocatorType_CustomHeap,
  1861. /*maxFreePageCount*/ 0,
  1862. /*zeroPages*/ false,
  1863. /*zeroPageQueue*/ nullptr,
  1864. /*maxAllocPageCount*/ allocXdata ? (DefaultMaxAllocPageCount - XDATA_RESERVE_PAGE_COUNT) : DefaultMaxAllocPageCount,
  1865. /*secondaryAllocPageCount=*/ allocXdata ? XDATA_RESERVE_PAGE_COUNT : 0,
  1866. /*stopAllocationOnOutOfMemory*/ false,
  1867. excludeGuardPages),
  1868. allocXdata(allocXdata)
  1869. {
  1870. }
  1871. template<typename T>
  1872. void
  1873. HeapPageAllocator<T>::ReleaseDecommited(void * address, size_t pageCount, __in void * segmentParam)
  1874. {
  1875. SegmentBase<T> * segment = (SegmentBase<T>*) segmentParam;
  1876. if (pageCount > this->maxAllocPageCount)
  1877. {
  1878. Assert(address == segment->GetAddress());
  1879. Assert(pageCount == segment->GetAvailablePageCount());
  1880. this->ReleaseDecommitedSegment(segment);
  1881. }
  1882. else
  1883. {
  1884. Assert(pageCount <= UINT_MAX);
  1885. this->TrackDecommitedPages(address, (uint)pageCount, (PageSegment *)segment);
  1886. }
  1887. }
  1888. template<typename T>
  1889. void
  1890. HeapPageAllocator<T>::ReleaseDecommitedSegment(__in SegmentBase<T>* segment)
  1891. {
  1892. ASSERT_THREAD();
  1893. LogFreeDecommittedSegment(segment);
  1894. largeSegments.RemoveElement(&NoThrowNoMemProtectHeapAllocator::Instance, segment);
  1895. }
  1896. // decommit the page but don't release it
  1897. template<typename T>
  1898. void
  1899. HeapPageAllocator<T>::DecommitPages(__in char* address, size_t pageCount = 1)
  1900. {
  1901. Assert(pageCount <= MAXUINT32);
  1902. #pragma prefast(suppress:__WARNING_WIN32UNRELEASEDVADS, "The remainder of the clean-up is done later.");
  1903. virtualAllocator->Free(address, pageCount * AutoSystemInfo::PageSize, MEM_DECOMMIT);
  1904. LogFreePages(pageCount);
  1905. LogDecommitPages(pageCount);
  1906. }
  1907. template<typename TVirtualAlloc>
  1908. template <typename T>
  1909. void PageAllocatorBase<TVirtualAlloc>::ReleaseSegmentList(DListBase<T> * segmentList)
  1910. {
  1911. segmentList->Clear(&NoThrowNoMemProtectHeapAllocator::Instance);
  1912. }
  1913. template<typename T>
  1914. BOOL
  1915. HeapPageAllocator<T>::ProtectPages(__in char* address, size_t pageCount, __in void* segmentParam, DWORD dwVirtualProtectFlags, DWORD desiredOldProtectFlag)
  1916. {
  1917. SegmentBase<T> * segment = (SegmentBase<T>*)segmentParam;
  1918. #if DBG
  1919. Assert(address >= segment->GetAddress());
  1920. Assert(((uint)(((char *)address) - segment->GetAddress()) <= (segment->GetPageCount() - pageCount) * AutoSystemInfo::PageSize));
  1921. if (IsPageSegment(segment))
  1922. {
  1923. PageSegmentBase<T> * pageSegment = static_cast<PageSegmentBase<T>*>(segment);
  1924. AssertMsg(pageCount <= MAXUINT32, "PageSegment should always be smaller than 4G pages");
  1925. Assert(!pageSegment->IsFreeOrDecommitted(address, static_cast<uint>(pageCount)));
  1926. }
  1927. #endif
  1928. #if DBG_DUMP || defined(RECYCLER_TRACE)
  1929. if (this->pageAllocatorFlagTable.IsEnabled(Js::TraceProtectPagesFlag))
  1930. {
  1931. Output::Print(L"VirtualProtect(0x%p, %d, %d, %d)\n", address, pageCount, pageCount * AutoSystemInfo::PageSize, dwVirtualProtectFlags);
  1932. }
  1933. #endif
  1934. // check address alignment, and that the address is in correct range
  1935. if (((uintptr_t)address & (AutoSystemInfo::PageSize - 1)) != 0
  1936. || address < segment->GetAddress()
  1937. || ((uint)(((char *)address) - segment->GetAddress()) > (segment->GetPageCount() - pageCount) * AutoSystemInfo::PageSize))
  1938. {
  1939. CustomHeap_BadPageState_fatal_error((ULONG_PTR)this);
  1940. return FALSE;
  1941. }
  1942. MEMORY_BASIC_INFORMATION memBasicInfo;
  1943. // check old protection on all pages about to change, ensure the fidelity
  1944. size_t bytes = VirtualQuery(address, &memBasicInfo, sizeof(memBasicInfo));
  1945. if (bytes == 0
  1946. || memBasicInfo.RegionSize < pageCount * AutoSystemInfo::PageSize
  1947. || desiredOldProtectFlag != memBasicInfo.Protect)
  1948. {
  1949. CustomHeap_BadPageState_fatal_error((ULONG_PTR)this);
  1950. return FALSE;
  1951. }
  1952. /*Verify if we always pass the PAGE_TARGETS_NO_UPDATE flag, if the protect flag is EXECUTE*/
  1953. #if defined(_CONTROL_FLOW_GUARD)
  1954. if (AutoSystemInfo::Data.IsCFGEnabled() &&
  1955. (dwVirtualProtectFlags & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE)) &&
  1956. ((dwVirtualProtectFlags & PAGE_TARGETS_NO_UPDATE) == 0))
  1957. {
  1958. CustomHeap_BadPageState_fatal_error((ULONG_PTR)this);
  1959. return FALSE;
  1960. }
  1961. #endif
  1962. DWORD oldProtect; // this is only for first page
  1963. BOOL retVal = ::VirtualProtect(address, pageCount * AutoSystemInfo::PageSize, dwVirtualProtectFlags, &oldProtect);
  1964. Assert(oldProtect == desiredOldProtectFlag);
  1965. return retVal;
  1966. }
  1967. template<typename T>
  1968. void
  1969. HeapPageAllocator<T>::TrackDecommitedPages(void * address, uint pageCount, __in void* segmentParam)
  1970. {
  1971. PageSegmentBase<T> * segment = (PageSegmentBase<T>*)segmentParam;
  1972. ASSERT_THREAD();
  1973. Assert(!HasMultiThreadAccess());
  1974. Assert(pageCount <= this->maxAllocPageCount);
  1975. DListBase<PageSegmentBase<T>> * fromSegmentList = GetSegmentList(segment);
  1976. // Update the state of the segment with the decommitted pages
  1977. segment->DecommitPages<true>(address, pageCount);
  1978. // Move the segment to its appropriate list
  1979. TransferSegment(segment, fromSegmentList);
  1980. }
  1981. template<typename T>
  1982. bool HeapPageAllocator<T>::AllocSecondary(void* segmentParam, ULONG_PTR functionStart, DWORD functionSize, ushort pdataCount, ushort xdataSize, SecondaryAllocation* allocation)
  1983. {
  1984. SegmentBase<T> * segment = (SegmentBase<T> *)segmentParam;
  1985. Assert(segment->GetSecondaryAllocator());
  1986. bool success;
  1987. if (IsPageSegment(segment))
  1988. {
  1989. PageSegmentBase<T>* pageSegment = static_cast<PageSegmentBase<T>*>(segment);
  1990. // We should get the segment list BEFORE xdata allocation happens.
  1991. DListBase<PageSegmentBase<T>> * fromSegmentList = GetSegmentList(pageSegment);
  1992. success = segment->GetSecondaryAllocator()->Alloc(functionStart, functionSize, pdataCount, xdataSize, allocation);
  1993. // If no more XDATA allocations can take place.
  1994. if (success && !pageSegment->CanAllocSecondary() && fromSegmentList != &fullSegments)
  1995. {
  1996. AssertMsg(GetSegmentList(pageSegment) == &fullSegments, "This segment should now be in the full list if it can't allocate secondary");
  1997. OUTPUT_TRACE(Js::EmitterPhase, L"XDATA Wasted pages:%u\n", pageSegment->GetFreePageCount());
  1998. this->freePageCount -= pageSegment->GetFreePageCount();
  1999. fromSegmentList->MoveElementTo(pageSegment, &fullSegments);
  2000. #if DBG
  2001. UpdateMinimum(this->debugMinFreePageCount, this->freePageCount);
  2002. #endif
  2003. }
  2004. }
  2005. else
  2006. {
  2007. // A large segment should always be able to do secondary allocations
  2008. Assert(segment->CanAllocSecondary());
  2009. success = segment->GetSecondaryAllocator()->Alloc(functionStart, functionSize, pdataCount, xdataSize, allocation);
  2010. }
  2011. #ifdef _M_X64
  2012. // In ARM it's OK to have xdata size be 0
  2013. AssertMsg(allocation->address != nullptr, "All segments that cannot allocate xdata should have been already moved to full segments list");
  2014. #endif
  2015. return success;
  2016. }
  2017. template<typename T>
  2018. void HeapPageAllocator<T>::ReleaseSecondary(const SecondaryAllocation& allocation, void* segmentParam)
  2019. {
  2020. SegmentBase<T> * segment = (SegmentBase<T>*)segmentParam;
  2021. Assert(allocation.address != nullptr);
  2022. Assert(segment->GetSecondaryAllocator());
  2023. if (IsPageSegment(segment))
  2024. {
  2025. PageSegmentBase<T>* pageSegment = static_cast<PageSegmentBase<T>*>(segment);
  2026. auto fromList = GetSegmentList(pageSegment);
  2027. pageSegment->GetSecondaryAllocator()->Release(allocation);
  2028. auto toList = GetSegmentList(pageSegment);
  2029. if (fromList != toList)
  2030. {
  2031. OUTPUT_TRACE(Js::EmitterPhase, L"XDATA reclaimed pages:%u\n", pageSegment->GetFreePageCount());
  2032. fromList->MoveElementTo(pageSegment, toList);
  2033. AssertMsg(fromList == &fullSegments, "Releasing a secondary allocator should make a state change only if the segment was originally in the full list");
  2034. AssertMsg(pageSegment->CanAllocSecondary(), "It should be allocate secondary now");
  2035. this->AddFreePageCount(pageSegment->GetFreePageCount());
  2036. }
  2037. }
  2038. else
  2039. {
  2040. Assert(segment->CanAllocSecondary());
  2041. segment->GetSecondaryAllocator()->Release(allocation);
  2042. }
  2043. }
  2044. template<typename T>
  2045. bool
  2046. HeapPageAllocator<T>::IsAddressFromAllocator(__in void* address)
  2047. {
  2048. DListBase<PageSegmentBase<T>>::Iterator segmentsIterator(&segments);
  2049. while (segmentsIterator.Next())
  2050. {
  2051. if (IsAddressInSegment(address, segmentsIterator.Data()))
  2052. {
  2053. return true;
  2054. }
  2055. }
  2056. DListBase<PageSegmentBase<T>>::Iterator fullSegmentsIterator(&fullSegments);
  2057. while (fullSegmentsIterator.Next())
  2058. {
  2059. if (IsAddressInSegment(address, fullSegmentsIterator.Data()))
  2060. {
  2061. return true;
  2062. }
  2063. }
  2064. DListBase<SegmentBase<T>>::Iterator largeSegmentsIterator(&largeSegments);
  2065. while (largeSegmentsIterator.Next())
  2066. {
  2067. if (IsAddressInSegment(address, largeSegmentsIterator.Data()))
  2068. {
  2069. return true;
  2070. }
  2071. }
  2072. DListBase<PageSegmentBase<T>>::Iterator decommitSegmentsIterator(&decommitSegments);
  2073. while (decommitSegmentsIterator.Next())
  2074. {
  2075. if (IsAddressInSegment(address, decommitSegmentsIterator.Data()))
  2076. {
  2077. return true;
  2078. }
  2079. }
  2080. return false;
  2081. }
  2082. template<typename T>
  2083. bool
  2084. PageAllocatorBase<T>::IsAddressInSegment(__in void* address, const PageSegmentBase<T>& segment)
  2085. {
  2086. bool inSegment = this->IsAddressInSegment(address, static_cast<const SegmentBase<T>&>(segment));
  2087. if (inSegment)
  2088. {
  2089. return !segment.IsFreeOrDecommitted(address);
  2090. }
  2091. return inSegment;
  2092. }
  2093. template<typename T>
  2094. bool
  2095. PageAllocatorBase<T>::IsAddressInSegment(__in void* address, const SegmentBase<T>& segment)
  2096. {
  2097. return segment.IsInSegment(address);
  2098. }
  2099. #if PDATA_ENABLED
  2100. #include "Memory\XDataAllocator.h"
  2101. template<typename T>
  2102. bool HeapPageAllocator<T>::CreateSecondaryAllocator(SegmentBase<T>* segment, SecondaryAllocator** allocator)
  2103. {
  2104. Assert(segment->GetAllocator() == this);
  2105. // If we are not allocating xdata there is nothing to do
  2106. // ARM might allocate XDATA but not have a reserved region for it (no secondary alloc reserved space)
  2107. if(!allocXdata)
  2108. {
  2109. Assert(segment->GetSecondaryAllocSize() == 0);
  2110. *allocator = nullptr;
  2111. return true;
  2112. }
  2113. XDataAllocator* secondaryAllocator = HeapNewNoThrow(XDataAllocator, (BYTE*)segment->GetSecondaryAllocStartAddress(), segment->GetSecondaryAllocSize());
  2114. bool success = false;
  2115. if(secondaryAllocator)
  2116. {
  2117. if(secondaryAllocator->Initialize((BYTE*)segment->GetAddress(), (BYTE*)segment->GetEndAddress()))
  2118. {
  2119. success = true;
  2120. }
  2121. else
  2122. {
  2123. HeapDelete(secondaryAllocator);
  2124. secondaryAllocator = nullptr;
  2125. }
  2126. }
  2127. *allocator = secondaryAllocator;
  2128. return success;
  2129. }
  2130. #endif
  2131. template<typename T>
  2132. uint PageSegmentBase<T>::GetCountOfFreePages() const
  2133. {
  2134. return this->freePages.Count();
  2135. }
  2136. template<typename T>
  2137. uint PageSegmentBase<T>::GetNextBitInFreePagesBitVector(uint index) const
  2138. {
  2139. return this->freePages.GetNextBit(index);
  2140. }
  2141. template<typename T>
  2142. BOOLEAN PageSegmentBase<T>::TestRangeInFreePagesBitVector(uint index, uint pageCount) const
  2143. {
  2144. return this->freePages.TestRange(index, pageCount);
  2145. }
  2146. template<typename T>
  2147. BOOLEAN PageSegmentBase<T>::TestInFreePagesBitVector(uint index) const
  2148. {
  2149. return this->freePages.Test(index);
  2150. }
  2151. template<typename T>
  2152. void PageSegmentBase<T>::ClearAllInFreePagesBitVector()
  2153. {
  2154. return this->freePages.ClearAll();
  2155. }
  2156. template<typename T>
  2157. void PageSegmentBase<T>::ClearRangeInFreePagesBitVector(uint index, uint pageCount)
  2158. {
  2159. return this->freePages.ClearRange(index, pageCount);
  2160. }
  2161. template<typename T>
  2162. void PageSegmentBase<T>::SetRangeInFreePagesBitVector(uint index, uint pageCount)
  2163. {
  2164. return this->freePages.SetRange(index, pageCount);
  2165. }
  2166. template<typename T>
  2167. void PageSegmentBase<T>::ClearBitInFreePagesBitVector(uint index)
  2168. {
  2169. return this->freePages.Clear(index);
  2170. }
  2171. template<typename T>
  2172. BOOLEAN PageSegmentBase<T>::TestInDecommitPagesBitVector(uint index) const
  2173. {
  2174. return this->decommitPages.Test(index);
  2175. }
  2176. template<typename T>
  2177. BOOLEAN PageSegmentBase<T>::TestRangeInDecommitPagesBitVector(uint index, uint pageCount) const
  2178. {
  2179. return this->decommitPages.TestRange(index, pageCount);
  2180. }
  2181. template<typename T>
  2182. void PageSegmentBase<T>::SetRangeInDecommitPagesBitVector(uint index, uint pageCount)
  2183. {
  2184. return this->decommitPages.SetRange(index, pageCount);
  2185. }
  2186. template<typename T>
  2187. void PageSegmentBase<T>::ClearRangeInDecommitPagesBitVector(uint index, uint pageCount)
  2188. {
  2189. return this->decommitPages.ClearRange(index, pageCount);
  2190. }
  2191. template<typename T>
  2192. uint PageSegmentBase<T>::GetCountOfDecommitPages() const
  2193. {
  2194. return this->decommitPages.Count();
  2195. }
  2196. template<typename T>
  2197. void PageSegmentBase<T>::SetBitInDecommitPagesBitVector(uint index)
  2198. {
  2199. this->decommitPages.Set(index);
  2200. }
  2201. template<typename T>
  2202. template <bool noPageAligned>
  2203. char * PageSegmentBase<T>::DoAllocDecommitPages(uint pageCount, PageHeapMode pageHeapFlags)
  2204. {
  2205. return this->AllocDecommitPages<PageSegmentBase<T>::PageBitVector, noPageAligned>(pageCount, this->freePages, this->decommitPages, pageHeapFlags);
  2206. }
  2207. template<typename T>
  2208. uint PageSegmentBase<T>::GetMaxPageCount()
  2209. {
  2210. return MaxPageCount;
  2211. }
  2212. //Instantiate all the Templates in this class below.
  2213. template class PageAllocatorBase < PreReservedVirtualAllocWrapper >;
  2214. template class PageAllocatorBase < VirtualAllocWrapper >;
  2215. template class HeapPageAllocator < PreReservedVirtualAllocWrapper >;
  2216. template class HeapPageAllocator < VirtualAllocWrapper >;
  2217. template class SegmentBase < VirtualAllocWrapper > ;
  2218. template class SegmentBase < PreReservedVirtualAllocWrapper >;
  2219. template class PageSegmentBase < VirtualAllocWrapper >;
  2220. template class PageSegmentBase < PreReservedVirtualAllocWrapper >;