PageAllocator.cpp 101 KB

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