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
9#ifndef SCUDO_PRIMARY64_H_
10#define SCUDO_PRIMARY64_H_
11
12#include "allocator_common.h"
13#include "bytemap.h"
14#include "common.h"
15#include "condition_variable.h"
16#include "list.h"
17#include "mem_map.h"
18#include "memtag.h"
19#include "options.h"
20#include "release.h"
21#include "size_class_allocator.h"
22#include "stats.h"
23#include "string_utils.h"
24#include "thread_annotations.h"
25#include "tracing.h"
26
27#include <inttypes.h>
28
29namespace scudo {
30
31// SizeClassAllocator64 is an allocator tuned for 64-bit address space.
32//
33// It starts by reserving NumClasses * 2^RegionSizeLog bytes, equally divided in
34// Regions, specific to each size class. Note that the base of that mapping is
35// random (based to the platform specific map() capabilities). If
36// PrimaryEnableRandomOffset is set, each Region actually starts at a random
37// offset from its base.
38//
39// Regions are mapped incrementally on demand to fulfill allocation requests,
40// those mappings being split into equally sized Blocks based on the size class
41// they belong to. The Blocks created are shuffled to prevent predictable
42// address patterns (the predictability increases with the size of the Blocks).
43//
44// The 1st Region (for size class 0) holds the Batches. This is a
45// structure used to transfer arrays of available pointers from the class size
46// freelist to the thread specific freelist, and back.
47//
48// The memory used by this allocator is never unmapped, but can be partially
49// released if the platform allows for it.
50
51template <typename Config> class SizeClassAllocator64 {
52public:
53 typedef typename Config::CompactPtrT CompactPtrT;
54 typedef typename Config::SizeClassMap SizeClassMap;
55 typedef typename Config::ConditionVariableT ConditionVariableT;
56 static const uptr CompactPtrScale = Config::getCompactPtrScale();
57 static const uptr RegionSizeLog = Config::getRegionSizeLog();
58 static const uptr GroupSizeLog = Config::getGroupSizeLog();
59 static_assert(RegionSizeLog >= GroupSizeLog,
60 "Group size shouldn't be greater than the region size");
61 static const uptr GroupScale = GroupSizeLog - CompactPtrScale;
62 typedef SizeClassAllocator64<Config> ThisT;
63 typedef Batch<ThisT> BatchT;
64 typedef BatchGroup<ThisT> BatchGroupT;
65 using SizeClassAllocatorT =
66 typename Conditional<Config::getEnableBlockCache(),
67 SizeClassAllocatorLocalCache<ThisT>,
68 SizeClassAllocatorNoCache<ThisT>>::type;
69 static const u16 MaxNumBlocksInBatch = SizeClassMap::MaxNumCachedHint;
70
71 static constexpr uptr getSizeOfBatchClass() {
72 const uptr HeaderSize = sizeof(BatchT);
73 return roundUp(X: HeaderSize + sizeof(CompactPtrT) * MaxNumBlocksInBatch,
74 Boundary: 1 << CompactPtrScale);
75 }
76
77 static_assert(sizeof(BatchGroupT) <= getSizeOfBatchClass(),
78 "BatchGroupT also uses BatchClass");
79
80 // BachClass is used to store internal metadata so it needs to be at least as
81 // large as the largest data structure.
82 static uptr getSizeByClassId(uptr ClassId) {
83 return (ClassId == SizeClassMap::BatchClassId)
84 ? getSizeOfBatchClass()
85 : SizeClassMap::getSizeByClassId(ClassId);
86 }
87
88 static bool canAllocate(uptr Size) { return Size <= SizeClassMap::MaxSize; }
89 static constexpr bool conditionVariableEnabled() {
90 return Config::hasConditionVariableT();
91 }
92
93 BlockInfo findNearestBlock(uptr Ptr);
94
95 void init(s32 ReleaseToOsInterval) NO_THREAD_SAFETY_ANALYSIS;
96
97 void unmapTestOnly();
98
99 // When all blocks are freed, it has to be the same size as `AllocatedUser`.
100 void verifyAllBlocksAreReleasedTestOnly();
101
102 u16 popBlocks(SizeClassAllocatorT *SizeClassAllocator, uptr ClassId,
103 CompactPtrT *ToArray, const u16 MaxBlockCount);
104
105 // Push the array of free blocks to the designated batch group.
106 void pushBlocks(SizeClassAllocatorT *SizeClassAllocator, uptr ClassId,
107 CompactPtrT *Array, u32 Size);
108
109 void disable() NO_THREAD_SAFETY_ANALYSIS;
110 void enable(bool IsChild) NO_THREAD_SAFETY_ANALYSIS;
111
112 template <typename F> void iterateOverBlocks(F Callback);
113
114 void getStats(ScopedString *Str);
115 void getFragmentationInfo(ScopedString *Str);
116 void getMemoryGroupFragmentationInfo(ScopedString *Str);
117
118 bool setOption(Option O, sptr Value);
119
120 // These are used for returning unused pages. Note that it doesn't unmap the
121 // pages, it only suggests that the physical pages can be released.
122 uptr tryReleaseToOS(uptr ClassId, ReleaseToOS ReleaseType);
123 uptr releaseToOS(ReleaseToOS ReleaseType);
124
125 uptr getCompactPtrBaseByClassId(uptr ClassId) {
126 return getRegionInfo(ClassId)->RegionBeg;
127 }
128
129 CompactPtrT compactPtr(uptr ClassId, uptr Ptr) {
130 DCHECK_LE(ClassId, SizeClassMap::LargestClassId);
131 return compactPtrInternal(Base: getCompactPtrBaseByClassId(ClassId), Ptr);
132 }
133
134 void *decompactPtr(uptr ClassId, CompactPtrT CompactPtr) {
135 DCHECK_LE(ClassId, SizeClassMap::LargestClassId);
136 return reinterpret_cast<void *>(
137 decompactPtrInternal(Base: getCompactPtrBaseByClassId(ClassId), CompactPtr));
138 }
139
140 AtomicOptions Options;
141
142private:
143 static const uptr RegionSize = 1UL << RegionSizeLog;
144 static const uptr NumClasses = SizeClassMap::NumClasses;
145 static const uptr MapSizeIncrement = Config::getMapSizeIncrement();
146 // Fill at most this number of batches from the newly map'd memory.
147 static const u32 MaxNumBatches = SCUDO_ANDROID ? 4U : 8U;
148
149 struct ReleaseToOsInfo {
150 uptr BytesInFreeListAtLastCheckpoint;
151 uptr NumReleasesAttempted;
152 uptr LastReleasedBytes;
153 // The minimum size of pushed blocks to trigger page release.
154 uptr TryReleaseThreshold;
155 // The number of bytes not triggering `releaseToOSMaybe()` because of
156 // the length of release interval.
157 uptr PendingPushedBytesDelta;
158 u64 LastReleaseAtNs;
159 };
160
161 struct BlocksInfo {
162 SinglyLinkedList<BatchGroupT> BlockList = {};
163 uptr PoppedBlocks = 0;
164 uptr PushedBlocks = 0;
165 };
166
167 struct PagesInfo {
168 MemMapT MemMap = {};
169 // Bytes mapped for user memory.
170 uptr MappedUser = 0;
171 // Bytes allocated for user memory.
172 uptr AllocatedUser = 0;
173 };
174
175 struct UnpaddedRegionInfo {
176 // Mutex for operations on freelist
177 HybridMutex FLLock;
178 ConditionVariableT FLLockCV GUARDED_BY(FLLock);
179 // Mutex for memmap operations
180 HybridMutex MMLock ACQUIRED_BEFORE(FLLock);
181 // `RegionBeg` is initialized before thread creation and won't be changed.
182 uptr RegionBeg = 0;
183 BlocksInfo FreeListInfo GUARDED_BY(FLLock);
184 PagesInfo MemMapInfo GUARDED_BY(MMLock);
185 ReleaseToOsInfo ReleaseInfo GUARDED_BY(MMLock) = {};
186 bool Exhausted GUARDED_BY(MMLock) = false;
187 bool IsPopulatingFreeList GUARDED_BY(FLLock) = false;
188 u16 NumWaiting GUARDED_BY(FLLock) = 0;
189 u32 RandState GUARDED_BY(MMLock) = 0;
190 };
191 struct RegionInfo : UnpaddedRegionInfo {
192 char Padding[SCUDO_CACHE_LINE_SIZE -
193 (sizeof(UnpaddedRegionInfo) % SCUDO_CACHE_LINE_SIZE)] = {};
194 };
195 static_assert(sizeof(RegionInfo) % SCUDO_CACHE_LINE_SIZE == 0, "");
196
197 template <bool ConditionVariableEnabled = false, typename Dummy = void>
198 class SCOPED_CAPABILITY ScopedFLLockBase {
199 public:
200 ScopedFLLockBase(HybridMutex &M, UNUSED RegionInfo *Region) ACQUIRE(M)
201 : Mutex(M) {
202 Mutex.lock();
203 }
204 ~ScopedFLLockBase() RELEASE() { Mutex.unlock(); }
205
206 private:
207 HybridMutex &Mutex;
208
209 ScopedFLLockBase(const ScopedFLLockBase &) = delete;
210 void operator=(const ScopedFLLockBase &) = delete;
211 };
212
213 template <typename Dummy>
214 class SCOPED_CAPABILITY ScopedFLLockBase<true, Dummy> {
215 public:
216 ScopedFLLockBase(HybridMutex &M, RegionInfo *Region) ACQUIRE(M)
217 : Mutex(M), Region(Region) {
218 Mutex.lock();
219 }
220 ~ScopedFLLockBase() RELEASE() {
221 if (Region->NumWaiting > 0)
222 Region->FLLockCV.notifyAll(Mutex);
223 Mutex.unlock();
224 }
225
226 private:
227 HybridMutex &Mutex;
228 RegionInfo *Region;
229
230 ScopedFLLockBase(const ScopedFLLockBase &) = delete;
231 void operator=(const ScopedFLLockBase &) = delete;
232 };
233
234 using ScopedFLLock = ScopedFLLockBase<conditionVariableEnabled()>;
235
236 RegionInfo *getRegionInfo(uptr ClassId) {
237 DCHECK_LT(ClassId, NumClasses);
238 return &RegionInfoArray[ClassId];
239 }
240
241 uptr getRegionBaseByClassId(uptr ClassId) {
242 RegionInfo *Region = getRegionInfo(ClassId);
243 Region->MMLock.assertHeld();
244
245 if (!Config::getEnableContiguousRegions() &&
246 !Region->MemMapInfo.MemMap.isAllocated()) {
247 return 0U;
248 }
249 return Region->MemMapInfo.MemMap.getBase();
250 }
251
252 CompactPtrT compactPtrInternal(uptr Base, uptr Ptr) const {
253 return static_cast<CompactPtrT>((Ptr - Base) >> CompactPtrScale);
254 }
255 uptr decompactPtrInternal(uptr Base, CompactPtrT CompactPtr) const {
256 return Base + (static_cast<uptr>(CompactPtr) << CompactPtrScale);
257 }
258 uptr compactPtrGroup(CompactPtrT CompactPtr) const {
259 const uptr Mask = (static_cast<uptr>(1) << GroupScale) - 1;
260 return static_cast<uptr>(CompactPtr) & ~Mask;
261 }
262 uptr decompactGroupBase(uptr Base, uptr CompactPtrGroupBase) const {
263 DCHECK_EQ(CompactPtrGroupBase % (static_cast<uptr>(1) << (GroupScale)), 0U);
264 return Base + (CompactPtrGroupBase << CompactPtrScale);
265 }
266 ALWAYS_INLINE bool isSmallBlock(uptr BlockSize) const {
267 const uptr PageSize = getPageSizeCached();
268 return BlockSize < PageSize / 16U;
269 }
270 ALWAYS_INLINE uptr getMinReleaseAttemptSize(uptr BlockSize) {
271 return roundUp(X: BlockSize, Boundary: getPageSizeCached());
272 }
273
274 ALWAYS_INLINE void initRegion(RegionInfo *Region, uptr ClassId,
275 MemMapT MemMap, bool EnableRandomOffset)
276 REQUIRES(Region->MMLock);
277
278 void pushBlocksImpl(SizeClassAllocatorT *SizeClassAllocator, uptr ClassId,
279 RegionInfo *Region, CompactPtrT *Array, u32 Size,
280 bool SameGroup = false) REQUIRES(Region->FLLock);
281
282 // Similar to `pushBlocksImpl` but has some logics specific to BatchClass.
283 void pushBatchClassBlocks(RegionInfo *Region, CompactPtrT *Array, u32 Size)
284 REQUIRES(Region->FLLock);
285
286 // Pop at most `MaxBlockCount` from the freelist of the given region.
287 u16 popBlocksImpl(SizeClassAllocatorT *SizeClassAllocator, uptr ClassId,
288 RegionInfo *Region, CompactPtrT *ToArray,
289 const u16 MaxBlockCount) REQUIRES(Region->FLLock);
290 // Same as `popBlocksImpl` but is used when conditional variable is enabled.
291 u16 popBlocksWithCV(SizeClassAllocatorT *SizeClassAllocator, uptr ClassId,
292 RegionInfo *Region, CompactPtrT *ToArray,
293 const u16 MaxBlockCount, bool &ReportRegionExhausted);
294
295 // When there's no blocks available in the freelist, it tries to prepare more
296 // blocks by mapping more pages.
297 NOINLINE u16 populateFreeListAndPopBlocks(
298 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, RegionInfo *Region,
299 CompactPtrT *ToArray, const u16 MaxBlockCount) REQUIRES(Region->MMLock)
300 EXCLUDES(Region->FLLock);
301
302 void getStats(ScopedString *Str, uptr ClassId, RegionInfo *Region)
303 REQUIRES(Region->MMLock, Region->FLLock);
304 void getRegionFragmentationInfo(RegionInfo *Region, uptr ClassId,
305 ScopedString *Str) REQUIRES(Region->MMLock);
306 void getMemoryGroupFragmentationInfoInRegion(RegionInfo *Region, uptr ClassId,
307 ScopedString *Str)
308 REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock);
309
310 NOINLINE uptr releaseToOSMaybe(RegionInfo *Region, uptr ClassId,
311 ReleaseToOS ReleaseType = ReleaseToOS::Normal)
312 REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock);
313 bool hasChanceToReleasePages(RegionInfo *Region, uptr BlockSize,
314 uptr BytesInFreeList, ReleaseToOS ReleaseType)
315 REQUIRES(Region->MMLock, Region->FLLock);
316 SinglyLinkedList<BatchGroupT>
317 collectGroupsToRelease(RegionInfo *Region, const uptr BlockSize,
318 const uptr AllocatedUserEnd, const uptr CompactPtrBase)
319 REQUIRES(Region->MMLock, Region->FLLock);
320 PageReleaseContext
321 markFreeBlocks(RegionInfo *Region, const uptr BlockSize,
322 const uptr AllocatedUserEnd, const uptr CompactPtrBase,
323 SinglyLinkedList<BatchGroupT> &GroupsToRelease)
324 REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock);
325
326 void mergeGroupsToReleaseBack(RegionInfo *Region,
327 SinglyLinkedList<BatchGroupT> &GroupsToRelease)
328 REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock);
329
330 // The minimum size of pushed blocks that we will try to release the pages in
331 // that size class.
332 uptr SmallerBlockReleasePageDelta = 0;
333 atomic_s32 ReleaseToOsIntervalMs = {};
334 alignas(SCUDO_CACHE_LINE_SIZE) RegionInfo RegionInfoArray[NumClasses];
335};
336
337template <typename Config>
338void SizeClassAllocator64<Config>::init(s32 ReleaseToOsInterval)
339 NO_THREAD_SAFETY_ANALYSIS {
340 DCHECK(isAligned(reinterpret_cast<uptr>(this), alignof(ThisT)));
341
342 const uptr PageSize = getPageSizeCached();
343 const uptr GroupSize = (1UL << GroupSizeLog);
344 const uptr PagesInGroup = GroupSize / PageSize;
345 const uptr MinSizeClass = getSizeByClassId(ClassId: 1);
346 // When trying to release pages back to memory, visiting smaller size
347 // classes is expensive. Therefore, we only try to release smaller size
348 // classes when the amount of free blocks goes over a certain threshold (See
349 // the comment in releaseToOSMaybe() for more details). For example, for
350 // size class 32, we only do the release when the size of free blocks is
351 // greater than 97% of pages in a group. However, this may introduce another
352 // issue that if the number of free blocks is bouncing between 97% ~ 100%.
353 // Which means we may try many page releases but only release very few of
354 // them (less than 3% in a group). Even though we have
355 // `&ReleaseToOsIntervalMs` which slightly reduce the frequency of these
356 // calls but it will be better to have another guard to mitigate this issue.
357 //
358 // Here we add another constraint on the minimum size requirement. The
359 // constraint is determined by the size of in-use blocks in the minimal size
360 // class. Take size class 32 as an example,
361 //
362 // +- one memory group -+
363 // +----------------------+------+
364 // | 97% of free blocks | |
365 // +----------------------+------+
366 // \ /
367 // 3% in-use blocks
368 //
369 // * The release size threshold is 97%.
370 //
371 // The 3% size in a group is about 7 pages. For two consecutive
372 // releaseToOSMaybe(), we require the difference between `PushedBlocks`
373 // should be greater than 7 pages. This mitigates the page releasing
374 // thrashing which is caused by memory usage bouncing around the threshold.
375 // The smallest size class takes longest time to do the page release so we
376 // use its size of in-use blocks as a heuristic.
377 SmallerBlockReleasePageDelta = PagesInGroup * (1 + MinSizeClass / 16U) / 100;
378
379 u32 Seed;
380 const u64 Time = getMonotonicTimeFast();
381 if (!getRandom(Buffer: reinterpret_cast<void *>(&Seed), Length: sizeof(Seed)))
382 Seed = static_cast<u32>(Time ^ (reinterpret_cast<uptr>(&Seed) >> 12));
383
384 for (uptr I = 0; I < NumClasses; I++)
385 getRegionInfo(ClassId: I)->RandState = getRandomU32(State: &Seed);
386
387 if (Config::getEnableContiguousRegions()) {
388 ReservedMemoryT ReservedMemory = {};
389 // Reserve the space required for the Primary.
390 CHECK(ReservedMemory.create(/*Addr=*/0U, RegionSize * NumClasses,
391 "scudo:primary_reserve"));
392 const uptr PrimaryBase = ReservedMemory.getBase();
393
394 for (uptr I = 0; I < NumClasses; I++) {
395 MemMapT RegionMemMap = ReservedMemory.dispatch(
396 Addr: PrimaryBase + (I << RegionSizeLog), Size: RegionSize);
397 RegionInfo *Region = getRegionInfo(ClassId: I);
398
399 initRegion(Region, ClassId: I, MemMap: RegionMemMap, EnableRandomOffset: Config::getEnableRandomOffset());
400 }
401 shuffle(RegionInfoArray, NumClasses, &Seed);
402 }
403
404 if constexpr (SCUDO_DEBUG && conditionVariableEnabled()) {
405 // The binding should be done after region shuffling so that it won't bind
406 // the FLLock from the wrong region.
407 for (uptr I = 0; I < NumClasses; I++)
408 getRegionInfo(ClassId: I)->FLLockCV.bindTestOnly(getRegionInfo(ClassId: I)->FLLock);
409 }
410
411 // The default value in the primary config has the higher priority.
412 if (Config::getDefaultReleaseToOsIntervalMs() != INT32_MIN)
413 ReleaseToOsInterval = Config::getDefaultReleaseToOsIntervalMs();
414 setOption(O: Option::ReleaseInterval, Value: static_cast<sptr>(ReleaseToOsInterval));
415}
416
417template <typename Config>
418void SizeClassAllocator64<Config>::initRegion(RegionInfo *Region, uptr ClassId,
419 MemMapT MemMap,
420 bool EnableRandomOffset)
421 REQUIRES(Region->MMLock) {
422 DCHECK(!Region->MemMapInfo.MemMap.isAllocated());
423 DCHECK(MemMap.isAllocated());
424
425 const uptr PageSize = getPageSizeCached();
426
427 Region->MemMapInfo.MemMap = MemMap;
428
429 Region->RegionBeg = MemMap.getBase();
430 if (EnableRandomOffset) {
431 Region->RegionBeg += (getRandomModN(&Region->RandState, 16) + 1) * PageSize;
432 }
433
434 const uptr BlockSize = getSizeByClassId(ClassId);
435 // Releasing small blocks is expensive, set a higher threshold to avoid
436 // frequent page releases.
437 if (isSmallBlock(BlockSize)) {
438 Region->ReleaseInfo.TryReleaseThreshold =
439 PageSize * SmallerBlockReleasePageDelta;
440 } else {
441 Region->ReleaseInfo.TryReleaseThreshold =
442 getMinReleaseAttemptSize(BlockSize);
443 }
444}
445
446template <typename Config> void SizeClassAllocator64<Config>::unmapTestOnly() {
447 for (uptr I = 0; I < NumClasses; I++) {
448 RegionInfo *Region = getRegionInfo(ClassId: I);
449 {
450 ScopedLock ML(Region->MMLock);
451 MemMapT MemMap = Region->MemMapInfo.MemMap;
452 if (MemMap.isAllocated())
453 MemMap.unmap();
454 }
455 *Region = {};
456 }
457}
458
459template <typename Config>
460void SizeClassAllocator64<Config>::verifyAllBlocksAreReleasedTestOnly() {
461 // `BatchGroup` and `Batch` also use the blocks from BatchClass.
462 uptr BatchClassUsedInFreeLists = 0;
463 for (uptr I = 0; I < NumClasses; I++) {
464 // We have to count BatchClassUsedInFreeLists in other regions first.
465 if (I == SizeClassMap::BatchClassId)
466 continue;
467 RegionInfo *Region = getRegionInfo(ClassId: I);
468 ScopedLock ML(Region->MMLock);
469 ScopedFLLock FL(Region->FLLock, Region);
470 const uptr BlockSize = getSizeByClassId(ClassId: I);
471 uptr TotalBlocks = 0;
472 for (BatchGroupT &BG : Region->FreeListInfo.BlockList) {
473 // `BG::Batches` are `Batches`. +1 for `BatchGroup`.
474 BatchClassUsedInFreeLists += BG.Batches.size() + 1;
475 for (const auto &It : BG.Batches)
476 TotalBlocks += It.getCount();
477 }
478
479 DCHECK_EQ(TotalBlocks, Region->MemMapInfo.AllocatedUser / BlockSize);
480 DCHECK_EQ(Region->FreeListInfo.PushedBlocks,
481 Region->FreeListInfo.PoppedBlocks);
482 }
483
484 RegionInfo *Region = getRegionInfo(ClassId: SizeClassMap::BatchClassId);
485 ScopedLock ML(Region->MMLock);
486 ScopedFLLock FL(Region->FLLock, Region);
487 const uptr BlockSize = getSizeByClassId(ClassId: SizeClassMap::BatchClassId);
488 uptr TotalBlocks = 0;
489 for (BatchGroupT &BG : Region->FreeListInfo.BlockList) {
490 if (LIKELY(!BG.Batches.empty())) {
491 for (const auto &It : BG.Batches)
492 TotalBlocks += It.getCount();
493 } else {
494 // `BatchGroup` with empty freelist doesn't have `Batch` record
495 // itself.
496 ++TotalBlocks;
497 }
498 }
499 DCHECK_EQ(TotalBlocks + BatchClassUsedInFreeLists,
500 Region->MemMapInfo.AllocatedUser / BlockSize);
501 DCHECK_GE(Region->FreeListInfo.PoppedBlocks,
502 Region->FreeListInfo.PushedBlocks);
503 const uptr BlocksInUse =
504 Region->FreeListInfo.PoppedBlocks - Region->FreeListInfo.PushedBlocks;
505 DCHECK_EQ(BlocksInUse, BatchClassUsedInFreeLists);
506}
507
508template <typename Config>
509u16 SizeClassAllocator64<Config>::popBlocks(
510 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, CompactPtrT *ToArray,
511 const u16 MaxBlockCount) {
512 DCHECK_LT(ClassId, NumClasses);
513 RegionInfo *Region = getRegionInfo(ClassId);
514 u16 PopCount = 0;
515
516 {
517 ScopedFLLock FL(Region->FLLock, Region);
518 PopCount = popBlocksImpl(SizeClassAllocator, ClassId, Region, ToArray,
519 MaxBlockCount);
520 if (PopCount != 0U)
521 return PopCount;
522 }
523
524 bool ReportRegionExhausted = false;
525
526 if constexpr (conditionVariableEnabled()) {
527 PopCount = popBlocksWithCV(SizeClassAllocator, ClassId, Region, ToArray,
528 MaxBlockCount, ReportRegionExhausted);
529 } else {
530 while (true) {
531 // When two threads compete for `Region->MMLock`, we only want one of
532 // them to call populateFreeListAndPopBlocks(). To avoid both of them
533 // doing that, always check the freelist before mapping new pages.
534 ScopedLock ML(Region->MMLock);
535 {
536 ScopedFLLock FL(Region->FLLock, Region);
537 PopCount = popBlocksImpl(SizeClassAllocator, ClassId, Region, ToArray,
538 MaxBlockCount);
539 if (PopCount != 0U)
540 return PopCount;
541 }
542
543 const bool RegionIsExhausted = Region->Exhausted;
544 if (!RegionIsExhausted) {
545 PopCount = populateFreeListAndPopBlocks(SizeClassAllocator, ClassId,
546 Region, ToArray, MaxBlockCount);
547 }
548 ReportRegionExhausted = !RegionIsExhausted && Region->Exhausted;
549 break;
550 }
551 }
552
553 if (UNLIKELY(ReportRegionExhausted)) {
554 Printf(Format: "Can't populate more pages for size class %zu.\n",
555 getSizeByClassId(ClassId));
556
557 // Theoretically, BatchClass shouldn't be used up. Abort immediately when
558 // it happens.
559 if (ClassId == SizeClassMap::BatchClassId)
560 reportOutOfBatchClass();
561 }
562
563 return PopCount;
564}
565
566template <typename Config>
567u16 SizeClassAllocator64<Config>::popBlocksWithCV(
568 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, RegionInfo *Region,
569 CompactPtrT *ToArray, const u16 MaxBlockCount,
570 bool &ReportRegionExhausted) {
571 u16 PopCount = 0;
572
573 while (true) {
574 // We only expect one thread doing the freelist refillment and other
575 // threads will be waiting for either the completion of the
576 // `populateFreeListAndPopBlocks()` or `pushBlocks()` called by other
577 // threads.
578 bool PopulateFreeList = false;
579 {
580 ScopedFLLock FL(Region->FLLock, Region);
581 if (!Region->IsPopulatingFreeList) {
582 Region->IsPopulatingFreeList = true;
583 PopulateFreeList = true;
584 }
585 }
586
587 if (PopulateFreeList) {
588 ScopedLock ML(Region->MMLock);
589
590 const bool RegionIsExhausted = Region->Exhausted;
591 if (!RegionIsExhausted) {
592 PopCount = populateFreeListAndPopBlocks(SizeClassAllocator, ClassId,
593 Region, ToArray, MaxBlockCount);
594 }
595 ReportRegionExhausted = !RegionIsExhausted && Region->Exhausted;
596
597 {
598 // Before reacquiring the `FLLock`, the freelist may be used up again
599 // and some threads are waiting for the freelist refillment by the
600 // current thread. It's important to set
601 // `Region->IsPopulatingFreeList` to false so the threads about to
602 // sleep will notice the status change.
603 ScopedFLLock FL(Region->FLLock, Region);
604 Region->IsPopulatingFreeList = false;
605 }
606
607 break;
608 }
609
610 // At here, there are two preconditions to be met before waiting,
611 // 1. The freelist is empty.
612 // 2. Region->IsPopulatingFreeList == true, i.e, someone is still doing
613 // `populateFreeListAndPopBlocks()`.
614 //
615 // Note that it has the chance that freelist is empty but
616 // Region->IsPopulatingFreeList == false because all the new populated
617 // blocks were used up right after the refillment. Therefore, we have to
618 // check if someone is still populating the freelist.
619 ScopedFLLock FL(Region->FLLock, Region);
620 PopCount = popBlocksImpl(SizeClassAllocator, ClassId, Region, ToArray,
621 MaxBlockCount);
622 if (PopCount != 0U)
623 break;
624
625 if (!Region->IsPopulatingFreeList)
626 continue;
627
628 // Now the freelist is empty and someone's doing the refillment. We will
629 // wait until anyone refills the freelist or someone finishes doing
630 // `populateFreeListAndPopBlocks()`. The refillment can be done by
631 // `populateFreeListAndPopBlocks()`, `pushBlocks()`,
632 // `pushBatchClassBlocks()` and `mergeGroupsToReleaseBack()`.
633 ++Region->NumWaiting;
634 Region->FLLockCV.wait(Region->FLLock);
635 --Region->NumWaiting;
636
637 PopCount = popBlocksImpl(SizeClassAllocator, ClassId, Region, ToArray,
638 MaxBlockCount);
639 if (PopCount != 0U)
640 break;
641 }
642
643 return PopCount;
644}
645
646template <typename Config>
647u16 SizeClassAllocator64<Config>::popBlocksImpl(
648 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, RegionInfo *Region,
649 CompactPtrT *ToArray, const u16 MaxBlockCount) REQUIRES(Region->FLLock) {
650 if (Region->FreeListInfo.BlockList.empty())
651 return 0U;
652
653 SinglyLinkedList<BatchT> &Batches =
654 Region->FreeListInfo.BlockList.front()->Batches;
655
656 if (Batches.empty()) {
657 DCHECK_EQ(ClassId, SizeClassMap::BatchClassId);
658 BatchGroupT *BG = Region->FreeListInfo.BlockList.front();
659 Region->FreeListInfo.BlockList.pop_front();
660
661 // Block used by `BatchGroup` is from BatchClassId. Turn the block into
662 // `Batch` with single block.
663 BatchT *TB = reinterpret_cast<BatchT *>(BG);
664 ToArray[0] =
665 compactPtr(ClassId: SizeClassMap::BatchClassId, Ptr: reinterpret_cast<uptr>(TB));
666 Region->FreeListInfo.PoppedBlocks += 1;
667 return 1U;
668 }
669
670 // So far, instead of always filling blocks to `MaxBlockCount`, we only
671 // examine single `Batch` to minimize the time spent in the primary
672 // allocator. Besides, the sizes of `Batch` and
673 // `SizeClassAllocatorT::getMaxCached()` may also impact the time spent on
674 // accessing the primary allocator.
675 // TODO(chiahungduan): Evaluate if we want to always prepare `MaxBlockCount`
676 // blocks and/or adjust the size of `Batch` according to
677 // `SizeClassAllocatorT::getMaxCached()`.
678 BatchT *B = Batches.front();
679 DCHECK_NE(B, nullptr);
680 DCHECK_GT(B->getCount(), 0U);
681
682 // BachClassId should always take all blocks in the Batch. Read the
683 // comment in `pushBatchClassBlocks()` for more details.
684 const u16 PopCount = ClassId == SizeClassMap::BatchClassId
685 ? B->getCount()
686 : Min(MaxBlockCount, B->getCount());
687 B->moveNToArray(ToArray, PopCount);
688
689 // TODO(chiahungduan): The deallocation of unused BatchClassId blocks can be
690 // done without holding `FLLock`.
691 if (B->empty()) {
692 Batches.pop_front();
693 // `Batch` of BatchClassId is self-contained, no need to
694 // deallocate. Read the comment in `pushBatchClassBlocks()` for more
695 // details.
696 if (ClassId != SizeClassMap::BatchClassId)
697 SizeClassAllocator->deallocate(SizeClassMap::BatchClassId, B);
698
699 if (Batches.empty()) {
700 BatchGroupT *BG = Region->FreeListInfo.BlockList.front();
701 Region->FreeListInfo.BlockList.pop_front();
702
703 // We don't keep BatchGroup with zero blocks to avoid empty-checking
704 // while allocating. Note that block used for constructing BatchGroup is
705 // recorded as free blocks in the last element of BatchGroup::Batches.
706 // Which means, once we pop the last Batch, the block is
707 // implicitly deallocated.
708 if (ClassId != SizeClassMap::BatchClassId)
709 SizeClassAllocator->deallocate(SizeClassMap::BatchClassId, BG);
710 }
711 }
712
713 Region->FreeListInfo.PoppedBlocks += PopCount;
714
715 return PopCount;
716}
717
718template <typename Config>
719u16 SizeClassAllocator64<Config>::populateFreeListAndPopBlocks(
720 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, RegionInfo *Region,
721 CompactPtrT *ToArray, const u16 MaxBlockCount) REQUIRES(Region->MMLock)
722 EXCLUDES(Region->FLLock) {
723 if (!Config::getEnableContiguousRegions() &&
724 !Region->MemMapInfo.MemMap.isAllocated()) {
725 ReservedMemoryT ReservedMemory;
726 if (UNLIKELY(!ReservedMemory.create(/*Addr=*/0U, RegionSize,
727 "scudo:primary_reserve",
728 MAP_ALLOWNOMEM))) {
729 Printf(Format: "Can't reserve pages for size class %zu.\n",
730 getSizeByClassId(ClassId));
731 return 0U;
732 }
733 initRegion(Region, ClassId,
734 MemMap: ReservedMemory.dispatch(Addr: ReservedMemory.getBase(),
735 Size: ReservedMemory.getCapacity()),
736 /*EnableRandomOffset=*/EnableRandomOffset: false);
737 }
738
739 DCHECK(Region->MemMapInfo.MemMap.isAllocated());
740 const uptr Size = getSizeByClassId(ClassId);
741 const u16 MaxCount = SizeClassAllocatorT::getMaxCached(Size);
742 const uptr RegionBeg = Region->RegionBeg;
743 const uptr MappedUser = Region->MemMapInfo.MappedUser;
744 const uptr TotalUserBytes =
745 Region->MemMapInfo.AllocatedUser + MaxCount * Size;
746 // Map more space for blocks, if necessary.
747 if (TotalUserBytes > MappedUser) {
748 // Do the mmap for the user memory.
749 const uptr MapSize = roundUp(X: TotalUserBytes - MappedUser, Boundary: MapSizeIncrement);
750 const uptr RegionBase = RegionBeg - getRegionBaseByClassId(ClassId);
751 if (UNLIKELY(RegionBase + MappedUser + MapSize > RegionSize)) {
752 Region->Exhausted = true;
753 return 0U;
754 }
755
756 if (UNLIKELY(!Region->MemMapInfo.MemMap.remap(
757 RegionBeg + MappedUser, MapSize, "scudo:primary",
758 MAP_ALLOWNOMEM | MAP_RESIZABLE |
759 (useMemoryTagging<Config>(Options.load()) ? MAP_MEMTAG : 0)))) {
760 return 0U;
761 }
762 Region->MemMapInfo.MappedUser += MapSize;
763 SizeClassAllocator->getStats().add(StatMapped, MapSize);
764 }
765
766 const u32 NumberOfBlocks =
767 Min(A: MaxNumBatches * MaxCount,
768 B: static_cast<u32>((Region->MemMapInfo.MappedUser -
769 Region->MemMapInfo.AllocatedUser) /
770 Size));
771 DCHECK_GT(NumberOfBlocks, 0);
772
773 constexpr u32 ShuffleArraySize = MaxNumBatches * MaxNumBlocksInBatch;
774 CompactPtrT ShuffleArray[ShuffleArraySize];
775 DCHECK_LE(NumberOfBlocks, ShuffleArraySize);
776
777 const uptr CompactPtrBase = getCompactPtrBaseByClassId(ClassId);
778 uptr P = RegionBeg + Region->MemMapInfo.AllocatedUser;
779 for (u32 I = 0; I < NumberOfBlocks; I++, P += Size)
780 ShuffleArray[I] = compactPtrInternal(Base: CompactPtrBase, Ptr: P);
781
782 ScopedFLLock FL(Region->FLLock, Region);
783 if (ClassId != SizeClassMap::BatchClassId) {
784 u32 N = 1;
785 uptr CurGroup = compactPtrGroup(CompactPtr: ShuffleArray[0]);
786 for (u32 I = 1; I < NumberOfBlocks; I++) {
787 if (UNLIKELY(compactPtrGroup(ShuffleArray[I]) != CurGroup)) {
788 shuffle(ShuffleArray + I - N, N, &Region->RandState);
789 pushBlocksImpl(SizeClassAllocator, ClassId, Region,
790 Array: ShuffleArray + I - N, Size: N,
791 /*SameGroup=*/SameGroup: true);
792 N = 1;
793 CurGroup = compactPtrGroup(CompactPtr: ShuffleArray[I]);
794 } else {
795 ++N;
796 }
797 }
798
799 shuffle(ShuffleArray + NumberOfBlocks - N, N, &Region->RandState);
800 pushBlocksImpl(SizeClassAllocator, ClassId, Region,
801 Array: &ShuffleArray[NumberOfBlocks - N], Size: N,
802 /*SameGroup=*/SameGroup: true);
803 } else {
804 pushBatchClassBlocks(Region, Array: ShuffleArray, Size: NumberOfBlocks);
805 }
806
807 const u16 PopCount = popBlocksImpl(SizeClassAllocator, ClassId, Region,
808 ToArray, MaxBlockCount);
809 DCHECK_NE(PopCount, 0U);
810
811 // Note that `PushedBlocks` and `PoppedBlocks` are supposed to only record
812 // the requests from `PushBlocks` and `PopBatch` which are external
813 // interfaces. `populateFreeListAndPopBlocks` is the internal interface so
814 // we should set the values back to avoid incorrectly setting the stats.
815 Region->FreeListInfo.PushedBlocks -= NumberOfBlocks;
816
817 const uptr AllocatedUser = Size * NumberOfBlocks;
818 SizeClassAllocator->getStats().add(StatFree, AllocatedUser);
819 Region->MemMapInfo.AllocatedUser += AllocatedUser;
820
821 return PopCount;
822}
823
824template <typename Config>
825void SizeClassAllocator64<Config>::pushBlocks(
826 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, CompactPtrT *Array,
827 u32 Size) {
828 DCHECK_LT(ClassId, NumClasses);
829 DCHECK_GT(Size, 0);
830
831 RegionInfo *Region = getRegionInfo(ClassId);
832 if (ClassId == SizeClassMap::BatchClassId) {
833 ScopedFLLock FL(Region->FLLock, Region);
834 pushBatchClassBlocks(Region, Array, Size);
835 return;
836 }
837
838 // TODO(chiahungduan): Consider not doing grouping if the group size is not
839 // greater than the block size with a certain scale.
840 bool SameGroup = true;
841 if (GroupSizeLog < RegionSizeLog && Size > 1) {
842 // Sort the blocks such that blocks belonging to the same group are
843 // ordered together.
844 uptr FirstPtrGroup = compactPtrGroup(CompactPtr: Array[0]);
845 for (u32 I = 1; I < Size; ++I) {
846 CompactPtrT Cur = Array[I];
847 uptr CurPtrGroup = compactPtrGroup(CompactPtr: Cur);
848 SameGroup = SameGroup && CurPtrGroup == FirstPtrGroup;
849 if (!SameGroup) {
850 // Sorting only necessary if there are different groups.
851 u32 J = I;
852 while (J > 0 && CurPtrGroup < compactPtrGroup(CompactPtr: Array[J - 1])) {
853 Array[J] = Array[J - 1];
854 --J;
855 }
856 Array[J] = Cur;
857 }
858 }
859 }
860
861 {
862 ScopedFLLock FL(Region->FLLock, Region);
863 pushBlocksImpl(SizeClassAllocator, ClassId, Region, Array, Size, SameGroup);
864 }
865}
866
867// Push the blocks to their batch group. The layout will be like,
868//
869// FreeListInfo.BlockList - > BG -> BG -> BG
870// | | |
871// v v v
872// TB TB TB
873// |
874// v
875// TB
876//
877// Each BlockGroup(BG) will associate with unique group id and the free blocks
878// are managed by a list of Batch(TB). To reduce the time of inserting blocks,
879// BGs are sorted and the input `Array` are supposed to be sorted so that we can
880// get better performance of maintaining sorted property. Use `SameGroup=true`
881// to indicate that all blocks in the array are from the same group then we will
882// skip checking the group id of each block.
883template <typename Config>
884void SizeClassAllocator64<Config>::pushBlocksImpl(
885 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, RegionInfo *Region,
886 CompactPtrT *Array, u32 Size, bool SameGroup) REQUIRES(Region->FLLock) {
887 DCHECK_NE(ClassId, SizeClassMap::BatchClassId);
888 DCHECK_GT(Size, 0U);
889
890 auto CreateGroup = [&](uptr CompactPtrGroupBase) {
891 BatchGroupT *BG = reinterpret_cast<BatchGroupT *>(
892 SizeClassAllocator->getBatchClassBlock());
893 BG->Batches.clear();
894 BatchT *TB =
895 reinterpret_cast<BatchT *>(SizeClassAllocator->getBatchClassBlock());
896 TB->clear();
897
898 BG->CompactPtrGroupBase = CompactPtrGroupBase;
899 BG->Batches.push_front(TB);
900 BG->BytesInBGAtLastCheckpoint = 0;
901 BG->MaxCachedPerBatch = MaxNumBlocksInBatch;
902
903 return BG;
904 };
905
906 auto InsertBlocks = [&](BatchGroupT *BG, CompactPtrT *Array, u32 Size) {
907 SinglyLinkedList<BatchT> &Batches = BG->Batches;
908 BatchT *CurBatch = Batches.front();
909 DCHECK_NE(CurBatch, nullptr);
910
911 for (u32 I = 0; I < Size;) {
912 DCHECK_GE(BG->MaxCachedPerBatch, CurBatch->getCount());
913 u16 UnusedSlots =
914 static_cast<u16>(BG->MaxCachedPerBatch - CurBatch->getCount());
915 if (UnusedSlots == 0) {
916 CurBatch = reinterpret_cast<BatchT *>(
917 SizeClassAllocator->getBatchClassBlock());
918 CurBatch->clear();
919 Batches.push_front(CurBatch);
920 UnusedSlots = BG->MaxCachedPerBatch;
921 }
922 // `UnusedSlots` is u16 so the result will be also fit in u16.
923 u16 AppendSize = static_cast<u16>(Min<u32>(A: UnusedSlots, B: Size - I));
924 CurBatch->appendFromArray(&Array[I], AppendSize);
925 I += AppendSize;
926 }
927 };
928
929 Region->FreeListInfo.PushedBlocks += Size;
930 BatchGroupT *Cur = Region->FreeListInfo.BlockList.front();
931
932 // In the following, `Cur` always points to the BatchGroup for blocks that
933 // will be pushed next. `Prev` is the element right before `Cur`.
934 BatchGroupT *Prev = nullptr;
935
936 while (Cur != nullptr &&
937 compactPtrGroup(CompactPtr: Array[0]) > Cur->CompactPtrGroupBase) {
938 Prev = Cur;
939 Cur = Cur->Next;
940 }
941
942 if (Cur == nullptr || compactPtrGroup(CompactPtr: Array[0]) != Cur->CompactPtrGroupBase) {
943 Cur = CreateGroup(compactPtrGroup(CompactPtr: Array[0]));
944 if (Prev == nullptr)
945 Region->FreeListInfo.BlockList.push_front(Cur);
946 else
947 Region->FreeListInfo.BlockList.insert(Prev, Cur);
948 }
949
950 // All the blocks are from the same group, just push without checking group
951 // id.
952 if (SameGroup) {
953 for (u32 I = 0; I < Size; ++I)
954 DCHECK_EQ(compactPtrGroup(Array[I]), Cur->CompactPtrGroupBase);
955
956 InsertBlocks(Cur, Array, Size);
957 return;
958 }
959
960 // The blocks are sorted by group id. Determine the segment of group and
961 // push them to their group together.
962 u32 Count = 1;
963 for (u32 I = 1; I < Size; ++I) {
964 if (compactPtrGroup(CompactPtr: Array[I - 1]) != compactPtrGroup(CompactPtr: Array[I])) {
965 DCHECK_EQ(compactPtrGroup(Array[I - 1]), Cur->CompactPtrGroupBase);
966 InsertBlocks(Cur, Array + I - Count, Count);
967
968 while (Cur != nullptr &&
969 compactPtrGroup(CompactPtr: Array[I]) > Cur->CompactPtrGroupBase) {
970 Prev = Cur;
971 Cur = Cur->Next;
972 }
973
974 if (Cur == nullptr ||
975 compactPtrGroup(CompactPtr: Array[I]) != Cur->CompactPtrGroupBase) {
976 Cur = CreateGroup(compactPtrGroup(CompactPtr: Array[I]));
977 DCHECK_NE(Prev, nullptr);
978 Region->FreeListInfo.BlockList.insert(Prev, Cur);
979 }
980
981 Count = 1;
982 } else {
983 ++Count;
984 }
985 }
986
987 InsertBlocks(Cur, Array + Size - Count, Count);
988}
989
990template <typename Config>
991void SizeClassAllocator64<Config>::pushBatchClassBlocks(RegionInfo *Region,
992 CompactPtrT *Array,
993 u32 Size)
994 REQUIRES(Region->FLLock) {
995 DCHECK_EQ(Region, getRegionInfo(SizeClassMap::BatchClassId));
996
997 // Free blocks are recorded by Batch in freelist for all
998 // size-classes. In addition, Batch is allocated from BatchClassId.
999 // In order not to use additional block to record the free blocks in
1000 // BatchClassId, they are self-contained. I.e., A Batch records the
1001 // block address of itself. See the figure below:
1002 //
1003 // Batch at 0xABCD
1004 // +----------------------------+
1005 // | Free blocks' addr |
1006 // | +------+------+------+ |
1007 // | |0xABCD|... |... | |
1008 // | +------+------+------+ |
1009 // +----------------------------+
1010 //
1011 // When we allocate all the free blocks in the Batch, the block used
1012 // by Batch is also free for use. We don't need to recycle the
1013 // Batch. Note that the correctness is maintained by the invariant,
1014 //
1015 // Each popBlocks() request returns the entire Batch. Returning
1016 // part of the blocks in a Batch is invalid.
1017 //
1018 // This ensures that Batch won't leak the address itself while it's
1019 // still holding other valid data.
1020 //
1021 // Besides, BatchGroup is also allocated from BatchClassId and has its
1022 // address recorded in the Batch too. To maintain the correctness,
1023 //
1024 // The address of BatchGroup is always recorded in the last Batch
1025 // in the freelist (also imply that the freelist should only be
1026 // updated with push_front). Once the last Batch is popped,
1027 // the block used by BatchGroup is also free for use.
1028 //
1029 // With this approach, the blocks used by BatchGroup and Batch are
1030 // reusable and don't need additional space for them.
1031
1032 Region->FreeListInfo.PushedBlocks += Size;
1033 BatchGroupT *BG = Region->FreeListInfo.BlockList.front();
1034
1035 if (BG == nullptr) {
1036 // Construct `BatchGroup` on the last element.
1037 BG = reinterpret_cast<BatchGroupT *>(
1038 decompactPtr(ClassId: SizeClassMap::BatchClassId, CompactPtr: Array[Size - 1]));
1039 --Size;
1040 BG->Batches.clear();
1041 // BatchClass hasn't enabled memory group. Use `0` to indicate there's no
1042 // memory group here.
1043 BG->CompactPtrGroupBase = 0;
1044 BG->BytesInBGAtLastCheckpoint = 0;
1045 BG->MaxCachedPerBatch = SizeClassAllocatorT::getMaxCached(
1046 getSizeByClassId(ClassId: SizeClassMap::BatchClassId));
1047
1048 Region->FreeListInfo.BlockList.push_front(BG);
1049 }
1050
1051 if (UNLIKELY(Size == 0))
1052 return;
1053
1054 // This happens under 2 cases.
1055 // 1. just allocated a new `BatchGroup`.
1056 // 2. Only 1 block is pushed when the freelist is empty.
1057 if (BG->Batches.empty()) {
1058 // Construct the `Batch` on the last element.
1059 BatchT *TB = reinterpret_cast<BatchT *>(
1060 decompactPtr(ClassId: SizeClassMap::BatchClassId, CompactPtr: Array[Size - 1]));
1061 TB->clear();
1062 // As mentioned above, addresses of `Batch` and `BatchGroup` are
1063 // recorded in the Batch.
1064 TB->add(Array[Size - 1]);
1065 TB->add(compactPtr(ClassId: SizeClassMap::BatchClassId, Ptr: reinterpret_cast<uptr>(BG)));
1066 --Size;
1067 BG->Batches.push_front(TB);
1068 }
1069
1070 BatchT *CurBatch = BG->Batches.front();
1071 DCHECK_NE(CurBatch, nullptr);
1072
1073 for (u32 I = 0; I < Size;) {
1074 u16 UnusedSlots =
1075 static_cast<u16>(BG->MaxCachedPerBatch - CurBatch->getCount());
1076 if (UnusedSlots == 0) {
1077 CurBatch = reinterpret_cast<BatchT *>(
1078 decompactPtr(ClassId: SizeClassMap::BatchClassId, CompactPtr: Array[I]));
1079 CurBatch->clear();
1080 // Self-contained
1081 CurBatch->add(Array[I]);
1082 ++I;
1083 // TODO(chiahungduan): Avoid the use of push_back() in `Batches` of
1084 // BatchClassId.
1085 BG->Batches.push_front(CurBatch);
1086 UnusedSlots = static_cast<u16>(BG->MaxCachedPerBatch - 1);
1087 }
1088 // `UnusedSlots` is u16 so the result will be also fit in u16.
1089 const u16 AppendSize = static_cast<u16>(Min<u32>(A: UnusedSlots, B: Size - I));
1090 CurBatch->appendFromArray(&Array[I], AppendSize);
1091 I += AppendSize;
1092 }
1093}
1094
1095template <typename Config>
1096void SizeClassAllocator64<Config>::disable() NO_THREAD_SAFETY_ANALYSIS {
1097 // The BatchClassId must be locked last since other classes can use it.
1098 for (sptr I = static_cast<sptr>(NumClasses) - 1; I >= 0; I--) {
1099 if (static_cast<uptr>(I) == SizeClassMap::BatchClassId)
1100 continue;
1101 getRegionInfo(ClassId: static_cast<uptr>(I))->MMLock.lock();
1102 getRegionInfo(ClassId: static_cast<uptr>(I))->FLLock.lock();
1103 }
1104 getRegionInfo(ClassId: SizeClassMap::BatchClassId)->MMLock.lock();
1105 getRegionInfo(ClassId: SizeClassMap::BatchClassId)->FLLock.lock();
1106}
1107
1108template <typename Config>
1109void SizeClassAllocator64<Config>::enable(bool IsChild)
1110 NO_THREAD_SAFETY_ANALYSIS {
1111 auto *BatchRegion = getRegionInfo(ClassId: SizeClassMap::BatchClassId);
1112 if constexpr (conditionVariableEnabled()) {
1113 if (IsChild) {
1114 BatchRegion->NumWaiting = 0;
1115 BatchRegion->IsPopulatingFreeList = false;
1116 } else if (BatchRegion->NumWaiting > 0) {
1117 BatchRegion->FLLockCV.notifyAll(BatchRegion->FLLock);
1118 }
1119 }
1120 BatchRegion->FLLock.unlock();
1121 BatchRegion->MMLock.unlock();
1122
1123 for (uptr I = 0; I < NumClasses; I++) {
1124 if (I == SizeClassMap::BatchClassId)
1125 continue;
1126 auto *Region = getRegionInfo(ClassId: I);
1127 if constexpr (conditionVariableEnabled()) {
1128 if (IsChild) {
1129 Region->NumWaiting = 0;
1130 Region->IsPopulatingFreeList = false;
1131 } else if (Region->NumWaiting > 0) {
1132 Region->FLLockCV.notifyAll(Region->FLLock);
1133 }
1134 }
1135 Region->FLLock.unlock();
1136 Region->MMLock.unlock();
1137 }
1138}
1139
1140template <typename Config>
1141template <typename F>
1142void SizeClassAllocator64<Config>::iterateOverBlocks(F Callback) {
1143 for (uptr I = 0; I < NumClasses; I++) {
1144 if (I == SizeClassMap::BatchClassId)
1145 continue;
1146 RegionInfo *Region = getRegionInfo(ClassId: I);
1147 // TODO: The call of `iterateOverBlocks` requires disabling
1148 // SizeClassAllocator64. We may consider locking each region on demand
1149 // only.
1150 Region->FLLock.assertHeld();
1151 Region->MMLock.assertHeld();
1152 const uptr BlockSize = getSizeByClassId(ClassId: I);
1153 const uptr From = Region->RegionBeg;
1154 const uptr To = From + Region->MemMapInfo.AllocatedUser;
1155 for (uptr Block = From; Block < To; Block += BlockSize)
1156 Callback(Block);
1157 }
1158}
1159
1160template <typename Config>
1161void SizeClassAllocator64<Config>::getStats(ScopedString *Str) {
1162 // TODO(kostyak): get the RSS per region.
1163 Str->append(Format: "\nConfig Stats Primary64: ");
1164 Config::getConfigValues(Str);
1165 uptr TotalMapped = 0;
1166 uptr PoppedBlocks = 0;
1167 uptr PushedBlocks = 0;
1168 for (uptr I = 0; I < NumClasses; I++) {
1169 RegionInfo *Region = getRegionInfo(ClassId: I);
1170 {
1171 ScopedLock L(Region->MMLock);
1172 TotalMapped += Region->MemMapInfo.MappedUser;
1173 }
1174 {
1175 ScopedFLLock FL(Region->FLLock, Region);
1176 PoppedBlocks += Region->FreeListInfo.PoppedBlocks;
1177 PushedBlocks += Region->FreeListInfo.PushedBlocks;
1178 }
1179 }
1180 const s32 IntervalMs = atomic_load_relaxed(A: &ReleaseToOsIntervalMs);
1181 Str->append(Format: "Stats: SizeClassAllocator64: %zuM mapped (%uM rss) in %zu "
1182 "allocations; remains %zu; ReleaseToOsIntervalMs = %d\n",
1183 TotalMapped >> 20, 0U, PoppedBlocks, PoppedBlocks - PushedBlocks,
1184 IntervalMs >= 0 ? IntervalMs : -1);
1185
1186 for (uptr I = 0; I < NumClasses; I++) {
1187 RegionInfo *Region = getRegionInfo(ClassId: I);
1188 ScopedLock MM(Region->MMLock);
1189 ScopedFLLock FL(Region->FLLock, Region);
1190 getStats(Str, I, Region);
1191 }
1192}
1193
1194template <typename Config>
1195void SizeClassAllocator64<Config>::getStats(ScopedString *Str, uptr ClassId,
1196 RegionInfo *Region)
1197 REQUIRES(Region->MMLock, Region->FLLock) {
1198 if (Region->MemMapInfo.MappedUser == 0)
1199 return;
1200 const uptr BlockSize = getSizeByClassId(ClassId);
1201 const uptr InUseBlocks =
1202 Region->FreeListInfo.PoppedBlocks - Region->FreeListInfo.PushedBlocks;
1203 const uptr BytesInFreeList =
1204 Region->MemMapInfo.AllocatedUser - InUseBlocks * BlockSize;
1205 uptr RegionPushedBytesDelta = 0;
1206 if (BytesInFreeList >= Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint) {
1207 RegionPushedBytesDelta =
1208 BytesInFreeList - Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint;
1209 }
1210 const uptr TotalChunks = Region->MemMapInfo.AllocatedUser / BlockSize;
1211 Str->append(
1212 "%s %02zu (%6zu): mapped: %6zuK popped: %7zu pushed: %7zu "
1213 "inuse: %6zu total: %6zu releases attempted: %6zu last "
1214 "released: %6zuK latest pushed bytes: %6zuK region: 0x%zx "
1215 "(0x%zx)",
1216 Region->Exhausted ? "E" : " ", ClassId, getSizeByClassId(ClassId),
1217 Region->MemMapInfo.MappedUser >> 10, Region->FreeListInfo.PoppedBlocks,
1218 Region->FreeListInfo.PushedBlocks, InUseBlocks, TotalChunks,
1219 Region->ReleaseInfo.NumReleasesAttempted,
1220 Region->ReleaseInfo.LastReleasedBytes >> 10, RegionPushedBytesDelta >> 10,
1221 Region->RegionBeg, getRegionBaseByClassId(ClassId));
1222 const u64 CurTimeNs = getMonotonicTimeFast();
1223 const u64 LastReleaseAtNs = Region->ReleaseInfo.LastReleaseAtNs;
1224 if (LastReleaseAtNs != 0 && CurTimeNs != LastReleaseAtNs) {
1225 const u64 DiffSinceLastReleaseNs =
1226 CurTimeNs - Region->ReleaseInfo.LastReleaseAtNs;
1227 const u64 LastReleaseSecAgo = DiffSinceLastReleaseNs / 1000000000;
1228 const u64 LastReleaseMsAgo =
1229 (DiffSinceLastReleaseNs % 1000000000) / 1000000;
1230 Str->append(Format: " Latest release: %6" PRIu64 ":%03" PRIu64 " seconds ago",
1231 LastReleaseSecAgo, LastReleaseMsAgo);
1232 }
1233 const s64 ResidentPages = Region->MemMapInfo.MemMap.getResidentPages();
1234 if (ResidentPages >= 0) {
1235 Str->append(Format: " Resident Pages: %6" PRIu64, ResidentPages);
1236 }
1237 Str->append(Format: "\n");
1238}
1239
1240template <typename Config>
1241void SizeClassAllocator64<Config>::getFragmentationInfo(ScopedString *Str) {
1242 Str->append(
1243 Format: "Fragmentation Stats: SizeClassAllocator64: page size = %zu bytes\n",
1244 getPageSizeCached());
1245
1246 for (uptr I = 1; I < NumClasses; I++) {
1247 RegionInfo *Region = getRegionInfo(ClassId: I);
1248 ScopedLock L(Region->MMLock);
1249 getRegionFragmentationInfo(Region, ClassId: I, Str);
1250 }
1251}
1252
1253template <typename Config>
1254void SizeClassAllocator64<Config>::getRegionFragmentationInfo(
1255 RegionInfo *Region, uptr ClassId, ScopedString *Str)
1256 REQUIRES(Region->MMLock) {
1257 const uptr BlockSize = getSizeByClassId(ClassId);
1258 const uptr AllocatedUserEnd =
1259 Region->MemMapInfo.AllocatedUser + Region->RegionBeg;
1260
1261 SinglyLinkedList<BatchGroupT> GroupsToRelease;
1262 {
1263 ScopedFLLock FL(Region->FLLock, Region);
1264 GroupsToRelease = Region->FreeListInfo.BlockList;
1265 Region->FreeListInfo.BlockList.clear();
1266 }
1267
1268 FragmentationRecorder Recorder;
1269 if (!GroupsToRelease.empty()) {
1270 PageReleaseContext Context =
1271 markFreeBlocks(Region, BlockSize, AllocatedUserEnd,
1272 CompactPtrBase: getCompactPtrBaseByClassId(ClassId), GroupsToRelease);
1273 auto SkipRegion = [](UNUSED uptr RegionIndex) { return false; };
1274 releaseFreeMemoryToOS(Context, Recorder, SkipRegion);
1275
1276 mergeGroupsToReleaseBack(Region, GroupsToRelease);
1277 }
1278
1279 ScopedFLLock FL(Region->FLLock, Region);
1280 const uptr PageSize = getPageSizeCached();
1281 const uptr TotalBlocks = Region->MemMapInfo.AllocatedUser / BlockSize;
1282 const uptr InUseBlocks =
1283 Region->FreeListInfo.PoppedBlocks - Region->FreeListInfo.PushedBlocks;
1284 const uptr AllocatedPagesCount =
1285 roundUp(Region->MemMapInfo.AllocatedUser, PageSize) / PageSize;
1286 DCHECK_GE(AllocatedPagesCount, Recorder.getReleasedPagesCount());
1287 const uptr InUsePages =
1288 AllocatedPagesCount - Recorder.getReleasedPagesCount();
1289 const uptr InUseBytes = InUsePages * PageSize;
1290
1291 uptr Integral;
1292 uptr Fractional;
1293 computePercentage(Numerator: BlockSize * InUseBlocks, Denominator: InUseBytes, Integral: &Integral,
1294 Fractional: &Fractional);
1295 Str->append(Format: " %02zu (%6zu): inuse/total blocks: %6zu/%6zu inuse/total "
1296 "pages: %6zu/%6zu inuse bytes: %6zuK util: %3zu.%02zu%%\n",
1297 ClassId, BlockSize, InUseBlocks, TotalBlocks, InUsePages,
1298 AllocatedPagesCount, InUseBytes >> 10, Integral, Fractional);
1299}
1300
1301template <typename Config>
1302void SizeClassAllocator64<Config>::getMemoryGroupFragmentationInfoInRegion(
1303 RegionInfo *Region, uptr ClassId, ScopedString *Str)
1304 REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {
1305 const uptr BlockSize = getSizeByClassId(ClassId);
1306 const uptr AllocatedUserEnd =
1307 Region->MemMapInfo.AllocatedUser + Region->RegionBeg;
1308
1309 SinglyLinkedList<BatchGroupT> GroupsToRelease;
1310 {
1311 ScopedFLLock FL(Region->FLLock, Region);
1312 GroupsToRelease = Region->FreeListInfo.BlockList;
1313 Region->FreeListInfo.BlockList.clear();
1314 }
1315
1316 constexpr uptr GroupSize = (1UL << GroupSizeLog);
1317 constexpr uptr MaxNumGroups = RegionSize / GroupSize;
1318
1319 MemoryGroupFragmentationRecorder<GroupSize, MaxNumGroups> Recorder;
1320 if (!GroupsToRelease.empty()) {
1321 PageReleaseContext Context =
1322 markFreeBlocks(Region, BlockSize, AllocatedUserEnd,
1323 CompactPtrBase: getCompactPtrBaseByClassId(ClassId), GroupsToRelease);
1324 auto SkipRegion = [](UNUSED uptr RegionIndex) { return false; };
1325 releaseFreeMemoryToOS(Context, Recorder, SkipRegion);
1326
1327 mergeGroupsToReleaseBack(Region, GroupsToRelease);
1328 }
1329
1330 Str->append(Format: "MemoryGroupFragmentationInfo in Region %zu (%zu)\n", ClassId,
1331 BlockSize);
1332
1333 const uptr MaxNumGroupsInUse =
1334 roundUp(Region->MemMapInfo.AllocatedUser, GroupSize) / GroupSize;
1335 for (uptr I = 0; I < MaxNumGroupsInUse; ++I) {
1336 uptr Integral;
1337 uptr Fractional;
1338 computePercentage(Recorder.NumPagesInOneGroup - Recorder.getNumFreePages(I),
1339 Recorder.NumPagesInOneGroup, &Integral, &Fractional);
1340 Str->append("MemoryGroup #%zu (0x%zx): util: %3zu.%02zu%%\n", I,
1341 Region->RegionBeg + I * GroupSize, Integral, Fractional);
1342 }
1343}
1344
1345template <typename Config>
1346void SizeClassAllocator64<Config>::getMemoryGroupFragmentationInfo(
1347 ScopedString *Str) {
1348 Str->append(
1349 Format: "Fragmentation Stats: SizeClassAllocator64: page size = %zu bytes\n",
1350 getPageSizeCached());
1351
1352 for (uptr I = 1; I < NumClasses; I++) {
1353 RegionInfo *Region = getRegionInfo(ClassId: I);
1354 ScopedLock L(Region->MMLock);
1355 getMemoryGroupFragmentationInfoInRegion(Region, ClassId: I, Str);
1356 }
1357}
1358
1359template <typename Config>
1360bool SizeClassAllocator64<Config>::setOption(Option O, sptr Value) {
1361 if (O == Option::ReleaseInterval) {
1362 const s32 Interval =
1363 Max(Min(static_cast<s32>(Value), Config::getMaxReleaseToOsIntervalMs()),
1364 Config::getMinReleaseToOsIntervalMs());
1365 atomic_store_relaxed(A: &ReleaseToOsIntervalMs, V: Interval);
1366 return true;
1367 }
1368 // Not supported by the Primary, but not an error either.
1369 return true;
1370}
1371
1372template <typename Config>
1373uptr SizeClassAllocator64<Config>::tryReleaseToOS(uptr ClassId,
1374 ReleaseToOS ReleaseType) {
1375 RegionInfo *Region = getRegionInfo(ClassId);
1376 // Note that the tryLock() may fail spuriously, given that it should rarely
1377 // happen and page releasing is fine to skip, we don't take certain
1378 // approaches to ensure one page release is done.
1379 if (Region->MMLock.tryLock()) {
1380 uptr BytesReleased = releaseToOSMaybe(Region, ClassId, ReleaseType);
1381 Region->MMLock.unlock();
1382 return BytesReleased;
1383 }
1384 return 0;
1385}
1386
1387template <typename Config>
1388uptr SizeClassAllocator64<Config>::releaseToOS(ReleaseToOS ReleaseType) {
1389 SCUDO_SCOPED_TRACE(GetPrimaryReleaseToOSTraceName(ReleaseType));
1390
1391 uptr TotalReleasedBytes = 0;
1392 for (uptr I = 0; I < NumClasses; I++) {
1393 if (I == SizeClassMap::BatchClassId)
1394 continue;
1395 RegionInfo *Region = getRegionInfo(ClassId: I);
1396 if (ReleaseType == ReleaseToOS::ForceFast) {
1397 // Never wait for the lock, always move on if there is already
1398 // a release operation in progress.
1399 if (Region->MMLock.tryLock()) {
1400 TotalReleasedBytes += releaseToOSMaybe(Region, ClassId: I, ReleaseType);
1401 Region->MMLock.unlock();
1402 }
1403 } else {
1404 ScopedLock L(Region->MMLock);
1405 TotalReleasedBytes += releaseToOSMaybe(Region, ClassId: I, ReleaseType);
1406 }
1407 }
1408 return TotalReleasedBytes;
1409}
1410
1411template <typename Config>
1412BlockInfo SizeClassAllocator64<Config>::findNearestBlock(uptr Ptr)
1413 NO_THREAD_SAFETY_ANALYSIS {
1414 uptr ClassId;
1415 uptr MinDistance = -1UL;
1416 for (uptr I = 0; I != NumClasses; ++I) {
1417 if (I == SizeClassMap::BatchClassId)
1418 continue;
1419
1420 ScopedLock ML(RegionInfoArray[I].MMLock);
1421 uptr Begin = RegionInfoArray[I].RegionBeg;
1422 uptr End = Begin + RegionInfoArray[I].MemMapInfo.AllocatedUser;
1423 if (Begin > End || End - Begin < SizeClassMap::getSizeByClassId(I))
1424 continue;
1425 uptr RegionDistance;
1426 if (Begin <= Ptr) {
1427 if (Ptr < End)
1428 RegionDistance = 0;
1429 else
1430 RegionDistance = Ptr - End;
1431 } else {
1432 RegionDistance = Begin - Ptr;
1433 }
1434
1435 if (RegionDistance < MinDistance) {
1436 MinDistance = RegionDistance;
1437 ClassId = I;
1438 if (RegionDistance == 0)
1439 break;
1440 }
1441 }
1442
1443 if (MinDistance > 8192) {
1444 return {};
1445 }
1446
1447 ScopedLock ML(RegionInfoArray[ClassId].MMLock);
1448 BlockInfo B = {};
1449 B.RegionBegin = RegionInfoArray[ClassId].RegionBeg;
1450 B.RegionEnd =
1451 B.RegionBegin + RegionInfoArray[ClassId].MemMapInfo.AllocatedUser;
1452 B.BlockSize = SizeClassMap::getSizeByClassId(ClassId);
1453 B.BlockBegin = B.RegionBegin + uptr(sptr(Ptr - B.RegionBegin) /
1454 sptr(B.BlockSize) * sptr(B.BlockSize));
1455 while (B.BlockBegin < B.RegionBegin)
1456 B.BlockBegin += B.BlockSize;
1457 while (B.RegionEnd < B.BlockBegin + B.BlockSize)
1458 B.BlockBegin -= B.BlockSize;
1459 return B;
1460}
1461
1462template <typename Config>
1463uptr SizeClassAllocator64<Config>::releaseToOSMaybe(RegionInfo *Region,
1464 uptr ClassId,
1465 ReleaseToOS ReleaseType)
1466 REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {
1467 const uptr BlockSize = getSizeByClassId(ClassId);
1468 uptr BytesInFreeList;
1469 const uptr AllocatedUserEnd =
1470 Region->MemMapInfo.AllocatedUser + Region->RegionBeg;
1471 uptr RegionPushedBytesDelta = 0;
1472 SinglyLinkedList<BatchGroupT> GroupsToRelease;
1473
1474 {
1475 ScopedFLLock FL(Region->FLLock, Region);
1476
1477 BytesInFreeList =
1478 Region->MemMapInfo.AllocatedUser - (Region->FreeListInfo.PoppedBlocks -
1479 Region->FreeListInfo.PushedBlocks) *
1480 BlockSize;
1481 if (UNLIKELY(BytesInFreeList == 0))
1482 return 0;
1483
1484 // ==================================================================== //
1485 // 1. Check if we have enough free blocks and if it's worth doing a page
1486 // release.
1487 // ==================================================================== //
1488 if (ReleaseType != ReleaseToOS::ForceAll &&
1489 !hasChanceToReleasePages(Region, BlockSize, BytesInFreeList,
1490 ReleaseType)) {
1491 return 0;
1492 }
1493
1494 // Given that we will unlock the freelist for block operations, cache the
1495 // value here so that when we are adapting the `TryReleaseThreshold`
1496 // later, we are using the right metric.
1497 RegionPushedBytesDelta =
1498 BytesInFreeList - Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint;
1499
1500 // ==================================================================== //
1501 // 2. Determine which groups can release the pages. Use a heuristic to
1502 // gather groups that are candidates for doing a release.
1503 // ==================================================================== //
1504 if (ReleaseType == ReleaseToOS::ForceAll) {
1505 GroupsToRelease = Region->FreeListInfo.BlockList;
1506 Region->FreeListInfo.BlockList.clear();
1507 } else {
1508 GroupsToRelease =
1509 collectGroupsToRelease(Region, BlockSize, AllocatedUserEnd,
1510 CompactPtrBase: getCompactPtrBaseByClassId(ClassId));
1511 }
1512 if (GroupsToRelease.empty())
1513 return 0;
1514 }
1515
1516 // The following steps contribute to the majority time spent in page
1517 // releasing thus we increment the counter here.
1518 ++Region->ReleaseInfo.NumReleasesAttempted;
1519
1520 // Note that we have extracted the `GroupsToRelease` from region freelist.
1521 // It's safe to let pushBlocks()/popBlocks() access the remaining region
1522 // freelist. In the steps 3 and 4, we will temporarily release the FLLock
1523 // and lock it again before step 5.
1524
1525 // ==================================================================== //
1526 // 3. Mark the free blocks in `GroupsToRelease` in the `PageReleaseContext`.
1527 // Then we can tell which pages are in-use by querying
1528 // `PageReleaseContext`.
1529 // ==================================================================== //
1530
1531 // Only add trace point after the quick returns have occurred to avoid
1532 // incurring performance penalties. Most of the time in this function
1533 // will be the mark free blocks call and the actual release to OS call.
1534 SCUDO_SCOPED_TRACE(GetPrimaryReleaseToOSMaybeTraceName(ReleaseType));
1535
1536 PageReleaseContext Context =
1537 markFreeBlocks(Region, BlockSize, AllocatedUserEnd,
1538 CompactPtrBase: getCompactPtrBaseByClassId(ClassId), GroupsToRelease);
1539 if (UNLIKELY(!Context.hasBlockMarked())) {
1540 mergeGroupsToReleaseBack(Region, GroupsToRelease);
1541 return 0;
1542 }
1543
1544 // ==================================================================== //
1545 // 4. Release the unused physical pages back to the OS.
1546 // ==================================================================== //
1547 RegionReleaseRecorder<MemMapT> Recorder(&Region->MemMapInfo.MemMap,
1548 Region->RegionBeg,
1549 Context.getReleaseOffset());
1550 auto SkipRegion = [](UNUSED uptr RegionIndex) { return false; };
1551 releaseFreeMemoryToOS(Context, Recorder, SkipRegion);
1552 if (Recorder.getReleasedBytes() > 0) {
1553 // This is the case that we didn't hit the release threshold but it has
1554 // been past a certain period of time. Thus we try to release some pages
1555 // and if it does release some additional pages, it's hint that we are
1556 // able to lower the threshold. Currently, this case happens when the
1557 // `RegionPushedBytesDelta` is over half of the `TryReleaseThreshold`. As
1558 // a result, we shrink the threshold to half accordingly.
1559 // TODO(chiahungduan): Apply the same adjustment strategy to small blocks.
1560 if (!isSmallBlock(BlockSize)) {
1561 if (RegionPushedBytesDelta < Region->ReleaseInfo.TryReleaseThreshold &&
1562 Recorder.getReleasedBytes() >
1563 Region->ReleaseInfo.LastReleasedBytes +
1564 getMinReleaseAttemptSize(BlockSize)) {
1565 Region->ReleaseInfo.TryReleaseThreshold =
1566 Max(Region->ReleaseInfo.TryReleaseThreshold / 2,
1567 getMinReleaseAttemptSize(BlockSize));
1568 }
1569 }
1570
1571 Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint = BytesInFreeList;
1572 Region->ReleaseInfo.LastReleasedBytes = Recorder.getReleasedBytes();
1573 }
1574 Region->ReleaseInfo.LastReleaseAtNs = getMonotonicTimeFast();
1575
1576 if (Region->ReleaseInfo.PendingPushedBytesDelta > 0) {
1577 // Instead of increasing the threshold by the amount of
1578 // `PendingPushedBytesDelta`, we only increase half of the amount so that
1579 // it won't be a leap (which may lead to higher memory pressure) because
1580 // of certain memory usage bursts which don't happen frequently.
1581 Region->ReleaseInfo.TryReleaseThreshold +=
1582 Region->ReleaseInfo.PendingPushedBytesDelta / 2;
1583 // This is another guard of avoiding the growth of threshold indefinitely.
1584 // Note that we may consider to make this configurable if we have a better
1585 // way to model this.
1586 Region->ReleaseInfo.TryReleaseThreshold = Min<uptr>(
1587 Region->ReleaseInfo.TryReleaseThreshold, (1UL << GroupSizeLog) / 2);
1588 Region->ReleaseInfo.PendingPushedBytesDelta = 0;
1589 }
1590
1591 // ====================================================================== //
1592 // 5. Merge the `GroupsToRelease` back to the freelist.
1593 // ====================================================================== //
1594 mergeGroupsToReleaseBack(Region, GroupsToRelease);
1595
1596 return Recorder.getReleasedBytes();
1597}
1598
1599template <typename Config>
1600bool SizeClassAllocator64<Config>::hasChanceToReleasePages(
1601 RegionInfo *Region, uptr BlockSize, uptr BytesInFreeList,
1602 ReleaseToOS ReleaseType) REQUIRES(Region->MMLock, Region->FLLock) {
1603 DCHECK_GE(Region->FreeListInfo.PoppedBlocks,
1604 Region->FreeListInfo.PushedBlocks);
1605 // Always update `BytesInFreeListAtLastCheckpoint` with the smallest value
1606 // so that we won't underestimate the releasable pages. For example, the
1607 // following is the region usage,
1608 //
1609 // BytesInFreeListAtLastCheckpoint AllocatedUser
1610 // v v
1611 // |--------------------------------------->
1612 // ^ ^
1613 // BytesInFreeList ReleaseThreshold
1614 //
1615 // In general, if we have collected enough bytes and the amount of free
1616 // bytes meets the ReleaseThreshold, we will try to do page release. If we
1617 // don't update `BytesInFreeListAtLastCheckpoint` when the current
1618 // `BytesInFreeList` is smaller, we may take longer time to wait for enough
1619 // freed blocks because we miss the bytes between
1620 // (BytesInFreeListAtLastCheckpoint - BytesInFreeList).
1621 if (BytesInFreeList <= Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint) {
1622 Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint = BytesInFreeList;
1623 }
1624
1625 const uptr RegionPushedBytesDelta =
1626 BytesInFreeList - Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint;
1627
1628 if (ReleaseType == ReleaseToOS::Normal) {
1629 if (RegionPushedBytesDelta < Region->ReleaseInfo.TryReleaseThreshold / 2)
1630 return false;
1631
1632 const s64 IntervalMs = atomic_load_relaxed(A: &ReleaseToOsIntervalMs);
1633 if (IntervalMs < 0)
1634 return false;
1635
1636 const u64 IntervalNs = static_cast<u64>(IntervalMs) * 1000000;
1637 const u64 CurTimeNs = getMonotonicTimeFast();
1638 const u64 DiffSinceLastReleaseNs =
1639 CurTimeNs - Region->ReleaseInfo.LastReleaseAtNs;
1640
1641 // At here, `RegionPushedBytesDelta` is more than half of
1642 // `TryReleaseThreshold`. If the last release happened 2 release interval
1643 // before, we will still try to see if there's any chance to release some
1644 // memory even it doesn't exceed the threshold.
1645 if (RegionPushedBytesDelta < Region->ReleaseInfo.TryReleaseThreshold) {
1646 // We want the threshold to have a shorter response time to the variant
1647 // memory usage patterns. According to data collected during experiments
1648 // (which were done with 1, 2, 4, 8 intervals), `2` strikes the better
1649 // balance between the memory usage and number of page release attempts.
1650 if (DiffSinceLastReleaseNs < 2 * IntervalNs)
1651 return false;
1652 } else if (DiffSinceLastReleaseNs < IntervalNs) {
1653 // `TryReleaseThreshold` is capped by (1UL << GroupSizeLog) / 2). If
1654 // RegionPushedBytesDelta grows to twice the threshold, it implies some
1655 // huge deallocations have happened so we better try to release some
1656 // pages. Note this tends to happen for larger block sizes.
1657 if (RegionPushedBytesDelta > (1ULL << GroupSizeLog))
1658 return true;
1659
1660 // In this case, we are over the threshold but we just did some page
1661 // release in the same release interval. This is a hint that we may want
1662 // a higher threshold so that we can release more memory at once.
1663 // `TryReleaseThreshold` will be adjusted according to how many bytes
1664 // are not released, i.e., the `PendingPushedBytesdelta` here.
1665 // TODO(chiahungduan): Apply the same adjustment strategy to small
1666 // blocks.
1667 if (!isSmallBlock(BlockSize))
1668 Region->ReleaseInfo.PendingPushedBytesDelta = RegionPushedBytesDelta;
1669
1670 // Memory was returned recently.
1671 return false;
1672 }
1673 } // if (ReleaseType == ReleaseToOS::Normal)
1674
1675 return true;
1676}
1677
1678template <typename Config>
1679SinglyLinkedList<typename SizeClassAllocator64<Config>::BatchGroupT>
1680SizeClassAllocator64<Config>::collectGroupsToRelease(
1681 RegionInfo *Region, const uptr BlockSize, const uptr AllocatedUserEnd,
1682 const uptr CompactPtrBase) REQUIRES(Region->MMLock, Region->FLLock) {
1683 const uptr GroupSize = (1UL << GroupSizeLog);
1684 const uptr PageSize = getPageSizeCached();
1685 SinglyLinkedList<BatchGroupT> GroupsToRelease;
1686
1687 // We are examining each group and will take the minimum distance to the
1688 // release threshold as the next `TryReleaseThreshold`. Note that if the
1689 // size of free blocks has reached the release threshold, the distance to
1690 // the next release will be PageSize * SmallerBlockReleasePageDelta. See the
1691 // comment on `SmallerBlockReleasePageDelta` for more details.
1692 uptr MinDistToThreshold = GroupSize;
1693
1694 for (BatchGroupT *BG = Region->FreeListInfo.BlockList.front(),
1695 *Prev = nullptr;
1696 BG != nullptr;) {
1697 // Group boundary is always GroupSize-aligned from CompactPtr base. The
1698 // layout of memory groups is like,
1699 //
1700 // (CompactPtrBase)
1701 // #1 CompactPtrGroupBase #2 CompactPtrGroupBase ...
1702 // | | |
1703 // v v v
1704 // +-----------------------+-----------------------+
1705 // \ / \ /
1706 // --- GroupSize --- --- GroupSize ---
1707 //
1708 // After decompacting the CompactPtrGroupBase, we expect the alignment
1709 // property is held as well.
1710 const uptr BatchGroupBase =
1711 decompactGroupBase(Base: CompactPtrBase, CompactPtrGroupBase: BG->CompactPtrGroupBase);
1712 DCHECK_LE(Region->RegionBeg, BatchGroupBase);
1713 DCHECK_GE(AllocatedUserEnd, BatchGroupBase);
1714 DCHECK_EQ((Region->RegionBeg - BatchGroupBase) % GroupSize, 0U);
1715 // Batches are pushed in front of BG.Batches. The first one may
1716 // not have all caches used.
1717 const uptr NumBlocks = (BG->Batches.size() - 1) * BG->MaxCachedPerBatch +
1718 BG->Batches.front()->getCount();
1719 const uptr BytesInBG = NumBlocks * BlockSize;
1720
1721 if (BytesInBG <= BG->BytesInBGAtLastCheckpoint) {
1722 BG->BytesInBGAtLastCheckpoint = BytesInBG;
1723 Prev = BG;
1724 BG = BG->Next;
1725 continue;
1726 }
1727
1728 const uptr PushedBytesDelta = BytesInBG - BG->BytesInBGAtLastCheckpoint;
1729 if (PushedBytesDelta < getMinReleaseAttemptSize(BlockSize)) {
1730 Prev = BG;
1731 BG = BG->Next;
1732 continue;
1733 }
1734
1735 // Given the randomness property, we try to release the pages only if the
1736 // bytes used by free blocks exceed certain proportion of group size. Note
1737 // that this heuristic only applies when all the spaces in a BatchGroup
1738 // are allocated.
1739 if (isSmallBlock(BlockSize)) {
1740 const uptr BatchGroupEnd = BatchGroupBase + GroupSize;
1741 const uptr AllocatedGroupSize = AllocatedUserEnd >= BatchGroupEnd
1742 ? GroupSize
1743 : AllocatedUserEnd - BatchGroupBase;
1744 const uptr ReleaseThreshold =
1745 (AllocatedGroupSize * (100 - 1U - BlockSize / 16U)) / 100U;
1746 const bool HighDensity = BytesInBG >= ReleaseThreshold;
1747 const bool MayHaveReleasedAll = NumBlocks >= (GroupSize / BlockSize);
1748 // If all blocks in the group are released, we will do range marking
1749 // which is fast. Otherwise, we will wait until we have accumulated
1750 // a certain amount of free memory.
1751 const bool ReachReleaseDelta =
1752 MayHaveReleasedAll
1753 ? true
1754 : PushedBytesDelta >= PageSize * SmallerBlockReleasePageDelta;
1755
1756 if (!HighDensity) {
1757 DCHECK_LE(BytesInBG, ReleaseThreshold);
1758 // The following is the usage of a memory group,
1759 //
1760 // BytesInBG ReleaseThreshold
1761 // / \ v
1762 // +---+---------------------------+-----+
1763 // | | | | |
1764 // +---+---------------------------+-----+
1765 // \ / ^
1766 // PushedBytesDelta GroupEnd
1767 MinDistToThreshold =
1768 Min(A: MinDistToThreshold,
1769 B: ReleaseThreshold - BytesInBG + PushedBytesDelta);
1770 } else {
1771 // If it reaches high density at this round, the next time we will try
1772 // to release is based on SmallerBlockReleasePageDelta
1773 MinDistToThreshold =
1774 Min(A: MinDistToThreshold, B: PageSize * SmallerBlockReleasePageDelta);
1775 }
1776
1777 if (!HighDensity || !ReachReleaseDelta) {
1778 Prev = BG;
1779 BG = BG->Next;
1780 continue;
1781 }
1782 }
1783
1784 // If `BG` is the first BatchGroupT in the list, we only need to advance
1785 // `BG` and call FreeListInfo.BlockList::pop_front(). No update is needed
1786 // for `Prev`.
1787 //
1788 // (BG) (BG->Next)
1789 // Prev Cur BG
1790 // | | |
1791 // v v v
1792 // nil +--+ +--+
1793 // |X | -> | | -> ...
1794 // +--+ +--+
1795 //
1796 // Otherwise, `Prev` will be used to extract the `Cur` from the
1797 // `FreeListInfo.BlockList`.
1798 //
1799 // (BG) (BG->Next)
1800 // Prev Cur BG
1801 // | | |
1802 // v v v
1803 // +--+ +--+ +--+
1804 // | | -> |X | -> | | -> ...
1805 // +--+ +--+ +--+
1806 //
1807 // After FreeListInfo.BlockList::extract(),
1808 //
1809 // Prev Cur BG
1810 // | | |
1811 // v v v
1812 // +--+ +--+ +--+
1813 // | |-+ |X | +->| | -> ...
1814 // +--+ | +--+ | +--+
1815 // +--------+
1816 //
1817 // Note that we need to advance before pushing this BatchGroup to
1818 // GroupsToRelease because it's a destructive operation.
1819
1820 BatchGroupT *Cur = BG;
1821 BG = BG->Next;
1822
1823 // Ideally, we may want to update this only after successful release.
1824 // However, for smaller blocks, each block marking is a costly operation.
1825 // Therefore, we update it earlier.
1826 // TODO: Consider updating this after releasing pages if `ReleaseRecorder`
1827 // can tell the released bytes in each group.
1828 Cur->BytesInBGAtLastCheckpoint = BytesInBG;
1829
1830 if (Prev != nullptr)
1831 Region->FreeListInfo.BlockList.extract(Prev, Cur);
1832 else
1833 Region->FreeListInfo.BlockList.pop_front();
1834 GroupsToRelease.push_back(Cur);
1835 }
1836
1837 // Only small blocks have the adaptive `TryReleaseThreshold`.
1838 if (isSmallBlock(BlockSize)) {
1839 // If the MinDistToThreshold is not updated, that means each memory group
1840 // may have only pushed less than a page size. In that case, just set it
1841 // back to normal.
1842 if (MinDistToThreshold == GroupSize)
1843 MinDistToThreshold = PageSize * SmallerBlockReleasePageDelta;
1844 Region->ReleaseInfo.TryReleaseThreshold = MinDistToThreshold;
1845 }
1846
1847 return GroupsToRelease;
1848}
1849
1850template <typename Config>
1851PageReleaseContext SizeClassAllocator64<Config>::markFreeBlocks(
1852 RegionInfo *Region, const uptr BlockSize, const uptr AllocatedUserEnd,
1853 const uptr CompactPtrBase, SinglyLinkedList<BatchGroupT> &GroupsToRelease)
1854 REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {
1855 const uptr GroupSize = (1UL << GroupSizeLog);
1856 auto DecompactPtr = [CompactPtrBase, this](CompactPtrT CompactPtr) {
1857 return decompactPtrInternal(Base: CompactPtrBase, CompactPtr);
1858 };
1859
1860 const uptr ReleaseBase = decompactGroupBase(
1861 Base: CompactPtrBase, CompactPtrGroupBase: GroupsToRelease.front()->CompactPtrGroupBase);
1862 const uptr LastGroupEnd =
1863 Min(decompactGroupBase(Base: CompactPtrBase,
1864 CompactPtrGroupBase: GroupsToRelease.back()->CompactPtrGroupBase) +
1865 GroupSize,
1866 AllocatedUserEnd);
1867 // The last block may straddle the group boundary. Rounding up to BlockSize
1868 // to get the exact range.
1869 const uptr ReleaseEnd =
1870 roundUpSlow(LastGroupEnd - Region->RegionBeg, BlockSize) +
1871 Region->RegionBeg;
1872 const uptr ReleaseRangeSize = ReleaseEnd - ReleaseBase;
1873 const uptr ReleaseOffset = ReleaseBase - Region->RegionBeg;
1874
1875 PageReleaseContext Context(BlockSize, /*NumberOfRegions=*/1U,
1876 ReleaseRangeSize, ReleaseOffset);
1877 // We may not be able to do the page release in a rare case that we may
1878 // fail on PageMap allocation.
1879 if (UNLIKELY(!Context.ensurePageMapAllocated()))
1880 return Context;
1881
1882 for (BatchGroupT &BG : GroupsToRelease) {
1883 const uptr BatchGroupBase =
1884 decompactGroupBase(Base: CompactPtrBase, CompactPtrGroupBase: BG.CompactPtrGroupBase);
1885 const uptr BatchGroupEnd = BatchGroupBase + GroupSize;
1886 const uptr AllocatedGroupSize = AllocatedUserEnd >= BatchGroupEnd
1887 ? GroupSize
1888 : AllocatedUserEnd - BatchGroupBase;
1889 const uptr BatchGroupUsedEnd = BatchGroupBase + AllocatedGroupSize;
1890 const bool MayContainLastBlockInRegion =
1891 BatchGroupUsedEnd == AllocatedUserEnd;
1892 const bool BlockAlignedWithUsedEnd =
1893 (BatchGroupUsedEnd - Region->RegionBeg) % BlockSize == 0;
1894
1895 uptr MaxContainedBlocks = AllocatedGroupSize / BlockSize;
1896 if (!BlockAlignedWithUsedEnd)
1897 ++MaxContainedBlocks;
1898
1899 const uptr NumBlocks = (BG.Batches.size() - 1) * BG.MaxCachedPerBatch +
1900 BG.Batches.front()->getCount();
1901
1902 if (NumBlocks == MaxContainedBlocks) {
1903 for (const auto &It : BG.Batches) {
1904 if (&It != BG.Batches.front())
1905 DCHECK_EQ(It.getCount(), BG.MaxCachedPerBatch);
1906 for (u16 I = 0; I < It.getCount(); ++I)
1907 DCHECK_EQ(compactPtrGroup(It.get(I)), BG.CompactPtrGroupBase);
1908 }
1909
1910 Context.markRangeAsAllCounted(From: BatchGroupBase, To: BatchGroupUsedEnd,
1911 Base: Region->RegionBeg, /*RegionIndex=*/RegionIndex: 0,
1912 RegionSize: Region->MemMapInfo.AllocatedUser);
1913 } else {
1914 DCHECK_LT(NumBlocks, MaxContainedBlocks);
1915 // Note that we don't always visit blocks in each BatchGroup so that we
1916 // may miss the chance of releasing certain pages that cross
1917 // BatchGroups.
1918 Context.markFreeBlocksInRegion(
1919 BG.Batches, DecompactPtr, Region->RegionBeg, /*RegionIndex=*/0,
1920 Region->MemMapInfo.AllocatedUser, MayContainLastBlockInRegion);
1921 }
1922 }
1923
1924 DCHECK(Context.hasBlockMarked());
1925
1926 return Context;
1927}
1928
1929template <typename Config>
1930void SizeClassAllocator64<Config>::mergeGroupsToReleaseBack(
1931 RegionInfo *Region, SinglyLinkedList<BatchGroupT> &GroupsToRelease)
1932 REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {
1933 ScopedFLLock FL(Region->FLLock, Region);
1934
1935 // After merging two freelists, we may have redundant `BatchGroup`s that
1936 // need to be recycled. The number of unused `BatchGroup`s is expected to be
1937 // small. Pick a constant which is inferred from real programs.
1938 constexpr uptr MaxUnusedSize = 8;
1939 CompactPtrT Blocks[MaxUnusedSize];
1940 u32 Idx = 0;
1941 RegionInfo *BatchClassRegion = getRegionInfo(ClassId: SizeClassMap::BatchClassId);
1942 // We can't call pushBatchClassBlocks() to recycle the unused `BatchGroup`s
1943 // when we are manipulating the freelist of `BatchClassRegion`. Instead, we
1944 // should just push it back to the freelist when we merge two `BatchGroup`s.
1945 // This logic hasn't been implemented because we haven't supported releasing
1946 // pages in `BatchClassRegion`.
1947 DCHECK_NE(BatchClassRegion, Region);
1948
1949 // Merge GroupsToRelease back to the Region::FreeListInfo.BlockList. Note
1950 // that both `Region->FreeListInfo.BlockList` and `GroupsToRelease` are
1951 // sorted.
1952 for (BatchGroupT *BG = Region->FreeListInfo.BlockList.front(),
1953 *Prev = nullptr;
1954 ;) {
1955 if (BG == nullptr || GroupsToRelease.empty()) {
1956 if (!GroupsToRelease.empty())
1957 Region->FreeListInfo.BlockList.append_back(&GroupsToRelease);
1958 break;
1959 }
1960
1961 DCHECK(!BG->Batches.empty());
1962
1963 if (BG->CompactPtrGroupBase <
1964 GroupsToRelease.front()->CompactPtrGroupBase) {
1965 Prev = BG;
1966 BG = BG->Next;
1967 continue;
1968 }
1969
1970 BatchGroupT *Cur = GroupsToRelease.front();
1971 BatchT *UnusedBatch = nullptr;
1972 GroupsToRelease.pop_front();
1973
1974 if (BG->CompactPtrGroupBase == Cur->CompactPtrGroupBase) {
1975 // We have updated `BatchGroup::BytesInBGAtLastCheckpoint` while
1976 // collecting the `GroupsToRelease`.
1977 BG->BytesInBGAtLastCheckpoint = Cur->BytesInBGAtLastCheckpoint;
1978 const uptr MaxCachedPerBatch = BG->MaxCachedPerBatch;
1979
1980 // Note that the first Batches in both `Batches` may not be
1981 // full and only the first Batch can have non-full blocks. Thus
1982 // we have to merge them before appending one to another.
1983 if (Cur->Batches.front()->getCount() == MaxCachedPerBatch) {
1984 BG->Batches.append_back(&Cur->Batches);
1985 } else {
1986 BatchT *NonFullBatch = Cur->Batches.front();
1987 Cur->Batches.pop_front();
1988 const u16 NonFullBatchCount = NonFullBatch->getCount();
1989 // The remaining Batches in `Cur` are full.
1990 BG->Batches.append_back(&Cur->Batches);
1991
1992 if (BG->Batches.front()->getCount() == MaxCachedPerBatch) {
1993 // Only 1 non-full Batch, push it to the front.
1994 BG->Batches.push_front(NonFullBatch);
1995 } else {
1996 const u16 NumBlocksToMove = static_cast<u16>(
1997 Min(A: static_cast<u16>(MaxCachedPerBatch -
1998 BG->Batches.front()->getCount()),
1999 B: NonFullBatchCount));
2000 BG->Batches.front()->appendFromBatch(NonFullBatch, NumBlocksToMove);
2001 if (NonFullBatch->isEmpty())
2002 UnusedBatch = NonFullBatch;
2003 else
2004 BG->Batches.push_front(NonFullBatch);
2005 }
2006 }
2007
2008 const u32 NeededSlots = UnusedBatch == nullptr ? 1U : 2U;
2009 if (UNLIKELY(Idx + NeededSlots > MaxUnusedSize)) {
2010 ScopedFLLock FL(BatchClassRegion->FLLock, BatchClassRegion);
2011 pushBatchClassBlocks(Region: BatchClassRegion, Array: Blocks, Size: Idx);
2012 Idx = 0;
2013 }
2014 Blocks[Idx++] =
2015 compactPtr(ClassId: SizeClassMap::BatchClassId, Ptr: reinterpret_cast<uptr>(Cur));
2016 if (UnusedBatch) {
2017 Blocks[Idx++] = compactPtr(ClassId: SizeClassMap::BatchClassId,
2018 Ptr: reinterpret_cast<uptr>(UnusedBatch));
2019 }
2020 Prev = BG;
2021 BG = BG->Next;
2022 continue;
2023 }
2024
2025 // At here, the `BG` is the first BatchGroup with CompactPtrGroupBase
2026 // larger than the first element in `GroupsToRelease`. We need to insert
2027 // `GroupsToRelease::front()` (which is `Cur` below) before `BG`.
2028 //
2029 // 1. If `Prev` is nullptr, we simply push `Cur` to the front of
2030 // FreeListInfo.BlockList.
2031 // 2. Otherwise, use `insert()` which inserts an element next to `Prev`.
2032 //
2033 // Afterwards, we don't need to advance `BG` because the order between
2034 // `BG` and the new `GroupsToRelease::front()` hasn't been checked.
2035 if (Prev == nullptr)
2036 Region->FreeListInfo.BlockList.push_front(Cur);
2037 else
2038 Region->FreeListInfo.BlockList.insert(Prev, Cur);
2039 DCHECK_EQ(Cur->Next, BG);
2040 Prev = Cur;
2041 }
2042
2043 if (Idx != 0) {
2044 ScopedFLLock FL(BatchClassRegion->FLLock, BatchClassRegion);
2045 pushBatchClassBlocks(Region: BatchClassRegion, Array: Blocks, Size: Idx);
2046 }
2047
2048 if (SCUDO_DEBUG) {
2049 BatchGroupT *Prev = Region->FreeListInfo.BlockList.front();
2050 for (BatchGroupT *Cur = Prev->Next; Cur != nullptr;
2051 Prev = Cur, Cur = Cur->Next) {
2052 CHECK_LT(Prev->CompactPtrGroupBase, Cur->CompactPtrGroupBase);
2053 }
2054 }
2055}
2056
2057} // namespace scudo
2058
2059#endif // SCUDO_PRIMARY64_H_
2060