1//===-- primary32.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_PRIMARY32_H_
10#define SCUDO_PRIMARY32_H_
11
12#include "allocator_common.h"
13#include "bytemap.h"
14#include "common.h"
15#include "list.h"
16#include "options.h"
17#include "release.h"
18#include "report.h"
19#include "size_class_allocator.h"
20#include "stats.h"
21#include "string_utils.h"
22#include "thread_annotations.h"
23#include "tracing.h"
24
25namespace scudo {
26
27// SizeClassAllocator32 is an allocator for 32 or 64-bit address space.
28//
29// It maps Regions of 2^RegionSizeLog bytes aligned on a 2^RegionSizeLog bytes
30// boundary, and keeps a bytemap of the mappable address space to track the size
31// class they are associated with.
32//
33// Mapped regions are split into equally sized Blocks according to the size
34// class they belong to, and the associated pointers are shuffled to prevent any
35// predictable address pattern (the predictability increases with the block
36// size).
37//
38// Regions for size class 0 are special and used to hold Batches, which
39// allow to transfer arrays of pointers from the global size class freelist to
40// the thread specific freelist for said class, and back.
41//
42// Memory used by this allocator is never unmapped but can be partially
43// reclaimed if the platform allows for it.
44
45template <typename Config> class SizeClassAllocator32 {
46public:
47 typedef typename Config::CompactPtrT CompactPtrT;
48 typedef typename Config::SizeClassMap SizeClassMap;
49 static const uptr GroupSizeLog = Config::getGroupSizeLog();
50 // The bytemap can only track UINT8_MAX - 1 classes.
51 static_assert(SizeClassMap::LargestClassId <= (UINT8_MAX - 1), "");
52 // Regions should be large enough to hold the largest Block.
53 static_assert((1UL << Config::getRegionSizeLog()) >= SizeClassMap::MaxSize,
54 "");
55 typedef SizeClassAllocator32<Config> ThisT;
56 using SizeClassAllocatorT =
57 typename Conditional<Config::getEnableBlockCache(),
58 SizeClassAllocatorLocalCache<ThisT>,
59 SizeClassAllocatorNoCache<ThisT>>::type;
60 typedef Batch<ThisT> BatchT;
61 typedef BatchGroup<ThisT> BatchGroupT;
62 static const u16 MaxNumBlocksInBatch = SizeClassMap::MaxNumCachedHint;
63
64 static constexpr uptr getSizeOfBatchClass() {
65 const uptr HeaderSize = sizeof(BatchT);
66 return HeaderSize + sizeof(CompactPtrT) * MaxNumBlocksInBatch;
67 }
68
69 static_assert(sizeof(BatchGroupT) <= getSizeOfBatchClass(),
70 "BatchGroupT also uses BatchClass");
71
72 static uptr getSizeByClassId(uptr ClassId) {
73 return (ClassId == SizeClassMap::BatchClassId)
74 ? getSizeOfBatchClass()
75 : SizeClassMap::getSizeByClassId(ClassId);
76 }
77
78 static bool canAllocate(uptr Size) { return Size <= SizeClassMap::MaxSize; }
79
80 void init(s32 ReleaseToOsInterval) NO_THREAD_SAFETY_ANALYSIS;
81
82 void unmapTestOnly();
83
84 // When all blocks are freed, it has to be the same size as `AllocatedUser`.
85 void verifyAllBlocksAreReleasedTestOnly();
86
87 CompactPtrT compactPtr(UNUSED uptr ClassId, uptr Ptr) const {
88 return static_cast<CompactPtrT>(Ptr);
89 }
90 void *decompactPtr(UNUSED uptr ClassId, CompactPtrT CompactPtr) const {
91 return reinterpret_cast<void *>(static_cast<uptr>(CompactPtr));
92 }
93 uptr compactPtrGroupBase(CompactPtrT CompactPtr) {
94 const uptr Mask = (static_cast<uptr>(1) << GroupSizeLog) - 1;
95 return CompactPtr & ~Mask;
96 }
97 uptr decompactGroupBase(uptr CompactPtrGroupBase) {
98 return CompactPtrGroupBase;
99 }
100 ALWAYS_INLINE bool isSmallBlock(uptr BlockSize) {
101 const uptr PageSize = getPageSizeCached();
102 return BlockSize < PageSize / 16U;
103 }
104 ALWAYS_INLINE bool isLargeBlock(uptr BlockSize) {
105 const uptr PageSize = getPageSizeCached();
106 return BlockSize > PageSize;
107 }
108
109 u16 popBlocks(SizeClassAllocatorT *SizeClassAllocator, uptr ClassId,
110 CompactPtrT *ToArray, const u16 MaxBlockCount);
111
112 // Push the array of free blocks to the designated batch group.
113 void pushBlocks(SizeClassAllocatorT *SizeClassAllocator, uptr ClassId,
114 CompactPtrT *Array, u32 Size);
115
116 void disable() NO_THREAD_SAFETY_ANALYSIS;
117 void enable() NO_THREAD_SAFETY_ANALYSIS;
118
119 template <typename F> void iterateOverBlocks(F Callback);
120
121 void getStats(ScopedString *Str);
122 void getFragmentationInfo(ScopedString *Str);
123 void getMemoryGroupFragmentationInfo(ScopedString *Str) {
124 // Each region is also a memory group because region size is the same as
125 // group size.
126 getFragmentationInfo(Str);
127 }
128
129 bool setOption(Option O, sptr Value);
130
131 uptr tryReleaseToOS(uptr ClassId, ReleaseToOS ReleaseType);
132 uptr releaseToOS(ReleaseToOS ReleaseType);
133
134 // Not supported in SizeClassAllocator32.
135 BlockInfo findNearestBlock(UNUSED uptr Ptr) { return {}; }
136
137 AtomicOptions Options;
138
139private:
140 static const uptr NumClasses = SizeClassMap::NumClasses;
141 static const uptr RegionSize = 1UL << Config::getRegionSizeLog();
142 static const uptr NumRegions = SCUDO_MMAP_RANGE_SIZE >>
143 Config::getRegionSizeLog();
144 static const u32 MaxNumBatches = SCUDO_ANDROID ? 4U : 8U;
145 typedef FlatByteMap<NumRegions> ByteMap;
146
147 struct ReleaseToOsInfo {
148 uptr BytesInFreeListAtLastCheckpoint;
149 uptr NumReleasesAttempted;
150 uptr LastReleasedBytes;
151 u64 LastReleaseAtNs;
152 };
153
154 struct BlocksInfo {
155 SinglyLinkedList<BatchGroupT> BlockList = {};
156 uptr PoppedBlocks = 0;
157 uptr PushedBlocks = 0;
158 };
159
160 struct alignas(SCUDO_CACHE_LINE_SIZE) SizeClassInfo {
161 HybridMutex Mutex;
162 BlocksInfo FreeListInfo GUARDED_BY(Mutex);
163 uptr CurrentRegion GUARDED_BY(Mutex);
164 uptr CurrentRegionAllocated GUARDED_BY(Mutex);
165 u32 RandState;
166 uptr AllocatedUser GUARDED_BY(Mutex);
167 // Lowest & highest region index allocated for this size class, to avoid
168 // looping through the whole NumRegions.
169 uptr MinRegionIndex GUARDED_BY(Mutex);
170 uptr MaxRegionIndex GUARDED_BY(Mutex);
171 ReleaseToOsInfo ReleaseInfo GUARDED_BY(Mutex);
172 };
173 static_assert(sizeof(SizeClassInfo) % SCUDO_CACHE_LINE_SIZE == 0, "");
174
175 uptr computeRegionId(uptr Mem) {
176 const uptr Id = Mem >> Config::getRegionSizeLog();
177 CHECK_LT(Id, NumRegions);
178 return Id;
179 }
180
181 uptr allocateRegion(SizeClassInfo *Sci, uptr ClassId) REQUIRES(Sci->Mutex);
182 uptr allocateRegionSlow();
183
184 SizeClassInfo *getSizeClassInfo(uptr ClassId) {
185 DCHECK_LT(ClassId, NumClasses);
186 return &SizeClassInfoArray[ClassId];
187 }
188
189 void pushBatchClassBlocks(SizeClassInfo *Sci, CompactPtrT *Array, u32 Size)
190 REQUIRES(Sci->Mutex);
191
192 void pushBlocksImpl(SizeClassAllocatorT *SizeClassAllocator, uptr ClassId,
193 SizeClassInfo *Sci, CompactPtrT *Array, u32 Size,
194 bool SameGroup = false) REQUIRES(Sci->Mutex);
195 u16 popBlocksImpl(SizeClassAllocatorT *SizeClassAllocator, uptr ClassId,
196 SizeClassInfo *Sci, CompactPtrT *ToArray,
197 const u16 MaxBlockCount) REQUIRES(Sci->Mutex);
198 NOINLINE bool populateFreeList(SizeClassAllocatorT *SizeClassAllocator,
199 uptr ClassId, SizeClassInfo *Sci)
200 REQUIRES(Sci->Mutex);
201
202 void getStats(ScopedString *Str, uptr ClassId, SizeClassInfo *Sci)
203 REQUIRES(Sci->Mutex);
204 void getSizeClassFragmentationInfo(SizeClassInfo *Sci, uptr ClassId,
205 ScopedString *Str) REQUIRES(Sci->Mutex);
206
207 NOINLINE uptr releaseToOSMaybe(SizeClassInfo *Sci, uptr ClassId,
208 ReleaseToOS ReleaseType = ReleaseToOS::Normal)
209 REQUIRES(Sci->Mutex);
210 bool hasChanceToReleasePages(SizeClassInfo *Sci, uptr BlockSize,
211 uptr BytesInFreeList, ReleaseToOS ReleaseType)
212 REQUIRES(Sci->Mutex);
213 PageReleaseContext markFreeBlocks(SizeClassInfo *Sci, const uptr ClassId,
214 const uptr BlockSize, const uptr Base,
215 const uptr NumberOfRegions,
216 ReleaseToOS ReleaseType)
217 REQUIRES(Sci->Mutex);
218
219 SizeClassInfo SizeClassInfoArray[NumClasses] = {};
220 HybridMutex ByteMapMutex;
221 // Track the regions in use, 0 is unused, otherwise store ClassId + 1.
222 ByteMap PossibleRegions GUARDED_BY(ByteMapMutex) = {};
223 atomic_s32 ReleaseToOsIntervalMs = {};
224 // Unless several threads request regions simultaneously from different size
225 // classes, the stash rarely contains more than 1 entry.
226 static constexpr uptr MaxStashedRegions = 4;
227 HybridMutex RegionsStashMutex;
228 uptr NumberOfStashedRegions GUARDED_BY(RegionsStashMutex) = 0;
229 uptr RegionsStash[MaxStashedRegions] GUARDED_BY(RegionsStashMutex) = {};
230};
231
232template <typename Config>
233void SizeClassAllocator32<Config>::init(s32 ReleaseToOsInterval)
234 NO_THREAD_SAFETY_ANALYSIS {
235 if (SCUDO_FUCHSIA)
236 reportError(Message: "SizeClassAllocator32 is not supported on Fuchsia");
237
238 if (SCUDO_TRUSTY)
239 reportError(Message: "SizeClassAllocator32 is not supported on Trusty");
240
241 DCHECK(isAligned(reinterpret_cast<uptr>(this), alignof(ThisT)));
242 PossibleRegions.init();
243 u32 Seed;
244 const u64 Time = getMonotonicTimeFast();
245 if (!getRandom(Buffer: reinterpret_cast<void *>(&Seed), Length: sizeof(Seed)))
246 Seed = static_cast<u32>(Time ^
247 (reinterpret_cast<uptr>(SizeClassInfoArray) >> 6));
248 for (uptr I = 0; I < NumClasses; I++) {
249 SizeClassInfo *Sci = getSizeClassInfo(ClassId: I);
250 Sci->RandState = getRandomU32(State: &Seed);
251 // Sci->MaxRegionIndex is already initialized to 0.
252 Sci->MinRegionIndex = NumRegions;
253 Sci->ReleaseInfo.LastReleaseAtNs = Time;
254 }
255
256 // The default value in the primary config has the higher priority.
257 if (Config::getDefaultReleaseToOsIntervalMs() != INT32_MIN)
258 ReleaseToOsInterval = Config::getDefaultReleaseToOsIntervalMs();
259 setOption(O: Option::ReleaseInterval, Value: static_cast<sptr>(ReleaseToOsInterval));
260}
261
262template <typename Config> void SizeClassAllocator32<Config>::unmapTestOnly() {
263 {
264 ScopedLock L(RegionsStashMutex);
265 while (NumberOfStashedRegions > 0) {
266 unmap(Addr: reinterpret_cast<void *>(RegionsStash[--NumberOfStashedRegions]),
267 Size: RegionSize);
268 }
269 }
270
271 uptr MinRegionIndex = NumRegions, MaxRegionIndex = 0;
272 for (uptr I = 0; I < NumClasses; I++) {
273 SizeClassInfo *Sci = getSizeClassInfo(ClassId: I);
274 ScopedLock L(Sci->Mutex);
275 if (Sci->MinRegionIndex < MinRegionIndex)
276 MinRegionIndex = Sci->MinRegionIndex;
277 if (Sci->MaxRegionIndex > MaxRegionIndex)
278 MaxRegionIndex = Sci->MaxRegionIndex;
279 *Sci = {};
280 }
281
282 ScopedLock L(ByteMapMutex);
283 for (uptr I = MinRegionIndex; I <= MaxRegionIndex; I++)
284 if (PossibleRegions[I])
285 unmap(Addr: reinterpret_cast<void *>(I * RegionSize), Size: RegionSize);
286 PossibleRegions.unmapTestOnly();
287}
288
289template <typename Config>
290void SizeClassAllocator32<Config>::verifyAllBlocksAreReleasedTestOnly() {
291 // `BatchGroup` and `Batch` also use the blocks from BatchClass.
292 uptr BatchClassUsedInFreeLists = 0;
293 for (uptr I = 0; I < NumClasses; I++) {
294 // We have to count BatchClassUsedInFreeLists in other regions first.
295 if (I == SizeClassMap::BatchClassId)
296 continue;
297 SizeClassInfo *Sci = getSizeClassInfo(ClassId: I);
298 ScopedLock L1(Sci->Mutex);
299 uptr TotalBlocks = 0;
300 for (BatchGroupT &BG : Sci->FreeListInfo.BlockList) {
301 // `BG::Batches` are `Batches`. +1 for `BatchGroup`.
302 BatchClassUsedInFreeLists += BG.Batches.size() + 1;
303 for (const auto &It : BG.Batches)
304 TotalBlocks += It.getCount();
305 }
306
307 const uptr BlockSize = getSizeByClassId(ClassId: I);
308 DCHECK_EQ(TotalBlocks, Sci->AllocatedUser / BlockSize);
309 DCHECK_EQ(Sci->FreeListInfo.PushedBlocks, Sci->FreeListInfo.PoppedBlocks);
310 }
311
312 SizeClassInfo *Sci = getSizeClassInfo(ClassId: SizeClassMap::BatchClassId);
313 ScopedLock L1(Sci->Mutex);
314 uptr TotalBlocks = 0;
315 for (BatchGroupT &BG : Sci->FreeListInfo.BlockList) {
316 if (LIKELY(!BG.Batches.empty())) {
317 for (const auto &It : BG.Batches)
318 TotalBlocks += It.getCount();
319 } else {
320 // `BatchGroup` with empty freelist doesn't have `Batch` record
321 // itself.
322 ++TotalBlocks;
323 }
324 }
325
326 const uptr BlockSize = getSizeByClassId(ClassId: SizeClassMap::BatchClassId);
327 DCHECK_EQ(TotalBlocks + BatchClassUsedInFreeLists,
328 Sci->AllocatedUser / BlockSize);
329 const uptr BlocksInUse =
330 Sci->FreeListInfo.PoppedBlocks - Sci->FreeListInfo.PushedBlocks;
331 DCHECK_EQ(BlocksInUse, BatchClassUsedInFreeLists);
332}
333
334template <typename Config>
335u16 SizeClassAllocator32<Config>::popBlocks(
336 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, CompactPtrT *ToArray,
337 const u16 MaxBlockCount) {
338 DCHECK_LT(ClassId, NumClasses);
339 SizeClassInfo *Sci = getSizeClassInfo(ClassId);
340 ScopedLock L(Sci->Mutex);
341
342 u16 PopCount =
343 popBlocksImpl(SizeClassAllocator, ClassId, Sci, ToArray, MaxBlockCount);
344 if (UNLIKELY(PopCount == 0)) {
345 if (UNLIKELY(!populateFreeList(SizeClassAllocator, ClassId, Sci)))
346 return 0U;
347 PopCount =
348 popBlocksImpl(SizeClassAllocator, ClassId, Sci, ToArray, MaxBlockCount);
349 DCHECK_NE(PopCount, 0U);
350 }
351
352 return PopCount;
353}
354
355template <typename Config>
356void SizeClassAllocator32<Config>::pushBlocks(
357 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, CompactPtrT *Array,
358 u32 Size) {
359 DCHECK_LT(ClassId, NumClasses);
360 DCHECK_GT(Size, 0);
361
362 SizeClassInfo *Sci = getSizeClassInfo(ClassId);
363 if (ClassId == SizeClassMap::BatchClassId) {
364 ScopedLock L(Sci->Mutex);
365 pushBatchClassBlocks(Sci, Array, Size);
366 return;
367 }
368
369 // TODO(chiahungduan): Consider not doing grouping if the group size is not
370 // greater than the block size with a certain scale.
371
372 // Sort the blocks so that blocks belonging to the same group can be pushed
373 // together.
374 bool SameGroup = true;
375 for (u32 I = 1; I < Size; ++I) {
376 if (compactPtrGroupBase(CompactPtr: Array[I - 1]) != compactPtrGroupBase(CompactPtr: Array[I]))
377 SameGroup = false;
378 CompactPtrT Cur = Array[I];
379 u32 J = I;
380 while (J > 0 &&
381 compactPtrGroupBase(CompactPtr: Cur) < compactPtrGroupBase(CompactPtr: Array[J - 1])) {
382 Array[J] = Array[J - 1];
383 --J;
384 }
385 Array[J] = Cur;
386 }
387
388 ScopedLock L(Sci->Mutex);
389 pushBlocksImpl(SizeClassAllocator, ClassId, Sci, Array, Size, SameGroup);
390}
391
392template <typename Config>
393void SizeClassAllocator32<Config>::disable() NO_THREAD_SAFETY_ANALYSIS {
394 // The BatchClassId must be locked last since other classes can use it.
395 for (sptr I = static_cast<sptr>(NumClasses) - 1; I >= 0; I--) {
396 if (static_cast<uptr>(I) == SizeClassMap::BatchClassId)
397 continue;
398 getSizeClassInfo(ClassId: static_cast<uptr>(I))->Mutex.lock();
399 }
400 getSizeClassInfo(ClassId: SizeClassMap::BatchClassId)->Mutex.lock();
401 RegionsStashMutex.lock();
402 ByteMapMutex.lock();
403}
404
405template <typename Config>
406void SizeClassAllocator32<Config>::enable() NO_THREAD_SAFETY_ANALYSIS {
407 ByteMapMutex.unlock();
408 RegionsStashMutex.unlock();
409 getSizeClassInfo(ClassId: SizeClassMap::BatchClassId)->Mutex.unlock();
410 for (uptr I = 0; I < NumClasses; I++) {
411 if (I == SizeClassMap::BatchClassId)
412 continue;
413 getSizeClassInfo(ClassId: I)->Mutex.unlock();
414 }
415}
416
417template <typename Config>
418template <typename F>
419void SizeClassAllocator32<Config>::iterateOverBlocks(F Callback) {
420 uptr MinRegionIndex = NumRegions, MaxRegionIndex = 0;
421 for (uptr I = 0; I < NumClasses; I++) {
422 SizeClassInfo *Sci = getSizeClassInfo(ClassId: I);
423 // TODO: The call of `iterateOverBlocks` requires disabling
424 // SizeClassAllocator32. We may consider locking each region on demand
425 // only.
426 Sci->Mutex.assertHeld();
427 if (Sci->MinRegionIndex < MinRegionIndex)
428 MinRegionIndex = Sci->MinRegionIndex;
429 if (Sci->MaxRegionIndex > MaxRegionIndex)
430 MaxRegionIndex = Sci->MaxRegionIndex;
431 }
432
433 // SizeClassAllocator32 is disabled, i.e., ByteMapMutex is held.
434 ByteMapMutex.assertHeld();
435
436 for (uptr I = MinRegionIndex; I <= MaxRegionIndex; I++) {
437 if (PossibleRegions[I] &&
438 (PossibleRegions[I] - 1U) != SizeClassMap::BatchClassId) {
439 const uptr BlockSize = getSizeByClassId(ClassId: PossibleRegions[I] - 1U);
440 const uptr From = I * RegionSize;
441 const uptr To = From + (RegionSize / BlockSize) * BlockSize;
442 for (uptr Block = From; Block < To; Block += BlockSize)
443 Callback(Block);
444 }
445 }
446}
447
448template <typename Config>
449void SizeClassAllocator32<Config>::getStats(ScopedString *Str) {
450 // TODO(kostyak): get the RSS per region.
451 Str->append(Format: "\nConfig Stats Primary32: ");
452 Config::getConfigValues(Str);
453 uptr TotalMapped = 0;
454 uptr PoppedBlocks = 0;
455 uptr PushedBlocks = 0;
456 for (uptr I = 0; I < NumClasses; I++) {
457 SizeClassInfo *Sci = getSizeClassInfo(ClassId: I);
458 ScopedLock L(Sci->Mutex);
459 TotalMapped += Sci->AllocatedUser;
460 PoppedBlocks += Sci->FreeListInfo.PoppedBlocks;
461 PushedBlocks += Sci->FreeListInfo.PushedBlocks;
462 }
463 Str->append(Format: "Stats: SizeClassAllocator32: %zuM mapped in %zu allocations; "
464 "remains %zu\n",
465 TotalMapped >> 20, PoppedBlocks, PoppedBlocks - PushedBlocks);
466 for (uptr I = 0; I < NumClasses; I++) {
467 SizeClassInfo *Sci = getSizeClassInfo(ClassId: I);
468 ScopedLock L(Sci->Mutex);
469 getStats(Str, I, Sci);
470 }
471}
472
473template <typename Config>
474void SizeClassAllocator32<Config>::getFragmentationInfo(ScopedString *Str) {
475 Str->append(
476 Format: "Fragmentation Stats: SizeClassAllocator32: page size = %zu bytes\n",
477 getPageSizeCached());
478
479 for (uptr I = 1; I < NumClasses; I++) {
480 SizeClassInfo *Sci = getSizeClassInfo(ClassId: I);
481 ScopedLock L(Sci->Mutex);
482 getSizeClassFragmentationInfo(Sci, ClassId: I, Str);
483 }
484}
485
486template <typename Config>
487bool SizeClassAllocator32<Config>::setOption(Option O, sptr Value) {
488 if (O == Option::ReleaseInterval) {
489 const s32 Interval =
490 Max(Min(static_cast<s32>(Value), Config::getMaxReleaseToOsIntervalMs()),
491 Config::getMinReleaseToOsIntervalMs());
492 atomic_store_relaxed(A: &ReleaseToOsIntervalMs, V: Interval);
493 return true;
494 }
495 // Not supported by the Primary, but not an error either.
496 return true;
497}
498
499template <typename Config>
500uptr SizeClassAllocator32<Config>::tryReleaseToOS(uptr ClassId,
501 ReleaseToOS ReleaseType) {
502 SizeClassInfo *Sci = getSizeClassInfo(ClassId);
503 // TODO: Once we have separate locks like primary64, we may consider using
504 // tryLock() as well.
505 ScopedLock L(Sci->Mutex);
506 return releaseToOSMaybe(Sci, ClassId, ReleaseType);
507}
508
509template <typename Config>
510uptr SizeClassAllocator32<Config>::releaseToOS(ReleaseToOS ReleaseType) {
511 SCUDO_SCOPED_TRACE(GetPrimaryReleaseToOSTraceName(ReleaseType));
512
513 uptr TotalReleasedBytes = 0;
514 for (uptr I = 0; I < NumClasses; I++) {
515 if (I == SizeClassMap::BatchClassId)
516 continue;
517 SizeClassInfo *Sci = getSizeClassInfo(ClassId: I);
518 if (ReleaseType == ReleaseToOS::ForceFast) {
519 // Never wait for the lock, always move on if there is already
520 // a release operation in progress.
521 if (Sci->Mutex.tryLock()) {
522 TotalReleasedBytes += releaseToOSMaybe(Sci, ClassId: I, ReleaseType);
523 Sci->Mutex.unlock();
524 }
525 } else {
526 ScopedLock L(Sci->Mutex);
527 TotalReleasedBytes += releaseToOSMaybe(Sci, ClassId: I, ReleaseType);
528 }
529 }
530 return TotalReleasedBytes;
531}
532
533template <typename Config>
534uptr SizeClassAllocator32<Config>::allocateRegion(SizeClassInfo *Sci,
535 uptr ClassId)
536 REQUIRES(Sci->Mutex) {
537 DCHECK_LT(ClassId, NumClasses);
538 uptr Region = 0;
539 {
540 ScopedLock L(RegionsStashMutex);
541 if (NumberOfStashedRegions > 0)
542 Region = RegionsStash[--NumberOfStashedRegions];
543 }
544 if (!Region)
545 Region = allocateRegionSlow();
546 if (LIKELY(Region)) {
547 // Sci->Mutex is held by the caller, updating the Min/Max is safe.
548 const uptr RegionIndex = computeRegionId(Mem: Region);
549 if (RegionIndex < Sci->MinRegionIndex)
550 Sci->MinRegionIndex = RegionIndex;
551 if (RegionIndex > Sci->MaxRegionIndex)
552 Sci->MaxRegionIndex = RegionIndex;
553 ScopedLock L(ByteMapMutex);
554 PossibleRegions.set(RegionIndex, static_cast<u8>(ClassId + 1U));
555 }
556 return Region;
557}
558
559template <typename Config>
560uptr SizeClassAllocator32<Config>::allocateRegionSlow() {
561 uptr MapSize = 2 * RegionSize;
562 const uptr MapBase = reinterpret_cast<uptr>(
563 map(Addr: nullptr, Size: MapSize, Name: "scudo:primary", MAP_ALLOWNOMEM));
564 if (!MapBase)
565 return 0;
566 const uptr MapEnd = MapBase + MapSize;
567 uptr Region = MapBase;
568 if (isAligned(X: Region, Alignment: RegionSize)) {
569 ScopedLock L(RegionsStashMutex);
570 if (NumberOfStashedRegions < MaxStashedRegions)
571 RegionsStash[NumberOfStashedRegions++] = MapBase + RegionSize;
572 else
573 MapSize = RegionSize;
574 } else {
575 Region = roundUp(X: MapBase, Boundary: RegionSize);
576 unmap(Addr: reinterpret_cast<void *>(MapBase), Size: Region - MapBase);
577 MapSize = RegionSize;
578 }
579 const uptr End = Region + MapSize;
580 if (End != MapEnd)
581 unmap(Addr: reinterpret_cast<void *>(End), Size: MapEnd - End);
582
583 DCHECK_EQ(Region % RegionSize, 0U);
584 static_assert(Config::getRegionSizeLog() == GroupSizeLog,
585 "Memory group should be the same size as Region");
586
587 return Region;
588}
589
590template <typename Config>
591void SizeClassAllocator32<Config>::pushBatchClassBlocks(SizeClassInfo *Sci,
592 CompactPtrT *Array,
593 u32 Size)
594 REQUIRES(Sci->Mutex) {
595 DCHECK_EQ(Sci, getSizeClassInfo(SizeClassMap::BatchClassId));
596
597 // Free blocks are recorded by Batch in freelist for all
598 // size-classes. In addition, Batch is allocated from BatchClassId.
599 // In order not to use additional block to record the free blocks in
600 // BatchClassId, they are self-contained. I.e., A Batch records the
601 // block address of itself. See the figure below:
602 //
603 // Batch at 0xABCD
604 // +----------------------------+
605 // | Free blocks' addr |
606 // | +------+------+------+ |
607 // | |0xABCD|... |... | |
608 // | +------+------+------+ |
609 // +----------------------------+
610 //
611 // When we allocate all the free blocks in the Batch, the block used
612 // by Batch is also free for use. We don't need to recycle the
613 // Batch. Note that the correctness is maintained by the invariant,
614 //
615 // Each popBlocks() request returns the entire Batch. Returning
616 // part of the blocks in a Batch is invalid.
617 //
618 // This ensures that Batch won't leak the address itself while it's
619 // still holding other valid data.
620 //
621 // Besides, BatchGroup is also allocated from BatchClassId and has its
622 // address recorded in the Batch too. To maintain the correctness,
623 //
624 // The address of BatchGroup is always recorded in the last Batch
625 // in the freelist (also imply that the freelist should only be
626 // updated with push_front). Once the last Batch is popped,
627 // the block used by BatchGroup is also free for use.
628 //
629 // With this approach, the blocks used by BatchGroup and Batch are
630 // reusable and don't need additional space for them.
631
632 Sci->FreeListInfo.PushedBlocks += Size;
633 BatchGroupT *BG = Sci->FreeListInfo.BlockList.front();
634
635 if (BG == nullptr) {
636 // Construct `BatchGroup` on the last element.
637 BG = reinterpret_cast<BatchGroupT *>(
638 decompactPtr(ClassId: SizeClassMap::BatchClassId, CompactPtr: Array[Size - 1]));
639 --Size;
640 BG->Batches.clear();
641 // BatchClass hasn't enabled memory group. Use `0` to indicate there's no
642 // memory group here.
643 BG->CompactPtrGroupBase = 0;
644 BG->BytesInBGAtLastCheckpoint = 0;
645 BG->MaxCachedPerBatch = SizeClassAllocatorT::getMaxCached(
646 getSizeByClassId(ClassId: SizeClassMap::BatchClassId));
647
648 Sci->FreeListInfo.BlockList.push_front(BG);
649 }
650
651 if (UNLIKELY(Size == 0))
652 return;
653
654 // This happens under 2 cases.
655 // 1. just allocated a new `BatchGroup`.
656 // 2. Only 1 block is pushed when the freelist is empty.
657 if (BG->Batches.empty()) {
658 // Construct the `Batch` on the last element.
659 BatchT *TB = reinterpret_cast<BatchT *>(
660 decompactPtr(ClassId: SizeClassMap::BatchClassId, CompactPtr: Array[Size - 1]));
661 TB->clear();
662 // As mentioned above, addresses of `Batch` and `BatchGroup` are
663 // recorded in the Batch.
664 TB->add(Array[Size - 1]);
665 TB->add(compactPtr(ClassId: SizeClassMap::BatchClassId, Ptr: reinterpret_cast<uptr>(BG)));
666 --Size;
667 BG->Batches.push_front(TB);
668 }
669
670 BatchT *CurBatch = BG->Batches.front();
671 DCHECK_NE(CurBatch, nullptr);
672
673 for (u32 I = 0; I < Size;) {
674 u16 UnusedSlots =
675 static_cast<u16>(BG->MaxCachedPerBatch - CurBatch->getCount());
676 if (UnusedSlots == 0) {
677 CurBatch = reinterpret_cast<BatchT *>(
678 decompactPtr(ClassId: SizeClassMap::BatchClassId, CompactPtr: Array[I]));
679 CurBatch->clear();
680 // Self-contained
681 CurBatch->add(Array[I]);
682 ++I;
683 // TODO(chiahungduan): Avoid the use of push_back() in `Batches` of
684 // BatchClassId.
685 BG->Batches.push_front(CurBatch);
686 UnusedSlots = static_cast<u16>(BG->MaxCachedPerBatch - 1);
687 }
688 // `UnusedSlots` is u16 so the result will be also fit in u16.
689 const u16 AppendSize = static_cast<u16>(Min<u32>(A: UnusedSlots, B: Size - I));
690 CurBatch->appendFromArray(&Array[I], AppendSize);
691 I += AppendSize;
692 }
693}
694
695// Push the blocks to their batch group. The layout will be like,
696//
697// FreeListInfo.BlockList - > BG -> BG -> BG
698// | | |
699// v v v
700// TB TB TB
701// |
702// v
703// TB
704//
705// Each BlockGroup(BG) will associate with unique group id and the free blocks
706// are managed by a list of Batch(TB). To reduce the time of inserting blocks,
707// BGs are sorted and the input `Array` are supposed to be sorted so that we can
708// get better performance of maintaining sorted property. Use `SameGroup=true`
709// to indicate that all blocks in the array are from the same group then we will
710// skip checking the group id of each block.
711//
712// The region mutex needs to be held while calling this method.
713template <typename Config>
714void SizeClassAllocator32<Config>::pushBlocksImpl(
715 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, SizeClassInfo *Sci,
716 CompactPtrT *Array, u32 Size, bool SameGroup) REQUIRES(Sci->Mutex) {
717 DCHECK_NE(ClassId, SizeClassMap::BatchClassId);
718 DCHECK_GT(Size, 0U);
719
720 auto CreateGroup = [&](uptr CompactPtrGroupBase) {
721 BatchGroupT *BG = reinterpret_cast<BatchGroupT *>(
722 SizeClassAllocator->getBatchClassBlock());
723 BG->Batches.clear();
724 BatchT *TB =
725 reinterpret_cast<BatchT *>(SizeClassAllocator->getBatchClassBlock());
726 TB->clear();
727
728 BG->CompactPtrGroupBase = CompactPtrGroupBase;
729 BG->Batches.push_front(TB);
730 BG->BytesInBGAtLastCheckpoint = 0;
731 BG->MaxCachedPerBatch = MaxNumBlocksInBatch;
732
733 return BG;
734 };
735
736 auto InsertBlocks = [&](BatchGroupT *BG, CompactPtrT *Array, u32 Size) {
737 SinglyLinkedList<BatchT> &Batches = BG->Batches;
738 BatchT *CurBatch = Batches.front();
739 DCHECK_NE(CurBatch, nullptr);
740
741 for (u32 I = 0; I < Size;) {
742 DCHECK_GE(BG->MaxCachedPerBatch, CurBatch->getCount());
743 u16 UnusedSlots =
744 static_cast<u16>(BG->MaxCachedPerBatch - CurBatch->getCount());
745 if (UnusedSlots == 0) {
746 CurBatch = reinterpret_cast<BatchT *>(
747 SizeClassAllocator->getBatchClassBlock());
748 CurBatch->clear();
749 Batches.push_front(CurBatch);
750 UnusedSlots = BG->MaxCachedPerBatch;
751 }
752 // `UnusedSlots` is u16 so the result will be also fit in u16.
753 u16 AppendSize = static_cast<u16>(Min<u32>(A: UnusedSlots, B: Size - I));
754 CurBatch->appendFromArray(&Array[I], AppendSize);
755 I += AppendSize;
756 }
757 };
758
759 Sci->FreeListInfo.PushedBlocks += Size;
760 BatchGroupT *Cur = Sci->FreeListInfo.BlockList.front();
761
762 // In the following, `Cur` always points to the BatchGroup for blocks that
763 // will be pushed next. `Prev` is the element right before `Cur`.
764 BatchGroupT *Prev = nullptr;
765
766 while (Cur != nullptr &&
767 compactPtrGroupBase(CompactPtr: Array[0]) > Cur->CompactPtrGroupBase) {
768 Prev = Cur;
769 Cur = Cur->Next;
770 }
771
772 if (Cur == nullptr ||
773 compactPtrGroupBase(CompactPtr: Array[0]) != Cur->CompactPtrGroupBase) {
774 Cur = CreateGroup(compactPtrGroupBase(CompactPtr: Array[0]));
775 if (Prev == nullptr)
776 Sci->FreeListInfo.BlockList.push_front(Cur);
777 else
778 Sci->FreeListInfo.BlockList.insert(Prev, Cur);
779 }
780
781 // All the blocks are from the same group, just push without checking group
782 // id.
783 if (SameGroup) {
784 for (u32 I = 0; I < Size; ++I)
785 DCHECK_EQ(compactPtrGroupBase(Array[I]), Cur->CompactPtrGroupBase);
786
787 InsertBlocks(Cur, Array, Size);
788 return;
789 }
790
791 // The blocks are sorted by group id. Determine the segment of group and
792 // push them to their group together.
793 u32 Count = 1;
794 for (u32 I = 1; I < Size; ++I) {
795 if (compactPtrGroupBase(CompactPtr: Array[I - 1]) != compactPtrGroupBase(CompactPtr: Array[I])) {
796 DCHECK_EQ(compactPtrGroupBase(Array[I - 1]), Cur->CompactPtrGroupBase);
797 InsertBlocks(Cur, Array + I - Count, Count);
798
799 while (Cur != nullptr &&
800 compactPtrGroupBase(CompactPtr: Array[I]) > Cur->CompactPtrGroupBase) {
801 Prev = Cur;
802 Cur = Cur->Next;
803 }
804
805 if (Cur == nullptr ||
806 compactPtrGroupBase(CompactPtr: Array[I]) != Cur->CompactPtrGroupBase) {
807 Cur = CreateGroup(compactPtrGroupBase(CompactPtr: Array[I]));
808 DCHECK_NE(Prev, nullptr);
809 Sci->FreeListInfo.BlockList.insert(Prev, Cur);
810 }
811
812 Count = 1;
813 } else {
814 ++Count;
815 }
816 }
817
818 InsertBlocks(Cur, Array + Size - Count, Count);
819}
820
821template <typename Config>
822u16 SizeClassAllocator32<Config>::popBlocksImpl(
823 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, SizeClassInfo *Sci,
824 CompactPtrT *ToArray, const u16 MaxBlockCount) REQUIRES(Sci->Mutex) {
825 if (Sci->FreeListInfo.BlockList.empty())
826 return 0U;
827
828 SinglyLinkedList<BatchT> &Batches =
829 Sci->FreeListInfo.BlockList.front()->Batches;
830
831 if (Batches.empty()) {
832 DCHECK_EQ(ClassId, SizeClassMap::BatchClassId);
833 BatchGroupT *BG = Sci->FreeListInfo.BlockList.front();
834 Sci->FreeListInfo.BlockList.pop_front();
835
836 // Block used by `BatchGroup` is from BatchClassId. Turn the block into
837 // `Batch` with single block.
838 BatchT *TB = reinterpret_cast<BatchT *>(BG);
839 ToArray[0] =
840 compactPtr(ClassId: SizeClassMap::BatchClassId, Ptr: reinterpret_cast<uptr>(TB));
841 Sci->FreeListInfo.PoppedBlocks += 1;
842 return 1U;
843 }
844
845 // So far, instead of always filling the blocks to `MaxBlockCount`, we only
846 // examine single `Batch` to minimize the time spent on the primary
847 // allocator. Besides, the sizes of `Batch` and
848 // `SizeClassAllocatorT::getMaxCached()` may also impact the time spent on
849 // accessing the primary allocator.
850 // TODO(chiahungduan): Evaluate if we want to always prepare `MaxBlockCount`
851 // blocks and/or adjust the size of `Batch` according to
852 // `SizeClassAllocatorT::getMaxCached()`.
853 BatchT *B = Batches.front();
854 DCHECK_NE(B, nullptr);
855 DCHECK_GT(B->getCount(), 0U);
856
857 // BachClassId should always take all blocks in the Batch. Read the
858 // comment in `pushBatchClassBlocks()` for more details.
859 const u16 PopCount = ClassId == SizeClassMap::BatchClassId
860 ? B->getCount()
861 : Min(MaxBlockCount, B->getCount());
862 B->moveNToArray(ToArray, PopCount);
863
864 // TODO(chiahungduan): The deallocation of unused BatchClassId blocks can be
865 // done without holding `Mutex`.
866 if (B->empty()) {
867 Batches.pop_front();
868 // `Batch` of BatchClassId is self-contained, no need to
869 // deallocate. Read the comment in `pushBatchClassBlocks()` for more
870 // details.
871 if (ClassId != SizeClassMap::BatchClassId)
872 SizeClassAllocator->deallocate(SizeClassMap::BatchClassId, B);
873
874 if (Batches.empty()) {
875 BatchGroupT *BG = Sci->FreeListInfo.BlockList.front();
876 Sci->FreeListInfo.BlockList.pop_front();
877
878 // We don't keep BatchGroup with zero blocks to avoid empty-checking
879 // while allocating. Note that block used for constructing BatchGroup is
880 // recorded as free blocks in the last element of BatchGroup::Batches.
881 // Which means, once we pop the last Batch, the block is
882 // implicitly deallocated.
883 if (ClassId != SizeClassMap::BatchClassId)
884 SizeClassAllocator->deallocate(SizeClassMap::BatchClassId, BG);
885 }
886 }
887
888 Sci->FreeListInfo.PoppedBlocks += PopCount;
889 return PopCount;
890}
891
892template <typename Config>
893bool SizeClassAllocator32<Config>::populateFreeList(
894 SizeClassAllocatorT *SizeClassAllocator, uptr ClassId, SizeClassInfo *Sci)
895 REQUIRES(Sci->Mutex) {
896 uptr Region;
897 uptr Offset;
898 // If the size-class currently has a region associated to it, use it. The
899 // newly created blocks will be located after the currently allocated memory
900 // for that region (up to RegionSize). Otherwise, create a new region, where
901 // the new blocks will be carved from the beginning.
902 if (Sci->CurrentRegion) {
903 Region = Sci->CurrentRegion;
904 DCHECK_GT(Sci->CurrentRegionAllocated, 0U);
905 Offset = Sci->CurrentRegionAllocated;
906 } else {
907 DCHECK_EQ(Sci->CurrentRegionAllocated, 0U);
908 Region = allocateRegion(Sci, ClassId);
909 if (UNLIKELY(!Region))
910 return false;
911 SizeClassAllocator->getStats().add(StatMapped, RegionSize);
912 Sci->CurrentRegion = Region;
913 Offset = 0;
914 }
915
916 const uptr Size = getSizeByClassId(ClassId);
917 const u16 MaxCount = SizeClassAllocatorT::getMaxCached(Size);
918 DCHECK_GT(MaxCount, 0U);
919 // The maximum number of blocks we should carve in the region is dictated
920 // by the maximum number of batches we want to fill, and the amount of
921 // memory left in the current region (we use the lowest of the two). This
922 // will not be 0 as we ensure that a region can at least hold one block (via
923 // static_assert and at the end of this function).
924 const u32 NumberOfBlocks = Min(
925 A: MaxNumBatches * MaxCount, B: static_cast<u32>((RegionSize - Offset) / Size));
926 DCHECK_GT(NumberOfBlocks, 0U);
927
928 constexpr u32 ShuffleArraySize = MaxNumBatches * MaxNumBlocksInBatch;
929 // Fill the transfer batches and put them in the size-class freelist. We
930 // need to randomize the blocks for security purposes, so we first fill a
931 // local array that we then shuffle before populating the batches.
932 CompactPtrT ShuffleArray[ShuffleArraySize];
933 DCHECK_LE(NumberOfBlocks, ShuffleArraySize);
934
935 uptr P = Region + Offset;
936 for (u32 I = 0; I < NumberOfBlocks; I++, P += Size)
937 ShuffleArray[I] = reinterpret_cast<CompactPtrT>(P);
938
939 if (ClassId != SizeClassMap::BatchClassId) {
940 u32 N = 1;
941 uptr CurGroup = compactPtrGroupBase(CompactPtr: ShuffleArray[0]);
942 for (u32 I = 1; I < NumberOfBlocks; I++) {
943 if (UNLIKELY(compactPtrGroupBase(ShuffleArray[I]) != CurGroup)) {
944 shuffle(ShuffleArray + I - N, N, &Sci->RandState);
945 pushBlocksImpl(SizeClassAllocator, ClassId, Sci, Array: ShuffleArray + I - N,
946 Size: N,
947 /*SameGroup=*/SameGroup: true);
948 N = 1;
949 CurGroup = compactPtrGroupBase(CompactPtr: ShuffleArray[I]);
950 } else {
951 ++N;
952 }
953 }
954
955 shuffle(ShuffleArray + NumberOfBlocks - N, N, &Sci->RandState);
956 pushBlocksImpl(SizeClassAllocator, ClassId, Sci,
957 Array: &ShuffleArray[NumberOfBlocks - N], Size: N,
958 /*SameGroup=*/SameGroup: true);
959 } else {
960 pushBatchClassBlocks(Sci, Array: ShuffleArray, Size: NumberOfBlocks);
961 }
962
963 // Note that `pushedBlocks` and `poppedBlocks` are supposed to only record
964 // the requests from `pushBlocks` and `PopBatch` which are external
965 // interfaces. `populateFreeList` is the internal interface so we should set
966 // the values back to avoid incorrectly setting the stats.
967 Sci->FreeListInfo.PushedBlocks -= NumberOfBlocks;
968
969 const uptr AllocatedUser = Size * NumberOfBlocks;
970 SizeClassAllocator->getStats().add(StatFree, AllocatedUser);
971 DCHECK_LE(Sci->CurrentRegionAllocated + AllocatedUser, RegionSize);
972 // If there is not enough room in the region currently associated to fit
973 // more blocks, we deassociate the region by resetting CurrentRegion and
974 // CurrentRegionAllocated. Otherwise, update the allocated amount.
975 if (RegionSize - (Sci->CurrentRegionAllocated + AllocatedUser) < Size) {
976 Sci->CurrentRegion = 0;
977 Sci->CurrentRegionAllocated = 0;
978 } else {
979 Sci->CurrentRegionAllocated += AllocatedUser;
980 }
981 Sci->AllocatedUser += AllocatedUser;
982
983 return true;
984}
985
986template <typename Config>
987void SizeClassAllocator32<Config>::getStats(ScopedString *Str, uptr ClassId,
988 SizeClassInfo *Sci)
989 REQUIRES(Sci->Mutex) {
990 if (Sci->AllocatedUser == 0)
991 return;
992 const uptr BlockSize = getSizeByClassId(ClassId);
993 const uptr InUse =
994 Sci->FreeListInfo.PoppedBlocks - Sci->FreeListInfo.PushedBlocks;
995 const uptr BytesInFreeList = Sci->AllocatedUser - InUse * BlockSize;
996 uptr PushedBytesDelta = 0;
997 if (BytesInFreeList >= Sci->ReleaseInfo.BytesInFreeListAtLastCheckpoint) {
998 PushedBytesDelta =
999 BytesInFreeList - Sci->ReleaseInfo.BytesInFreeListAtLastCheckpoint;
1000 }
1001 const uptr AvailableChunks = Sci->AllocatedUser / BlockSize;
1002 Str->append(
1003 " %02zu (%6zu): mapped: %6zuK popped: %7zu pushed: %7zu "
1004 "inuse: %6zu avail: %6zu releases attempted: %6zu last released: %6zuK "
1005 "latest pushed bytes: %6zuK\n",
1006 ClassId, getSizeByClassId(ClassId), Sci->AllocatedUser >> 10,
1007 Sci->FreeListInfo.PoppedBlocks, Sci->FreeListInfo.PushedBlocks, InUse,
1008 AvailableChunks, Sci->ReleaseInfo.NumReleasesAttempted,
1009 Sci->ReleaseInfo.LastReleasedBytes >> 10, PushedBytesDelta >> 10);
1010}
1011
1012template <typename Config>
1013void SizeClassAllocator32<Config>::getSizeClassFragmentationInfo(
1014 SizeClassInfo *Sci, uptr ClassId, ScopedString *Str) REQUIRES(Sci->Mutex) {
1015 const uptr BlockSize = getSizeByClassId(ClassId);
1016 const uptr First = Sci->MinRegionIndex;
1017 const uptr Last = Sci->MaxRegionIndex;
1018 const uptr Base = First * RegionSize;
1019 const uptr NumberOfRegions = Last - First + 1U;
1020 auto SkipRegion = [this, First, ClassId](uptr RegionIndex) {
1021 ScopedLock L(ByteMapMutex);
1022 return (PossibleRegions[First + RegionIndex] - 1U) != ClassId;
1023 };
1024
1025 FragmentationRecorder Recorder;
1026 if (!Sci->FreeListInfo.BlockList.empty()) {
1027 PageReleaseContext Context = markFreeBlocks(
1028 Sci, ClassId, BlockSize, Base, NumberOfRegions, ReleaseType: ReleaseToOS::ForceAll);
1029 releaseFreeMemoryToOS(Context, Recorder, SkipRegion);
1030 }
1031
1032 const uptr PageSize = getPageSizeCached();
1033 const uptr TotalBlocks = Sci->AllocatedUser / BlockSize;
1034 const uptr InUseBlocks =
1035 Sci->FreeListInfo.PoppedBlocks - Sci->FreeListInfo.PushedBlocks;
1036 uptr AllocatedPagesCount = 0;
1037 if (TotalBlocks != 0U) {
1038 for (uptr I = 0; I < NumberOfRegions; ++I) {
1039 if (SkipRegion(I))
1040 continue;
1041 AllocatedPagesCount += RegionSize / PageSize;
1042 }
1043
1044 DCHECK_NE(AllocatedPagesCount, 0U);
1045 }
1046
1047 DCHECK_GE(AllocatedPagesCount, Recorder.getReleasedPagesCount());
1048 const uptr InUsePages =
1049 AllocatedPagesCount - Recorder.getReleasedPagesCount();
1050 const uptr InUseBytes = InUsePages * PageSize;
1051
1052 uptr Integral;
1053 uptr Fractional;
1054 computePercentage(Numerator: BlockSize * InUseBlocks, Denominator: InUseBytes, Integral: &Integral,
1055 Fractional: &Fractional);
1056 Str->append(Format: " %02zu (%6zu): inuse/total blocks: %6zu/%6zu inuse/total "
1057 "pages: %6zu/%6zu inuse bytes: %6zuK util: %3zu.%02zu%%\n",
1058 ClassId, BlockSize, InUseBlocks, TotalBlocks, InUsePages,
1059 AllocatedPagesCount, InUseBytes >> 10, Integral, Fractional);
1060}
1061
1062template <typename Config>
1063uptr SizeClassAllocator32<Config>::releaseToOSMaybe(SizeClassInfo *Sci,
1064 uptr ClassId,
1065 ReleaseToOS ReleaseType)
1066 REQUIRES(Sci->Mutex) {
1067 const uptr BlockSize = getSizeByClassId(ClassId);
1068
1069 DCHECK_GE(Sci->FreeListInfo.PoppedBlocks, Sci->FreeListInfo.PushedBlocks);
1070 const uptr BytesInFreeList =
1071 Sci->AllocatedUser -
1072 (Sci->FreeListInfo.PoppedBlocks - Sci->FreeListInfo.PushedBlocks) *
1073 BlockSize;
1074
1075 if (UNLIKELY(BytesInFreeList == 0))
1076 return 0;
1077
1078 // ====================================================================== //
1079 // 1. Check if we have enough free blocks and if it's worth doing a page
1080 // release.
1081 // ====================================================================== //
1082 if (ReleaseType != ReleaseToOS::ForceAll &&
1083 !hasChanceToReleasePages(Sci, BlockSize, BytesInFreeList, ReleaseType)) {
1084 return 0;
1085 }
1086
1087 const uptr First = Sci->MinRegionIndex;
1088 const uptr Last = Sci->MaxRegionIndex;
1089 DCHECK_NE(Last, 0U);
1090 DCHECK_LE(First, Last);
1091 uptr TotalReleasedBytes = 0;
1092 const uptr Base = First * RegionSize;
1093 const uptr NumberOfRegions = Last - First + 1U;
1094
1095 // The following steps contribute to the majority time spent in page
1096 // releasing thus we increment the counter here.
1097 ++Sci->ReleaseInfo.NumReleasesAttempted;
1098
1099 // ==================================================================== //
1100 // 2. Mark the free blocks and we can tell which pages are in-use by
1101 // querying `PageReleaseContext`.
1102 // ==================================================================== //
1103
1104 // Only add trace point after the quick returns have occurred to avoid
1105 // incurring performance penalties. Most of the time in this function
1106 // will be the mark free blocks call and the actual release to OS call.
1107 SCUDO_SCOPED_TRACE(GetPrimaryReleaseToOSMaybeTraceName(ReleaseType));
1108
1109 PageReleaseContext Context = markFreeBlocks(Sci, ClassId, BlockSize, Base,
1110 NumberOfRegions, ReleaseType);
1111 if (!Context.hasBlockMarked())
1112 return 0;
1113
1114 // ==================================================================== //
1115 // 3. Release the unused physical pages back to the OS.
1116 // ==================================================================== //
1117 ReleaseRecorder Recorder(Base);
1118 auto SkipRegion = [this, First, ClassId](uptr RegionIndex) {
1119 ScopedLock L(ByteMapMutex);
1120 return (PossibleRegions[First + RegionIndex] - 1U) != ClassId;
1121 };
1122 releaseFreeMemoryToOS(Context, Recorder, SkipRegion);
1123
1124 if (Recorder.getReleasedBytes() > 0) {
1125 Sci->ReleaseInfo.BytesInFreeListAtLastCheckpoint = BytesInFreeList;
1126 Sci->ReleaseInfo.LastReleasedBytes = Recorder.getReleasedBytes();
1127 TotalReleasedBytes += Sci->ReleaseInfo.LastReleasedBytes;
1128 }
1129 Sci->ReleaseInfo.LastReleaseAtNs = getMonotonicTimeFast();
1130
1131 return TotalReleasedBytes;
1132}
1133
1134template <typename Config>
1135bool SizeClassAllocator32<Config>::hasChanceToReleasePages(
1136 SizeClassInfo *Sci, uptr BlockSize, uptr BytesInFreeList,
1137 ReleaseToOS ReleaseType) REQUIRES(Sci->Mutex) {
1138 DCHECK_GE(Sci->FreeListInfo.PoppedBlocks, Sci->FreeListInfo.PushedBlocks);
1139 const uptr PageSize = getPageSizeCached();
1140
1141 if (BytesInFreeList <= Sci->ReleaseInfo.BytesInFreeListAtLastCheckpoint)
1142 Sci->ReleaseInfo.BytesInFreeListAtLastCheckpoint = BytesInFreeList;
1143
1144 // Always update `BytesInFreeListAtLastCheckpoint` with the smallest value
1145 // so that we won't underestimate the releasable pages. For example, the
1146 // following is the region usage,
1147 //
1148 // BytesInFreeListAtLastCheckpoint AllocatedUser
1149 // v v
1150 // |--------------------------------------->
1151 // ^ ^
1152 // BytesInFreeList ReleaseThreshold
1153 //
1154 // In general, if we have collected enough bytes and the amount of free
1155 // bytes meets the ReleaseThreshold, we will try to do page release. If we
1156 // don't update `BytesInFreeListAtLastCheckpoint` when the current
1157 // `BytesInFreeList` is smaller, we may take longer time to wait for enough
1158 // freed blocks because we miss the bytes between
1159 // (BytesInFreeListAtLastCheckpoint - BytesInFreeList).
1160 const uptr PushedBytesDelta =
1161 BytesInFreeList - Sci->ReleaseInfo.BytesInFreeListAtLastCheckpoint;
1162 if (PushedBytesDelta < PageSize)
1163 return false;
1164
1165 // Releasing smaller blocks is expensive, so we want to make sure that a
1166 // significant amount of bytes are free, and that there has been a good
1167 // amount of batches pushed to the freelist before attempting to release.
1168 if (isSmallBlock(BlockSize) && ReleaseType == ReleaseToOS::Normal)
1169 if (PushedBytesDelta < Sci->AllocatedUser / 16U)
1170 return false;
1171
1172 if (ReleaseType == ReleaseToOS::Normal) {
1173 const s32 IntervalMs = atomic_load_relaxed(A: &ReleaseToOsIntervalMs);
1174 if (IntervalMs < 0)
1175 return false;
1176
1177 // The constant 8 here is selected from profiling some apps and the number
1178 // of unreleased pages in the large size classes is around 16 pages or
1179 // more. Choose half of it as a heuristic and which also avoids page
1180 // release every time for every pushBlocks() attempt by large blocks.
1181 const bool ByPassReleaseInterval =
1182 isLargeBlock(BlockSize) && PushedBytesDelta > 8 * PageSize;
1183 if (!ByPassReleaseInterval) {
1184 if (Sci->ReleaseInfo.LastReleaseAtNs +
1185 static_cast<u64>(IntervalMs) * 1000000 >
1186 getMonotonicTimeFast()) {
1187 // Memory was returned recently.
1188 return false;
1189 }
1190 }
1191 } // if (ReleaseType == ReleaseToOS::Normal)
1192
1193 return true;
1194}
1195
1196template <typename Config>
1197PageReleaseContext SizeClassAllocator32<Config>::markFreeBlocks(
1198 SizeClassInfo *Sci, const uptr ClassId, const uptr BlockSize,
1199 const uptr Base, const uptr NumberOfRegions, ReleaseToOS ReleaseType)
1200 REQUIRES(Sci->Mutex) {
1201 const uptr PageSize = getPageSizeCached();
1202 const uptr GroupSize = (1UL << GroupSizeLog);
1203 const uptr CurGroupBase =
1204 compactPtrGroupBase(CompactPtr: compactPtr(ClassId, Ptr: Sci->CurrentRegion));
1205
1206 PageReleaseContext Context(BlockSize, NumberOfRegions,
1207 /*ReleaseSize=*/RegionSize);
1208
1209 auto DecompactPtr = [](CompactPtrT CompactPtr) {
1210 return reinterpret_cast<uptr>(CompactPtr);
1211 };
1212 for (BatchGroupT &BG : Sci->FreeListInfo.BlockList) {
1213 const uptr GroupBase = decompactGroupBase(CompactPtrGroupBase: BG.CompactPtrGroupBase);
1214 // The `GroupSize` may not be divided by `BlockSize`, which means there is
1215 // an unused space at the end of Region. Exclude that space to avoid
1216 // unused page map entry.
1217 uptr AllocatedGroupSize = GroupBase == CurGroupBase
1218 ? Sci->CurrentRegionAllocated
1219 : roundDownSlow(X: GroupSize, Boundary: BlockSize);
1220 if (AllocatedGroupSize == 0)
1221 continue;
1222
1223 // Batches are pushed in front of BG.Batches. The first one may
1224 // not have all caches used.
1225 const uptr NumBlocks = (BG.Batches.size() - 1) * BG.MaxCachedPerBatch +
1226 BG.Batches.front()->getCount();
1227 const uptr BytesInBG = NumBlocks * BlockSize;
1228
1229 if (ReleaseType != ReleaseToOS::ForceAll) {
1230 if (BytesInBG <= BG.BytesInBGAtLastCheckpoint) {
1231 BG.BytesInBGAtLastCheckpoint = BytesInBG;
1232 continue;
1233 }
1234
1235 const uptr PushedBytesDelta = BytesInBG - BG.BytesInBGAtLastCheckpoint;
1236 if (PushedBytesDelta < PageSize)
1237 continue;
1238
1239 // Given the randomness property, we try to release the pages only if
1240 // the bytes used by free blocks exceed certain proportion of allocated
1241 // spaces.
1242 if (isSmallBlock(BlockSize) && (BytesInBG * 100U) / AllocatedGroupSize <
1243 (100U - 1U - BlockSize / 16U)) {
1244 continue;
1245 }
1246 }
1247
1248 // TODO: Consider updating this after page release if `ReleaseRecorder`
1249 // can tell the released bytes in each group.
1250 BG.BytesInBGAtLastCheckpoint = BytesInBG;
1251
1252 const uptr MaxContainedBlocks = AllocatedGroupSize / BlockSize;
1253 const uptr RegionIndex = (GroupBase - Base) / RegionSize;
1254
1255 if (NumBlocks == MaxContainedBlocks) {
1256 for (const auto &It : BG.Batches)
1257 for (u16 I = 0; I < It.getCount(); ++I)
1258 DCHECK_EQ(compactPtrGroupBase(It.get(I)), BG.CompactPtrGroupBase);
1259
1260 const uptr To = GroupBase + AllocatedGroupSize;
1261 Context.markRangeAsAllCounted(From: GroupBase, To, Base: GroupBase, RegionIndex,
1262 RegionSize: AllocatedGroupSize);
1263 } else {
1264 DCHECK_LT(NumBlocks, MaxContainedBlocks);
1265
1266 // Note that we don't always visit blocks in each BatchGroup so that we
1267 // may miss the chance of releasing certain pages that cross
1268 // BatchGroups.
1269 Context.markFreeBlocksInRegion(BG.Batches, DecompactPtr, GroupBase,
1270 RegionIndex, AllocatedGroupSize,
1271 /*MayContainLastBlockInRegion=*/true);
1272 }
1273
1274 // We may not be able to do the page release In a rare case that we may
1275 // fail on PageMap allocation.
1276 if (UNLIKELY(!Context.hasBlockMarked()))
1277 break;
1278 }
1279
1280 return Context;
1281}
1282
1283} // namespace scudo
1284
1285#endif // SCUDO_PRIMARY32_H_
1286