Path: blob/main/contrib/llvm-project/compiler-rt/lib/scudo/standalone/primary64.h
35292 views
//===-- primary64.h ---------------------------------------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#ifndef SCUDO_PRIMARY64_H_9#define SCUDO_PRIMARY64_H_1011#include "allocator_common.h"12#include "bytemap.h"13#include "common.h"14#include "condition_variable.h"15#include "list.h"16#include "local_cache.h"17#include "mem_map.h"18#include "memtag.h"19#include "options.h"20#include "release.h"21#include "stats.h"22#include "string_utils.h"23#include "thread_annotations.h"2425namespace scudo {2627// SizeClassAllocator64 is an allocator tuned for 64-bit address space.28//29// It starts by reserving NumClasses * 2^RegionSizeLog bytes, equally divided in30// Regions, specific to each size class. Note that the base of that mapping is31// random (based to the platform specific map() capabilities). If32// PrimaryEnableRandomOffset is set, each Region actually starts at a random33// offset from its base.34//35// Regions are mapped incrementally on demand to fulfill allocation requests,36// those mappings being split into equally sized Blocks based on the size class37// they belong to. The Blocks created are shuffled to prevent predictable38// address patterns (the predictability increases with the size of the Blocks).39//40// The 1st Region (for size class 0) holds the TransferBatches. This is a41// structure used to transfer arrays of available pointers from the class size42// freelist to the thread specific freelist, and back.43//44// The memory used by this allocator is never unmapped, but can be partially45// released if the platform allows for it.4647template <typename Config> class SizeClassAllocator64 {48public:49typedef typename Config::CompactPtrT CompactPtrT;50typedef typename Config::SizeClassMap SizeClassMap;51typedef typename Config::ConditionVariableT ConditionVariableT;52static const uptr CompactPtrScale = Config::getCompactPtrScale();53static const uptr RegionSizeLog = Config::getRegionSizeLog();54static const uptr GroupSizeLog = Config::getGroupSizeLog();55static_assert(RegionSizeLog >= GroupSizeLog,56"Group size shouldn't be greater than the region size");57static const uptr GroupScale = GroupSizeLog - CompactPtrScale;58typedef SizeClassAllocator64<Config> ThisT;59typedef SizeClassAllocatorLocalCache<ThisT> CacheT;60typedef TransferBatch<ThisT> TransferBatchT;61typedef BatchGroup<ThisT> BatchGroupT;6263static_assert(sizeof(BatchGroupT) <= sizeof(TransferBatchT),64"BatchGroupT uses the same class size as TransferBatchT");6566static uptr getSizeByClassId(uptr ClassId) {67return (ClassId == SizeClassMap::BatchClassId)68? roundUp(sizeof(TransferBatchT), 1U << CompactPtrScale)69: SizeClassMap::getSizeByClassId(ClassId);70}7172static bool canAllocate(uptr Size) { return Size <= SizeClassMap::MaxSize; }7374static bool conditionVariableEnabled() {75return Config::hasConditionVariableT();76}7778void init(s32 ReleaseToOsInterval) NO_THREAD_SAFETY_ANALYSIS {79DCHECK(isAligned(reinterpret_cast<uptr>(this), alignof(ThisT)));8081const uptr PageSize = getPageSizeCached();82const uptr GroupSize = (1UL << GroupSizeLog);83const uptr PagesInGroup = GroupSize / PageSize;84const uptr MinSizeClass = getSizeByClassId(1);85// When trying to release pages back to memory, visiting smaller size86// classes is expensive. Therefore, we only try to release smaller size87// classes when the amount of free blocks goes over a certain threshold (See88// the comment in releaseToOSMaybe() for more details). For example, for89// size class 32, we only do the release when the size of free blocks is90// greater than 97% of pages in a group. However, this may introduce another91// issue that if the number of free blocks is bouncing between 97% ~ 100%.92// Which means we may try many page releases but only release very few of93// them (less than 3% in a group). Even though we have94// `&ReleaseToOsIntervalMs` which slightly reduce the frequency of these95// calls but it will be better to have another guard to mitigate this issue.96//97// Here we add another constraint on the minimum size requirement. The98// constraint is determined by the size of in-use blocks in the minimal size99// class. Take size class 32 as an example,100//101// +- one memory group -+102// +----------------------+------+103// | 97% of free blocks | |104// +----------------------+------+105// \ /106// 3% in-use blocks107//108// * The release size threshold is 97%.109//110// The 3% size in a group is about 7 pages. For two consecutive111// releaseToOSMaybe(), we require the difference between `PushedBlocks`112// should be greater than 7 pages. This mitigates the page releasing113// thrashing which is caused by memory usage bouncing around the threshold.114// The smallest size class takes longest time to do the page release so we115// use its size of in-use blocks as a heuristic.116SmallerBlockReleasePageDelta =117PagesInGroup * (1 + MinSizeClass / 16U) / 100;118119u32 Seed;120const u64 Time = getMonotonicTimeFast();121if (!getRandom(reinterpret_cast<void *>(&Seed), sizeof(Seed)))122Seed = static_cast<u32>(Time ^ (reinterpret_cast<uptr>(&Seed) >> 12));123124for (uptr I = 0; I < NumClasses; I++)125getRegionInfo(I)->RandState = getRandomU32(&Seed);126127if (Config::getEnableContiguousRegions()) {128ReservedMemoryT ReservedMemory = {};129// Reserve the space required for the Primary.130CHECK(ReservedMemory.create(/*Addr=*/0U, RegionSize * NumClasses,131"scudo:primary_reserve"));132const uptr PrimaryBase = ReservedMemory.getBase();133134for (uptr I = 0; I < NumClasses; I++) {135MemMapT RegionMemMap = ReservedMemory.dispatch(136PrimaryBase + (I << RegionSizeLog), RegionSize);137RegionInfo *Region = getRegionInfo(I);138139initRegion(Region, I, RegionMemMap, Config::getEnableRandomOffset());140}141shuffle(RegionInfoArray, NumClasses, &Seed);142}143144// The binding should be done after region shuffling so that it won't bind145// the FLLock from the wrong region.146for (uptr I = 0; I < NumClasses; I++)147getRegionInfo(I)->FLLockCV.bindTestOnly(getRegionInfo(I)->FLLock);148149// The default value in the primary config has the higher priority.150if (Config::getDefaultReleaseToOsIntervalMs() != INT32_MIN)151ReleaseToOsInterval = Config::getDefaultReleaseToOsIntervalMs();152setOption(Option::ReleaseInterval, static_cast<sptr>(ReleaseToOsInterval));153}154155void unmapTestOnly() {156for (uptr I = 0; I < NumClasses; I++) {157RegionInfo *Region = getRegionInfo(I);158{159ScopedLock ML(Region->MMLock);160MemMapT MemMap = Region->MemMapInfo.MemMap;161if (MemMap.isAllocated())162MemMap.unmap(MemMap.getBase(), MemMap.getCapacity());163}164*Region = {};165}166}167168// When all blocks are freed, it has to be the same size as `AllocatedUser`.169void verifyAllBlocksAreReleasedTestOnly() {170// `BatchGroup` and `TransferBatch` also use the blocks from BatchClass.171uptr BatchClassUsedInFreeLists = 0;172for (uptr I = 0; I < NumClasses; I++) {173// We have to count BatchClassUsedInFreeLists in other regions first.174if (I == SizeClassMap::BatchClassId)175continue;176RegionInfo *Region = getRegionInfo(I);177ScopedLock ML(Region->MMLock);178ScopedLock FL(Region->FLLock);179const uptr BlockSize = getSizeByClassId(I);180uptr TotalBlocks = 0;181for (BatchGroupT &BG : Region->FreeListInfo.BlockList) {182// `BG::Batches` are `TransferBatches`. +1 for `BatchGroup`.183BatchClassUsedInFreeLists += BG.Batches.size() + 1;184for (const auto &It : BG.Batches)185TotalBlocks += It.getCount();186}187188DCHECK_EQ(TotalBlocks, Region->MemMapInfo.AllocatedUser / BlockSize);189DCHECK_EQ(Region->FreeListInfo.PushedBlocks,190Region->FreeListInfo.PoppedBlocks);191}192193RegionInfo *Region = getRegionInfo(SizeClassMap::BatchClassId);194ScopedLock ML(Region->MMLock);195ScopedLock FL(Region->FLLock);196const uptr BlockSize = getSizeByClassId(SizeClassMap::BatchClassId);197uptr TotalBlocks = 0;198for (BatchGroupT &BG : Region->FreeListInfo.BlockList) {199if (LIKELY(!BG.Batches.empty())) {200for (const auto &It : BG.Batches)201TotalBlocks += It.getCount();202} else {203// `BatchGroup` with empty freelist doesn't have `TransferBatch` record204// itself.205++TotalBlocks;206}207}208DCHECK_EQ(TotalBlocks + BatchClassUsedInFreeLists,209Region->MemMapInfo.AllocatedUser / BlockSize);210DCHECK_GE(Region->FreeListInfo.PoppedBlocks,211Region->FreeListInfo.PushedBlocks);212const uptr BlocksInUse =213Region->FreeListInfo.PoppedBlocks - Region->FreeListInfo.PushedBlocks;214DCHECK_EQ(BlocksInUse, BatchClassUsedInFreeLists);215}216217u16 popBlocks(CacheT *C, uptr ClassId, CompactPtrT *ToArray,218const u16 MaxBlockCount) {219DCHECK_LT(ClassId, NumClasses);220RegionInfo *Region = getRegionInfo(ClassId);221u16 PopCount = 0;222223{224ScopedLock L(Region->FLLock);225PopCount = popBlocksImpl(C, ClassId, Region, ToArray, MaxBlockCount);226if (PopCount != 0U)227return PopCount;228}229230bool ReportRegionExhausted = false;231232if (conditionVariableEnabled()) {233PopCount = popBlocksWithCV(C, ClassId, Region, ToArray, MaxBlockCount,234ReportRegionExhausted);235} else {236while (true) {237// When two threads compete for `Region->MMLock`, we only want one of238// them to call populateFreeListAndPopBatch(). To avoid both of them239// doing that, always check the freelist before mapping new pages.240ScopedLock ML(Region->MMLock);241{242ScopedLock FL(Region->FLLock);243PopCount = popBlocksImpl(C, ClassId, Region, ToArray, MaxBlockCount);244if (PopCount != 0U)245return PopCount;246}247248const bool RegionIsExhausted = Region->Exhausted;249if (!RegionIsExhausted) {250PopCount = populateFreeListAndPopBlocks(C, ClassId, Region, ToArray,251MaxBlockCount);252}253ReportRegionExhausted = !RegionIsExhausted && Region->Exhausted;254break;255}256}257258if (UNLIKELY(ReportRegionExhausted)) {259Printf("Can't populate more pages for size class %zu.\n",260getSizeByClassId(ClassId));261262// Theoretically, BatchClass shouldn't be used up. Abort immediately when263// it happens.264if (ClassId == SizeClassMap::BatchClassId)265reportOutOfBatchClass();266}267268return PopCount;269}270271// Push the array of free blocks to the designated batch group.272void pushBlocks(CacheT *C, uptr ClassId, CompactPtrT *Array, u32 Size) {273DCHECK_LT(ClassId, NumClasses);274DCHECK_GT(Size, 0);275276RegionInfo *Region = getRegionInfo(ClassId);277if (ClassId == SizeClassMap::BatchClassId) {278ScopedLock L(Region->FLLock);279pushBatchClassBlocks(Region, Array, Size);280if (conditionVariableEnabled())281Region->FLLockCV.notifyAll(Region->FLLock);282return;283}284285// TODO(chiahungduan): Consider not doing grouping if the group size is not286// greater than the block size with a certain scale.287288bool SameGroup = true;289if (GroupSizeLog < RegionSizeLog) {290// Sort the blocks so that blocks belonging to the same group can be291// pushed together.292for (u32 I = 1; I < Size; ++I) {293if (compactPtrGroup(Array[I - 1]) != compactPtrGroup(Array[I]))294SameGroup = false;295CompactPtrT Cur = Array[I];296u32 J = I;297while (J > 0 && compactPtrGroup(Cur) < compactPtrGroup(Array[J - 1])) {298Array[J] = Array[J - 1];299--J;300}301Array[J] = Cur;302}303}304305{306ScopedLock L(Region->FLLock);307pushBlocksImpl(C, ClassId, Region, Array, Size, SameGroup);308if (conditionVariableEnabled())309Region->FLLockCV.notifyAll(Region->FLLock);310}311}312313void disable() NO_THREAD_SAFETY_ANALYSIS {314// The BatchClassId must be locked last since other classes can use it.315for (sptr I = static_cast<sptr>(NumClasses) - 1; I >= 0; I--) {316if (static_cast<uptr>(I) == SizeClassMap::BatchClassId)317continue;318getRegionInfo(static_cast<uptr>(I))->MMLock.lock();319getRegionInfo(static_cast<uptr>(I))->FLLock.lock();320}321getRegionInfo(SizeClassMap::BatchClassId)->MMLock.lock();322getRegionInfo(SizeClassMap::BatchClassId)->FLLock.lock();323}324325void enable() NO_THREAD_SAFETY_ANALYSIS {326getRegionInfo(SizeClassMap::BatchClassId)->FLLock.unlock();327getRegionInfo(SizeClassMap::BatchClassId)->MMLock.unlock();328for (uptr I = 0; I < NumClasses; I++) {329if (I == SizeClassMap::BatchClassId)330continue;331getRegionInfo(I)->FLLock.unlock();332getRegionInfo(I)->MMLock.unlock();333}334}335336template <typename F> void iterateOverBlocks(F Callback) {337for (uptr I = 0; I < NumClasses; I++) {338if (I == SizeClassMap::BatchClassId)339continue;340RegionInfo *Region = getRegionInfo(I);341// TODO: The call of `iterateOverBlocks` requires disabling342// SizeClassAllocator64. We may consider locking each region on demand343// only.344Region->FLLock.assertHeld();345Region->MMLock.assertHeld();346const uptr BlockSize = getSizeByClassId(I);347const uptr From = Region->RegionBeg;348const uptr To = From + Region->MemMapInfo.AllocatedUser;349for (uptr Block = From; Block < To; Block += BlockSize)350Callback(Block);351}352}353354void getStats(ScopedString *Str) {355// TODO(kostyak): get the RSS per region.356uptr TotalMapped = 0;357uptr PoppedBlocks = 0;358uptr PushedBlocks = 0;359for (uptr I = 0; I < NumClasses; I++) {360RegionInfo *Region = getRegionInfo(I);361{362ScopedLock L(Region->MMLock);363TotalMapped += Region->MemMapInfo.MappedUser;364}365{366ScopedLock L(Region->FLLock);367PoppedBlocks += Region->FreeListInfo.PoppedBlocks;368PushedBlocks += Region->FreeListInfo.PushedBlocks;369}370}371const s32 IntervalMs = atomic_load_relaxed(&ReleaseToOsIntervalMs);372Str->append("Stats: SizeClassAllocator64: %zuM mapped (%uM rss) in %zu "373"allocations; remains %zu; ReleaseToOsIntervalMs = %d\n",374TotalMapped >> 20, 0U, PoppedBlocks,375PoppedBlocks - PushedBlocks, IntervalMs >= 0 ? IntervalMs : -1);376377for (uptr I = 0; I < NumClasses; I++) {378RegionInfo *Region = getRegionInfo(I);379ScopedLock L1(Region->MMLock);380ScopedLock L2(Region->FLLock);381getStats(Str, I, Region);382}383}384385void getFragmentationInfo(ScopedString *Str) {386Str->append(387"Fragmentation Stats: SizeClassAllocator64: page size = %zu bytes\n",388getPageSizeCached());389390for (uptr I = 1; I < NumClasses; I++) {391RegionInfo *Region = getRegionInfo(I);392ScopedLock L(Region->MMLock);393getRegionFragmentationInfo(Region, I, Str);394}395}396397bool setOption(Option O, sptr Value) {398if (O == Option::ReleaseInterval) {399const s32 Interval = Max(400Min(static_cast<s32>(Value), Config::getMaxReleaseToOsIntervalMs()),401Config::getMinReleaseToOsIntervalMs());402atomic_store_relaxed(&ReleaseToOsIntervalMs, Interval);403return true;404}405// Not supported by the Primary, but not an error either.406return true;407}408409uptr tryReleaseToOS(uptr ClassId, ReleaseToOS ReleaseType) {410RegionInfo *Region = getRegionInfo(ClassId);411// Note that the tryLock() may fail spuriously, given that it should rarely412// happen and page releasing is fine to skip, we don't take certain413// approaches to ensure one page release is done.414if (Region->MMLock.tryLock()) {415uptr BytesReleased = releaseToOSMaybe(Region, ClassId, ReleaseType);416Region->MMLock.unlock();417return BytesReleased;418}419return 0;420}421422uptr releaseToOS(ReleaseToOS ReleaseType) {423uptr TotalReleasedBytes = 0;424for (uptr I = 0; I < NumClasses; I++) {425if (I == SizeClassMap::BatchClassId)426continue;427RegionInfo *Region = getRegionInfo(I);428ScopedLock L(Region->MMLock);429TotalReleasedBytes += releaseToOSMaybe(Region, I, ReleaseType);430}431return TotalReleasedBytes;432}433434const char *getRegionInfoArrayAddress() const {435return reinterpret_cast<const char *>(RegionInfoArray);436}437438static uptr getRegionInfoArraySize() { return sizeof(RegionInfoArray); }439440uptr getCompactPtrBaseByClassId(uptr ClassId) {441return getRegionInfo(ClassId)->RegionBeg;442}443444CompactPtrT compactPtr(uptr ClassId, uptr Ptr) {445DCHECK_LE(ClassId, SizeClassMap::LargestClassId);446return compactPtrInternal(getCompactPtrBaseByClassId(ClassId), Ptr);447}448449void *decompactPtr(uptr ClassId, CompactPtrT CompactPtr) {450DCHECK_LE(ClassId, SizeClassMap::LargestClassId);451return reinterpret_cast<void *>(452decompactPtrInternal(getCompactPtrBaseByClassId(ClassId), CompactPtr));453}454455static BlockInfo findNearestBlock(const char *RegionInfoData,456uptr Ptr) NO_THREAD_SAFETY_ANALYSIS {457const RegionInfo *RegionInfoArray =458reinterpret_cast<const RegionInfo *>(RegionInfoData);459460uptr ClassId;461uptr MinDistance = -1UL;462for (uptr I = 0; I != NumClasses; ++I) {463if (I == SizeClassMap::BatchClassId)464continue;465uptr Begin = RegionInfoArray[I].RegionBeg;466// TODO(chiahungduan): In fact, We need to lock the RegionInfo::MMLock.467// However, the RegionInfoData is passed with const qualifier and lock the468// mutex requires modifying RegionInfoData, which means we need to remove469// the const qualifier. This may lead to another undefined behavior (The470// first one is accessing `AllocatedUser` without locking. It's better to471// pass `RegionInfoData` as `void *` then we can lock the mutex properly.472uptr End = Begin + RegionInfoArray[I].MemMapInfo.AllocatedUser;473if (Begin > End || End - Begin < SizeClassMap::getSizeByClassId(I))474continue;475uptr RegionDistance;476if (Begin <= Ptr) {477if (Ptr < End)478RegionDistance = 0;479else480RegionDistance = Ptr - End;481} else {482RegionDistance = Begin - Ptr;483}484485if (RegionDistance < MinDistance) {486MinDistance = RegionDistance;487ClassId = I;488}489}490491BlockInfo B = {};492if (MinDistance <= 8192) {493B.RegionBegin = RegionInfoArray[ClassId].RegionBeg;494B.RegionEnd =495B.RegionBegin + RegionInfoArray[ClassId].MemMapInfo.AllocatedUser;496B.BlockSize = SizeClassMap::getSizeByClassId(ClassId);497B.BlockBegin =498B.RegionBegin + uptr(sptr(Ptr - B.RegionBegin) / sptr(B.BlockSize) *499sptr(B.BlockSize));500while (B.BlockBegin < B.RegionBegin)501B.BlockBegin += B.BlockSize;502while (B.RegionEnd < B.BlockBegin + B.BlockSize)503B.BlockBegin -= B.BlockSize;504}505return B;506}507508AtomicOptions Options;509510private:511static const uptr RegionSize = 1UL << RegionSizeLog;512static const uptr NumClasses = SizeClassMap::NumClasses;513514static const uptr MapSizeIncrement = Config::getMapSizeIncrement();515// Fill at most this number of batches from the newly map'd memory.516static const u32 MaxNumBatches = SCUDO_ANDROID ? 4U : 8U;517518struct ReleaseToOsInfo {519uptr BytesInFreeListAtLastCheckpoint;520uptr RangesReleased;521uptr LastReleasedBytes;522u64 LastReleaseAtNs;523};524525struct BlocksInfo {526SinglyLinkedList<BatchGroupT> BlockList = {};527uptr PoppedBlocks = 0;528uptr PushedBlocks = 0;529};530531struct PagesInfo {532MemMapT MemMap = {};533// Bytes mapped for user memory.534uptr MappedUser = 0;535// Bytes allocated for user memory.536uptr AllocatedUser = 0;537};538539struct UnpaddedRegionInfo {540// Mutex for operations on freelist541HybridMutex FLLock;542ConditionVariableT FLLockCV GUARDED_BY(FLLock);543// Mutex for memmap operations544HybridMutex MMLock ACQUIRED_BEFORE(FLLock);545// `RegionBeg` is initialized before thread creation and won't be changed.546uptr RegionBeg = 0;547u32 RandState GUARDED_BY(MMLock) = 0;548BlocksInfo FreeListInfo GUARDED_BY(FLLock);549PagesInfo MemMapInfo GUARDED_BY(MMLock);550// The minimum size of pushed blocks to trigger page release.551uptr TryReleaseThreshold GUARDED_BY(MMLock) = 0;552ReleaseToOsInfo ReleaseInfo GUARDED_BY(MMLock) = {};553bool Exhausted GUARDED_BY(MMLock) = false;554bool isPopulatingFreeList GUARDED_BY(FLLock) = false;555};556struct RegionInfo : UnpaddedRegionInfo {557char Padding[SCUDO_CACHE_LINE_SIZE -558(sizeof(UnpaddedRegionInfo) % SCUDO_CACHE_LINE_SIZE)] = {};559};560static_assert(sizeof(RegionInfo) % SCUDO_CACHE_LINE_SIZE == 0, "");561562RegionInfo *getRegionInfo(uptr ClassId) {563DCHECK_LT(ClassId, NumClasses);564return &RegionInfoArray[ClassId];565}566567uptr getRegionBaseByClassId(uptr ClassId) {568RegionInfo *Region = getRegionInfo(ClassId);569Region->MMLock.assertHeld();570571if (!Config::getEnableContiguousRegions() &&572!Region->MemMapInfo.MemMap.isAllocated()) {573return 0U;574}575return Region->MemMapInfo.MemMap.getBase();576}577578static CompactPtrT compactPtrInternal(uptr Base, uptr Ptr) {579return static_cast<CompactPtrT>((Ptr - Base) >> CompactPtrScale);580}581582static uptr decompactPtrInternal(uptr Base, CompactPtrT CompactPtr) {583return Base + (static_cast<uptr>(CompactPtr) << CompactPtrScale);584}585586static uptr compactPtrGroup(CompactPtrT CompactPtr) {587const uptr Mask = (static_cast<uptr>(1) << GroupScale) - 1;588return static_cast<uptr>(CompactPtr) & ~Mask;589}590static uptr decompactGroupBase(uptr Base, uptr CompactPtrGroupBase) {591DCHECK_EQ(CompactPtrGroupBase % (static_cast<uptr>(1) << (GroupScale)), 0U);592return Base + (CompactPtrGroupBase << CompactPtrScale);593}594595ALWAYS_INLINE static bool isSmallBlock(uptr BlockSize) {596const uptr PageSize = getPageSizeCached();597return BlockSize < PageSize / 16U;598}599600ALWAYS_INLINE static bool isLargeBlock(uptr BlockSize) {601const uptr PageSize = getPageSizeCached();602return BlockSize > PageSize;603}604605ALWAYS_INLINE void initRegion(RegionInfo *Region, uptr ClassId,606MemMapT MemMap, bool EnableRandomOffset)607REQUIRES(Region->MMLock) {608DCHECK(!Region->MemMapInfo.MemMap.isAllocated());609DCHECK(MemMap.isAllocated());610611const uptr PageSize = getPageSizeCached();612613Region->MemMapInfo.MemMap = MemMap;614615Region->RegionBeg = MemMap.getBase();616if (EnableRandomOffset) {617Region->RegionBeg +=618(getRandomModN(&Region->RandState, 16) + 1) * PageSize;619}620621// Releasing small blocks is expensive, set a higher threshold to avoid622// frequent page releases.623if (isSmallBlock(getSizeByClassId(ClassId)))624Region->TryReleaseThreshold = PageSize * SmallerBlockReleasePageDelta;625else626Region->TryReleaseThreshold = PageSize;627}628629void pushBatchClassBlocks(RegionInfo *Region, CompactPtrT *Array, u32 Size)630REQUIRES(Region->FLLock) {631DCHECK_EQ(Region, getRegionInfo(SizeClassMap::BatchClassId));632633// Free blocks are recorded by TransferBatch in freelist for all634// size-classes. In addition, TransferBatch is allocated from BatchClassId.635// In order not to use additional block to record the free blocks in636// BatchClassId, they are self-contained. I.e., A TransferBatch records the637// block address of itself. See the figure below:638//639// TransferBatch at 0xABCD640// +----------------------------+641// | Free blocks' addr |642// | +------+------+------+ |643// | |0xABCD|... |... | |644// | +------+------+------+ |645// +----------------------------+646//647// When we allocate all the free blocks in the TransferBatch, the block used648// by TransferBatch is also free for use. We don't need to recycle the649// TransferBatch. Note that the correctness is maintained by the invariant,650//651// Each popBlocks() request returns the entire TransferBatch. Returning652// part of the blocks in a TransferBatch is invalid.653//654// This ensures that TransferBatch won't leak the address itself while it's655// still holding other valid data.656//657// Besides, BatchGroup is also allocated from BatchClassId and has its658// address recorded in the TransferBatch too. To maintain the correctness,659//660// The address of BatchGroup is always recorded in the last TransferBatch661// in the freelist (also imply that the freelist should only be662// updated with push_front). Once the last TransferBatch is popped,663// the block used by BatchGroup is also free for use.664//665// With this approach, the blocks used by BatchGroup and TransferBatch are666// reusable and don't need additional space for them.667668Region->FreeListInfo.PushedBlocks += Size;669BatchGroupT *BG = Region->FreeListInfo.BlockList.front();670671if (BG == nullptr) {672// Construct `BatchGroup` on the last element.673BG = reinterpret_cast<BatchGroupT *>(674decompactPtr(SizeClassMap::BatchClassId, Array[Size - 1]));675--Size;676BG->Batches.clear();677// BatchClass hasn't enabled memory group. Use `0` to indicate there's no678// memory group here.679BG->CompactPtrGroupBase = 0;680// `BG` is also the block of BatchClassId. Note that this is different681// from `CreateGroup` in `pushBlocksImpl`682BG->PushedBlocks = 1;683BG->BytesInBGAtLastCheckpoint = 0;684BG->MaxCachedPerBatch =685CacheT::getMaxCached(getSizeByClassId(SizeClassMap::BatchClassId));686687Region->FreeListInfo.BlockList.push_front(BG);688}689690if (UNLIKELY(Size == 0))691return;692693// This happens under 2 cases.694// 1. just allocated a new `BatchGroup`.695// 2. Only 1 block is pushed when the freelist is empty.696if (BG->Batches.empty()) {697// Construct the `TransferBatch` on the last element.698TransferBatchT *TB = reinterpret_cast<TransferBatchT *>(699decompactPtr(SizeClassMap::BatchClassId, Array[Size - 1]));700TB->clear();701// As mentioned above, addresses of `TransferBatch` and `BatchGroup` are702// recorded in the TransferBatch.703TB->add(Array[Size - 1]);704TB->add(705compactPtr(SizeClassMap::BatchClassId, reinterpret_cast<uptr>(BG)));706--Size;707DCHECK_EQ(BG->PushedBlocks, 1U);708// `TB` is also the block of BatchClassId.709BG->PushedBlocks += 1;710BG->Batches.push_front(TB);711}712713TransferBatchT *CurBatch = BG->Batches.front();714DCHECK_NE(CurBatch, nullptr);715716for (u32 I = 0; I < Size;) {717u16 UnusedSlots =718static_cast<u16>(BG->MaxCachedPerBatch - CurBatch->getCount());719if (UnusedSlots == 0) {720CurBatch = reinterpret_cast<TransferBatchT *>(721decompactPtr(SizeClassMap::BatchClassId, Array[I]));722CurBatch->clear();723// Self-contained724CurBatch->add(Array[I]);725++I;726// TODO(chiahungduan): Avoid the use of push_back() in `Batches` of727// BatchClassId.728BG->Batches.push_front(CurBatch);729UnusedSlots = static_cast<u16>(BG->MaxCachedPerBatch - 1);730}731// `UnusedSlots` is u16 so the result will be also fit in u16.732const u16 AppendSize = static_cast<u16>(Min<u32>(UnusedSlots, Size - I));733CurBatch->appendFromArray(&Array[I], AppendSize);734I += AppendSize;735}736737BG->PushedBlocks += Size;738}739740// Push the blocks to their batch group. The layout will be like,741//742// FreeListInfo.BlockList - > BG -> BG -> BG743// | | |744// v v v745// TB TB TB746// |747// v748// TB749//750// Each BlockGroup(BG) will associate with unique group id and the free blocks751// are managed by a list of TransferBatch(TB). To reduce the time of inserting752// blocks, BGs are sorted and the input `Array` are supposed to be sorted so753// that we can get better performance of maintaining sorted property.754// Use `SameGroup=true` to indicate that all blocks in the array are from the755// same group then we will skip checking the group id of each block.756void pushBlocksImpl(CacheT *C, uptr ClassId, RegionInfo *Region,757CompactPtrT *Array, u32 Size, bool SameGroup = false)758REQUIRES(Region->FLLock) {759DCHECK_NE(ClassId, SizeClassMap::BatchClassId);760DCHECK_GT(Size, 0U);761762auto CreateGroup = [&](uptr CompactPtrGroupBase) {763BatchGroupT *BG =764reinterpret_cast<BatchGroupT *>(C->getBatchClassBlock());765BG->Batches.clear();766TransferBatchT *TB =767reinterpret_cast<TransferBatchT *>(C->getBatchClassBlock());768TB->clear();769770BG->CompactPtrGroupBase = CompactPtrGroupBase;771BG->Batches.push_front(TB);772BG->PushedBlocks = 0;773BG->BytesInBGAtLastCheckpoint = 0;774BG->MaxCachedPerBatch = TransferBatchT::MaxNumCached;775776return BG;777};778779auto InsertBlocks = [&](BatchGroupT *BG, CompactPtrT *Array, u32 Size) {780SinglyLinkedList<TransferBatchT> &Batches = BG->Batches;781TransferBatchT *CurBatch = Batches.front();782DCHECK_NE(CurBatch, nullptr);783784for (u32 I = 0; I < Size;) {785DCHECK_GE(BG->MaxCachedPerBatch, CurBatch->getCount());786u16 UnusedSlots =787static_cast<u16>(BG->MaxCachedPerBatch - CurBatch->getCount());788if (UnusedSlots == 0) {789CurBatch =790reinterpret_cast<TransferBatchT *>(C->getBatchClassBlock());791CurBatch->clear();792Batches.push_front(CurBatch);793UnusedSlots = BG->MaxCachedPerBatch;794}795// `UnusedSlots` is u16 so the result will be also fit in u16.796u16 AppendSize = static_cast<u16>(Min<u32>(UnusedSlots, Size - I));797CurBatch->appendFromArray(&Array[I], AppendSize);798I += AppendSize;799}800801BG->PushedBlocks += Size;802};803804Region->FreeListInfo.PushedBlocks += Size;805BatchGroupT *Cur = Region->FreeListInfo.BlockList.front();806807// In the following, `Cur` always points to the BatchGroup for blocks that808// will be pushed next. `Prev` is the element right before `Cur`.809BatchGroupT *Prev = nullptr;810811while (Cur != nullptr &&812compactPtrGroup(Array[0]) > Cur->CompactPtrGroupBase) {813Prev = Cur;814Cur = Cur->Next;815}816817if (Cur == nullptr ||818compactPtrGroup(Array[0]) != Cur->CompactPtrGroupBase) {819Cur = CreateGroup(compactPtrGroup(Array[0]));820if (Prev == nullptr)821Region->FreeListInfo.BlockList.push_front(Cur);822else823Region->FreeListInfo.BlockList.insert(Prev, Cur);824}825826// All the blocks are from the same group, just push without checking group827// id.828if (SameGroup) {829for (u32 I = 0; I < Size; ++I)830DCHECK_EQ(compactPtrGroup(Array[I]), Cur->CompactPtrGroupBase);831832InsertBlocks(Cur, Array, Size);833return;834}835836// The blocks are sorted by group id. Determine the segment of group and837// push them to their group together.838u32 Count = 1;839for (u32 I = 1; I < Size; ++I) {840if (compactPtrGroup(Array[I - 1]) != compactPtrGroup(Array[I])) {841DCHECK_EQ(compactPtrGroup(Array[I - 1]), Cur->CompactPtrGroupBase);842InsertBlocks(Cur, Array + I - Count, Count);843844while (Cur != nullptr &&845compactPtrGroup(Array[I]) > Cur->CompactPtrGroupBase) {846Prev = Cur;847Cur = Cur->Next;848}849850if (Cur == nullptr ||851compactPtrGroup(Array[I]) != Cur->CompactPtrGroupBase) {852Cur = CreateGroup(compactPtrGroup(Array[I]));853DCHECK_NE(Prev, nullptr);854Region->FreeListInfo.BlockList.insert(Prev, Cur);855}856857Count = 1;858} else {859++Count;860}861}862863InsertBlocks(Cur, Array + Size - Count, Count);864}865866u16 popBlocksWithCV(CacheT *C, uptr ClassId, RegionInfo *Region,867CompactPtrT *ToArray, const u16 MaxBlockCount,868bool &ReportRegionExhausted) {869u16 PopCount = 0;870871while (true) {872// We only expect one thread doing the freelist refillment and other873// threads will be waiting for either the completion of the874// `populateFreeListAndPopBatch()` or `pushBlocks()` called by other875// threads.876bool PopulateFreeList = false;877{878ScopedLock FL(Region->FLLock);879if (!Region->isPopulatingFreeList) {880Region->isPopulatingFreeList = true;881PopulateFreeList = true;882}883}884885if (PopulateFreeList) {886ScopedLock ML(Region->MMLock);887888const bool RegionIsExhausted = Region->Exhausted;889if (!RegionIsExhausted) {890PopCount = populateFreeListAndPopBlocks(C, ClassId, Region, ToArray,891MaxBlockCount);892}893ReportRegionExhausted = !RegionIsExhausted && Region->Exhausted;894895{896// Before reacquiring the `FLLock`, the freelist may be used up again897// and some threads are waiting for the freelist refillment by the898// current thread. It's important to set899// `Region->isPopulatingFreeList` to false so the threads about to900// sleep will notice the status change.901ScopedLock FL(Region->FLLock);902Region->isPopulatingFreeList = false;903Region->FLLockCV.notifyAll(Region->FLLock);904}905906break;907}908909// At here, there are two preconditions to be met before waiting,910// 1. The freelist is empty.911// 2. Region->isPopulatingFreeList == true, i.e, someone is still doing912// `populateFreeListAndPopBatch()`.913//914// Note that it has the chance that freelist is empty but915// Region->isPopulatingFreeList == false because all the new populated916// blocks were used up right after the refillment. Therefore, we have to917// check if someone is still populating the freelist.918ScopedLock FL(Region->FLLock);919PopCount = popBlocksImpl(C, ClassId, Region, ToArray, MaxBlockCount);920if (PopCount != 0U)921break;922923if (!Region->isPopulatingFreeList)924continue;925926// Now the freelist is empty and someone's doing the refillment. We will927// wait until anyone refills the freelist or someone finishes doing928// `populateFreeListAndPopBatch()`. The refillment can be done by929// `populateFreeListAndPopBatch()`, `pushBlocks()`,930// `pushBatchClassBlocks()` and `mergeGroupsToReleaseBack()`.931Region->FLLockCV.wait(Region->FLLock);932933PopCount = popBlocksImpl(C, ClassId, Region, ToArray, MaxBlockCount);934if (PopCount != 0U)935break;936}937938return PopCount;939}940941u16 popBlocksImpl(CacheT *C, uptr ClassId, RegionInfo *Region,942CompactPtrT *ToArray, const u16 MaxBlockCount)943REQUIRES(Region->FLLock) {944if (Region->FreeListInfo.BlockList.empty())945return 0U;946947SinglyLinkedList<TransferBatchT> &Batches =948Region->FreeListInfo.BlockList.front()->Batches;949950if (Batches.empty()) {951DCHECK_EQ(ClassId, SizeClassMap::BatchClassId);952BatchGroupT *BG = Region->FreeListInfo.BlockList.front();953Region->FreeListInfo.BlockList.pop_front();954955// Block used by `BatchGroup` is from BatchClassId. Turn the block into956// `TransferBatch` with single block.957TransferBatchT *TB = reinterpret_cast<TransferBatchT *>(BG);958ToArray[0] =959compactPtr(SizeClassMap::BatchClassId, reinterpret_cast<uptr>(TB));960Region->FreeListInfo.PoppedBlocks += 1;961return 1U;962}963964// So far, instead of always filling blocks to `MaxBlockCount`, we only965// examine single `TransferBatch` to minimize the time spent in the primary966// allocator. Besides, the sizes of `TransferBatch` and967// `CacheT::getMaxCached()` may also impact the time spent on accessing the968// primary allocator.969// TODO(chiahungduan): Evaluate if we want to always prepare `MaxBlockCount`970// blocks and/or adjust the size of `TransferBatch` according to971// `CacheT::getMaxCached()`.972TransferBatchT *B = Batches.front();973DCHECK_NE(B, nullptr);974DCHECK_GT(B->getCount(), 0U);975976// BachClassId should always take all blocks in the TransferBatch. Read the977// comment in `pushBatchClassBlocks()` for more details.978const u16 PopCount = ClassId == SizeClassMap::BatchClassId979? B->getCount()980: Min(MaxBlockCount, B->getCount());981B->moveNToArray(ToArray, PopCount);982983// TODO(chiahungduan): The deallocation of unused BatchClassId blocks can be984// done without holding `FLLock`.985if (B->empty()) {986Batches.pop_front();987// `TransferBatch` of BatchClassId is self-contained, no need to988// deallocate. Read the comment in `pushBatchClassBlocks()` for more989// details.990if (ClassId != SizeClassMap::BatchClassId)991C->deallocate(SizeClassMap::BatchClassId, B);992993if (Batches.empty()) {994BatchGroupT *BG = Region->FreeListInfo.BlockList.front();995Region->FreeListInfo.BlockList.pop_front();996997// We don't keep BatchGroup with zero blocks to avoid empty-checking998// while allocating. Note that block used for constructing BatchGroup is999// recorded as free blocks in the last element of BatchGroup::Batches.1000// Which means, once we pop the last TransferBatch, the block is1001// implicitly deallocated.1002if (ClassId != SizeClassMap::BatchClassId)1003C->deallocate(SizeClassMap::BatchClassId, BG);1004}1005}10061007Region->FreeListInfo.PoppedBlocks += PopCount;10081009return PopCount;1010}10111012NOINLINE u16 populateFreeListAndPopBlocks(CacheT *C, uptr ClassId,1013RegionInfo *Region,1014CompactPtrT *ToArray,1015const u16 MaxBlockCount)1016REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {1017if (!Config::getEnableContiguousRegions() &&1018!Region->MemMapInfo.MemMap.isAllocated()) {1019ReservedMemoryT ReservedMemory;1020if (UNLIKELY(!ReservedMemory.create(/*Addr=*/0U, RegionSize,1021"scudo:primary_reserve",1022MAP_ALLOWNOMEM))) {1023Printf("Can't reserve pages for size class %zu.\n",1024getSizeByClassId(ClassId));1025return 0U;1026}1027initRegion(Region, ClassId,1028ReservedMemory.dispatch(ReservedMemory.getBase(),1029ReservedMemory.getCapacity()),1030/*EnableRandomOffset=*/false);1031}10321033DCHECK(Region->MemMapInfo.MemMap.isAllocated());1034const uptr Size = getSizeByClassId(ClassId);1035const u16 MaxCount = CacheT::getMaxCached(Size);1036const uptr RegionBeg = Region->RegionBeg;1037const uptr MappedUser = Region->MemMapInfo.MappedUser;1038const uptr TotalUserBytes =1039Region->MemMapInfo.AllocatedUser + MaxCount * Size;1040// Map more space for blocks, if necessary.1041if (TotalUserBytes > MappedUser) {1042// Do the mmap for the user memory.1043const uptr MapSize =1044roundUp(TotalUserBytes - MappedUser, MapSizeIncrement);1045const uptr RegionBase = RegionBeg - getRegionBaseByClassId(ClassId);1046if (UNLIKELY(RegionBase + MappedUser + MapSize > RegionSize)) {1047Region->Exhausted = true;1048return 0U;1049}10501051if (UNLIKELY(!Region->MemMapInfo.MemMap.remap(1052RegionBeg + MappedUser, MapSize, "scudo:primary",1053MAP_ALLOWNOMEM | MAP_RESIZABLE |1054(useMemoryTagging<Config>(Options.load()) ? MAP_MEMTAG1055: 0)))) {1056return 0U;1057}1058Region->MemMapInfo.MappedUser += MapSize;1059C->getStats().add(StatMapped, MapSize);1060}10611062const u32 NumberOfBlocks =1063Min(MaxNumBatches * MaxCount,1064static_cast<u32>((Region->MemMapInfo.MappedUser -1065Region->MemMapInfo.AllocatedUser) /1066Size));1067DCHECK_GT(NumberOfBlocks, 0);10681069constexpr u32 ShuffleArraySize =1070MaxNumBatches * TransferBatchT::MaxNumCached;1071CompactPtrT ShuffleArray[ShuffleArraySize];1072DCHECK_LE(NumberOfBlocks, ShuffleArraySize);10731074const uptr CompactPtrBase = getCompactPtrBaseByClassId(ClassId);1075uptr P = RegionBeg + Region->MemMapInfo.AllocatedUser;1076for (u32 I = 0; I < NumberOfBlocks; I++, P += Size)1077ShuffleArray[I] = compactPtrInternal(CompactPtrBase, P);10781079ScopedLock L(Region->FLLock);10801081if (ClassId != SizeClassMap::BatchClassId) {1082u32 N = 1;1083uptr CurGroup = compactPtrGroup(ShuffleArray[0]);1084for (u32 I = 1; I < NumberOfBlocks; I++) {1085if (UNLIKELY(compactPtrGroup(ShuffleArray[I]) != CurGroup)) {1086shuffle(ShuffleArray + I - N, N, &Region->RandState);1087pushBlocksImpl(C, ClassId, Region, ShuffleArray + I - N, N,1088/*SameGroup=*/true);1089N = 1;1090CurGroup = compactPtrGroup(ShuffleArray[I]);1091} else {1092++N;1093}1094}10951096shuffle(ShuffleArray + NumberOfBlocks - N, N, &Region->RandState);1097pushBlocksImpl(C, ClassId, Region, &ShuffleArray[NumberOfBlocks - N], N,1098/*SameGroup=*/true);1099} else {1100pushBatchClassBlocks(Region, ShuffleArray, NumberOfBlocks);1101}11021103const u16 PopCount =1104popBlocksImpl(C, ClassId, Region, ToArray, MaxBlockCount);1105DCHECK_NE(PopCount, 0U);11061107// Note that `PushedBlocks` and `PoppedBlocks` are supposed to only record1108// the requests from `PushBlocks` and `PopBatch` which are external1109// interfaces. `populateFreeListAndPopBatch` is the internal interface so we1110// should set the values back to avoid incorrectly setting the stats.1111Region->FreeListInfo.PushedBlocks -= NumberOfBlocks;11121113const uptr AllocatedUser = Size * NumberOfBlocks;1114C->getStats().add(StatFree, AllocatedUser);1115Region->MemMapInfo.AllocatedUser += AllocatedUser;11161117return PopCount;1118}11191120void getStats(ScopedString *Str, uptr ClassId, RegionInfo *Region)1121REQUIRES(Region->MMLock, Region->FLLock) {1122if (Region->MemMapInfo.MappedUser == 0)1123return;1124const uptr BlockSize = getSizeByClassId(ClassId);1125const uptr InUseBlocks =1126Region->FreeListInfo.PoppedBlocks - Region->FreeListInfo.PushedBlocks;1127const uptr BytesInFreeList =1128Region->MemMapInfo.AllocatedUser - InUseBlocks * BlockSize;1129uptr RegionPushedBytesDelta = 0;1130if (BytesInFreeList >=1131Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint) {1132RegionPushedBytesDelta =1133BytesInFreeList - Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint;1134}1135const uptr TotalChunks = Region->MemMapInfo.AllocatedUser / BlockSize;1136Str->append(1137"%s %02zu (%6zu): mapped: %6zuK popped: %7zu pushed: %7zu "1138"inuse: %6zu total: %6zu releases: %6zu last "1139"released: %6zuK latest pushed bytes: %6zuK region: 0x%zx (0x%zx)\n",1140Region->Exhausted ? "E" : " ", ClassId, getSizeByClassId(ClassId),1141Region->MemMapInfo.MappedUser >> 10, Region->FreeListInfo.PoppedBlocks,1142Region->FreeListInfo.PushedBlocks, InUseBlocks, TotalChunks,1143Region->ReleaseInfo.RangesReleased,1144Region->ReleaseInfo.LastReleasedBytes >> 10,1145RegionPushedBytesDelta >> 10, Region->RegionBeg,1146getRegionBaseByClassId(ClassId));1147}11481149void getRegionFragmentationInfo(RegionInfo *Region, uptr ClassId,1150ScopedString *Str) REQUIRES(Region->MMLock) {1151const uptr BlockSize = getSizeByClassId(ClassId);1152const uptr AllocatedUserEnd =1153Region->MemMapInfo.AllocatedUser + Region->RegionBeg;11541155SinglyLinkedList<BatchGroupT> GroupsToRelease;1156{1157ScopedLock L(Region->FLLock);1158GroupsToRelease = Region->FreeListInfo.BlockList;1159Region->FreeListInfo.BlockList.clear();1160}11611162FragmentationRecorder Recorder;1163if (!GroupsToRelease.empty()) {1164PageReleaseContext Context =1165markFreeBlocks(Region, BlockSize, AllocatedUserEnd,1166getCompactPtrBaseByClassId(ClassId), GroupsToRelease);1167auto SkipRegion = [](UNUSED uptr RegionIndex) { return false; };1168releaseFreeMemoryToOS(Context, Recorder, SkipRegion);11691170mergeGroupsToReleaseBack(Region, GroupsToRelease);1171}11721173ScopedLock L(Region->FLLock);1174const uptr PageSize = getPageSizeCached();1175const uptr TotalBlocks = Region->MemMapInfo.AllocatedUser / BlockSize;1176const uptr InUseBlocks =1177Region->FreeListInfo.PoppedBlocks - Region->FreeListInfo.PushedBlocks;1178const uptr AllocatedPagesCount =1179roundUp(Region->MemMapInfo.AllocatedUser, PageSize) / PageSize;1180DCHECK_GE(AllocatedPagesCount, Recorder.getReleasedPagesCount());1181const uptr InUsePages =1182AllocatedPagesCount - Recorder.getReleasedPagesCount();1183const uptr InUseBytes = InUsePages * PageSize;11841185uptr Integral;1186uptr Fractional;1187computePercentage(BlockSize * InUseBlocks, InUsePages * PageSize, &Integral,1188&Fractional);1189Str->append(" %02zu (%6zu): inuse/total blocks: %6zu/%6zu inuse/total "1190"pages: %6zu/%6zu inuse bytes: %6zuK util: %3zu.%02zu%%\n",1191ClassId, BlockSize, InUseBlocks, TotalBlocks, InUsePages,1192AllocatedPagesCount, InUseBytes >> 10, Integral, Fractional);1193}11941195NOINLINE uptr releaseToOSMaybe(RegionInfo *Region, uptr ClassId,1196ReleaseToOS ReleaseType = ReleaseToOS::Normal)1197REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {1198const uptr BlockSize = getSizeByClassId(ClassId);1199uptr BytesInFreeList;1200const uptr AllocatedUserEnd =1201Region->MemMapInfo.AllocatedUser + Region->RegionBeg;1202SinglyLinkedList<BatchGroupT> GroupsToRelease;12031204{1205ScopedLock L(Region->FLLock);12061207BytesInFreeList = Region->MemMapInfo.AllocatedUser -1208(Region->FreeListInfo.PoppedBlocks -1209Region->FreeListInfo.PushedBlocks) *1210BlockSize;1211if (UNLIKELY(BytesInFreeList == 0))1212return false;12131214// ==================================================================== //1215// 1. Check if we have enough free blocks and if it's worth doing a page1216// release.1217// ==================================================================== //1218if (ReleaseType != ReleaseToOS::ForceAll &&1219!hasChanceToReleasePages(Region, BlockSize, BytesInFreeList,1220ReleaseType)) {1221return 0;1222}12231224// ==================================================================== //1225// 2. Determine which groups can release the pages. Use a heuristic to1226// gather groups that are candidates for doing a release.1227// ==================================================================== //1228if (ReleaseType == ReleaseToOS::ForceAll) {1229GroupsToRelease = Region->FreeListInfo.BlockList;1230Region->FreeListInfo.BlockList.clear();1231} else {1232GroupsToRelease =1233collectGroupsToRelease(Region, BlockSize, AllocatedUserEnd,1234getCompactPtrBaseByClassId(ClassId));1235}1236if (GroupsToRelease.empty())1237return 0;1238}12391240// Note that we have extracted the `GroupsToRelease` from region freelist.1241// It's safe to let pushBlocks()/popBlocks() access the remaining region1242// freelist. In the steps 3 and 4, we will temporarily release the FLLock1243// and lock it again before step 5.12441245// ==================================================================== //1246// 3. Mark the free blocks in `GroupsToRelease` in the `PageReleaseContext`.1247// Then we can tell which pages are in-use by querying1248// `PageReleaseContext`.1249// ==================================================================== //1250PageReleaseContext Context =1251markFreeBlocks(Region, BlockSize, AllocatedUserEnd,1252getCompactPtrBaseByClassId(ClassId), GroupsToRelease);1253if (UNLIKELY(!Context.hasBlockMarked())) {1254mergeGroupsToReleaseBack(Region, GroupsToRelease);1255return 0;1256}12571258// ==================================================================== //1259// 4. Release the unused physical pages back to the OS.1260// ==================================================================== //1261RegionReleaseRecorder<MemMapT> Recorder(&Region->MemMapInfo.MemMap,1262Region->RegionBeg,1263Context.getReleaseOffset());1264auto SkipRegion = [](UNUSED uptr RegionIndex) { return false; };1265releaseFreeMemoryToOS(Context, Recorder, SkipRegion);1266if (Recorder.getReleasedRangesCount() > 0) {1267Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint = BytesInFreeList;1268Region->ReleaseInfo.RangesReleased += Recorder.getReleasedRangesCount();1269Region->ReleaseInfo.LastReleasedBytes = Recorder.getReleasedBytes();1270}1271Region->ReleaseInfo.LastReleaseAtNs = getMonotonicTimeFast();12721273// ====================================================================== //1274// 5. Merge the `GroupsToRelease` back to the freelist.1275// ====================================================================== //1276mergeGroupsToReleaseBack(Region, GroupsToRelease);12771278return Recorder.getReleasedBytes();1279}12801281bool hasChanceToReleasePages(RegionInfo *Region, uptr BlockSize,1282uptr BytesInFreeList, ReleaseToOS ReleaseType)1283REQUIRES(Region->MMLock, Region->FLLock) {1284DCHECK_GE(Region->FreeListInfo.PoppedBlocks,1285Region->FreeListInfo.PushedBlocks);1286const uptr PageSize = getPageSizeCached();12871288// Always update `BytesInFreeListAtLastCheckpoint` with the smallest value1289// so that we won't underestimate the releasable pages. For example, the1290// following is the region usage,1291//1292// BytesInFreeListAtLastCheckpoint AllocatedUser1293// v v1294// |--------------------------------------->1295// ^ ^1296// BytesInFreeList ReleaseThreshold1297//1298// In general, if we have collected enough bytes and the amount of free1299// bytes meets the ReleaseThreshold, we will try to do page release. If we1300// don't update `BytesInFreeListAtLastCheckpoint` when the current1301// `BytesInFreeList` is smaller, we may take longer time to wait for enough1302// freed blocks because we miss the bytes between1303// (BytesInFreeListAtLastCheckpoint - BytesInFreeList).1304if (BytesInFreeList <=1305Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint) {1306Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint = BytesInFreeList;1307}13081309const uptr RegionPushedBytesDelta =1310BytesInFreeList - Region->ReleaseInfo.BytesInFreeListAtLastCheckpoint;1311if (RegionPushedBytesDelta < PageSize)1312return false;13131314// Releasing smaller blocks is expensive, so we want to make sure that a1315// significant amount of bytes are free, and that there has been a good1316// amount of batches pushed to the freelist before attempting to release.1317if (isSmallBlock(BlockSize) && ReleaseType == ReleaseToOS::Normal)1318if (RegionPushedBytesDelta < Region->TryReleaseThreshold)1319return false;13201321if (ReleaseType == ReleaseToOS::Normal) {1322const s32 IntervalMs = atomic_load_relaxed(&ReleaseToOsIntervalMs);1323if (IntervalMs < 0)1324return false;13251326// The constant 8 here is selected from profiling some apps and the number1327// of unreleased pages in the large size classes is around 16 pages or1328// more. Choose half of it as a heuristic and which also avoids page1329// release every time for every pushBlocks() attempt by large blocks.1330const bool ByPassReleaseInterval =1331isLargeBlock(BlockSize) && RegionPushedBytesDelta > 8 * PageSize;1332if (!ByPassReleaseInterval) {1333if (Region->ReleaseInfo.LastReleaseAtNs +1334static_cast<u64>(IntervalMs) * 1000000 >1335getMonotonicTimeFast()) {1336// Memory was returned recently.1337return false;1338}1339}1340} // if (ReleaseType == ReleaseToOS::Normal)13411342return true;1343}13441345SinglyLinkedList<BatchGroupT>1346collectGroupsToRelease(RegionInfo *Region, const uptr BlockSize,1347const uptr AllocatedUserEnd, const uptr CompactPtrBase)1348REQUIRES(Region->MMLock, Region->FLLock) {1349const uptr GroupSize = (1UL << GroupSizeLog);1350const uptr PageSize = getPageSizeCached();1351SinglyLinkedList<BatchGroupT> GroupsToRelease;13521353// We are examining each group and will take the minimum distance to the1354// release threshold as the next Region::TryReleaseThreshold(). Note that if1355// the size of free blocks has reached the release threshold, the distance1356// to the next release will be PageSize * SmallerBlockReleasePageDelta. See1357// the comment on `SmallerBlockReleasePageDelta` for more details.1358uptr MinDistToThreshold = GroupSize;13591360for (BatchGroupT *BG = Region->FreeListInfo.BlockList.front(),1361*Prev = nullptr;1362BG != nullptr;) {1363// Group boundary is always GroupSize-aligned from CompactPtr base. The1364// layout of memory groups is like,1365//1366// (CompactPtrBase)1367// #1 CompactPtrGroupBase #2 CompactPtrGroupBase ...1368// | | |1369// v v v1370// +-----------------------+-----------------------+1371// \ / \ /1372// --- GroupSize --- --- GroupSize ---1373//1374// After decompacting the CompactPtrGroupBase, we expect the alignment1375// property is held as well.1376const uptr BatchGroupBase =1377decompactGroupBase(CompactPtrBase, BG->CompactPtrGroupBase);1378DCHECK_LE(Region->RegionBeg, BatchGroupBase);1379DCHECK_GE(AllocatedUserEnd, BatchGroupBase);1380DCHECK_EQ((Region->RegionBeg - BatchGroupBase) % GroupSize, 0U);1381// TransferBatches are pushed in front of BG.Batches. The first one may1382// not have all caches used.1383const uptr NumBlocks = (BG->Batches.size() - 1) * BG->MaxCachedPerBatch +1384BG->Batches.front()->getCount();1385const uptr BytesInBG = NumBlocks * BlockSize;13861387if (BytesInBG <= BG->BytesInBGAtLastCheckpoint) {1388BG->BytesInBGAtLastCheckpoint = BytesInBG;1389Prev = BG;1390BG = BG->Next;1391continue;1392}13931394const uptr PushedBytesDelta = BytesInBG - BG->BytesInBGAtLastCheckpoint;13951396// Given the randomness property, we try to release the pages only if the1397// bytes used by free blocks exceed certain proportion of group size. Note1398// that this heuristic only applies when all the spaces in a BatchGroup1399// are allocated.1400if (isSmallBlock(BlockSize)) {1401const uptr BatchGroupEnd = BatchGroupBase + GroupSize;1402const uptr AllocatedGroupSize = AllocatedUserEnd >= BatchGroupEnd1403? GroupSize1404: AllocatedUserEnd - BatchGroupBase;1405const uptr ReleaseThreshold =1406(AllocatedGroupSize * (100 - 1U - BlockSize / 16U)) / 100U;1407const bool HighDensity = BytesInBG >= ReleaseThreshold;1408const bool MayHaveReleasedAll = NumBlocks >= (GroupSize / BlockSize);1409// If all blocks in the group are released, we will do range marking1410// which is fast. Otherwise, we will wait until we have accumulated1411// a certain amount of free memory.1412const bool ReachReleaseDelta =1413MayHaveReleasedAll1414? true1415: PushedBytesDelta >= PageSize * SmallerBlockReleasePageDelta;14161417if (!HighDensity) {1418DCHECK_LE(BytesInBG, ReleaseThreshold);1419// The following is the usage of a memroy group,1420//1421// BytesInBG ReleaseThreshold1422// / \ v1423// +---+---------------------------+-----+1424// | | | | |1425// +---+---------------------------+-----+1426// \ / ^1427// PushedBytesDelta GroupEnd1428MinDistToThreshold =1429Min(MinDistToThreshold,1430ReleaseThreshold - BytesInBG + PushedBytesDelta);1431} else {1432// If it reaches high density at this round, the next time we will try1433// to release is based on SmallerBlockReleasePageDelta1434MinDistToThreshold =1435Min(MinDistToThreshold, PageSize * SmallerBlockReleasePageDelta);1436}14371438if (!HighDensity || !ReachReleaseDelta) {1439Prev = BG;1440BG = BG->Next;1441continue;1442}1443}14441445// If `BG` is the first BatchGroupT in the list, we only need to advance1446// `BG` and call FreeListInfo.BlockList::pop_front(). No update is needed1447// for `Prev`.1448//1449// (BG) (BG->Next)1450// Prev Cur BG1451// | | |1452// v v v1453// nil +--+ +--+1454// |X | -> | | -> ...1455// +--+ +--+1456//1457// Otherwise, `Prev` will be used to extract the `Cur` from the1458// `FreeListInfo.BlockList`.1459//1460// (BG) (BG->Next)1461// Prev Cur BG1462// | | |1463// v v v1464// +--+ +--+ +--+1465// | | -> |X | -> | | -> ...1466// +--+ +--+ +--+1467//1468// After FreeListInfo.BlockList::extract(),1469//1470// Prev Cur BG1471// | | |1472// v v v1473// +--+ +--+ +--+1474// | |-+ |X | +->| | -> ...1475// +--+ | +--+ | +--+1476// +--------+1477//1478// Note that we need to advance before pushing this BatchGroup to1479// GroupsToRelease because it's a destructive operation.14801481BatchGroupT *Cur = BG;1482BG = BG->Next;14831484// Ideally, we may want to update this only after successful release.1485// However, for smaller blocks, each block marking is a costly operation.1486// Therefore, we update it earlier.1487// TODO: Consider updating this after releasing pages if `ReleaseRecorder`1488// can tell the released bytes in each group.1489Cur->BytesInBGAtLastCheckpoint = BytesInBG;14901491if (Prev != nullptr)1492Region->FreeListInfo.BlockList.extract(Prev, Cur);1493else1494Region->FreeListInfo.BlockList.pop_front();1495GroupsToRelease.push_back(Cur);1496}14971498// Only small blocks have the adaptive `TryReleaseThreshold`.1499if (isSmallBlock(BlockSize)) {1500// If the MinDistToThreshold is not updated, that means each memory group1501// may have only pushed less than a page size. In that case, just set it1502// back to normal.1503if (MinDistToThreshold == GroupSize)1504MinDistToThreshold = PageSize * SmallerBlockReleasePageDelta;1505Region->TryReleaseThreshold = MinDistToThreshold;1506}15071508return GroupsToRelease;1509}15101511PageReleaseContext1512markFreeBlocks(RegionInfo *Region, const uptr BlockSize,1513const uptr AllocatedUserEnd, const uptr CompactPtrBase,1514SinglyLinkedList<BatchGroupT> &GroupsToRelease)1515REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {1516const uptr GroupSize = (1UL << GroupSizeLog);1517auto DecompactPtr = [CompactPtrBase](CompactPtrT CompactPtr) {1518return decompactPtrInternal(CompactPtrBase, CompactPtr);1519};15201521const uptr ReleaseBase = decompactGroupBase(1522CompactPtrBase, GroupsToRelease.front()->CompactPtrGroupBase);1523const uptr LastGroupEnd =1524Min(decompactGroupBase(CompactPtrBase,1525GroupsToRelease.back()->CompactPtrGroupBase) +1526GroupSize,1527AllocatedUserEnd);1528// The last block may straddle the group boundary. Rounding up to BlockSize1529// to get the exact range.1530const uptr ReleaseEnd =1531roundUpSlow(LastGroupEnd - Region->RegionBeg, BlockSize) +1532Region->RegionBeg;1533const uptr ReleaseRangeSize = ReleaseEnd - ReleaseBase;1534const uptr ReleaseOffset = ReleaseBase - Region->RegionBeg;15351536PageReleaseContext Context(BlockSize, /*NumberOfRegions=*/1U,1537ReleaseRangeSize, ReleaseOffset);1538// We may not be able to do the page release in a rare case that we may1539// fail on PageMap allocation.1540if (UNLIKELY(!Context.ensurePageMapAllocated()))1541return Context;15421543for (BatchGroupT &BG : GroupsToRelease) {1544const uptr BatchGroupBase =1545decompactGroupBase(CompactPtrBase, BG.CompactPtrGroupBase);1546const uptr BatchGroupEnd = BatchGroupBase + GroupSize;1547const uptr AllocatedGroupSize = AllocatedUserEnd >= BatchGroupEnd1548? GroupSize1549: AllocatedUserEnd - BatchGroupBase;1550const uptr BatchGroupUsedEnd = BatchGroupBase + AllocatedGroupSize;1551const bool MayContainLastBlockInRegion =1552BatchGroupUsedEnd == AllocatedUserEnd;1553const bool BlockAlignedWithUsedEnd =1554(BatchGroupUsedEnd - Region->RegionBeg) % BlockSize == 0;15551556uptr MaxContainedBlocks = AllocatedGroupSize / BlockSize;1557if (!BlockAlignedWithUsedEnd)1558++MaxContainedBlocks;15591560const uptr NumBlocks = (BG.Batches.size() - 1) * BG.MaxCachedPerBatch +1561BG.Batches.front()->getCount();15621563if (NumBlocks == MaxContainedBlocks) {1564for (const auto &It : BG.Batches) {1565if (&It != BG.Batches.front())1566DCHECK_EQ(It.getCount(), BG.MaxCachedPerBatch);1567for (u16 I = 0; I < It.getCount(); ++I)1568DCHECK_EQ(compactPtrGroup(It.get(I)), BG.CompactPtrGroupBase);1569}15701571Context.markRangeAsAllCounted(BatchGroupBase, BatchGroupUsedEnd,1572Region->RegionBeg, /*RegionIndex=*/0,1573Region->MemMapInfo.AllocatedUser);1574} else {1575DCHECK_LT(NumBlocks, MaxContainedBlocks);1576// Note that we don't always visit blocks in each BatchGroup so that we1577// may miss the chance of releasing certain pages that cross1578// BatchGroups.1579Context.markFreeBlocksInRegion(1580BG.Batches, DecompactPtr, Region->RegionBeg, /*RegionIndex=*/0,1581Region->MemMapInfo.AllocatedUser, MayContainLastBlockInRegion);1582}1583}15841585DCHECK(Context.hasBlockMarked());15861587return Context;1588}15891590void mergeGroupsToReleaseBack(RegionInfo *Region,1591SinglyLinkedList<BatchGroupT> &GroupsToRelease)1592REQUIRES(Region->MMLock) EXCLUDES(Region->FLLock) {1593ScopedLock L(Region->FLLock);15941595// After merging two freelists, we may have redundant `BatchGroup`s that1596// need to be recycled. The number of unused `BatchGroup`s is expected to be1597// small. Pick a constant which is inferred from real programs.1598constexpr uptr MaxUnusedSize = 8;1599CompactPtrT Blocks[MaxUnusedSize];1600u32 Idx = 0;1601RegionInfo *BatchClassRegion = getRegionInfo(SizeClassMap::BatchClassId);1602// We can't call pushBatchClassBlocks() to recycle the unused `BatchGroup`s1603// when we are manipulating the freelist of `BatchClassRegion`. Instead, we1604// should just push it back to the freelist when we merge two `BatchGroup`s.1605// This logic hasn't been implemented because we haven't supported releasing1606// pages in `BatchClassRegion`.1607DCHECK_NE(BatchClassRegion, Region);16081609// Merge GroupsToRelease back to the Region::FreeListInfo.BlockList. Note1610// that both `Region->FreeListInfo.BlockList` and `GroupsToRelease` are1611// sorted.1612for (BatchGroupT *BG = Region->FreeListInfo.BlockList.front(),1613*Prev = nullptr;1614;) {1615if (BG == nullptr || GroupsToRelease.empty()) {1616if (!GroupsToRelease.empty())1617Region->FreeListInfo.BlockList.append_back(&GroupsToRelease);1618break;1619}16201621DCHECK(!BG->Batches.empty());16221623if (BG->CompactPtrGroupBase <1624GroupsToRelease.front()->CompactPtrGroupBase) {1625Prev = BG;1626BG = BG->Next;1627continue;1628}16291630BatchGroupT *Cur = GroupsToRelease.front();1631TransferBatchT *UnusedTransferBatch = nullptr;1632GroupsToRelease.pop_front();16331634if (BG->CompactPtrGroupBase == Cur->CompactPtrGroupBase) {1635BG->PushedBlocks += Cur->PushedBlocks;1636// We have updated `BatchGroup::BytesInBGAtLastCheckpoint` while1637// collecting the `GroupsToRelease`.1638BG->BytesInBGAtLastCheckpoint = Cur->BytesInBGAtLastCheckpoint;1639const uptr MaxCachedPerBatch = BG->MaxCachedPerBatch;16401641// Note that the first TransferBatches in both `Batches` may not be1642// full and only the first TransferBatch can have non-full blocks. Thus1643// we have to merge them before appending one to another.1644if (Cur->Batches.front()->getCount() == MaxCachedPerBatch) {1645BG->Batches.append_back(&Cur->Batches);1646} else {1647TransferBatchT *NonFullBatch = Cur->Batches.front();1648Cur->Batches.pop_front();1649const u16 NonFullBatchCount = NonFullBatch->getCount();1650// The remaining Batches in `Cur` are full.1651BG->Batches.append_back(&Cur->Batches);16521653if (BG->Batches.front()->getCount() == MaxCachedPerBatch) {1654// Only 1 non-full TransferBatch, push it to the front.1655BG->Batches.push_front(NonFullBatch);1656} else {1657const u16 NumBlocksToMove = static_cast<u16>(1658Min(static_cast<u16>(MaxCachedPerBatch -1659BG->Batches.front()->getCount()),1660NonFullBatchCount));1661BG->Batches.front()->appendFromTransferBatch(NonFullBatch,1662NumBlocksToMove);1663if (NonFullBatch->isEmpty())1664UnusedTransferBatch = NonFullBatch;1665else1666BG->Batches.push_front(NonFullBatch);1667}1668}16691670const u32 NeededSlots = UnusedTransferBatch == nullptr ? 1U : 2U;1671if (UNLIKELY(Idx + NeededSlots > MaxUnusedSize)) {1672ScopedLock L(BatchClassRegion->FLLock);1673pushBatchClassBlocks(BatchClassRegion, Blocks, Idx);1674if (conditionVariableEnabled())1675BatchClassRegion->FLLockCV.notifyAll(BatchClassRegion->FLLock);1676Idx = 0;1677}1678Blocks[Idx++] =1679compactPtr(SizeClassMap::BatchClassId, reinterpret_cast<uptr>(Cur));1680if (UnusedTransferBatch) {1681Blocks[Idx++] =1682compactPtr(SizeClassMap::BatchClassId,1683reinterpret_cast<uptr>(UnusedTransferBatch));1684}1685Prev = BG;1686BG = BG->Next;1687continue;1688}16891690// At here, the `BG` is the first BatchGroup with CompactPtrGroupBase1691// larger than the first element in `GroupsToRelease`. We need to insert1692// `GroupsToRelease::front()` (which is `Cur` below) before `BG`.1693//1694// 1. If `Prev` is nullptr, we simply push `Cur` to the front of1695// FreeListInfo.BlockList.1696// 2. Otherwise, use `insert()` which inserts an element next to `Prev`.1697//1698// Afterwards, we don't need to advance `BG` because the order between1699// `BG` and the new `GroupsToRelease::front()` hasn't been checked.1700if (Prev == nullptr)1701Region->FreeListInfo.BlockList.push_front(Cur);1702else1703Region->FreeListInfo.BlockList.insert(Prev, Cur);1704DCHECK_EQ(Cur->Next, BG);1705Prev = Cur;1706}17071708if (Idx != 0) {1709ScopedLock L(BatchClassRegion->FLLock);1710pushBatchClassBlocks(BatchClassRegion, Blocks, Idx);1711if (conditionVariableEnabled())1712BatchClassRegion->FLLockCV.notifyAll(BatchClassRegion->FLLock);1713}17141715if (SCUDO_DEBUG) {1716BatchGroupT *Prev = Region->FreeListInfo.BlockList.front();1717for (BatchGroupT *Cur = Prev->Next; Cur != nullptr;1718Prev = Cur, Cur = Cur->Next) {1719CHECK_LT(Prev->CompactPtrGroupBase, Cur->CompactPtrGroupBase);1720}1721}17221723if (conditionVariableEnabled())1724Region->FLLockCV.notifyAll(Region->FLLock);1725}17261727// The minimum size of pushed blocks that we will try to release the pages in1728// that size class.1729uptr SmallerBlockReleasePageDelta = 0;1730atomic_s32 ReleaseToOsIntervalMs = {};1731alignas(SCUDO_CACHE_LINE_SIZE) RegionInfo RegionInfoArray[NumClasses];1732};17331734} // namespace scudo17351736#endif // SCUDO_PRIMARY64_H_173717381739