blob: f9854cbfd4d68da507fedf625ea276ea3e4b50a7 [file] [log] [blame]
Dynamic Tools Team517193e2019-09-11 14:48:41 +00001//===-- 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 "bytemap.h"
13#include "common.h"
14#include "list.h"
15#include "local_cache.h"
Dynamic Tools Team48429c72019-12-04 17:46:15 -080016#include "memtag.h"
Peter Collingbourne3cf60372020-09-24 17:01:24 -070017#include "options.h"
Dynamic Tools Team517193e2019-09-11 14:48:41 +000018#include "release.h"
19#include "stats.h"
20#include "string_utils.h"
21
22namespace scudo {
23
24// SizeClassAllocator64 is an allocator tuned for 64-bit address space.
25//
26// It starts by reserving NumClasses * 2^RegionSizeLog bytes, equally divided in
27// Regions, specific to each size class. Note that the base of that mapping is
28// random (based to the platform specific map() capabilities), and that each
29// Region actually starts at a random offset from its base.
30//
31// Regions are mapped incrementally on demand to fulfill allocation requests,
32// those mappings being split into equally sized Blocks based on the size class
33// they belong to. The Blocks created are shuffled to prevent predictable
34// address patterns (the predictability increases with the size of the Blocks).
35//
36// The 1st Region (for size class 0) holds the TransferBatches. This is a
37// structure used to transfer arrays of available pointers from the class size
38// freelist to the thread specific freelist, and back.
39//
40// The memory used by this allocator is never unmapped, but can be partially
41// released if the platform allows for it.
42
Dynamic Tools Team48429c72019-12-04 17:46:15 -080043template <class SizeClassMapT, uptr RegionSizeLog,
Dynamic Tools Team26387462020-02-14 12:24:03 -080044 s32 MinReleaseToOsIntervalMs = INT32_MIN,
45 s32 MaxReleaseToOsIntervalMs = INT32_MAX,
Dynamic Tools Team48429c72019-12-04 17:46:15 -080046 bool MaySupportMemoryTagging = false>
47class SizeClassAllocator64 {
Dynamic Tools Team517193e2019-09-11 14:48:41 +000048public:
49 typedef SizeClassMapT SizeClassMap;
Dynamic Tools Team2e7fec22020-02-16 15:29:46 -080050 typedef SizeClassAllocator64<
51 SizeClassMap, RegionSizeLog, MinReleaseToOsIntervalMs,
52 MaxReleaseToOsIntervalMs, MaySupportMemoryTagging>
Dynamic Tools Team48429c72019-12-04 17:46:15 -080053 ThisT;
Dynamic Tools Team517193e2019-09-11 14:48:41 +000054 typedef SizeClassAllocatorLocalCache<ThisT> CacheT;
55 typedef typename CacheT::TransferBatch TransferBatch;
Dynamic Tools Team48429c72019-12-04 17:46:15 -080056 static const bool SupportsMemoryTagging =
57 MaySupportMemoryTagging && archSupportsMemoryTagging();
Dynamic Tools Team517193e2019-09-11 14:48:41 +000058
59 static uptr getSizeByClassId(uptr ClassId) {
60 return (ClassId == SizeClassMap::BatchClassId)
61 ? sizeof(TransferBatch)
62 : SizeClassMap::getSizeByClassId(ClassId);
63 }
64
65 static bool canAllocate(uptr Size) { return Size <= SizeClassMap::MaxSize; }
66
67 void initLinkerInitialized(s32 ReleaseToOsInterval) {
68 // Reserve the space required for the Primary.
69 PrimaryBase = reinterpret_cast<uptr>(
70 map(nullptr, PrimarySize, "scudo:primary", MAP_NOACCESS, &Data));
71
Dynamic Tools Team517193e2019-09-11 14:48:41 +000072 u32 Seed;
Dynamic Tools Team6a8384a2020-03-03 11:16:31 -080073 const u64 Time = getMonotonicTime();
Dynamic Tools Team517193e2019-09-11 14:48:41 +000074 if (UNLIKELY(!getRandom(reinterpret_cast<void *>(&Seed), sizeof(Seed))))
Dynamic Tools Team6a8384a2020-03-03 11:16:31 -080075 Seed = static_cast<u32>(Time ^ (PrimaryBase >> 12));
Dynamic Tools Team517193e2019-09-11 14:48:41 +000076 const uptr PageSize = getPageSizeCached();
77 for (uptr I = 0; I < NumClasses; I++) {
78 RegionInfo *Region = getRegionInfo(I);
79 // The actual start of a region is offseted by a random number of pages.
80 Region->RegionBeg =
81 getRegionBaseByClassId(I) + (getRandomModN(&Seed, 16) + 1) * PageSize;
Dynamic Tools Team6a8384a2020-03-03 11:16:31 -080082 Region->RandState = getRandomU32(&Seed);
Kostya Kortchinsky156d47c2020-12-11 14:04:47 -080083 Region->ReleaseInfo.LastReleaseAtNs = Time;
Dynamic Tools Team517193e2019-09-11 14:48:41 +000084 }
Kostya Kortchinskyc72ca562020-07-27 09:13:42 -070085 setOption(Option::ReleaseInterval, static_cast<sptr>(ReleaseToOsInterval));
Dynamic Tools Team48429c72019-12-04 17:46:15 -080086
Peter Collingbourne3cf60372020-09-24 17:01:24 -070087 if (SupportsMemoryTagging && systemSupportsMemoryTagging())
88 Options.set(OptionBit::UseMemoryTagging);
Dynamic Tools Team517193e2019-09-11 14:48:41 +000089 }
90 void init(s32 ReleaseToOsInterval) {
91 memset(this, 0, sizeof(*this));
92 initLinkerInitialized(ReleaseToOsInterval);
93 }
94
95 void unmapTestOnly() {
96 unmap(reinterpret_cast<void *>(PrimaryBase), PrimarySize, UNMAP_ALL, &Data);
Dynamic Tools Team517193e2019-09-11 14:48:41 +000097 }
98
99 TransferBatch *popBatch(CacheT *C, uptr ClassId) {
100 DCHECK_LT(ClassId, NumClasses);
101 RegionInfo *Region = getRegionInfo(ClassId);
102 ScopedLock L(Region->Mutex);
103 TransferBatch *B = Region->FreeList.front();
104 if (B) {
105 Region->FreeList.pop_front();
106 } else {
107 B = populateFreeList(C, ClassId, Region);
108 if (UNLIKELY(!B))
109 return nullptr;
110 }
111 DCHECK_GT(B->getCount(), 0);
112 Region->Stats.PoppedBlocks += B->getCount();
113 return B;
114 }
115
116 void pushBatch(uptr ClassId, TransferBatch *B) {
117 DCHECK_GT(B->getCount(), 0);
118 RegionInfo *Region = getRegionInfo(ClassId);
119 ScopedLock L(Region->Mutex);
120 Region->FreeList.push_front(B);
121 Region->Stats.PushedBlocks += B->getCount();
Kostya Kortchinsky156d47c2020-12-11 14:04:47 -0800122 if (ClassId != SizeClassMap::BatchClassId)
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000123 releaseToOSMaybe(Region, ClassId);
124 }
125
126 void disable() {
Dynamic Tools Team83eaa512020-01-09 11:43:16 -0800127 // The BatchClassId must be locked last since other classes can use it.
128 for (sptr I = static_cast<sptr>(NumClasses) - 1; I >= 0; I--) {
129 if (static_cast<uptr>(I) == SizeClassMap::BatchClassId)
130 continue;
131 getRegionInfo(static_cast<uptr>(I))->Mutex.lock();
132 }
133 getRegionInfo(SizeClassMap::BatchClassId)->Mutex.lock();
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000134 }
135
136 void enable() {
Dynamic Tools Team83eaa512020-01-09 11:43:16 -0800137 getRegionInfo(SizeClassMap::BatchClassId)->Mutex.unlock();
138 for (uptr I = 0; I < NumClasses; I++) {
139 if (I == SizeClassMap::BatchClassId)
140 continue;
141 getRegionInfo(I)->Mutex.unlock();
142 }
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000143 }
144
Dynamic Tools Team2e7fec22020-02-16 15:29:46 -0800145 template <typename F> void iterateOverBlocks(F Callback) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000146 for (uptr I = 0; I < NumClasses; I++) {
147 if (I == SizeClassMap::BatchClassId)
148 continue;
149 const RegionInfo *Region = getRegionInfo(I);
150 const uptr BlockSize = getSizeByClassId(I);
151 const uptr From = Region->RegionBeg;
152 const uptr To = From + Region->AllocatedUser;
153 for (uptr Block = From; Block < To; Block += BlockSize)
154 Callback(Block);
155 }
156 }
157
Dynamic Tools Team2e7fec22020-02-16 15:29:46 -0800158 void getStats(ScopedString *Str) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000159 // TODO(kostyak): get the RSS per region.
160 uptr TotalMapped = 0;
161 uptr PoppedBlocks = 0;
162 uptr PushedBlocks = 0;
163 for (uptr I = 0; I < NumClasses; I++) {
164 RegionInfo *Region = getRegionInfo(I);
165 if (Region->MappedUser)
166 TotalMapped += Region->MappedUser;
167 PoppedBlocks += Region->Stats.PoppedBlocks;
168 PushedBlocks += Region->Stats.PushedBlocks;
169 }
Dynamic Tools Team3e8c65b2019-10-18 20:00:32 +0000170 Str->append("Stats: SizeClassAllocator64: %zuM mapped (%zuM rss) in %zu "
171 "allocations; remains %zu\n",
172 TotalMapped >> 20, 0, PoppedBlocks,
173 PoppedBlocks - PushedBlocks);
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000174
175 for (uptr I = 0; I < NumClasses; I++)
Dynamic Tools Team3e8c65b2019-10-18 20:00:32 +0000176 getStats(Str, I, 0);
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000177 }
178
Kostya Kortchinskyc72ca562020-07-27 09:13:42 -0700179 bool setOption(Option O, sptr Value) {
180 if (O == Option::ReleaseInterval) {
181 const s32 Interval =
182 Max(Min(static_cast<s32>(Value), MaxReleaseToOsIntervalMs),
183 MinReleaseToOsIntervalMs);
Kostya Kortchinskya51a8922020-11-02 14:27:11 -0800184 atomic_store_relaxed(&ReleaseToOsIntervalMs, Interval);
Kostya Kortchinskyc72ca562020-07-27 09:13:42 -0700185 return true;
Dynamic Tools Team26387462020-02-14 12:24:03 -0800186 }
Kostya Kortchinskyc72ca562020-07-27 09:13:42 -0700187 // Not supported by the Primary, but not an error either.
188 return true;
Dynamic Tools Team26387462020-02-14 12:24:03 -0800189 }
190
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000191 uptr releaseToOS() {
192 uptr TotalReleasedBytes = 0;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000193 for (uptr I = 0; I < NumClasses; I++) {
Kostya Kortchinsky156d47c2020-12-11 14:04:47 -0800194 if (I == SizeClassMap::BatchClassId)
195 continue;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000196 RegionInfo *Region = getRegionInfo(I);
197 ScopedLock L(Region->Mutex);
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000198 TotalReleasedBytes += releaseToOSMaybe(Region, I, /*Force=*/true);
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000199 }
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000200 return TotalReleasedBytes;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000201 }
202
Peter Collingbourne3cf60372020-09-24 17:01:24 -0700203 static bool useMemoryTagging(Options Options) {
204 return SupportsMemoryTagging && Options.get(OptionBit::UseMemoryTagging);
Dynamic Tools Team48429c72019-12-04 17:46:15 -0800205 }
Peter Collingbourne3cf60372020-09-24 17:01:24 -0700206 void disableMemoryTagging() { Options.clear(OptionBit::UseMemoryTagging); }
Dynamic Tools Team48429c72019-12-04 17:46:15 -0800207
Dynamic Tools Team0d7d2ae2020-04-21 15:30:50 -0700208 const char *getRegionInfoArrayAddress() const {
209 return reinterpret_cast<const char *>(RegionInfoArray);
210 }
211
Kostya Kortchinsky394cc822020-06-17 10:31:53 -0700212 static uptr getRegionInfoArraySize() { return sizeof(RegionInfoArray); }
Dynamic Tools Team0d7d2ae2020-04-21 15:30:50 -0700213
214 static BlockInfo findNearestBlock(const char *RegionInfoData, uptr Ptr) {
215 const RegionInfo *RegionInfoArray =
216 reinterpret_cast<const RegionInfo *>(RegionInfoData);
217 uptr ClassId;
218 uptr MinDistance = -1UL;
219 for (uptr I = 0; I != NumClasses; ++I) {
220 if (I == SizeClassMap::BatchClassId)
221 continue;
222 uptr Begin = RegionInfoArray[I].RegionBeg;
223 uptr End = Begin + RegionInfoArray[I].AllocatedUser;
224 if (Begin > End || End - Begin < SizeClassMap::getSizeByClassId(I))
225 continue;
226 uptr RegionDistance;
227 if (Begin <= Ptr) {
228 if (Ptr < End)
229 RegionDistance = 0;
230 else
231 RegionDistance = Ptr - End;
232 } else {
233 RegionDistance = Begin - Ptr;
234 }
235
236 if (RegionDistance < MinDistance) {
237 MinDistance = RegionDistance;
238 ClassId = I;
239 }
240 }
241
242 BlockInfo B = {};
243 if (MinDistance <= 8192) {
244 B.RegionBegin = RegionInfoArray[ClassId].RegionBeg;
245 B.RegionEnd = B.RegionBegin + RegionInfoArray[ClassId].AllocatedUser;
246 B.BlockSize = SizeClassMap::getSizeByClassId(ClassId);
247 B.BlockBegin =
248 B.RegionBegin + uptr(sptr(Ptr - B.RegionBegin) / sptr(B.BlockSize) *
249 sptr(B.BlockSize));
250 while (B.BlockBegin < B.RegionBegin)
251 B.BlockBegin += B.BlockSize;
252 while (B.RegionEnd < B.BlockBegin + B.BlockSize)
253 B.BlockBegin -= B.BlockSize;
254 }
255 return B;
256 }
257
Peter Collingbourne3cf60372020-09-24 17:01:24 -0700258 AtomicOptions Options;
259
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000260private:
261 static const uptr RegionSize = 1UL << RegionSizeLog;
262 static const uptr NumClasses = SizeClassMap::NumClasses;
263 static const uptr PrimarySize = RegionSize * NumClasses;
264
265 // Call map for user memory with at least this size.
Dynamic Tools Team75868b72020-01-30 15:26:46 -0800266 static const uptr MapSizeIncrement = 1UL << 18;
Dynamic Tools Teamaa152462019-11-19 10:18:38 -0800267 // Fill at most this number of batches from the newly map'd memory.
Dynamic Tools Team6a8384a2020-03-03 11:16:31 -0800268 static const u32 MaxNumBatches = SCUDO_ANDROID ? 4U : 8U;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000269
270 struct RegionStats {
271 uptr PoppedBlocks;
272 uptr PushedBlocks;
273 };
274
275 struct ReleaseToOsInfo {
276 uptr PushedBlocksAtLastRelease;
277 uptr RangesReleased;
278 uptr LastReleasedBytes;
279 u64 LastReleaseAtNs;
280 };
281
Dynamic Tools Team0d7d2ae2020-04-21 15:30:50 -0700282 struct UnpaddedRegionInfo {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000283 HybridMutex Mutex;
Dynamic Tools Team35997702019-10-28 15:06:10 -0700284 SinglyLinkedList<TransferBatch> FreeList;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000285 RegionStats Stats;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000286 bool Exhausted;
287 u32 RandState;
288 uptr RegionBeg;
289 uptr MappedUser; // Bytes mapped for user memory.
290 uptr AllocatedUser; // Bytes allocated for user memory.
291 MapPlatformData Data;
292 ReleaseToOsInfo ReleaseInfo;
293 };
Dynamic Tools Team0d7d2ae2020-04-21 15:30:50 -0700294 struct RegionInfo : UnpaddedRegionInfo {
295 char Padding[SCUDO_CACHE_LINE_SIZE -
296 (sizeof(UnpaddedRegionInfo) % SCUDO_CACHE_LINE_SIZE)];
297 };
Dynamic Tools Team09e6d482019-11-26 18:18:14 -0800298 static_assert(sizeof(RegionInfo) % SCUDO_CACHE_LINE_SIZE == 0, "");
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000299
300 uptr PrimaryBase;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000301 MapPlatformData Data;
Dynamic Tools Team26387462020-02-14 12:24:03 -0800302 atomic_s32 ReleaseToOsIntervalMs;
Dynamic Tools Team0d7d2ae2020-04-21 15:30:50 -0700303 alignas(SCUDO_CACHE_LINE_SIZE) RegionInfo RegionInfoArray[NumClasses];
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000304
Dynamic Tools Team2e7fec22020-02-16 15:29:46 -0800305 RegionInfo *getRegionInfo(uptr ClassId) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000306 DCHECK_LT(ClassId, NumClasses);
307 return &RegionInfoArray[ClassId];
308 }
309
310 uptr getRegionBaseByClassId(uptr ClassId) const {
311 return PrimaryBase + (ClassId << RegionSizeLog);
312 }
313
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000314 NOINLINE TransferBatch *populateFreeList(CacheT *C, uptr ClassId,
315 RegionInfo *Region) {
316 const uptr Size = getSizeByClassId(ClassId);
317 const u32 MaxCount = TransferBatch::getMaxCached(Size);
318
319 const uptr RegionBeg = Region->RegionBeg;
320 const uptr MappedUser = Region->MappedUser;
321 const uptr TotalUserBytes = Region->AllocatedUser + MaxCount * Size;
322 // Map more space for blocks, if necessary.
Kostya Kortchinskye7788062020-11-03 11:21:15 -0800323 if (UNLIKELY(TotalUserBytes > MappedUser)) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000324 // Do the mmap for the user memory.
325 const uptr UserMapSize =
326 roundUpTo(TotalUserBytes - MappedUser, MapSizeIncrement);
327 const uptr RegionBase = RegionBeg - getRegionBaseByClassId(ClassId);
Kostya Kortchinskye7788062020-11-03 11:21:15 -0800328 if (RegionBase + MappedUser + UserMapSize > RegionSize) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000329 if (!Region->Exhausted) {
330 Region->Exhausted = true;
Dynamic Tools Team3e8c65b2019-10-18 20:00:32 +0000331 ScopedString Str(1024);
332 getStats(&Str);
333 Str.append(
Kostya Kortchinskye7788062020-11-03 11:21:15 -0800334 "Scudo OOM: The process has exhausted %zuM for size class %zu.\n",
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000335 RegionSize >> 20, Size);
Dynamic Tools Team3e8c65b2019-10-18 20:00:32 +0000336 Str.output();
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000337 }
338 return nullptr;
339 }
Kostya Kortchinskye7788062020-11-03 11:21:15 -0800340 if (MappedUser == 0)
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000341 Region->Data = Data;
Kostya Kortchinskye7788062020-11-03 11:21:15 -0800342 if (!map(reinterpret_cast<void *>(RegionBeg + MappedUser), UserMapSize,
343 "scudo:primary",
344 MAP_ALLOWNOMEM | MAP_RESIZABLE |
345 (useMemoryTagging(Options.load()) ? MAP_MEMTAG : 0),
346 &Region->Data))
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000347 return nullptr;
348 Region->MappedUser += UserMapSize;
349 C->getStats().add(StatMapped, UserMapSize);
350 }
351
Dynamic Tools Teamaa152462019-11-19 10:18:38 -0800352 const u32 NumberOfBlocks = Min(
353 MaxNumBatches * MaxCount,
354 static_cast<u32>((Region->MappedUser - Region->AllocatedUser) / Size));
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000355 DCHECK_GT(NumberOfBlocks, 0);
356
Dynamic Tools Teamaa152462019-11-19 10:18:38 -0800357 constexpr u32 ShuffleArraySize =
358 MaxNumBatches * TransferBatch::MaxNumCached;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000359 void *ShuffleArray[ShuffleArraySize];
Kostya Kortchinskye7788062020-11-03 11:21:15 -0800360 DCHECK_LE(NumberOfBlocks, ShuffleArraySize);
361
362 uptr P = RegionBeg + Region->AllocatedUser;
363 for (u32 I = 0; I < NumberOfBlocks; I++, P += Size)
364 ShuffleArray[I] = reinterpret_cast<void *>(P);
365 // No need to shuffle the batches size class.
366 if (ClassId != SizeClassMap::BatchClassId)
367 shuffle(ShuffleArray, NumberOfBlocks, &Region->RandState);
368 for (u32 I = 0; I < NumberOfBlocks;) {
369 TransferBatch *B = C->createBatch(ClassId, ShuffleArray[I]);
370 if (UNLIKELY(!B))
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000371 return nullptr;
Kostya Kortchinskye7788062020-11-03 11:21:15 -0800372 const u32 N = Min(MaxCount, NumberOfBlocks - I);
373 B->setFromArray(&ShuffleArray[I], N);
Dynamic Tools Teamaa152462019-11-19 10:18:38 -0800374 Region->FreeList.push_back(B);
Kostya Kortchinskye7788062020-11-03 11:21:15 -0800375 I += N;
Dynamic Tools Teamaa152462019-11-19 10:18:38 -0800376 }
Kostya Kortchinskye7788062020-11-03 11:21:15 -0800377 TransferBatch *B = Region->FreeList.front();
378 Region->FreeList.pop_front();
379 DCHECK(B);
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000380 DCHECK_GT(B->getCount(), 0);
381
Kostya Kortchinskye7788062020-11-03 11:21:15 -0800382 const uptr AllocatedUser = Size * NumberOfBlocks;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000383 C->getStats().add(StatFree, AllocatedUser);
384 Region->AllocatedUser += AllocatedUser;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000385
386 return B;
387 }
388
Dynamic Tools Team2e7fec22020-02-16 15:29:46 -0800389 void getStats(ScopedString *Str, uptr ClassId, uptr Rss) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000390 RegionInfo *Region = getRegionInfo(ClassId);
391 if (Region->MappedUser == 0)
392 return;
393 const uptr InUse = Region->Stats.PoppedBlocks - Region->Stats.PushedBlocks;
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000394 const uptr TotalChunks = Region->AllocatedUser / getSizeByClassId(ClassId);
Dynamic Tools Team3e8c65b2019-10-18 20:00:32 +0000395 Str->append("%s %02zu (%6zu): mapped: %6zuK popped: %7zu pushed: %7zu "
396 "inuse: %6zu total: %6zu rss: %6zuK releases: %6zu last "
397 "released: %6zuK region: 0x%zx (0x%zx)\n",
398 Region->Exhausted ? "F" : " ", ClassId,
399 getSizeByClassId(ClassId), Region->MappedUser >> 10,
400 Region->Stats.PoppedBlocks, Region->Stats.PushedBlocks, InUse,
401 TotalChunks, Rss >> 10, Region->ReleaseInfo.RangesReleased,
402 Region->ReleaseInfo.LastReleasedBytes >> 10, Region->RegionBeg,
403 getRegionBaseByClassId(ClassId));
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000404 }
405
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000406 NOINLINE uptr releaseToOSMaybe(RegionInfo *Region, uptr ClassId,
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000407 bool Force = false) {
408 const uptr BlockSize = getSizeByClassId(ClassId);
409 const uptr PageSize = getPageSizeCached();
410
Kostya Kortchinsky156d47c2020-12-11 14:04:47 -0800411 DCHECK_GE(Region->Stats.PoppedBlocks, Region->Stats.PushedBlocks);
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000412 const uptr BytesInFreeList =
413 Region->AllocatedUser -
414 (Region->Stats.PoppedBlocks - Region->Stats.PushedBlocks) * BlockSize;
415 if (BytesInFreeList < PageSize)
416 return 0; // No chance to release anything.
Dynamic Tools Teamebcf82d2020-02-25 14:23:34 -0800417 const uptr BytesPushed = (Region->Stats.PushedBlocks -
418 Region->ReleaseInfo.PushedBlocksAtLastRelease) *
419 BlockSize;
420 if (BytesPushed < PageSize)
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000421 return 0; // Nothing new to release.
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000422
Kostya Kortchinsky394cc822020-06-17 10:31:53 -0700423 // Releasing smaller blocks is expensive, so we want to make sure that a
424 // significant amount of bytes are free, and that there has been a good
425 // amount of batches pushed to the freelist before attempting to release.
426 if (BlockSize < PageSize / 16U) {
427 if (!Force && BytesPushed < Region->AllocatedUser / 16U)
428 return 0;
429 // We want 8x% to 9x% free bytes (the larger the bock, the lower the %).
430 if ((BytesInFreeList * 100U) / Region->AllocatedUser <
431 (100U - 1U - BlockSize / 16U))
432 return 0;
433 }
434
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000435 if (!Force) {
Kostya Kortchinskya51a8922020-11-02 14:27:11 -0800436 const s32 IntervalMs = atomic_load_relaxed(&ReleaseToOsIntervalMs);
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000437 if (IntervalMs < 0)
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000438 return 0;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000439 if (Region->ReleaseInfo.LastReleaseAtNs +
Dynamic Tools Teamc5d5abc2020-01-27 14:03:21 -0800440 static_cast<u64>(IntervalMs) * 1000000 >
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000441 getMonotonicTime()) {
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000442 return 0; // Memory was returned recently.
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000443 }
444 }
445
Kostya Kortchinskybcd746b2020-08-24 14:13:12 -0700446 auto SkipRegion = [](UNUSED uptr RegionIndex) { return false; };
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000447 ReleaseRecorder Recorder(Region->RegionBeg, &Region->Data);
Dynamic Tools Team35997702019-10-28 15:06:10 -0700448 releaseFreeMemoryToOS(Region->FreeList, Region->RegionBeg,
Kostya Kortchinskybcd746b2020-08-24 14:13:12 -0700449 Region->AllocatedUser, 1U, BlockSize, &Recorder,
450 SkipRegion);
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000451
452 if (Recorder.getReleasedRangesCount() > 0) {
453 Region->ReleaseInfo.PushedBlocksAtLastRelease =
454 Region->Stats.PushedBlocks;
455 Region->ReleaseInfo.RangesReleased += Recorder.getReleasedRangesCount();
456 Region->ReleaseInfo.LastReleasedBytes = Recorder.getReleasedBytes();
457 }
458 Region->ReleaseInfo.LastReleaseAtNs = getMonotonicTime();
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000459 return Recorder.getReleasedBytes();
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000460 }
461};
462
463} // namespace scudo
464
465#endif // SCUDO_PRIMARY64_H_