primary64.h 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688
  1. //===-- primary64.h ---------------------------------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef SCUDO_PRIMARY64_H_
  9. #define SCUDO_PRIMARY64_H_
  10. #include "allocator_common.h"
  11. #include "bytemap.h"
  12. #include "common.h"
  13. #include "list.h"
  14. #include "local_cache.h"
  15. #include "mem_map.h"
  16. #include "memtag.h"
  17. #include "options.h"
  18. #include "release.h"
  19. #include "stats.h"
  20. #include "string_utils.h"
  21. #include "thread_annotations.h"
  22. #include "condition_variable.h"
  23. namespace scudo {
  24. // SizeClassAllocator64 is an allocator tuned for 64-bit address space.
  25. //
  26. // It starts by reserving NumClasses * 2^RegionSizeLog bytes, equally divided in
  27. // Regions, specific to each size class. Note that the base of that mapping is
  28. // random (based to the platform specific map() capabilities). If
  29. // PrimaryEnableRandomOffset is set, each Region actually starts at a random
  30. // offset from its base.
  31. //
  32. // Regions are mapped incrementally on demand to fulfill allocation requests,
  33. // those mappings being split into equally sized Blocks based on the size class
  34. // they belong to. The Blocks created are shuffled to prevent predictable
  35. // address patterns (the predictability increases with the size of the Blocks).
  36. //
  37. // The 1st Region (for size class 0) holds the TransferBatches. This is a
  38. // structure used to transfer arrays of available pointers from the class size
  39. // freelist to the thread specific freelist, and back.
  40. //
  41. // The memory used by this allocator is never unmapped, but can be partially
  42. // released if the platform allows for it.
  43. template <typename Config> class SizeClassAllocator64 {
  44. public:
  45. typedef typename Config::Primary::CompactPtrT CompactPtrT;
  46. typedef typename Config::Primary::SizeClassMap SizeClassMap;
  47. typedef typename ConditionVariableState<
  48. typename Config::Primary>::ConditionVariableT ConditionVariableT;
  49. static const uptr CompactPtrScale = Config::Primary::CompactPtrScale;
  50. static const uptr RegionSizeLog = Config::Primary::RegionSizeLog;
  51. static const uptr GroupSizeLog = Config::Primary::GroupSizeLog;
  52. static_assert(RegionSizeLog >= GroupSizeLog,
  53. "Group size shouldn't be greater than the region size");
  54. static const uptr GroupScale = GroupSizeLog - CompactPtrScale;
  55. typedef SizeClassAllocator64<Config> ThisT;
  56. typedef SizeClassAllocatorLocalCache<ThisT> CacheT;
  57. typedef TransferBatch<ThisT> TransferBatchT;
  58. typedef BatchGroup<ThisT> BatchGroupT;
  59. static_assert(sizeof(BatchGroupT) <= sizeof(TransferBatchT),
  60. "BatchGroupT uses the same class size as TransferBatchT");
  61. static uptr getSizeByClassId(uptr ClassId) {
  62. return (ClassId == SizeClassMap::BatchClassId)
  63. ? roundUp(sizeof(TransferBatchT), 1U << CompactPtrScale)
  64. : SizeClassMap::getSizeByClassId(ClassId);
  65. }
  66. static bool canAllocate(uptr Size) { return Size <= SizeClassMap::MaxSize; }
  67. static bool conditionVariableEnabled() {
  68. return ConditionVariableState<typename Config::Primary>::enabled();
  69. }
  70. void init(s32 ReleaseToOsInterval) NO_THREAD_SAFETY_ANALYSIS {
  71. DCHECK(isAligned(reinterpret_cast<uptr>(this), alignof(ThisT)));
  72. const uptr PageSize = getPageSizeCached();
  73. const uptr GroupSize = (1UL << GroupSizeLog);
  74. const uptr PagesInGroup = GroupSize / PageSize;
  75. const uptr MinSizeClass = getSizeByClassId(1);
  76. // When trying to release pages back to memory, visiting smaller size
  77. // classes is expensive. Therefore, we only try to release smaller size
  78. // classes when the amount of free blocks goes over a certain threshold (See
  79. // the comment in releaseToOSMaybe() for more details). For example, for
  80. // size class 32, we only do the release when the size of free blocks is
  81. // greater than 97% of pages in a group. However, this may introduce another
  82. // issue that if the number of free blocks is bouncing between 97% ~ 100%.
  83. // Which means we may try many page releases but only release very few of
  84. // them (less than 3% in a group). Even though we have
  85. // `&ReleaseToOsIntervalMs` which slightly reduce the frequency of these
  86. // calls but it will be better to have another guard to mitigate this issue.
  87. //
  88. // Here we add another constraint on the minimum size requirement. The
  89. // constraint is determined by the size of in-use blocks in the minimal size
  90. // class. Take size class 32 as an example,
  91. //
  92. // +- one memory group -+
  93. // +----------------------+------+
  94. // | 97% of free blocks | |
  95. // +----------------------+------+
  96. // \ /
  97. // 3% in-use blocks
  98. //
  99. // * The release size threshold is 97%.
  100. //
  101. // The 3% size in a group is about 7 pages. For two consecutive
  102. // releaseToOSMaybe(), we require the difference between `PushedBlocks`
  103. // should be greater than 7 pages. This mitigates the page releasing
  104. // thrashing which is caused by memory usage bouncing around the threshold.
  105. // The smallest size class takes longest time to do the page release so we
  106. // use its size of in-use blocks as a heuristic.
  107. SmallerBlockReleasePageDelta =
  108. PagesInGroup * (1 + MinSizeClass / 16U) / 100;
  109. // Reserve the space required for the Primary.
  110. CHECK(ReservedMemory.create(/*Addr=*/0U, PrimarySize,
  111. "scudo:primary_reserve"));
  112. PrimaryBase = ReservedMemory.getBase();
  113. DCHECK_NE(PrimaryBase, 0U);
  114. u32 Seed;
  115. const u64 Time = getMonotonicTimeFast();
  116. if (!getRandom(reinterpret_cast<void *>(&Seed), sizeof(Seed)))
  117. Seed = static_cast<u32>(Time ^ (PrimaryBase >> 12));
  118. for (uptr I = 0; I < NumClasses; I++) {
  119. RegionInfo *Region = getRegionInfo(I);
  120. // The actual start of a region is offset by a random number of pages
  121. // when PrimaryEnableRandomOffset is set.
  122. Region->RegionBeg = (PrimaryBase + (I << RegionSizeLog)) +
  123. (Config::Primary::EnableRandomOffset
  124. ? ((getRandomModN(&Seed, 16) + 1) * PageSize)
  125. : 0);
  126. Region->RandState = getRandomU32(&Seed);
  127. // Releasing small blocks is expensive, set a higher threshold to avoid
  128. // frequent page releases.
  129. if (isSmallBlock(getSizeByClassId(I)))
  130. Region->TryReleaseThreshold = PageSize * SmallerBlockReleasePageDelta;
  131. else
  132. Region->TryReleaseThreshold = PageSize;
  133. Region->ReleaseInfo.LastReleaseAtNs = Time;
  134. Region->MemMapInfo.MemMap = ReservedMemory.dispatch(
  135. PrimaryBase + (I << RegionSizeLog), RegionSize);
  136. CHECK(Region->MemMapInfo.MemMap.isAllocated());
  137. }
  138. shuffle(RegionInfoArray, NumClasses, &Seed);
  139. // The binding should be done after region shuffling so that it won't bind
  140. // the FLLock from the wrong region.
  141. for (uptr I = 0; I < NumClasses; I++)
  142. getRegionInfo(I)->FLLockCV.bindTestOnly(getRegionInfo(I)->FLLock);
  143. setOption(Option::ReleaseInterval, static_cast<sptr>(ReleaseToOsInterval));
  144. }
  145. void unmapTestOnly() NO_THREAD_SAFETY_ANALYSIS {
  146. for (uptr I = 0; I < NumClasses; I++) {
  147. RegionInfo *Region = getRegionInfo(I);
  148. *Region = {};
  149. }
  150. if (PrimaryBase)
  151. ReservedMemory.release();
  152. PrimaryBase = 0U;
  153. }
  154. // When all blocks are freed, it has to be the same size as `AllocatedUser`.
  155. void verifyAllBlocksAreReleasedTestOnly() {
  156. // `BatchGroup` and `TransferBatch` also use the blocks from BatchClass.
  157. uptr BatchClassUsedInFreeLists = 0;
  158. for (uptr I = 0; I < NumClasses; I++) {
  159. // We have to count BatchClassUsedInFreeLists in other regions first.
  160. if (I == SizeClassMap::BatchClassId)
  161. continue;
  162. RegionInfo *Region = getRegionInfo(I);
  163. ScopedLock ML(Region->MMLock);
  164. ScopedLock FL(Region->FLLock);
  165. const uptr BlockSize = getSizeByClassId(I);
  166. uptr TotalBlocks = 0;
  167. for (BatchGroupT &BG : Region->FreeListInfo.BlockList) {
  168. // `BG::Batches` are `TransferBatches`. +1 for `BatchGroup`.
  169. BatchClassUsedInFreeLists += BG.Batches.size() + 1;
  170. for (const auto &It : BG.Batches)
  171. TotalBlocks += It.getCount();
  172. }
  173. DCHECK_EQ(TotalBlocks, Region->MemMapInfo.AllocatedUser / BlockSize);
  174. DCHECK_EQ(Region->FreeListInfo.PushedBlocks,
  175. Region->FreeListInfo.PoppedBlocks);
  176. }
  177. RegionInfo *Region = getRegionInfo(SizeClassMap::BatchClassId);
  178. ScopedLock ML(Region->MMLock);
  179. ScopedLock FL(Region->FLLock);
  180. const uptr BlockSize = getSizeByClassId(SizeClassMap::BatchClassId);
  181. uptr TotalBlocks = 0;
  182. for (BatchGroupT &BG : Region->FreeListInfo.BlockList) {
  183. if (LIKELY(!BG.Batches.empty())) {
  184. for (const auto &It : BG.Batches)
  185. TotalBlocks += It.getCount();
  186. } else {
  187. // `BatchGroup` with empty freelist doesn't have `TransferBatch` record
  188. // itself.
  189. ++TotalBlocks;
  190. }
  191. }
  192. DCHECK_EQ(TotalBlocks + BatchClassUsedInFreeLists,
  193. Region->MemMapInfo.AllocatedUser / BlockSize);
  194. DCHECK_GE(Region->FreeListInfo.PoppedBlocks,
  195. Region->FreeListInfo.PushedBlocks);
  196. const uptr BlocksInUse =
  197. Region->FreeListInfo.PoppedBlocks - Region->FreeListInfo.PushedBlocks;
  198. DCHECK_EQ(BlocksInUse, BatchClassUsedInFreeLists);
  199. }
  200. // Note that the `MaxBlockCount` will be used when we support arbitrary blocks
  201. // count. Now it's the same as the number of blocks stored in the
  202. // `TransferBatch`.
  203. u16 popBlocks(CacheT *C, uptr ClassId, CompactPtrT *ToArray,
  204. UNUSED const u16 MaxBlockCount) {
  205. TransferBatchT *B = popBatch(C, ClassId);
  206. if (!B)
  207. return 0;
  208. const u16 Count = B->getCount();
  209. DCHECK_GT(Count, 0U);
  210. B->moveToArray(ToArray);
  211. if (ClassId != SizeClassMap::BatchClassId)
  212. C->deallocate(SizeClassMap::BatchClassId, B);
  213. return Count;
  214. }
  215. TransferBatchT *popBatch(CacheT *C, uptr ClassId) {
  216. DCHECK_LT(ClassId, NumClasses);
  217. RegionInfo *Region = getRegionInfo(ClassId);
  218. {
  219. ScopedLock L(Region->FLLock);
  220. TransferBatchT *B = popBatchImpl(C, ClassId, Region);
  221. if (LIKELY(B))
  222. return B;
  223. }
  224. bool ReportRegionExhausted = false;
  225. TransferBatchT *B = nullptr;
  226. if (conditionVariableEnabled()) {
  227. B = popBatchWithCV(C, ClassId, Region, ReportRegionExhausted);
  228. } else {
  229. while (true) {
  230. // When two threads compete for `Region->MMLock`, we only want one of
  231. // them to call populateFreeListAndPopBatch(). To avoid both of them
  232. // doing that, always check the freelist before mapping new pages.
  233. ScopedLock ML(Region->MMLock);
  234. {
  235. ScopedLock FL(Region->FLLock);
  236. if ((B = popBatchImpl(C, ClassId, Region)))
  237. break;
  238. }
  239. const bool RegionIsExhausted = Region->Exhausted;
  240. if (!RegionIsExhausted)
  241. B = populateFreeListAndPopBatch(C, ClassId, Region);
  242. ReportRegionExhausted = !RegionIsExhausted && Region->Exhausted;
  243. break;
  244. }
  245. }
  246. if (UNLIKELY(ReportRegionExhausted)) {
  247. Printf("Can't populate more pages for size class %zu.\n",
  248. getSizeByClassId(ClassId));
  249. // Theoretically, BatchClass shouldn't be used up. Abort immediately when
  250. // it happens.
  251. if (ClassId == SizeClassMap::BatchClassId)
  252. reportOutOfBatchClass();
  253. }
  254. return B;
  255. }
  256. // Push the array of free blocks to the designated batch group.
  257. void pushBlocks(CacheT *C, uptr ClassId, CompactPtrT *Array, u32 Size) {
  258. DCHECK_LT(ClassId, NumClasses);
  259. DCHECK_GT(Size, 0);
  260. RegionInfo *Region = getRegionInfo(ClassId);
  261. if (ClassId == SizeClassMap::BatchClassId) {
  262. ScopedLock L(Region->FLLock);
  263. pushBatchClassBlocks(Region, Array, Size);
  264. if (conditionVariableEnabled())
  265. Region->FLLockCV.notifyAll(Region->FLLock);
  266. return;
  267. }
  268. // TODO(chiahungduan): Consider not doing grouping if the group size is not
  269. // greater than the block size with a certain scale.
  270. bool SameGroup = true;
  271. if (GroupSizeLog < RegionSizeLog) {
  272. // Sort the blocks so that blocks belonging to the same group can be
  273. // pushed together.
  274. for (u32 I = 1; I < Size; ++I) {
  275. if (compactPtrGroup(Array[I - 1]) != compactPtrGroup(Array[I]))
  276. SameGroup = false;
  277. CompactPtrT Cur = Array[I];
  278. u32 J = I;
  279. while (J > 0 && compactPtrGroup(Cur) < compactPtrGroup(Array[J - 1])) {
  280. Array[J] = Array[J - 1];
  281. --J;
  282. }
  283. Array[J] = Cur;
  284. }
  285. }
  286. {
  287. ScopedLock L(Region->FLLock);
  288. pushBlocksImpl(C, ClassId, Region, Array, Size, SameGroup);
  289. if (conditionVariableEnabled())
  290. Region->FLLockCV.notifyAll(Region->FLLock);
  291. }
  292. }
  293. void disable() NO_THREAD_SAFETY_ANALYSIS {
  294. // The BatchClassId must be locked last since other classes can use it.
  295. for (sptr I = static_cast<sptr>(NumClasses) - 1; I >= 0; I--) {
  296. if (static_cast<uptr>(I) == SizeClassMap::BatchClassId)
  297. continue;
  298. getRegionInfo(static_cast<uptr>(I))->MMLock.lock();
  299. getRegionInfo(static_cast<uptr>(I))->FLLock.lock();
  300. }
  301. getRegionInfo(SizeClassMap::BatchClassId)->MMLock.lock();
  302. getRegionInfo(SizeClassMap::BatchClassId)->FLLock.lock();
  303. }
  304. void enable() NO_THREAD_SAFETY_ANALYSIS {
  305. getRegionInfo(SizeClassMap::BatchClassId)->FLLock.unlock();
  306. getRegionInfo(SizeClassMap::BatchClassId)->MMLock.unlock();
  307. for (uptr I = 0; I < NumClasses; I++) {
  308. if (I == SizeClassMap::BatchClassId)
  309. continue;
  310. getRegionInfo(I)->FLLock.unlock();
  311. getRegionInfo(I)->MMLock.unlock();
  312. }
  313. }
  314. template <typename F> void iterateOverBlocks(F Callback) {
  315. for (uptr I = 0; I < NumClasses; I++) {
  316. if (I == SizeClassMap::BatchClassId)
  317. continue;
  318. RegionInfo *Region = getRegionInfo(I);
  319. // TODO: The call of `iterateOverBlocks` requires disabling
  320. // SizeClassAllocator64. We may consider locking each region on demand
  321. // only.
  322. Region->FLLock.assertHeld();
  323. Region->MMLock.assertHeld();
  324. const uptr BlockSize = getSizeByClassId(I);
  325. const uptr From = Region->RegionBeg;
  326. const uptr To = From + Region->MemMapInfo.AllocatedUser;
  327. for (uptr Block = From; Block < To; Block += BlockSize)
  328. Callback(Block);
  329. }
  330. }
  331. void getStats(ScopedString *Str) {
  332. // TODO(kostyak): get the RSS per region.
  333. uptr TotalMapped = 0;
  334. uptr PoppedBlocks = 0;
  335. uptr PushedBlocks = 0;
  336. for (uptr I = 0; I < NumClasses; I++) {
  337. RegionInfo *Region = getRegionInfo(I);
  338. {
  339. ScopedLock L(Region->MMLock);
  340. TotalMapped += Region->MemMapInfo.MappedUser;
  341. }
  342. {
  343. ScopedLock L(Region->FLLock);
  344. PoppedBlocks += Region->FreeListInfo.PoppedBlocks;
  345. PushedBlocks += Region->FreeListInfo.PushedBlocks;
  346. }
  347. }
  348. Str->append("Stats: SizeClassAllocator64: %zuM mapped (%uM rss) in %zu "
  349. "allocations; remains %zu\n",
  350. TotalMapped >> 20, 0U, PoppedBlocks,
  351. PoppedBlocks - PushedBlocks);
  352. for (uptr I = 0; I < NumClasses; I++) {
  353. RegionInfo *Region = getRegionInfo(I);
  354. ScopedLock L1(Region->MMLock);
  355. ScopedLock L2(Region->FLLock);
  356. getStats(Str, I, Region);
  357. }
  358. }
  359. void getFragmentationInfo(ScopedString *Str) {
  360. Str->append(
  361. "Fragmentation Stats: SizeClassAllocator64: page size = %zu bytes\n",
  362. getPageSizeCached());
  363. for (uptr I = 1; I < NumClasses; I++) {
  364. RegionInfo *Region = getRegionInfo(I);
  365. ScopedLock L(Region->MMLock);
  366. getRegionFragmentationInfo(Region, I, Str);
  367. }
  368. }
  369. bool setOption(Option O, sptr Value) {
  370. if (O == Option::ReleaseInterval) {
  371. const s32 Interval = Max(Min(static_cast<s32>(Value),
  372. Config::Primary::MaxReleaseToOsIntervalMs),
  373. Config::Primary::MinReleaseToOsIntervalMs);
  374. atomic_store_relaxed(&ReleaseToOsIntervalMs, Interval);
  375. return true;
  376. }
  377. // Not supported by the Primary, but not an error either.
  378. return true;
  379. }
  380. uptr tryReleaseToOS(uptr ClassId, ReleaseToOS ReleaseType) {
  381. RegionInfo *Region = getRegionInfo(ClassId);
  382. // Note that the tryLock() may fail spuriously, given that it should rarely
  383. // happen and page releasing is fine to skip, we don't take certain
  384. // approaches to ensure one page release is done.
  385. if (Region->MMLock.tryLock()) {
  386. uptr BytesReleased = releaseToOSMaybe(Region, ClassId, ReleaseType);
  387. Region->MMLock.unlock();
  388. return BytesReleased;
  389. }
  390. return 0;
  391. }
  392. uptr releaseToOS(ReleaseToOS ReleaseType) {
  393. uptr TotalReleasedBytes = 0;
  394. for (uptr I = 0; I < NumClasses; I++) {
  395. if (I == SizeClassMap::BatchClassId)
  396. continue;
  397. RegionInfo *Region = getRegionInfo(I);
  398. ScopedLock L(Region->MMLock);
  399. TotalReleasedBytes += releaseToOSMaybe(Region, I, ReleaseType);
  400. }
  401. return TotalReleasedBytes;
  402. }
  403. const char *getRegionInfoArrayAddress() const {
  404. return reinterpret_cast<const char *>(RegionInfoArray);
  405. }
  406. static uptr getRegionInfoArraySize() { return sizeof(RegionInfoArray); }
  407. uptr getCompactPtrBaseByClassId(uptr ClassId) {
  408. return getRegionInfo(ClassId)->RegionBeg;
  409. }
  410. CompactPtrT compactPtr(uptr ClassId, uptr Ptr) {
  411. DCHECK_LE(ClassId, SizeClassMap::LargestClassId);
  412. return compactPtrInternal(getCompactPtrBaseByClassId(ClassId), Ptr);
  413. }
  414. void *decompactPtr(uptr ClassId, CompactPtrT CompactPtr) {
  415. DCHECK_LE(ClassId, SizeClassMap::LargestClassId);
  416. return reinterpret_cast<void *>(
  417. decompactPtrInternal(getCompactPtrBaseByClassId(ClassId), CompactPtr));
  418. }
  419. static BlockInfo findNearestBlock(const char *RegionInfoData,
  420. uptr Ptr) NO_THREAD_SAFETY_ANALYSIS {
  421. const RegionInfo *RegionInfoArray =
  422. reinterpret_cast<const RegionInfo *>(RegionInfoData);
  423. uptr ClassId;
  424. uptr MinDistance = -1UL;
  425. for (uptr I = 0; I != NumClasses; ++I) {
  426. if (I == SizeClassMap::BatchClassId)
  427. continue;
  428. uptr Begin = RegionInfoArray[I].RegionBeg;
  429. // TODO(chiahungduan): In fact, We need to lock the RegionInfo::MMLock.
  430. // However, the RegionInfoData is passed with const qualifier and lock the
  431. // mutex requires modifying RegionInfoData, which means we need to remove
  432. // the const qualifier. This may lead to another undefined behavior (The
  433. // first one is accessing `AllocatedUser` without locking. It's better to
  434. // pass `RegionInfoData` as `void *` then we can lock the mutex properly.
  435. uptr End = Begin + RegionInfoArray[I].MemMapInfo.AllocatedUser;
  436. if (Begin > End || End - Begin < SizeClassMap::getSizeByClassId(I))
  437. continue;
  438. uptr RegionDistance;
  439. if (Begin <= Ptr) {
  440. if (Ptr < End)
  441. RegionDistance = 0;
  442. else
  443. RegionDistance = Ptr - End;
  444. } else {
  445. RegionDistance = Begin - Ptr;
  446. }
  447. if (RegionDistance < MinDistance) {
  448. MinDistance = RegionDistance;
  449. ClassId = I;
  450. }
  451. }
  452. BlockInfo B = {};
  453. if (MinDistance <= 8192) {
  454. B.RegionBegin = RegionInfoArray[ClassId].RegionBeg;
  455. B.RegionEnd =
  456. B.RegionBegin + RegionInfoArray[ClassId].MemMapInfo.AllocatedUser;
  457. B.BlockSize = SizeClassMap::getSizeByClassId(ClassId);
  458. B.BlockBegin =
  459. B.RegionBegin + uptr(sptr(Ptr - B.RegionBegin) / sptr(B.BlockSize) *
  460. sptr(B.BlockSize));
  461. while (B.BlockBegin < B.RegionBegin)
  462. B.BlockBegin += B.BlockSize;
  463. while (B.RegionEnd < B.BlockBegin + B.BlockSize)
  464. B.BlockBegin -= B.BlockSize;
  465. }
  466. return B;
  467. }
  468. AtomicOptions Options;
  469. private:
  470. static const uptr RegionSize = 1UL << RegionSizeLog;
  471. static const uptr NumClasses = SizeClassMap::NumClasses;
  472. static const uptr PrimarySize = RegionSize * NumClasses;
  473. static const uptr MapSizeIncrement = Config::Primary::MapSizeIncrement;
  474. // Fill at most this number of batches from the newly map'd memory.
  475. static const u32 MaxNumBatches = SCUDO_ANDROID ? 4U : 8U;
  476. struct ReleaseToOsInfo {
  477. uptr BytesInFreeListAtLastCheckpoint;
  478. uptr RangesReleased;
  479. uptr LastReleasedBytes;
  480. u64 LastReleaseAtNs;
  481. };
  482. struct BlocksInfo {
  483. SinglyLinkedList<BatchGroupT> BlockList = {};
  484. uptr PoppedBlocks = 0;
  485. uptr PushedBlocks = 0;
  486. };
  487. struct PagesInfo {
  488. MemMapT MemMap = {};
  489. // Bytes mapped for user memory.
  490. uptr MappedUser = 0;
  491. // Bytes allocated for user memory.
  492. uptr AllocatedUser = 0;
  493. };
  494. struct UnpaddedRegionInfo {
  495. // Mutex for operations on freelist
  496. HybridMutex FLLock;
  497. ConditionVariableT FLLockCV GUARDED_BY(FLLock);
  498. // Mutex for memmap operations
  499. HybridMutex MMLock ACQUIRED_BEFORE(FLLock);
  500. // `RegionBeg` is initialized before thread creation and won't be changed.
  501. uptr RegionBeg = 0;
  502. u32 RandState GUARDED_BY(MMLock) = 0;
  503. BlocksInfo FreeListInfo GUARDED_BY(FLLock);
  504. PagesInfo MemMapInfo GUARDED_BY(MMLock);
  505. // The minimum size of pushed blocks to trigger page release.
  506. uptr TryReleaseThreshold GUARDED_BY(MMLock) = 0;
  507. ReleaseToOsInfo ReleaseInfo GUARDED_BY(MMLock) = {};
  508. bool Exhausted GUARDED_BY(MMLock) = false;
  509. bool isPopulatingFreeList GUARDED_BY(FLLock) = false;
  510. };
  511. struct RegionInfo : UnpaddedRegionInfo {
  512. char Padding[SCUDO_CACHE_LINE_SIZE -
  513. (sizeof(UnpaddedRegionInfo) % SCUDO_CACHE_LINE_SIZE)] = {};
  514. };
  515. static_assert(sizeof(RegionInfo) % SCUDO_CACHE_LINE_SIZE == 0, "");
  516. RegionInfo *getRegionInfo(uptr ClassId) {
  517. DCHECK_LT(ClassId, NumClasses);
  518. return &RegionInfoArray[ClassId];
  519. }
  520. uptr getRegionBaseByClassId(uptr ClassId) {
  521. return roundDown(getRegionInfo(ClassId)->RegionBeg - PrimaryBase,
  522. RegionSize) +
  523. PrimaryBase;
  524. }
  525. static CompactPtrT compactPtrInternal(uptr Base, uptr Ptr) {
  526. return static_cast<CompactPtrT>((Ptr - Base) >> CompactPtrScale);
  527. }
  528. static uptr decompactPtrInternal(uptr Base, CompactPtrT CompactPtr) {
  529. return Base + (static_cast<uptr>(CompactPtr) << CompactPtrScale);
  530. }
  531. static uptr compactPtrGroup(CompactPtrT CompactPtr) {
  532. const uptr Mask = (static_cast<uptr>(1) << GroupScale) - 1;
  533. return static_cast<uptr>(CompactPtr) & ~Mask;
  534. }
  535. static uptr decompactGroupBase(uptr Base, uptr CompactPtrGroupBase) {
  536. DCHECK_EQ(CompactPtrGroupBase % (static_cast<uptr>(1) << (GroupScale)), 0U);
  537. return Base + (CompactPtrGroupBase << CompactPtrScale);
  538. }
  539. ALWAYS_INLINE static bool isSmallBlock(uptr BlockSize) {
  540. const uptr PageSize = getPageSizeCached();
  541. return BlockSize < PageSize / 16U;
  542. }
  543. ALWAYS_INLINE static bool isLargeBlock(uptr BlockSize) {
  544. const uptr PageSize = getPageSizeCached();
  545. return BlockSize > PageSize;
  546. }
  547. void pushBatchClassBlocks(RegionInfo *Region, CompactPtrT *Array, u32 Size)
  548. REQUIRES(Region->FLLock) {
  549. DCHECK_EQ(Region, getRegionInfo(SizeClassMap::BatchClassId));
  550. // Free blocks are recorded by TransferBatch in freelist for all
  551. // size-classes. In addition, TransferBatch is allocated from BatchClassId.
  552. // In order not to use additional block to record the free blocks in
  553. // BatchClassId, they are self-contained. I.e., A TransferBatch records the
  554. // block address of itself. See the figure below:
  555. //
  556. // TransferBatch at 0xABCD
  557. // +----------------------------+
  558. // | Free blocks' addr |
  559. // | +------+------+------+ |
  560. // | |0xABCD|... |... | |
  561. // | +------+------+------+ |
  562. // +----------------------------+
  563. //
  564. // When we allocate all the free blocks in the TransferBatch, the block used
  565. // by TransferBatch is also free for use. We don't need to recycle the
  566. // TransferBatch. Note that the correctness is maintained by the invariant,
  567. //
  568. // The unit of each popBatch() request is entire TransferBatch. Return
  569. // part of the blocks in a TransferBatch is invalid.
  570. //
  571. // This ensures that TransferBatch won't leak the address itself while it's
  572. // still holding other valid data.
  573. //
  574. // Besides, BatchGroup is also allocated from BatchClassId and has its
  575. // address recorded in the TransferBatch too. To maintain the correctness,
  576. //
  577. // The address of BatchGroup is always recorded in the last TransferBatch
  578. // in the freelist (also imply that the freelist should only be
  579. // updated with push_front). Once the last TransferBatch is popped,
  580. // the block used by BatchGroup is also free for use.
  581. //
  582. // With this approach, the blocks used by BatchGroup and TransferBatch are
  583. // reusable and don't need additional space for them.
  584. Region->FreeListInfo.PushedBlocks += Size;
  585. BatchGroupT *BG = Region->FreeListInfo.BlockList.front();
  586. if (BG == nullptr) {
  587. // Construct `BatchGroup` on the last element.
  588. BG = reinterpret_cast<BatchGroupT *>(
  589. decompactPtr(SizeClassMap::BatchClassId, Array[Size - 1]));
  590. --Size;
  591. BG->Batches.clear();
  592. // BatchClass hasn't enabled memory group. Use `0` to indicate there's no
  593. // memory group here.
  594. BG->CompactPtrGroupBase = 0;
  595. // `BG` is also the block of BatchClassId. Note that this is different
  596. // from `CreateGroup` in `pushBlocksImpl`
  597. BG->PushedBlocks = 1;
  598. BG->BytesInBGAtLastCheckpoint = 0;
  599. BG->MaxCachedPerBatch =
  600. CacheT::getMaxCached(getSizeByClassId(SizeClassMap::BatchClassId));
  601. Region->FreeListInfo.BlockList.push_front(BG);
  602. }
  603. if (UNLIKELY(Size == 0))
  604. return;
  605. // This happens under 2 cases.
  606. // 1. just allocated a new `BatchGroup`.
  607. // 2. Only 1 block is pushed when the freelist is empty.
  608. if (BG->Batches.empty()) {
  609. // Construct the `TransferBatch` on the last element.
  610. TransferBatchT *TB = reinterpret_cast<TransferBatchT *>(
  611. decompactPtr(SizeClassMap::BatchClassId, Array[Size - 1]));
  612. TB->clear();
  613. // As mentioned above, addresses of `TransferBatch` and `BatchGroup` are
  614. // recorded in the TransferBatch.
  615. TB->add(Array[Size - 1]);
  616. TB->add(
  617. compactPtr(SizeClassMap::BatchClassId, reinterpret_cast<uptr>(BG)));
  618. --Size;
  619. DCHECK_EQ(BG->PushedBlocks, 1U);
  620. // `TB` is also the block of BatchClassId.
  621. BG->PushedBlocks += 1;
  622. BG->Batches.push_front(TB);
  623. }
  624. TransferBatchT *CurBatch = BG->Batches.front();
  625. DCHECK_NE(CurBatch, nullptr);
  626. for (u32 I = 0; I < Size;) {
  627. u16 UnusedSlots =
  628. static_cast<u16>(BG->MaxCachedPerBatch - CurBatch->getCount());
  629. if (UnusedSlots == 0) {
  630. CurBatch = reinterpret_cast<TransferBatchT *>(
  631. decompactPtr(SizeClassMap::BatchClassId, Array[I]));
  632. CurBatch->clear();
  633. // Self-contained
  634. CurBatch->add(Array[I]);
  635. ++I;
  636. // TODO(chiahungduan): Avoid the use of push_back() in `Batches` of
  637. // BatchClassId.
  638. BG->Batches.push_front(CurBatch);
  639. UnusedSlots = static_cast<u16>(BG->MaxCachedPerBatch - 1);
  640. }
  641. // `UnusedSlots` is u16 so the result will be also fit in u16.
  642. const u16 AppendSize = static_cast<u16>(Min<u32>(UnusedSlots, Size - I));
  643. CurBatch->appendFromArray(&Array[I], AppendSize);
  644. I += AppendSize;
  645. }
  646. BG->PushedBlocks += Size;
  647. }
  648. // Push the blocks to their batch group. The layout will be like,
  649. //
  650. // FreeListInfo.BlockList - > BG -> BG -> BG
  651. // | | |
  652. // v v v
  653. // TB TB TB
  654. // |
  655. // v
  656. // TB
  657. //
  658. // Each BlockGroup(BG) will associate with unique group id and the free blocks
  659. // are managed by a list of TransferBatch(TB). To reduce the time of inserting
  660. // blocks, BGs are sorted and the input `Array` are supposed to be sorted so
  661. // that we can get better performance of maintaining sorted property.
  662. // Use `SameGroup=true` to indicate that all blocks in the array are from the
  663. // same group then we will skip checking the group id of each block.
  664. void pushBlocksImpl(CacheT *C, uptr ClassId, RegionInfo *Region,
  665. CompactPtrT *Array, u32 Size, bool SameGroup = false)
  666. REQUIRES(Region->FLLock) {
  667. DCHECK_NE(ClassId, SizeClassMap::BatchClassId);
  668. DCHECK_GT(Size, 0U);
  669. auto CreateGroup = [&](uptr CompactPtrGroupBase) {
  670. BatchGroupT *BG =
  671. reinterpret_cast<BatchGroupT *>(C->getBatchClassBlock());
  672. BG->Batches.clear();
  673. TransferBatchT *TB =
  674. reinterpret_cast<TransferBatchT *>(C->getBatchClassBlock());
  675. TB->clear();
  676. BG->CompactPtrGroupBase = CompactPtrGroupBase;
  677. BG->Batches.push_front(TB);
  678. BG->PushedBlocks = 0;
  679. BG->BytesInBGAtLastCheckpoint = 0;
  680. BG->MaxCachedPerBatch = CacheT::getMaxCached(getSizeByClassId(ClassId));
  681. return BG;
  682. };
  683. auto InsertBlocks = [&](BatchGroupT *BG, CompactPtrT *Array, u32 Size) {
  684. SinglyLinkedList<TransferBatchT> &Batches = BG->Batches;
  685. TransferBatchT *CurBatch = Batches.front();
  686. DCHECK_NE(CurBatch, nullptr);
  687. for (u32 I = 0; I < Size;) {
  688. DCHECK_GE(BG->MaxCachedPerBatch, CurBatch->getCount());
  689. u16 UnusedSlots =
  690. static_cast<u16>(BG->MaxCachedPerBatch - CurBatch->getCount());
  691. if (UnusedSlots == 0) {
  692. CurBatch =
  693. reinterpret_cast<TransferBatchT *>(C->getBatchClassBlock());
  694. CurBatch->clear();
  695. Batches.push_front(CurBatch);
  696. UnusedSlots = BG->MaxCachedPerBatch;
  697. }
  698. // `UnusedSlots` is u16 so the result will be also fit in u16.
  699. u16 AppendSize = static_cast<u16>(Min<u32>(UnusedSlots, Size - I));
  700. CurBatch->appendFromArray(&Array[I], AppendSize);
  701. I += AppendSize;
  702. }
  703. BG->PushedBlocks += Size;
  704. };
  705. Region->FreeListInfo.PushedBlocks += Size;
  706. BatchGroupT *Cur = Region->FreeListInfo.BlockList.front();
  707. // In the following, `Cur` always points to the BatchGroup for blocks that
  708. // will be pushed next. `Prev` is the element right before `Cur`.
  709. BatchGroupT *Prev = nullptr;
  710. while (Cur != nullptr &&
  711. compactPtrGroup(Array[0]) > Cur->CompactPtrGroupBase) {
  712. Prev = Cur;
  713. Cur = Cur->Next;
  714. }
  715. if (Cur == nullptr ||
  716. compactPtrGroup(Array[0]) != Cur->CompactPtrGroupBase) {
  717. Cur = CreateGroup(compactPtrGroup(Array[0]));
  718. if (Prev == nullptr)
  719. Region->FreeListInfo.BlockList.push_front(Cur);
  720. else
  721. Region->FreeListInfo.BlockList.insert(Prev, Cur);
  722. }
  723. // All the blocks are from the same group, just push without checking group
  724. // id.
  725. if (SameGroup) {
  726. for (u32 I = 0; I < Size; ++I)
  727. DCHECK_EQ(compactPtrGroup(Array[I]), Cur->CompactPtrGroupBase);
  728. InsertBlocks(Cur, Array, Size);
  729. return;
  730. }
  731. // The blocks are sorted by group id. Determine the segment of group and
  732. // push them to their group together.
  733. u32 Count = 1;
  734. for (u32 I = 1; I < Size; ++I) {
  735. if (compactPtrGroup(Array[I - 1]) != compactPtrGroup(Array[I])) {
  736. DCHECK_EQ(compactPtrGroup(Array[I - 1]), Cur->CompactPtrGroupBase);
  737. InsertBlocks(Cur, Array + I - Count, Count);
  738. while (Cur != nullptr &&
  739. compactPtrGroup(Array[I]) > Cur->CompactPtrGroupBase) {
  740. Prev = Cur;
  741. Cur = Cur->Next;
  742. }
  743. if (Cur == nullptr ||
  744. compactPtrGroup(Array[I]) != Cur->CompactPtrGroupBase) {
  745. Cur = CreateGroup(compactPtrGroup(Array[I]));
  746. DCHECK_NE(Prev, nullptr);
  747. Region->FreeListInfo.BlockList.insert(Prev, Cur);
  748. }
  749. Count = 1;
  750. } else {
  751. ++Count;
  752. }
  753. }
  754. InsertBlocks(Cur, Array + Size - Count, Count);
  755. }
  756. TransferBatchT *popBatchWithCV(CacheT *C, uptr ClassId, RegionInfo *Region,
  757. bool &ReportRegionExhausted) {
  758. TransferBatchT *B = nullptr;
  759. while (true) {
  760. // We only expect one thread doing the freelist refillment and other
  761. // threads will be waiting for either the completion of the
  762. // `populateFreeListAndPopBatch()` or `pushBlocks()` called by other
  763. // threads.
  764. bool PopulateFreeList = false;
  765. {
  766. ScopedLock FL(Region->FLLock);
  767. if (!Region->isPopulatingFreeList) {
  768. Region->isPopulatingFreeList = true;
  769. PopulateFreeList = true;
  770. }
  771. }
  772. if (PopulateFreeList) {
  773. ScopedLock ML(Region->MMLock);
  774. const bool RegionIsExhausted = Region->Exhausted;
  775. if (!RegionIsExhausted)
  776. B = populateFreeListAndPopBatch(C, ClassId, Region);
  777. ReportRegionExhausted = !RegionIsExhausted && Region->Exhausted;
  778. {
  779. // Before reacquiring the `FLLock`, the freelist may be used up again
  780. // and some threads are waiting for the freelist refillment by the
  781. // current thread. It's important to set
  782. // `Region->isPopulatingFreeList` to false so the threads about to
  783. // sleep will notice the status change.
  784. ScopedLock FL(Region->FLLock);
  785. Region->isPopulatingFreeList = false;
  786. Region->FLLockCV.notifyAll(Region->FLLock);
  787. }
  788. break;
  789. }
  790. // At here, there are two preconditions to be met before waiting,
  791. // 1. The freelist is empty.
  792. // 2. Region->isPopulatingFreeList == true, i.e, someone is still doing
  793. // `populateFreeListAndPopBatch()`.
  794. //
  795. // Note that it has the chance that freelist is empty but
  796. // Region->isPopulatingFreeList == false because all the new populated
  797. // blocks were used up right after the refillment. Therefore, we have to
  798. // check if someone is still populating the freelist.
  799. ScopedLock FL(Region->FLLock);
  800. if (LIKELY(B = popBatchImpl(C, ClassId, Region)))
  801. break;
  802. if (!Region->isPopulatingFreeList)
  803. continue;
  804. // Now the freelist is empty and someone's doing the refillment. We will
  805. // wait until anyone refills the freelist or someone finishes doing
  806. // `populateFreeListAndPopBatch()`. The refillment can be done by
  807. // `populateFreeListAndPopBatch()`, `pushBlocks()`,
  808. // `pushBatchClassBlocks()` and `mergeGroupsToReleaseBack()`.
  809. Region->FLLockCV.wait(Region->FLLock);
  810. if (LIKELY(B = popBatchImpl(C, ClassId, Region)))
  811. break;
  812. }
  813. return B;
  814. }
  815. // Pop one TransferBatch from a BatchGroup. The BatchGroup with the smallest
  816. // group id will be considered first.
  817. //
  818. // The region mutex needs to be held while calling this method.
  819. TransferBatchT *popBatchImpl(CacheT *C, uptr ClassId, RegionInfo *Region)
  820. REQUIRES(Region->FLLock) {
  821. if (Region->FreeListInfo.BlockList.empty())
  822. return nullptr;
  823. SinglyLinkedList<TransferBatchT> &Batches =
  824. Region->FreeListInfo.BlockList.front()->Batches;
  825. if (Batches.empty()) {
  826. DCHECK_EQ(ClassId, SizeClassMap::BatchClassId);
  827. BatchGroupT *BG = Region->FreeListInfo.BlockList.front();
  828. Region->FreeListInfo.BlockList.pop_front();
  829. // Block used by `BatchGroup` is from BatchClassId. Turn the block into
  830. // `TransferBatch` with single block.
  831. TransferBatchT *TB = reinterpret_cast<TransferBatchT *>(BG);
  832. TB->clear();
  833. TB->add(
  834. compactPtr(SizeClassMap::BatchClassId, reinterpret_cast<uptr>(TB)));
  835. Region->FreeListInfo.PoppedBlocks += 1;
  836. return TB;
  837. }
  838. TransferBatchT *B = Batches.front();
  839. Batches.pop_front();
  840. DCHECK_NE(B, nullptr);
  841. DCHECK_GT(B->getCount(), 0U);
  842. if (Batches.empty()) {
  843. BatchGroupT *BG = Region->FreeListInfo.BlockList.front();
  844. Region->FreeListInfo.BlockList.pop_front();
  845. // We don't keep BatchGroup with zero blocks to avoid empty-checking while
  846. // allocating. Note that block used by constructing BatchGroup is recorded
  847. // as free blocks in the last element of BatchGroup::Batches. Which means,
  848. // once we pop the last TransferBatch, the block is implicitly
  849. // deallocated.
  850. if (ClassId != SizeClassMap::BatchClassId)
  851. C->deallocate(SizeClassMap::BatchClassId, BG);
  852. }
  853. Region->FreeListInfo.PoppedBlocks += B->getCount();
  854. return B;
  855. }
  856. // Refill the freelist and return one batch.
  857. NOINLINE TransferBatchT *populateFreeListAndPopBatch(CacheT *C, uptr ClassId,
  858. RegionInfo *Region)
  859. REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {
  860. const uptr Size = getSizeByClassId(ClassId);
  861. const u16 MaxCount = CacheT::getMaxCached(Size);
  862. const uptr RegionBeg = Region->RegionBeg;
  863. const uptr MappedUser = Region->MemMapInfo.MappedUser;
  864. const uptr TotalUserBytes =
  865. Region->MemMapInfo.AllocatedUser + MaxCount * Size;
  866. // Map more space for blocks, if necessary.
  867. if (TotalUserBytes > MappedUser) {
  868. // Do the mmap for the user memory.
  869. const uptr MapSize =
  870. roundUp(TotalUserBytes - MappedUser, MapSizeIncrement);
  871. const uptr RegionBase = RegionBeg - getRegionBaseByClassId(ClassId);
  872. if (UNLIKELY(RegionBase + MappedUser + MapSize > RegionSize)) {
  873. Region->Exhausted = true;
  874. return nullptr;
  875. }
  876. if (UNLIKELY(!Region->MemMapInfo.MemMap.remap(
  877. RegionBeg + MappedUser, MapSize, "scudo:primary",
  878. MAP_ALLOWNOMEM | MAP_RESIZABLE |
  879. (useMemoryTagging<Config>(Options.load()) ? MAP_MEMTAG
  880. : 0)))) {
  881. return nullptr;
  882. }
  883. Region->MemMapInfo.MappedUser += MapSize;
  884. C->getStats().add(StatMapped, MapSize);
  885. }
  886. const u32 NumberOfBlocks =
  887. Min(MaxNumBatches * MaxCount,
  888. static_cast<u32>((Region->MemMapInfo.MappedUser -
  889. Region->MemMapInfo.AllocatedUser) /
  890. Size));
  891. DCHECK_GT(NumberOfBlocks, 0);
  892. constexpr u32 ShuffleArraySize =
  893. MaxNumBatches * TransferBatchT::MaxNumCached;
  894. CompactPtrT ShuffleArray[ShuffleArraySize];
  895. DCHECK_LE(NumberOfBlocks, ShuffleArraySize);
  896. const uptr CompactPtrBase = getCompactPtrBaseByClassId(ClassId);
  897. uptr P = RegionBeg + Region->MemMapInfo.AllocatedUser;
  898. for (u32 I = 0; I < NumberOfBlocks; I++, P += Size)
  899. ShuffleArray[I] = compactPtrInternal(CompactPtrBase, P);
  900. ScopedLock L(Region->FLLock);
  901. if (ClassId != SizeClassMap::BatchClassId) {
  902. u32 N = 1;
  903. uptr CurGroup = compactPtrGroup(ShuffleArray[0]);
  904. for (u32 I = 1; I < NumberOfBlocks; I++) {
  905. if (UNLIKELY(compactPtrGroup(ShuffleArray[I]) != CurGroup)) {
  906. shuffle(ShuffleArray + I - N, N, &Region->RandState);
  907. pushBlocksImpl(C, ClassId, Region, ShuffleArray + I - N, N,
  908. /*SameGroup=*/true);
  909. N = 1;
  910. CurGroup = compactPtrGroup(ShuffleArray[I]);
  911. } else {
  912. ++N;
  913. }
  914. }
  915. shuffle(ShuffleArray + NumberOfBlocks - N, N, &Region->RandState);
  916. pushBlocksImpl(C, ClassId, Region, &ShuffleArray[NumberOfBlocks - N], N,
  917. /*SameGroup=*/true);
  918. } else {
  919. pushBatchClassBlocks(Region, ShuffleArray, NumberOfBlocks);
  920. }
  921. TransferBatchT *B = popBatchImpl(C, ClassId, Region);
  922. DCHECK_NE(B, nullptr);
  923. // Note that `PushedBlocks` and `PoppedBlocks` are supposed to only record
  924. // the requests from `PushBlocks` and `PopBatch` which are external
  925. // interfaces. `populateFreeListAndPopBatch` is the internal interface so we
  926. // should set the values back to avoid incorrectly setting the stats.
  927. Region->FreeListInfo.PushedBlocks -= NumberOfBlocks;
  928. const uptr AllocatedUser = Size * NumberOfBlocks;
  929. C->getStats().add(StatFree, AllocatedUser);
  930. Region->MemMapInfo.AllocatedUser += AllocatedUser;
  931. return B;
  932. }
  933. void getStats(ScopedString *Str, uptr ClassId, RegionInfo *Region)
  934. REQUIRES(Region->MMLock, Region->FLLock) {
  935. if (Region->MemMapInfo.MappedUser == 0)
  936. return;
  937. const uptr BlockSize = getSizeByClassId(ClassId);
  938. const uptr InUseBlocks =
  939. Region->FreeListInfo.PoppedBlocks - Region->FreeListInfo.PushedBlocks;
  940. const uptr BytesInFreeList =
  941. Region->MemMapInfo.AllocatedUser - InUseBlocks * BlockSize;
  942. uptr RegionPushedBytesDelta = 0;
  943. if (BytesInFreeList >=
  944. Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint) {
  945. RegionPushedBytesDelta =
  946. BytesInFreeList - Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint;
  947. }
  948. const uptr TotalChunks = Region->MemMapInfo.AllocatedUser / BlockSize;
  949. Str->append(
  950. "%s %02zu (%6zu): mapped: %6zuK popped: %7zu pushed: %7zu "
  951. "inuse: %6zu total: %6zu releases: %6zu last "
  952. "released: %6zuK latest pushed bytes: %6zuK region: 0x%zx (0x%zx)\n",
  953. Region->Exhausted ? "E" : " ", ClassId, getSizeByClassId(ClassId),
  954. Region->MemMapInfo.MappedUser >> 10, Region->FreeListInfo.PoppedBlocks,
  955. Region->FreeListInfo.PushedBlocks, InUseBlocks, TotalChunks,
  956. Region->ReleaseInfo.RangesReleased,
  957. Region->ReleaseInfo.LastReleasedBytes >> 10,
  958. RegionPushedBytesDelta >> 10, Region->RegionBeg,
  959. getRegionBaseByClassId(ClassId));
  960. }
  961. void getRegionFragmentationInfo(RegionInfo *Region, uptr ClassId,
  962. ScopedString *Str) REQUIRES(Region->MMLock) {
  963. const uptr BlockSize = getSizeByClassId(ClassId);
  964. const uptr AllocatedUserEnd =
  965. Region->MemMapInfo.AllocatedUser + Region->RegionBeg;
  966. SinglyLinkedList<BatchGroupT> GroupsToRelease;
  967. {
  968. ScopedLock L(Region->FLLock);
  969. GroupsToRelease = Region->FreeListInfo.BlockList;
  970. Region->FreeListInfo.BlockList.clear();
  971. }
  972. FragmentationRecorder Recorder;
  973. if (!GroupsToRelease.empty()) {
  974. PageReleaseContext Context =
  975. markFreeBlocks(Region, BlockSize, AllocatedUserEnd,
  976. getCompactPtrBaseByClassId(ClassId), GroupsToRelease);
  977. auto SkipRegion = [](UNUSED uptr RegionIndex) { return false; };
  978. releaseFreeMemoryToOS(Context, Recorder, SkipRegion);
  979. mergeGroupsToReleaseBack(Region, GroupsToRelease);
  980. }
  981. ScopedLock L(Region->FLLock);
  982. const uptr PageSize = getPageSizeCached();
  983. const uptr TotalBlocks = Region->MemMapInfo.AllocatedUser / BlockSize;
  984. const uptr InUseBlocks =
  985. Region->FreeListInfo.PoppedBlocks - Region->FreeListInfo.PushedBlocks;
  986. const uptr AllocatedPagesCount =
  987. roundUp(Region->MemMapInfo.AllocatedUser, PageSize) / PageSize;
  988. DCHECK_GE(AllocatedPagesCount, Recorder.getReleasedPagesCount());
  989. const uptr InUsePages =
  990. AllocatedPagesCount - Recorder.getReleasedPagesCount();
  991. const uptr InUseBytes = InUsePages * PageSize;
  992. uptr Integral;
  993. uptr Fractional;
  994. computePercentage(BlockSize * InUseBlocks, InUsePages * PageSize, &Integral,
  995. &Fractional);
  996. Str->append(" %02zu (%6zu): inuse/total blocks: %6zu/%6zu inuse/total "
  997. "pages: %6zu/%6zu inuse bytes: %6zuK util: %3zu.%02zu%%\n",
  998. ClassId, BlockSize, InUseBlocks, TotalBlocks, InUsePages,
  999. AllocatedPagesCount, InUseBytes >> 10, Integral, Fractional);
  1000. }
  1001. NOINLINE uptr releaseToOSMaybe(RegionInfo *Region, uptr ClassId,
  1002. ReleaseToOS ReleaseType = ReleaseToOS::Normal)
  1003. REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {
  1004. const uptr BlockSize = getSizeByClassId(ClassId);
  1005. uptr BytesInFreeList;
  1006. const uptr AllocatedUserEnd =
  1007. Region->MemMapInfo.AllocatedUser + Region->RegionBeg;
  1008. SinglyLinkedList<BatchGroupT> GroupsToRelease;
  1009. {
  1010. ScopedLock L(Region->FLLock);
  1011. BytesInFreeList = Region->MemMapInfo.AllocatedUser -
  1012. (Region->FreeListInfo.PoppedBlocks -
  1013. Region->FreeListInfo.PushedBlocks) *
  1014. BlockSize;
  1015. if (UNLIKELY(BytesInFreeList == 0))
  1016. return false;
  1017. // ==================================================================== //
  1018. // 1. Check if we have enough free blocks and if it's worth doing a page
  1019. // release.
  1020. // ==================================================================== //
  1021. if (ReleaseType != ReleaseToOS::ForceAll &&
  1022. !hasChanceToReleasePages(Region, BlockSize, BytesInFreeList,
  1023. ReleaseType)) {
  1024. return 0;
  1025. }
  1026. // ==================================================================== //
  1027. // 2. Determine which groups can release the pages. Use a heuristic to
  1028. // gather groups that are candidates for doing a release.
  1029. // ==================================================================== //
  1030. if (ReleaseType == ReleaseToOS::ForceAll) {
  1031. GroupsToRelease = Region->FreeListInfo.BlockList;
  1032. Region->FreeListInfo.BlockList.clear();
  1033. } else {
  1034. GroupsToRelease =
  1035. collectGroupsToRelease(Region, BlockSize, AllocatedUserEnd,
  1036. getCompactPtrBaseByClassId(ClassId));
  1037. }
  1038. if (GroupsToRelease.empty())
  1039. return 0;
  1040. }
  1041. // Note that we have extracted the `GroupsToRelease` from region freelist.
  1042. // It's safe to let pushBlocks()/popBatches() access the remaining region
  1043. // freelist. In the steps 3 and 4, we will temporarily release the FLLock
  1044. // and lock it again before step 5.
  1045. // ==================================================================== //
  1046. // 3. Mark the free blocks in `GroupsToRelease` in the `PageReleaseContext`.
  1047. // Then we can tell which pages are in-use by querying
  1048. // `PageReleaseContext`.
  1049. // ==================================================================== //
  1050. PageReleaseContext Context =
  1051. markFreeBlocks(Region, BlockSize, AllocatedUserEnd,
  1052. getCompactPtrBaseByClassId(ClassId), GroupsToRelease);
  1053. if (UNLIKELY(!Context.hasBlockMarked())) {
  1054. mergeGroupsToReleaseBack(Region, GroupsToRelease);
  1055. return 0;
  1056. }
  1057. // ==================================================================== //
  1058. // 4. Release the unused physical pages back to the OS.
  1059. // ==================================================================== //
  1060. RegionReleaseRecorder<MemMapT> Recorder(&Region->MemMapInfo.MemMap,
  1061. Region->RegionBeg,
  1062. Context.getReleaseOffset());
  1063. auto SkipRegion = [](UNUSED uptr RegionIndex) { return false; };
  1064. releaseFreeMemoryToOS(Context, Recorder, SkipRegion);
  1065. if (Recorder.getReleasedRangesCount() > 0) {
  1066. Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint = BytesInFreeList;
  1067. Region->ReleaseInfo.RangesReleased += Recorder.getReleasedRangesCount();
  1068. Region->ReleaseInfo.LastReleasedBytes = Recorder.getReleasedBytes();
  1069. }
  1070. Region->ReleaseInfo.LastReleaseAtNs = getMonotonicTimeFast();
  1071. // ====================================================================== //
  1072. // 5. Merge the `GroupsToRelease` back to the freelist.
  1073. // ====================================================================== //
  1074. mergeGroupsToReleaseBack(Region, GroupsToRelease);
  1075. return Recorder.getReleasedBytes();
  1076. }
  1077. bool hasChanceToReleasePages(RegionInfo *Region, uptr BlockSize,
  1078. uptr BytesInFreeList, ReleaseToOS ReleaseType)
  1079. REQUIRES(Region->MMLock, Region->FLLock) {
  1080. DCHECK_GE(Region->FreeListInfo.PoppedBlocks,
  1081. Region->FreeListInfo.PushedBlocks);
  1082. const uptr PageSize = getPageSizeCached();
  1083. // Always update `BytesInFreeListAtLastCheckpoint` with the smallest value
  1084. // so that we won't underestimate the releasable pages. For example, the
  1085. // following is the region usage,
  1086. //
  1087. // BytesInFreeListAtLastCheckpoint AllocatedUser
  1088. // v v
  1089. // |--------------------------------------->
  1090. // ^ ^
  1091. // BytesInFreeList ReleaseThreshold
  1092. //
  1093. // In general, if we have collected enough bytes and the amount of free
  1094. // bytes meets the ReleaseThreshold, we will try to do page release. If we
  1095. // don't update `BytesInFreeListAtLastCheckpoint` when the current
  1096. // `BytesInFreeList` is smaller, we may take longer time to wait for enough
  1097. // freed blocks because we miss the bytes between
  1098. // (BytesInFreeListAtLastCheckpoint - BytesInFreeList).
  1099. if (BytesInFreeList <=
  1100. Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint) {
  1101. Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint = BytesInFreeList;
  1102. }
  1103. const uptr RegionPushedBytesDelta =
  1104. BytesInFreeList - Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint;
  1105. if (RegionPushedBytesDelta < PageSize)
  1106. return false;
  1107. // Releasing smaller blocks is expensive, so we want to make sure that a
  1108. // significant amount of bytes are free, and that there has been a good
  1109. // amount of batches pushed to the freelist before attempting to release.
  1110. if (isSmallBlock(BlockSize) && ReleaseType == ReleaseToOS::Normal)
  1111. if (RegionPushedBytesDelta < Region->TryReleaseThreshold)
  1112. return false;
  1113. if (ReleaseType == ReleaseToOS::Normal) {
  1114. const s32 IntervalMs = atomic_load_relaxed(&ReleaseToOsIntervalMs);
  1115. if (IntervalMs < 0)
  1116. return false;
  1117. // The constant 8 here is selected from profiling some apps and the number
  1118. // of unreleased pages in the large size classes is around 16 pages or
  1119. // more. Choose half of it as a heuristic and which also avoids page
  1120. // release every time for every pushBlocks() attempt by large blocks.
  1121. const bool ByPassReleaseInterval =
  1122. isLargeBlock(BlockSize) && RegionPushedBytesDelta > 8 * PageSize;
  1123. if (!ByPassReleaseInterval) {
  1124. if (Region->ReleaseInfo.LastReleaseAtNs +
  1125. static_cast<u64>(IntervalMs) * 1000000 >
  1126. getMonotonicTimeFast()) {
  1127. // Memory was returned recently.
  1128. return false;
  1129. }
  1130. }
  1131. } // if (ReleaseType == ReleaseToOS::Normal)
  1132. return true;
  1133. }
  1134. SinglyLinkedList<BatchGroupT>
  1135. collectGroupsToRelease(RegionInfo *Region, const uptr BlockSize,
  1136. const uptr AllocatedUserEnd, const uptr CompactPtrBase)
  1137. REQUIRES(Region->MMLock, Region->FLLock) {
  1138. const uptr GroupSize = (1UL << GroupSizeLog);
  1139. const uptr PageSize = getPageSizeCached();
  1140. SinglyLinkedList<BatchGroupT> GroupsToRelease;
  1141. // We are examining each group and will take the minimum distance to the
  1142. // release threshold as the next Region::TryReleaseThreshold(). Note that if
  1143. // the size of free blocks has reached the release threshold, the distance
  1144. // to the next release will be PageSize * SmallerBlockReleasePageDelta. See
  1145. // the comment on `SmallerBlockReleasePageDelta` for more details.
  1146. uptr MinDistToThreshold = GroupSize;
  1147. for (BatchGroupT *BG = Region->FreeListInfo.BlockList.front(),
  1148. *Prev = nullptr;
  1149. BG != nullptr;) {
  1150. // Group boundary is always GroupSize-aligned from CompactPtr base. The
  1151. // layout of memory groups is like,
  1152. //
  1153. // (CompactPtrBase)
  1154. // #1 CompactPtrGroupBase #2 CompactPtrGroupBase ...
  1155. // | | |
  1156. // v v v
  1157. // +-----------------------+-----------------------+
  1158. // \ / \ /
  1159. // --- GroupSize --- --- GroupSize ---
  1160. //
  1161. // After decompacting the CompactPtrGroupBase, we expect the alignment
  1162. // property is held as well.
  1163. const uptr BatchGroupBase =
  1164. decompactGroupBase(CompactPtrBase, BG->CompactPtrGroupBase);
  1165. DCHECK_LE(Region->RegionBeg, BatchGroupBase);
  1166. DCHECK_GE(AllocatedUserEnd, BatchGroupBase);
  1167. DCHECK_EQ((Region->RegionBeg - BatchGroupBase) % GroupSize, 0U);
  1168. // TransferBatches are pushed in front of BG.Batches. The first one may
  1169. // not have all caches used.
  1170. const uptr NumBlocks = (BG->Batches.size() - 1) * BG->MaxCachedPerBatch +
  1171. BG->Batches.front()->getCount();
  1172. const uptr BytesInBG = NumBlocks * BlockSize;
  1173. if (BytesInBG <= BG->BytesInBGAtLastCheckpoint) {
  1174. BG->BytesInBGAtLastCheckpoint = BytesInBG;
  1175. Prev = BG;
  1176. BG = BG->Next;
  1177. continue;
  1178. }
  1179. const uptr PushedBytesDelta = BG->BytesInBGAtLastCheckpoint - BytesInBG;
  1180. // Given the randomness property, we try to release the pages only if the
  1181. // bytes used by free blocks exceed certain proportion of group size. Note
  1182. // that this heuristic only applies when all the spaces in a BatchGroup
  1183. // are allocated.
  1184. if (isSmallBlock(BlockSize)) {
  1185. const uptr BatchGroupEnd = BatchGroupBase + GroupSize;
  1186. const uptr AllocatedGroupSize = AllocatedUserEnd >= BatchGroupEnd
  1187. ? GroupSize
  1188. : AllocatedUserEnd - BatchGroupBase;
  1189. const uptr ReleaseThreshold =
  1190. (AllocatedGroupSize * (100 - 1U - BlockSize / 16U)) / 100U;
  1191. const bool HighDensity = BytesInBG >= ReleaseThreshold;
  1192. const bool MayHaveReleasedAll = NumBlocks >= (GroupSize / BlockSize);
  1193. // If all blocks in the group are released, we will do range marking
  1194. // which is fast. Otherwise, we will wait until we have accumulated
  1195. // a certain amount of free memory.
  1196. const bool ReachReleaseDelta =
  1197. MayHaveReleasedAll
  1198. ? true
  1199. : PushedBytesDelta >= PageSize * SmallerBlockReleasePageDelta;
  1200. if (!HighDensity) {
  1201. DCHECK_LE(BytesInBG, ReleaseThreshold);
  1202. // The following is the usage of a memroy group,
  1203. //
  1204. // BytesInBG ReleaseThreshold
  1205. // / \ v
  1206. // +---+---------------------------+-----+
  1207. // | | | | |
  1208. // +---+---------------------------+-----+
  1209. // \ / ^
  1210. // PushedBytesDelta GroupEnd
  1211. MinDistToThreshold =
  1212. Min(MinDistToThreshold,
  1213. ReleaseThreshold - BytesInBG + PushedBytesDelta);
  1214. } else {
  1215. // If it reaches high density at this round, the next time we will try
  1216. // to release is based on SmallerBlockReleasePageDelta
  1217. MinDistToThreshold =
  1218. Min(MinDistToThreshold, PageSize * SmallerBlockReleasePageDelta);
  1219. }
  1220. if (!HighDensity || !ReachReleaseDelta) {
  1221. Prev = BG;
  1222. BG = BG->Next;
  1223. continue;
  1224. }
  1225. }
  1226. // If `BG` is the first BatchGroupT in the list, we only need to advance
  1227. // `BG` and call FreeListInfo.BlockList::pop_front(). No update is needed
  1228. // for `Prev`.
  1229. //
  1230. // (BG) (BG->Next)
  1231. // Prev Cur BG
  1232. // | | |
  1233. // v v v
  1234. // nil +--+ +--+
  1235. // |X | -> | | -> ...
  1236. // +--+ +--+
  1237. //
  1238. // Otherwise, `Prev` will be used to extract the `Cur` from the
  1239. // `FreeListInfo.BlockList`.
  1240. //
  1241. // (BG) (BG->Next)
  1242. // Prev Cur BG
  1243. // | | |
  1244. // v v v
  1245. // +--+ +--+ +--+
  1246. // | | -> |X | -> | | -> ...
  1247. // +--+ +--+ +--+
  1248. //
  1249. // After FreeListInfo.BlockList::extract(),
  1250. //
  1251. // Prev Cur BG
  1252. // | | |
  1253. // v v v
  1254. // +--+ +--+ +--+
  1255. // | |-+ |X | +->| | -> ...
  1256. // +--+ | +--+ | +--+
  1257. // +--------+
  1258. //
  1259. // Note that we need to advance before pushing this BatchGroup to
  1260. // GroupsToRelease because it's a destructive operation.
  1261. BatchGroupT *Cur = BG;
  1262. BG = BG->Next;
  1263. // Ideally, we may want to update this only after successful release.
  1264. // However, for smaller blocks, each block marking is a costly operation.
  1265. // Therefore, we update it earlier.
  1266. // TODO: Consider updating this after releasing pages if `ReleaseRecorder`
  1267. // can tell the released bytes in each group.
  1268. Cur->BytesInBGAtLastCheckpoint = BytesInBG;
  1269. if (Prev != nullptr)
  1270. Region->FreeListInfo.BlockList.extract(Prev, Cur);
  1271. else
  1272. Region->FreeListInfo.BlockList.pop_front();
  1273. GroupsToRelease.push_back(Cur);
  1274. }
  1275. // Only small blocks have the adaptive `TryReleaseThreshold`.
  1276. if (isSmallBlock(BlockSize)) {
  1277. // If the MinDistToThreshold is not updated, that means each memory group
  1278. // may have only pushed less than a page size. In that case, just set it
  1279. // back to normal.
  1280. if (MinDistToThreshold == GroupSize)
  1281. MinDistToThreshold = PageSize * SmallerBlockReleasePageDelta;
  1282. Region->TryReleaseThreshold = MinDistToThreshold;
  1283. }
  1284. return GroupsToRelease;
  1285. }
  1286. PageReleaseContext
  1287. markFreeBlocks(RegionInfo *Region, const uptr BlockSize,
  1288. const uptr AllocatedUserEnd, const uptr CompactPtrBase,
  1289. SinglyLinkedList<BatchGroupT> &GroupsToRelease)
  1290. REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {
  1291. const uptr GroupSize = (1UL << GroupSizeLog);
  1292. auto DecompactPtr = [CompactPtrBase](CompactPtrT CompactPtr) {
  1293. return decompactPtrInternal(CompactPtrBase, CompactPtr);
  1294. };
  1295. const uptr ReleaseBase = decompactGroupBase(
  1296. CompactPtrBase, GroupsToRelease.front()->CompactPtrGroupBase);
  1297. const uptr LastGroupEnd =
  1298. Min(decompactGroupBase(CompactPtrBase,
  1299. GroupsToRelease.back()->CompactPtrGroupBase) +
  1300. GroupSize,
  1301. AllocatedUserEnd);
  1302. // The last block may straddle the group boundary. Rounding up to BlockSize
  1303. // to get the exact range.
  1304. const uptr ReleaseEnd =
  1305. roundUpSlow(LastGroupEnd - Region->RegionBeg, BlockSize) +
  1306. Region->RegionBeg;
  1307. const uptr ReleaseRangeSize = ReleaseEnd - ReleaseBase;
  1308. const uptr ReleaseOffset = ReleaseBase - Region->RegionBeg;
  1309. PageReleaseContext Context(BlockSize, /*NumberOfRegions=*/1U,
  1310. ReleaseRangeSize, ReleaseOffset);
  1311. // We may not be able to do the page release in a rare case that we may
  1312. // fail on PageMap allocation.
  1313. if (UNLIKELY(!Context.ensurePageMapAllocated()))
  1314. return Context;
  1315. for (BatchGroupT &BG : GroupsToRelease) {
  1316. const uptr BatchGroupBase =
  1317. decompactGroupBase(CompactPtrBase, BG.CompactPtrGroupBase);
  1318. const uptr BatchGroupEnd = BatchGroupBase + GroupSize;
  1319. const uptr AllocatedGroupSize = AllocatedUserEnd >= BatchGroupEnd
  1320. ? GroupSize
  1321. : AllocatedUserEnd - BatchGroupBase;
  1322. const uptr BatchGroupUsedEnd = BatchGroupBase + AllocatedGroupSize;
  1323. const bool MayContainLastBlockInRegion =
  1324. BatchGroupUsedEnd == AllocatedUserEnd;
  1325. const bool BlockAlignedWithUsedEnd =
  1326. (BatchGroupUsedEnd - Region->RegionBeg) % BlockSize == 0;
  1327. uptr MaxContainedBlocks = AllocatedGroupSize / BlockSize;
  1328. if (!BlockAlignedWithUsedEnd)
  1329. ++MaxContainedBlocks;
  1330. const uptr NumBlocks = (BG.Batches.size() - 1) * BG.MaxCachedPerBatch +
  1331. BG.Batches.front()->getCount();
  1332. if (NumBlocks == MaxContainedBlocks) {
  1333. for (const auto &It : BG.Batches) {
  1334. if (&It != BG.Batches.front())
  1335. DCHECK_EQ(It.getCount(), BG.MaxCachedPerBatch);
  1336. for (u16 I = 0; I < It.getCount(); ++I)
  1337. DCHECK_EQ(compactPtrGroup(It.get(I)), BG.CompactPtrGroupBase);
  1338. }
  1339. Context.markRangeAsAllCounted(BatchGroupBase, BatchGroupUsedEnd,
  1340. Region->RegionBeg, /*RegionIndex=*/0,
  1341. Region->MemMapInfo.AllocatedUser);
  1342. } else {
  1343. DCHECK_LT(NumBlocks, MaxContainedBlocks);
  1344. // Note that we don't always visit blocks in each BatchGroup so that we
  1345. // may miss the chance of releasing certain pages that cross
  1346. // BatchGroups.
  1347. Context.markFreeBlocksInRegion(
  1348. BG.Batches, DecompactPtr, Region->RegionBeg, /*RegionIndex=*/0,
  1349. Region->MemMapInfo.AllocatedUser, MayContainLastBlockInRegion);
  1350. }
  1351. }
  1352. DCHECK(Context.hasBlockMarked());
  1353. return Context;
  1354. }
  1355. void mergeGroupsToReleaseBack(RegionInfo *Region,
  1356. SinglyLinkedList<BatchGroupT> &GroupsToRelease)
  1357. REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {
  1358. ScopedLock L(Region->FLLock);
  1359. // After merging two freelists, we may have redundant `BatchGroup`s that
  1360. // need to be recycled. The number of unused `BatchGroup`s is expected to be
  1361. // small. Pick a constant which is inferred from real programs.
  1362. constexpr uptr MaxUnusedSize = 8;
  1363. CompactPtrT Blocks[MaxUnusedSize];
  1364. u32 Idx = 0;
  1365. RegionInfo *BatchClassRegion = getRegionInfo(SizeClassMap::BatchClassId);
  1366. // We can't call pushBatchClassBlocks() to recycle the unused `BatchGroup`s
  1367. // when we are manipulating the freelist of `BatchClassRegion`. Instead, we
  1368. // should just push it back to the freelist when we merge two `BatchGroup`s.
  1369. // This logic hasn't been implemented because we haven't supported releasing
  1370. // pages in `BatchClassRegion`.
  1371. DCHECK_NE(BatchClassRegion, Region);
  1372. // Merge GroupsToRelease back to the Region::FreeListInfo.BlockList. Note
  1373. // that both `Region->FreeListInfo.BlockList` and `GroupsToRelease` are
  1374. // sorted.
  1375. for (BatchGroupT *BG = Region->FreeListInfo.BlockList.front(),
  1376. *Prev = nullptr;
  1377. ;) {
  1378. if (BG == nullptr || GroupsToRelease.empty()) {
  1379. if (!GroupsToRelease.empty())
  1380. Region->FreeListInfo.BlockList.append_back(&GroupsToRelease);
  1381. break;
  1382. }
  1383. DCHECK(!BG->Batches.empty());
  1384. if (BG->CompactPtrGroupBase <
  1385. GroupsToRelease.front()->CompactPtrGroupBase) {
  1386. Prev = BG;
  1387. BG = BG->Next;
  1388. continue;
  1389. }
  1390. BatchGroupT *Cur = GroupsToRelease.front();
  1391. TransferBatchT *UnusedTransferBatch = nullptr;
  1392. GroupsToRelease.pop_front();
  1393. if (BG->CompactPtrGroupBase == Cur->CompactPtrGroupBase) {
  1394. BG->PushedBlocks += Cur->PushedBlocks;
  1395. // We have updated `BatchGroup::BytesInBGAtLastCheckpoint` while
  1396. // collecting the `GroupsToRelease`.
  1397. BG->BytesInBGAtLastCheckpoint = Cur->BytesInBGAtLastCheckpoint;
  1398. const uptr MaxCachedPerBatch = BG->MaxCachedPerBatch;
  1399. // Note that the first TransferBatches in both `Batches` may not be
  1400. // full and only the first TransferBatch can have non-full blocks. Thus
  1401. // we have to merge them before appending one to another.
  1402. if (Cur->Batches.front()->getCount() == MaxCachedPerBatch) {
  1403. BG->Batches.append_back(&Cur->Batches);
  1404. } else {
  1405. TransferBatchT *NonFullBatch = Cur->Batches.front();
  1406. Cur->Batches.pop_front();
  1407. const u16 NonFullBatchCount = NonFullBatch->getCount();
  1408. // The remaining Batches in `Cur` are full.
  1409. BG->Batches.append_back(&Cur->Batches);
  1410. if (BG->Batches.front()->getCount() == MaxCachedPerBatch) {
  1411. // Only 1 non-full TransferBatch, push it to the front.
  1412. BG->Batches.push_front(NonFullBatch);
  1413. } else {
  1414. const u16 NumBlocksToMove = static_cast<u16>(
  1415. Min(static_cast<u16>(MaxCachedPerBatch -
  1416. BG->Batches.front()->getCount()),
  1417. NonFullBatchCount));
  1418. BG->Batches.front()->appendFromTransferBatch(NonFullBatch,
  1419. NumBlocksToMove);
  1420. if (NonFullBatch->isEmpty())
  1421. UnusedTransferBatch = NonFullBatch;
  1422. else
  1423. BG->Batches.push_front(NonFullBatch);
  1424. }
  1425. }
  1426. const u32 NeededSlots = UnusedTransferBatch == nullptr ? 1U : 2U;
  1427. if (UNLIKELY(Idx + NeededSlots > MaxUnusedSize)) {
  1428. ScopedLock L(BatchClassRegion->FLLock);
  1429. pushBatchClassBlocks(BatchClassRegion, Blocks, Idx);
  1430. if (conditionVariableEnabled())
  1431. BatchClassRegion->FLLockCV.notifyAll(BatchClassRegion->FLLock);
  1432. Idx = 0;
  1433. }
  1434. Blocks[Idx++] =
  1435. compactPtr(SizeClassMap::BatchClassId, reinterpret_cast<uptr>(Cur));
  1436. if (UnusedTransferBatch) {
  1437. Blocks[Idx++] =
  1438. compactPtr(SizeClassMap::BatchClassId,
  1439. reinterpret_cast<uptr>(UnusedTransferBatch));
  1440. }
  1441. Prev = BG;
  1442. BG = BG->Next;
  1443. continue;
  1444. }
  1445. // At here, the `BG` is the first BatchGroup with CompactPtrGroupBase
  1446. // larger than the first element in `GroupsToRelease`. We need to insert
  1447. // `GroupsToRelease::front()` (which is `Cur` below) before `BG`.
  1448. //
  1449. // 1. If `Prev` is nullptr, we simply push `Cur` to the front of
  1450. // FreeListInfo.BlockList.
  1451. // 2. Otherwise, use `insert()` which inserts an element next to `Prev`.
  1452. //
  1453. // Afterwards, we don't need to advance `BG` because the order between
  1454. // `BG` and the new `GroupsToRelease::front()` hasn't been checked.
  1455. if (Prev == nullptr)
  1456. Region->FreeListInfo.BlockList.push_front(Cur);
  1457. else
  1458. Region->FreeListInfo.BlockList.insert(Prev, Cur);
  1459. DCHECK_EQ(Cur->Next, BG);
  1460. Prev = Cur;
  1461. }
  1462. if (Idx != 0) {
  1463. ScopedLock L(BatchClassRegion->FLLock);
  1464. pushBatchClassBlocks(BatchClassRegion, Blocks, Idx);
  1465. if (conditionVariableEnabled())
  1466. BatchClassRegion->FLLockCV.notifyAll(BatchClassRegion->FLLock);
  1467. }
  1468. if (SCUDO_DEBUG) {
  1469. BatchGroupT *Prev = Region->FreeListInfo.BlockList.front();
  1470. for (BatchGroupT *Cur = Prev->Next; Cur != nullptr;
  1471. Prev = Cur, Cur = Cur->Next) {
  1472. CHECK_LT(Prev->CompactPtrGroupBase, Cur->CompactPtrGroupBase);
  1473. }
  1474. }
  1475. if (conditionVariableEnabled())
  1476. Region->FLLockCV.notifyAll(Region->FLLock);
  1477. }
  1478. // TODO: `PrimaryBase` can be obtained from ReservedMemory. This needs to be
  1479. // deprecated.
  1480. uptr PrimaryBase = 0;
  1481. ReservedMemoryT ReservedMemory = {};
  1482. // The minimum size of pushed blocks that we will try to release the pages in
  1483. // that size class.
  1484. uptr SmallerBlockReleasePageDelta = 0;
  1485. atomic_s32 ReleaseToOsIntervalMs = {};
  1486. alignas(SCUDO_CACHE_LINE_SIZE) RegionInfo RegionInfoArray[NumClasses];
  1487. };
  1488. } // namespace scudo
  1489. #endif // SCUDO_PRIMARY64_H_