blob: 01e674bf3fba5e3ffaf70e891e943955f89d64ed [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"
Dynamic Tools Team517193e2019-09-11 14:48:41 +000017#include "release.h"
18#include "stats.h"
19#include "string_utils.h"
20
21namespace scudo {
22
23// SizeClassAllocator64 is an allocator tuned for 64-bit address space.
24//
25// It starts by reserving NumClasses * 2^RegionSizeLog bytes, equally divided in
26// Regions, specific to each size class. Note that the base of that mapping is
27// random (based to the platform specific map() capabilities), and that each
28// Region actually starts at a random offset from its base.
29//
30// Regions are mapped incrementally on demand to fulfill allocation requests,
31// those mappings being split into equally sized Blocks based on the size class
32// they belong to. The Blocks created are shuffled to prevent predictable
33// address patterns (the predictability increases with the size of the Blocks).
34//
35// The 1st Region (for size class 0) holds the TransferBatches. This is a
36// structure used to transfer arrays of available pointers from the class size
37// freelist to the thread specific freelist, and back.
38//
39// The memory used by this allocator is never unmapped, but can be partially
40// released if the platform allows for it.
41
Dynamic Tools Team48429c72019-12-04 17:46:15 -080042template <class SizeClassMapT, uptr RegionSizeLog,
Dynamic Tools Team26387462020-02-14 12:24:03 -080043 s32 MinReleaseToOsIntervalMs = INT32_MIN,
44 s32 MaxReleaseToOsIntervalMs = INT32_MAX,
Dynamic Tools Team48429c72019-12-04 17:46:15 -080045 bool MaySupportMemoryTagging = false>
46class SizeClassAllocator64 {
Dynamic Tools Team517193e2019-09-11 14:48:41 +000047public:
48 typedef SizeClassMapT SizeClassMap;
Dynamic Tools Team2e7fec22020-02-16 15:29:46 -080049 typedef SizeClassAllocator64<
50 SizeClassMap, RegionSizeLog, MinReleaseToOsIntervalMs,
51 MaxReleaseToOsIntervalMs, MaySupportMemoryTagging>
Dynamic Tools Team48429c72019-12-04 17:46:15 -080052 ThisT;
Dynamic Tools Team517193e2019-09-11 14:48:41 +000053 typedef SizeClassAllocatorLocalCache<ThisT> CacheT;
54 typedef typename CacheT::TransferBatch TransferBatch;
Dynamic Tools Team48429c72019-12-04 17:46:15 -080055 static const bool SupportsMemoryTagging =
56 MaySupportMemoryTagging && archSupportsMemoryTagging();
Dynamic Tools Team517193e2019-09-11 14:48:41 +000057
58 static uptr getSizeByClassId(uptr ClassId) {
59 return (ClassId == SizeClassMap::BatchClassId)
60 ? sizeof(TransferBatch)
61 : SizeClassMap::getSizeByClassId(ClassId);
62 }
63
64 static bool canAllocate(uptr Size) { return Size <= SizeClassMap::MaxSize; }
65
66 void initLinkerInitialized(s32 ReleaseToOsInterval) {
67 // Reserve the space required for the Primary.
68 PrimaryBase = reinterpret_cast<uptr>(
69 map(nullptr, PrimarySize, "scudo:primary", MAP_NOACCESS, &Data));
70
Dynamic Tools Team517193e2019-09-11 14:48:41 +000071 u32 Seed;
Dynamic Tools Team6a8384a2020-03-03 11:16:31 -080072 const u64 Time = getMonotonicTime();
Dynamic Tools Team517193e2019-09-11 14:48:41 +000073 if (UNLIKELY(!getRandom(reinterpret_cast<void *>(&Seed), sizeof(Seed))))
Dynamic Tools Team6a8384a2020-03-03 11:16:31 -080074 Seed = static_cast<u32>(Time ^ (PrimaryBase >> 12));
Dynamic Tools Team517193e2019-09-11 14:48:41 +000075 const uptr PageSize = getPageSizeCached();
76 for (uptr I = 0; I < NumClasses; I++) {
77 RegionInfo *Region = getRegionInfo(I);
78 // The actual start of a region is offseted by a random number of pages.
79 Region->RegionBeg =
80 getRegionBaseByClassId(I) + (getRandomModN(&Seed, 16) + 1) * PageSize;
Dynamic Tools Team6a8384a2020-03-03 11:16:31 -080081 Region->RandState = getRandomU32(&Seed);
Dynamic Tools Team517193e2019-09-11 14:48:41 +000082 // Releasing smaller size classes doesn't necessarily yield to a
83 // meaningful RSS impact: there are more blocks per page, they are
84 // randomized around, and thus pages are less likely to be entirely empty.
85 // On top of this, attempting to release those require more iterations and
86 // memory accesses which ends up being fairly costly. The current lower
87 // limit is mostly arbitrary and based on empirical observations.
88 // TODO(kostyak): make the lower limit a runtime option
Dynamic Tools Teamf6d5c5d2020-01-30 11:06:49 -080089 Region->CanRelease = (I != SizeClassMap::BatchClassId) &&
Dynamic Tools Team70cfbf12020-01-29 12:35:44 -080090 (getSizeByClassId(I) >= (PageSize / 32));
Dynamic Tools Team6a8384a2020-03-03 11:16:31 -080091 if (Region->CanRelease)
92 Region->ReleaseInfo.LastReleaseAtNs = Time;
Dynamic Tools Team517193e2019-09-11 14:48:41 +000093 }
Dynamic Tools Team26387462020-02-14 12:24:03 -080094 setReleaseToOsIntervalMs(ReleaseToOsInterval);
Dynamic Tools Team48429c72019-12-04 17:46:15 -080095
96 if (SupportsMemoryTagging)
97 UseMemoryTagging = systemSupportsMemoryTagging();
Dynamic Tools Team517193e2019-09-11 14:48:41 +000098 }
99 void init(s32 ReleaseToOsInterval) {
100 memset(this, 0, sizeof(*this));
101 initLinkerInitialized(ReleaseToOsInterval);
102 }
103
104 void unmapTestOnly() {
105 unmap(reinterpret_cast<void *>(PrimaryBase), PrimarySize, UNMAP_ALL, &Data);
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000106 }
107
108 TransferBatch *popBatch(CacheT *C, uptr ClassId) {
109 DCHECK_LT(ClassId, NumClasses);
110 RegionInfo *Region = getRegionInfo(ClassId);
111 ScopedLock L(Region->Mutex);
112 TransferBatch *B = Region->FreeList.front();
113 if (B) {
114 Region->FreeList.pop_front();
115 } else {
116 B = populateFreeList(C, ClassId, Region);
117 if (UNLIKELY(!B))
118 return nullptr;
119 }
120 DCHECK_GT(B->getCount(), 0);
121 Region->Stats.PoppedBlocks += B->getCount();
122 return B;
123 }
124
125 void pushBatch(uptr ClassId, TransferBatch *B) {
126 DCHECK_GT(B->getCount(), 0);
127 RegionInfo *Region = getRegionInfo(ClassId);
128 ScopedLock L(Region->Mutex);
129 Region->FreeList.push_front(B);
130 Region->Stats.PushedBlocks += B->getCount();
131 if (Region->CanRelease)
132 releaseToOSMaybe(Region, ClassId);
133 }
134
135 void disable() {
Dynamic Tools Team83eaa512020-01-09 11:43:16 -0800136 // The BatchClassId must be locked last since other classes can use it.
137 for (sptr I = static_cast<sptr>(NumClasses) - 1; I >= 0; I--) {
138 if (static_cast<uptr>(I) == SizeClassMap::BatchClassId)
139 continue;
140 getRegionInfo(static_cast<uptr>(I))->Mutex.lock();
141 }
142 getRegionInfo(SizeClassMap::BatchClassId)->Mutex.lock();
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000143 }
144
145 void enable() {
Dynamic Tools Team83eaa512020-01-09 11:43:16 -0800146 getRegionInfo(SizeClassMap::BatchClassId)->Mutex.unlock();
147 for (uptr I = 0; I < NumClasses; I++) {
148 if (I == SizeClassMap::BatchClassId)
149 continue;
150 getRegionInfo(I)->Mutex.unlock();
151 }
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000152 }
153
Dynamic Tools Team2e7fec22020-02-16 15:29:46 -0800154 template <typename F> void iterateOverBlocks(F Callback) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000155 for (uptr I = 0; I < NumClasses; I++) {
156 if (I == SizeClassMap::BatchClassId)
157 continue;
158 const RegionInfo *Region = getRegionInfo(I);
159 const uptr BlockSize = getSizeByClassId(I);
160 const uptr From = Region->RegionBeg;
161 const uptr To = From + Region->AllocatedUser;
162 for (uptr Block = From; Block < To; Block += BlockSize)
163 Callback(Block);
164 }
165 }
166
Dynamic Tools Team2e7fec22020-02-16 15:29:46 -0800167 void getStats(ScopedString *Str) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000168 // TODO(kostyak): get the RSS per region.
169 uptr TotalMapped = 0;
170 uptr PoppedBlocks = 0;
171 uptr PushedBlocks = 0;
172 for (uptr I = 0; I < NumClasses; I++) {
173 RegionInfo *Region = getRegionInfo(I);
174 if (Region->MappedUser)
175 TotalMapped += Region->MappedUser;
176 PoppedBlocks += Region->Stats.PoppedBlocks;
177 PushedBlocks += Region->Stats.PushedBlocks;
178 }
Dynamic Tools Team3e8c65b2019-10-18 20:00:32 +0000179 Str->append("Stats: SizeClassAllocator64: %zuM mapped (%zuM rss) in %zu "
180 "allocations; remains %zu\n",
181 TotalMapped >> 20, 0, PoppedBlocks,
182 PoppedBlocks - PushedBlocks);
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000183
184 for (uptr I = 0; I < NumClasses; I++)
Dynamic Tools Team3e8c65b2019-10-18 20:00:32 +0000185 getStats(Str, I, 0);
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000186 }
187
Dynamic Tools Team26387462020-02-14 12:24:03 -0800188 void setReleaseToOsIntervalMs(s32 Interval) {
189 if (Interval >= MaxReleaseToOsIntervalMs) {
190 Interval = MaxReleaseToOsIntervalMs;
191 } else if (Interval <= MinReleaseToOsIntervalMs) {
192 Interval = MinReleaseToOsIntervalMs;
193 }
194 atomic_store(&ReleaseToOsIntervalMs, Interval, memory_order_relaxed);
195 }
196
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000197 uptr releaseToOS() {
198 uptr TotalReleasedBytes = 0;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000199 for (uptr I = 0; I < NumClasses; I++) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000200 RegionInfo *Region = getRegionInfo(I);
201 ScopedLock L(Region->Mutex);
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000202 TotalReleasedBytes += releaseToOSMaybe(Region, I, /*Force=*/true);
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000203 }
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000204 return TotalReleasedBytes;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000205 }
206
Dynamic Tools Team48429c72019-12-04 17:46:15 -0800207 bool useMemoryTagging() const {
208 return SupportsMemoryTagging && UseMemoryTagging;
209 }
210 void disableMemoryTagging() { UseMemoryTagging = false; }
211
Dynamic Tools Team0d7d2ae2020-04-21 15:30:50 -0700212 const char *getRegionInfoArrayAddress() const {
213 return reinterpret_cast<const char *>(RegionInfoArray);
214 }
215
Kostya Kortchinsky394cc822020-06-17 10:31:53 -0700216 static uptr getRegionInfoArraySize() { return sizeof(RegionInfoArray); }
Dynamic Tools Team0d7d2ae2020-04-21 15:30:50 -0700217
218 static BlockInfo findNearestBlock(const char *RegionInfoData, uptr Ptr) {
219 const RegionInfo *RegionInfoArray =
220 reinterpret_cast<const RegionInfo *>(RegionInfoData);
221 uptr ClassId;
222 uptr MinDistance = -1UL;
223 for (uptr I = 0; I != NumClasses; ++I) {
224 if (I == SizeClassMap::BatchClassId)
225 continue;
226 uptr Begin = RegionInfoArray[I].RegionBeg;
227 uptr End = Begin + RegionInfoArray[I].AllocatedUser;
228 if (Begin > End || End - Begin < SizeClassMap::getSizeByClassId(I))
229 continue;
230 uptr RegionDistance;
231 if (Begin <= Ptr) {
232 if (Ptr < End)
233 RegionDistance = 0;
234 else
235 RegionDistance = Ptr - End;
236 } else {
237 RegionDistance = Begin - Ptr;
238 }
239
240 if (RegionDistance < MinDistance) {
241 MinDistance = RegionDistance;
242 ClassId = I;
243 }
244 }
245
246 BlockInfo B = {};
247 if (MinDistance <= 8192) {
248 B.RegionBegin = RegionInfoArray[ClassId].RegionBeg;
249 B.RegionEnd = B.RegionBegin + RegionInfoArray[ClassId].AllocatedUser;
250 B.BlockSize = SizeClassMap::getSizeByClassId(ClassId);
251 B.BlockBegin =
252 B.RegionBegin + uptr(sptr(Ptr - B.RegionBegin) / sptr(B.BlockSize) *
253 sptr(B.BlockSize));
254 while (B.BlockBegin < B.RegionBegin)
255 B.BlockBegin += B.BlockSize;
256 while (B.RegionEnd < B.BlockBegin + B.BlockSize)
257 B.BlockBegin -= B.BlockSize;
258 }
259 return B;
260 }
261
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000262private:
263 static const uptr RegionSize = 1UL << RegionSizeLog;
264 static const uptr NumClasses = SizeClassMap::NumClasses;
265 static const uptr PrimarySize = RegionSize * NumClasses;
266
267 // Call map for user memory with at least this size.
Dynamic Tools Team75868b72020-01-30 15:26:46 -0800268 static const uptr MapSizeIncrement = 1UL << 18;
Dynamic Tools Teamaa152462019-11-19 10:18:38 -0800269 // Fill at most this number of batches from the newly map'd memory.
Dynamic Tools Team6a8384a2020-03-03 11:16:31 -0800270 static const u32 MaxNumBatches = SCUDO_ANDROID ? 4U : 8U;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000271
272 struct RegionStats {
273 uptr PoppedBlocks;
274 uptr PushedBlocks;
275 };
276
277 struct ReleaseToOsInfo {
278 uptr PushedBlocksAtLastRelease;
279 uptr RangesReleased;
280 uptr LastReleasedBytes;
281 u64 LastReleaseAtNs;
282 };
283
Dynamic Tools Team0d7d2ae2020-04-21 15:30:50 -0700284 struct UnpaddedRegionInfo {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000285 HybridMutex Mutex;
Dynamic Tools Team35997702019-10-28 15:06:10 -0700286 SinglyLinkedList<TransferBatch> FreeList;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000287 RegionStats Stats;
288 bool CanRelease;
289 bool Exhausted;
290 u32 RandState;
291 uptr RegionBeg;
292 uptr MappedUser; // Bytes mapped for user memory.
293 uptr AllocatedUser; // Bytes allocated for user memory.
294 MapPlatformData Data;
295 ReleaseToOsInfo ReleaseInfo;
296 };
Dynamic Tools Team0d7d2ae2020-04-21 15:30:50 -0700297 struct RegionInfo : UnpaddedRegionInfo {
298 char Padding[SCUDO_CACHE_LINE_SIZE -
299 (sizeof(UnpaddedRegionInfo) % SCUDO_CACHE_LINE_SIZE)];
300 };
Dynamic Tools Team09e6d482019-11-26 18:18:14 -0800301 static_assert(sizeof(RegionInfo) % SCUDO_CACHE_LINE_SIZE == 0, "");
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000302
303 uptr PrimaryBase;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000304 MapPlatformData Data;
Dynamic Tools Team26387462020-02-14 12:24:03 -0800305 atomic_s32 ReleaseToOsIntervalMs;
Dynamic Tools Team48429c72019-12-04 17:46:15 -0800306 bool UseMemoryTagging;
Dynamic Tools Team0d7d2ae2020-04-21 15:30:50 -0700307 alignas(SCUDO_CACHE_LINE_SIZE) RegionInfo RegionInfoArray[NumClasses];
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000308
Dynamic Tools Team2e7fec22020-02-16 15:29:46 -0800309 RegionInfo *getRegionInfo(uptr ClassId) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000310 DCHECK_LT(ClassId, NumClasses);
311 return &RegionInfoArray[ClassId];
312 }
313
314 uptr getRegionBaseByClassId(uptr ClassId) const {
315 return PrimaryBase + (ClassId << RegionSizeLog);
316 }
317
318 bool populateBatches(CacheT *C, RegionInfo *Region, uptr ClassId,
319 TransferBatch **CurrentBatch, u32 MaxCount,
320 void **PointersArray, u32 Count) {
321 // No need to shuffle the batches size class.
322 if (ClassId != SizeClassMap::BatchClassId)
323 shuffle(PointersArray, Count, &Region->RandState);
324 TransferBatch *B = *CurrentBatch;
325 for (uptr I = 0; I < Count; I++) {
326 if (B && B->getCount() == MaxCount) {
327 Region->FreeList.push_back(B);
328 B = nullptr;
329 }
330 if (!B) {
331 B = C->createBatch(ClassId, PointersArray[I]);
332 if (UNLIKELY(!B))
333 return false;
334 B->clear();
335 }
336 B->add(PointersArray[I]);
337 }
338 *CurrentBatch = B;
339 return true;
340 }
341
342 NOINLINE TransferBatch *populateFreeList(CacheT *C, uptr ClassId,
343 RegionInfo *Region) {
344 const uptr Size = getSizeByClassId(ClassId);
345 const u32 MaxCount = TransferBatch::getMaxCached(Size);
346
347 const uptr RegionBeg = Region->RegionBeg;
348 const uptr MappedUser = Region->MappedUser;
349 const uptr TotalUserBytes = Region->AllocatedUser + MaxCount * Size;
350 // Map more space for blocks, if necessary.
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000351 if (TotalUserBytes > MappedUser) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000352 // Do the mmap for the user memory.
353 const uptr UserMapSize =
354 roundUpTo(TotalUserBytes - MappedUser, MapSizeIncrement);
355 const uptr RegionBase = RegionBeg - getRegionBaseByClassId(ClassId);
356 if (UNLIKELY(RegionBase + MappedUser + UserMapSize > RegionSize)) {
357 if (!Region->Exhausted) {
358 Region->Exhausted = true;
Dynamic Tools Team3e8c65b2019-10-18 20:00:32 +0000359 ScopedString Str(1024);
360 getStats(&Str);
361 Str.append(
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000362 "Scudo OOM: The process has Exhausted %zuM for size class %zu.\n",
363 RegionSize >> 20, Size);
Dynamic Tools Team3e8c65b2019-10-18 20:00:32 +0000364 Str.output();
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000365 }
366 return nullptr;
367 }
368 if (UNLIKELY(MappedUser == 0))
369 Region->Data = Data;
370 if (UNLIKELY(!map(reinterpret_cast<void *>(RegionBeg + MappedUser),
371 UserMapSize, "scudo:primary",
Dynamic Tools Team48429c72019-12-04 17:46:15 -0800372 MAP_ALLOWNOMEM | MAP_RESIZABLE |
373 (useMemoryTagging() ? MAP_MEMTAG : 0),
374 &Region->Data)))
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000375 return nullptr;
376 Region->MappedUser += UserMapSize;
377 C->getStats().add(StatMapped, UserMapSize);
378 }
379
Dynamic Tools Teamaa152462019-11-19 10:18:38 -0800380 const u32 NumberOfBlocks = Min(
381 MaxNumBatches * MaxCount,
382 static_cast<u32>((Region->MappedUser - Region->AllocatedUser) / Size));
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000383 DCHECK_GT(NumberOfBlocks, 0);
384
385 TransferBatch *B = nullptr;
Dynamic Tools Teamaa152462019-11-19 10:18:38 -0800386 constexpr u32 ShuffleArraySize =
387 MaxNumBatches * TransferBatch::MaxNumCached;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000388 void *ShuffleArray[ShuffleArraySize];
389 u32 Count = 0;
390 const uptr P = RegionBeg + Region->AllocatedUser;
Dynamic Tools Teamaa152462019-11-19 10:18:38 -0800391 const uptr AllocatedUser = Size * NumberOfBlocks;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000392 for (uptr I = P; I < P + AllocatedUser; I += Size) {
393 ShuffleArray[Count++] = reinterpret_cast<void *>(I);
394 if (Count == ShuffleArraySize) {
395 if (UNLIKELY(!populateBatches(C, Region, ClassId, &B, MaxCount,
396 ShuffleArray, Count)))
397 return nullptr;
398 Count = 0;
399 }
400 }
401 if (Count) {
402 if (UNLIKELY(!populateBatches(C, Region, ClassId, &B, MaxCount,
403 ShuffleArray, Count)))
404 return nullptr;
405 }
406 DCHECK(B);
Dynamic Tools Teamaa152462019-11-19 10:18:38 -0800407 if (!Region->FreeList.empty()) {
408 Region->FreeList.push_back(B);
409 B = Region->FreeList.front();
410 Region->FreeList.pop_front();
411 }
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000412 DCHECK_GT(B->getCount(), 0);
413
414 C->getStats().add(StatFree, AllocatedUser);
415 Region->AllocatedUser += AllocatedUser;
416 Region->Exhausted = false;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000417
418 return B;
419 }
420
Dynamic Tools Team2e7fec22020-02-16 15:29:46 -0800421 void getStats(ScopedString *Str, uptr ClassId, uptr Rss) {
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000422 RegionInfo *Region = getRegionInfo(ClassId);
423 if (Region->MappedUser == 0)
424 return;
425 const uptr InUse = Region->Stats.PoppedBlocks - Region->Stats.PushedBlocks;
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000426 const uptr TotalChunks = Region->AllocatedUser / getSizeByClassId(ClassId);
Dynamic Tools Team3e8c65b2019-10-18 20:00:32 +0000427 Str->append("%s %02zu (%6zu): mapped: %6zuK popped: %7zu pushed: %7zu "
428 "inuse: %6zu total: %6zu rss: %6zuK releases: %6zu last "
429 "released: %6zuK region: 0x%zx (0x%zx)\n",
430 Region->Exhausted ? "F" : " ", ClassId,
431 getSizeByClassId(ClassId), Region->MappedUser >> 10,
432 Region->Stats.PoppedBlocks, Region->Stats.PushedBlocks, InUse,
433 TotalChunks, Rss >> 10, Region->ReleaseInfo.RangesReleased,
434 Region->ReleaseInfo.LastReleasedBytes >> 10, Region->RegionBeg,
435 getRegionBaseByClassId(ClassId));
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000436 }
437
Dynamic Tools Team26387462020-02-14 12:24:03 -0800438 s32 getReleaseToOsIntervalMs() {
439 return atomic_load(&ReleaseToOsIntervalMs, memory_order_relaxed);
440 }
441
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000442 NOINLINE uptr releaseToOSMaybe(RegionInfo *Region, uptr ClassId,
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000443 bool Force = false) {
444 const uptr BlockSize = getSizeByClassId(ClassId);
445 const uptr PageSize = getPageSizeCached();
446
447 CHECK_GE(Region->Stats.PoppedBlocks, Region->Stats.PushedBlocks);
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000448 const uptr BytesInFreeList =
449 Region->AllocatedUser -
450 (Region->Stats.PoppedBlocks - Region->Stats.PushedBlocks) * BlockSize;
451 if (BytesInFreeList < PageSize)
452 return 0; // No chance to release anything.
Dynamic Tools Teamebcf82d2020-02-25 14:23:34 -0800453 const uptr BytesPushed = (Region->Stats.PushedBlocks -
454 Region->ReleaseInfo.PushedBlocksAtLastRelease) *
455 BlockSize;
456 if (BytesPushed < PageSize)
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000457 return 0; // Nothing new to release.
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000458
Kostya Kortchinsky394cc822020-06-17 10:31:53 -0700459 // Releasing smaller blocks is expensive, so we want to make sure that a
460 // significant amount of bytes are free, and that there has been a good
461 // amount of batches pushed to the freelist before attempting to release.
462 if (BlockSize < PageSize / 16U) {
463 if (!Force && BytesPushed < Region->AllocatedUser / 16U)
464 return 0;
465 // We want 8x% to 9x% free bytes (the larger the bock, the lower the %).
466 if ((BytesInFreeList * 100U) / Region->AllocatedUser <
467 (100U - 1U - BlockSize / 16U))
468 return 0;
469 }
470
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000471 if (!Force) {
Dynamic Tools Team26387462020-02-14 12:24:03 -0800472 const s32 IntervalMs = getReleaseToOsIntervalMs();
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000473 if (IntervalMs < 0)
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000474 return 0;
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000475 if (Region->ReleaseInfo.LastReleaseAtNs +
Dynamic Tools Teamc5d5abc2020-01-27 14:03:21 -0800476 static_cast<u64>(IntervalMs) * 1000000 >
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000477 getMonotonicTime()) {
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000478 return 0; // Memory was returned recently.
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000479 }
480 }
481
482 ReleaseRecorder Recorder(Region->RegionBeg, &Region->Data);
Dynamic Tools Team35997702019-10-28 15:06:10 -0700483 releaseFreeMemoryToOS(Region->FreeList, Region->RegionBeg,
Dynamic Tools Teamebcf82d2020-02-25 14:23:34 -0800484 Region->AllocatedUser, BlockSize, &Recorder);
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000485
486 if (Recorder.getReleasedRangesCount() > 0) {
487 Region->ReleaseInfo.PushedBlocksAtLastRelease =
488 Region->Stats.PushedBlocks;
489 Region->ReleaseInfo.RangesReleased += Recorder.getReleasedRangesCount();
490 Region->ReleaseInfo.LastReleasedBytes = Recorder.getReleasedBytes();
491 }
492 Region->ReleaseInfo.LastReleaseAtNs = getMonotonicTime();
Dynamic Tools Teamc283bab2019-10-07 17:37:39 +0000493 return Recorder.getReleasedBytes();
Dynamic Tools Team517193e2019-09-11 14:48:41 +0000494 }
495};
496
497} // namespace scudo
498
499#endif // SCUDO_PRIMARY64_H_