Loading...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- * * Copyright (c) 2023 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include <mach/mach_vm.h> #include "ChunkBumpAllocator.h" #if BUILDING_MACHO_WRITER #include "DynamicAtom.h" #endif // An allocated memory chunk and its size, this is always located // at the beginning of an allocated memory chunk, which allows to maintain // a free/used lists without extra misc allocations. struct ChunkBumpAllocatorChunk { ChunkBumpAllocatorChunk* next = nullptr; uint32_t size = 0; uint32_t pos = 0; uint32_t available() { return size - pos; } uint8_t* begin() { return (uint8_t*)this + pos; } }; using Entry = ChunkBumpAllocatorChunk; class ChunkBumpAllocatorZoneImpl { public: friend ChunkBumpAllocator; static const uint32_t headerSize = sizeof(Entry); ChunkBumpAllocatorZoneImpl(uint32_t chunkSize, uint32_t minReuseSize): _chunkSize(chunkSize), _minReuseSize(minReuseSize) { assert(chunkSize >= 512 && "too small chunk size?"); assert(chunkSize > _minReuseSize); assert(_minReuseSize > 0); } ~ChunkBumpAllocatorZoneImpl(); ChunkBumpAllocatorZoneImpl(const ChunkBumpAllocatorZoneImpl&) = delete; ChunkBumpAllocatorZoneImpl(ChunkBumpAllocatorZoneImpl&&) = delete; ChunkBumpAllocatorZoneImpl& operator=(const ChunkBumpAllocatorZoneImpl&) = delete; ChunkBumpAllocatorZoneImpl& operator=(ChunkBumpAllocatorZoneImpl&&) = delete; // Get a next available memory chunk that's large enough to serve Entry* nextFreeChunk(uint64_t size=0); void printStatistics(); private: size_t allocationSizeForRequestedSize(uint64_t); // chunk factory methods Entry* getFreeEntryLocked(uint64_t size); Entry* nextFreeChunkReclaimOld(uint64_t size, Entry* entry); // reclaim entry methods - either moves the entry to the free list or it will be retired and moved to the used list void reclaimEntry(Entry* entry); void reclaimFreeEntryLocked(Entry* entry); bool retireEntryIfSmall(Entry* entry); void retireEntry(Entry* entry); // Entry chunks allocation helpers Entry* makeNewEntry(uint64_t size); void free(Entry*); Entry* _freeList = nullptr; std::atomic<Entry*> _usedList = nullptr; // default chunk allocation size uint32_t _chunkSize = 0; // threshold size for chunk reuse, if an entry has less available memory // it will be retired into the used list uint32_t _minReuseSize = 0; os_unfair_lock_s _lock = OS_UNFAIR_LOCK_INIT; }; ChunkBumpAllocatorZoneImpl::~ChunkBumpAllocatorZoneImpl() { Entry* entry = _freeList; while ( entry ) { Entry* next = entry->next; free(entry); entry = next; } _freeList = nullptr; entry = _usedList; while ( entry ) { Entry* next = entry->next; free(entry); entry = next; } _usedList = nullptr; } Entry* ChunkBumpAllocatorZoneImpl::makeNewEntry(uint64_t size) { assert(size > sizeof(Entry)); Entry* entry = (Entry*)malloc(size); new (entry) Entry(); entry->size = (uint32_t)size; assert(entry->size == size && "size exceeds 32-bit allocation size limit"); entry->pos = sizeof(Entry); return entry; } void ChunkBumpAllocatorZoneImpl::free(Entry* entry) { ::free(entry); } Entry* ChunkBumpAllocatorZoneImpl::getFreeEntryLocked(uint64_t size) { Entry* rootEntry = _freeList; // free entries are sorted by size, so use root if it's big enough if ( rootEntry && rootEntry->available() >= size ) { _freeList = rootEntry->next; rootEntry->next = nullptr; return rootEntry; } // no free entry return nullptr; } size_t ChunkBumpAllocatorZoneImpl::allocationSizeForRequestedSize(uint64_t size) { uint64_t baseSize = std::max((uint64_t)_chunkSize, size + sizeof(Entry)); // align allocation size to a power of 2 uint64_t leadingZeros = __builtin_clzll(baseSize); uint64_t bufferSize = 1 << (64 - leadingZeros - 1); if ( bufferSize != baseSize ) { // for allocations smaller than 2mb align to a power of 2 if ( bufferSize < (1 << 21) ) bufferSize = bufferSize << 1; else // otherwise round up to a page size bufferSize = mach_vm_round_page(baseSize); } return bufferSize; } Entry* ChunkBumpAllocatorZoneImpl::nextFreeChunk(uint64_t size) { return nextFreeChunkReclaimOld(size, /* entry to reclaim */ nullptr); } Entry* ChunkBumpAllocatorZoneImpl::nextFreeChunkReclaimOld(uint64_t size, Entry* old) { uint64_t bufferSize = allocationSizeForRequestedSize(size); // quick check if top of the free list is set, we won't be using the actual value // so no lock is required if ( _freeList == nullptr ) { return (Entry*)makeNewEntry(bufferSize); } os_unfair_lock_lock(&_lock); Entry* freeEntry = getFreeEntryLocked(size); if ( old && !retireEntryIfSmall(old) ) { reclaimFreeEntryLocked(old); } os_unfair_lock_unlock(&_lock); if ( freeEntry == nullptr ) { // no free entry, make a new one freeEntry = (Entry*)makeNewEntry(bufferSize); } return freeEntry; } void ChunkBumpAllocatorZoneImpl::retireEntry(Entry* entry) { assert(entry->next == nullptr && "free entries shouldn't have the next entry set"); Entry* currentRoot = _usedList.load(std::memory_order_relaxed); entry->next = currentRoot; while ( !_usedList.compare_exchange_weak(currentRoot, entry, std::memory_order_release, std::memory_order_relaxed) ) entry->next = currentRoot; } bool ChunkBumpAllocatorZoneImpl::retireEntryIfSmall(Entry* entry) { bool reuse = entry->available() >= _minReuseSize; if ( reuse ) return false; retireEntry(entry); return true; } void ChunkBumpAllocatorZoneImpl::reclaimEntry(Entry* entry) { if ( retireEntryIfSmall(entry) ) return; os_unfair_lock_lock(&_lock); reclaimFreeEntryLocked(entry); os_unfair_lock_unlock(&_lock); } void ChunkBumpAllocatorZoneImpl::reclaimFreeEntryLocked(Entry* entry) { if ( _freeList == nullptr ) { _freeList = entry; return; } // free list is ordered by the available space, add as a root if larger or equal size_t newEntryAvailable = entry->available(); assert(newEntryAvailable >= _minReuseSize && "used entry should have been already reclaimed"); if ( newEntryAvailable >= _freeList->available() ) { entry->next = _freeList; _freeList = entry; return; } // otherwise walk the list to find the last entry that has more available space // than this new entry, but limit the depth of search for free entries // this is to prevent contention by ensuring we don't create a big // list with small available space int freeListCap = 15; Entry* previousEntry = _freeList; Entry* currentEntry = previousEntry->next; while ( currentEntry && currentEntry->available() > newEntryAvailable ) { previousEntry = currentEntry; currentEntry = currentEntry->next; if ( --freeListCap < 1 ) { // depth limit reached, retire this entry and add it to the used list retireEntry(entry); return; } } // current entry has the same or less available space // so add this new entry after the previous one entry->next = previousEntry->next; previousEntry->next = entry; } void ChunkBumpAllocatorZoneImpl::printStatistics() { size_t usedEntries = 0; size_t wastedSpace = 0; size_t usedSpace = 0; Entry* entry = _usedList; while ( entry ) { ++usedEntries; wastedSpace += entry->available(); usedSpace += entry->size - entry->available(); entry = entry->next; } size_t freeEntries = 0; size_t freeSpace = 0; entry = _freeList; while ( entry ) { ++freeEntries; freeSpace += entry->available(); usedSpace += entry->size - entry->available(); entry = entry->next; } printf("used space: %lu, free entries: %lu, free space: %lu, used entries: %lu, wasted space: %lu\n", usedSpace, freeEntries, freeSpace, usedEntries, wastedSpace); } ChunkBumpAllocator::ChunkBumpAllocator(ChunkBumpAllocatorZone& zone, ChunkBumpAllocatorChunk* chunk): _zone(zone), _chunk(chunk) {} std::span<uint8_t> ChunkBumpAllocator::allocate(uint64_t size, uint16_t align) { if ( !_chunk ) { assert(_zone); this->_chunk = _zone->nextFreeChunk(size); } uint8_t* begin = _chunk->begin(); size_t alignOffset = 0; size_t alignBytes = (uint64_t)begin % align; if ( alignBytes != 0 ) alignOffset = align - alignBytes; size_t totalSize = alignOffset + size; if ( _chunk->available() < totalSize ) { _chunk = _zone->nextFreeChunkReclaimOld(size, _chunk); // call allocate() recursively, as the alignment offset might be // different return allocate(size, align); } std::span<uint8_t> buffer(_chunk->begin() + alignOffset, size); _chunk->pos += totalSize; return buffer; } ChunkBumpAllocator::~ChunkBumpAllocator() { if ( _chunk && _zone ) { _zone->reclaimEntry(_chunk); } } ChunkBumpAllocatorZone ChunkBumpAllocatorZone::make(uint32_t chunkSize, uint32_t minSize) { return ChunkBumpAllocatorZone(new ChunkBumpAllocatorZoneImpl(chunkSize, minSize), /* global */ false); } ChunkBumpAllocatorZone::~ChunkBumpAllocatorZone() { if ( !_global && _zone ) { delete _zone; _zone = nullptr; } } void ChunkBumpAllocatorZone::printStatistics() { _zone->printStatistics(); } ChunkBumpAllocator ChunkBumpAllocatorZone::makeAllocator(size_t size) { return ChunkBumpAllocator(_zone, _zone->nextFreeChunk(size)); } ChunkBumpAllocator ChunkBumpAllocatorZone::makeEmptyAllocator() { return ChunkBumpAllocator(*this); } #if BUILDING_MACHO_WRITER const size_t sAtomAllocatorMinReuseSize = 0x1000 / sizeof(ld::DynamicAtom); static ChunkBumpAllocatorZoneImpl gAtomsZone(ChunkBumpAllocatorZone::defaultChunkSize, sAtomAllocatorMinReuseSize); static ChunkBumpAllocatorZoneImpl gSymbolStringZone(ChunkBumpAllocatorZone::defaultChunkSize, ChunkBumpAllocatorZone::defaultMinSize); constinit ChunkBumpAllocatorZone ChunkBumpAllocatorZone::atomsZone = ChunkBumpAllocatorZone(&gAtomsZone, /* global */ true); constinit ChunkBumpAllocatorZone ChunkBumpAllocatorZone::symbolStringZone = ChunkBumpAllocatorZone(&gSymbolStringZone, /* global */ true); #endif |