PageAllocator.cpp 98 KB

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