Debian Codegraph @

js/src/gc/BufferAllocator.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 // GC-internal header file for the buffer allocator.
8
9 #ifndef gc_BufferAllocator_h
10 #define gc_BufferAllocator_h
11
12 #include "mozilla/Array.h"
13 #include "mozilla/Atomics.h"
14 #include "mozilla/BitSet.h"
15 #include "mozilla/HashTable.h"
16 #include "mozilla/Maybe.h"
17 #include "mozilla/TimeStamp.h"
18
19 #include <cstdint>
20 #include <stddef.h>
21 #include <utility>
22
23 #include "jstypes.h" // JS_PUBLIC_API
24
25 #include "ds/SlimLinkedList.h"
26 #include "js/HeapAPI.h"
27 #include "threading/LockGuard.h"
28 #include "threading/Mutex.h"
29 #include "threading/ProtectedData.h"
30
31 class JS_PUBLIC_API JSTracer;
32
33 namespace JS {
34 class JS_PUBLIC_API Zone;
35 } // namespace JS
36
37 namespace js {
38
39 class GCMarker;
40 class Nursery;
41
42 namespace gc {
43
44 enum class AllocKind : uint8_t;
45
46 struct BufferChunk;
47 struct Cell;
48 class GCRuntime;
49 struct LargeBuffer;
50
51 // BufferAllocator allocates dynamically sized blocks of memory which can be
52 // reclaimed by the garbage collector and are associated with GC things.
53 //
54 // Although these blocks can be reclaimed by GC, explicit free and resize is
55 // also supported. This is important for buffers that can grow or shrink.
56 //
57 // The allocator uses a different strategy depending on the size of the
58 // allocation requested. There are three size ranges, divided as follows:
59 //
60 // Size: Kind: Allocator implementation:
61 // 16 B - 128 B Small Uses the cell (arena) allocator
62 // 256 B - 512 KB Medium Uses a free list allocator
63 // 1 MB - Large Uses the OS page allocator (e.g. mmap)
64 //
65 // The smallest supported allocation size is 16 bytes. This will be used for a
66 // dynamic slots allocation with zero slots to set a unique ID on a native
67 // object. This will be the size of two Values, i.e. 16 bytes.
68 //
69 // Supported operations
70 // --------------------
71 //
72 // - Allocate a buffer. Buffers are always owned by a GC cell, and the
73 // allocator tracks whether the owner is in the nursery or the tenured heap.
74 //
75 // - Trace an edge to buffer. When the owning cell is traced it must trace the
76 // edge to the buffer. This will mark the buffer in a GC and prevent it from
77 // being swept.
78 //
79 // - Free a buffer. This allows uniquely owned buffers to be freed and reused
80 // without waiting for the next GC. It is a hint only and is not supported
81 // for all buffer kinds.
82 //
83 // - Reallocate a buffer. This allows uniquely owned buffers to be resized,
84 // possibly in-place. This is important for performance on some benchmarks.
85 //
86 // Integration with the rest of the GC
87 // -----------------------------------
88 //
89 // The GC calls the allocator at several points during minor and major GC (at
90 // the start, when sweeping starts and at the end). Allocations are swept on a
91 // background thread and the memory used by unmarked allocations is reclaimed.
92 //
93 // The allocator tries hard to avoid locking, and where it is necessary tries to
94 // minimize the time spent holding locks. A lock is required to allocate a chunk
95 // but after that no locks are required to allocate on the main thread, even
96 // when off-thread sweeping is taking place. This is achieved by moving data to
97 // be swept to separate containers from those used for allocation on the main
98 // thread. Synchronization is required to merge data about swept allocations at
99 // the end of sweeping.
100 //
101 // Small allocations
102 // -----------------
103 //
104 // These are implemented by the cell allocator and are allocated in arenas (slab
105 // allocation).
106 //
107 // Note: currently we do not allocate these in the nursery because nursery-owned
108 // buffers are allocated directly in the nursery without going through this
109 // allocation API.
110 //
111 // Medium allocations
112 // ------------------
113 //
114 // These are allocated in their own zone-specific chunks using a segregated free
115 // list strategy. This is the main part of the allocator.
116 //
117 // The requested allocation size is used to pick a size class, which is used to
118 // index into an array giving a list of free regions of suitable size. The first
119 // region in the list is used and its start address updated; it may also be
120 // moved to a different list if it is now empty or too small to satisfy further
121 // allocations for this size class. A bitmap in the chunk header is used to
122 // track the start offsets of allocations.
123 //
124 // Sweeping works by processing a list of chunks, scanning each one for
125 // allocated but unmarked buffers and rebuilding the free region data for that
126 // chunk. Sweeping happens separately for minor and major GC and only
127 // nursery-owned or tenured-owned buffers are swept at one time. This means that
128 // chunks containing nursery-owned allocations are swept twice during a major
129 // GC, once to sweep nursery-owned allocations and once for tenured-owned
130 // allocations. This is required because the sweeping happens at different
131 // times.
132 //
133 // Chunks containing nursery-owned buffers are stored in a separate list to
134 // chunks that only contain tenured-owned buffers to reduce the number of chunks
135 // that need to be swept for minor GC. They are stored in |mediumMixedChunks|
136 // and are moved to |mediumMixedChunksToSweep| at the start of minor GC. They
137 // are then swept on a background thread and are placed in
138 // |sweptMediumMixedChunks| if they are not freed. From there they can merged
139 // back into one of the main thread lists (since they may no longer contain
140 // nursery-owned buffers).
141 //
142 // Chunks containing tenured-owned buffers are stored in |mediumTenuredChunks|
143 // and are moved to |mediumTenuredChunksToSweep| at the start of major GC. They
144 // are unavailable for allocation after this point and will be swept on a
145 // background thread and placed in |sweptMediumTenuredChunks| if they are not
146 // freed. From there they will be merged back into |mediumTenuredChunks|. This
147 // means that allocation during an incremental GC will allocate a new
148 // chunk.
149 //
150 // Merging swept data requires taking a lock and so only happens when
151 // necessary. This happens when a new chunk is needed or at various points
152 // during GC. During sweeping no additional synchronization is required for
153 // allocation.
154 //
155 // Since major GC requires doing a minor GC at the start and we don't want to
156 // have to wait for minor GC sweeping to finish there is an optimization where
157 // chunks containing nursery-owned buffers swept as part of minor GC at the
158 // start of a major GC are moved directly from |sweptMediumMixedChunks| to
159 // |mediumTenuredChunksToSweep| at the end of minor GC sweeping. This is
160 // controlled by the |majorStartedWhileMinorSweeping| flag.
161 //
162 // Similarly, if a major GC finishes while minor GC is sweeping then rather than
163 // waiting for it to finish we set the |majorFinishedWhileMinorSweeping| flag so
164 // that we clear the |allocatedDuringCollection| for these chunks the end of the
165 // minor sweeping.
166 //
167 // Free works by extending neighboring free regions to cover the freed
168 // allocation or adding a new one if necessary. Free regions are found by
169 // checking the allocated bitmap. Free is not supported if the containing chunk
170 // is currently being swept off-thread.
171 //
172 // Reallocation works by resizing in place if possible. It is always possible to
173 // shrink a medium allocation in place if the target size is still
174 // medium. In-place growth is possible if there is enough free space following
175 // the allocation. This is not supported if the containing chunk is currently
176 // being swept off-thread. If not possible, a new allocation is made and the
177 // contents of the buffer copied.
178 //
179 // Large allocations
180 // -----------------
181 //
182 // These are implemented using the OS page allocator. Allocations of this size
183 // are relatively rare and not much attempt is made to optimize them. They are
184 // chunk aligned which allows them to be distinguished from the other allocation
185 // kinds by checking the low bits the pointer.
186 //
187 // Naming conventions
188 // ------------------
189 //
190 // The following conventions are used in the code:
191 // - alloc: client pointer to allocated memory
192 // - buffer: pointer to per-allocation metadata
193 //
194
195 class BufferAllocator : public SlimLinkedListElement<BufferAllocator> {
196 public:
197 static constexpr size_t MinMediumAllocShift = 8; // 256 B
198 static constexpr size_t MaxMediumAllocShift = 19; // 512 KB
199
200 static constexpr size_t MediumAllocClasses =
201 MaxMediumAllocShift - MinMediumAllocShift + 1;
202
203 // An RAII guard to lock and unlock the buffer allocator lock.
204 class AutoLock : public LockGuard<Mutex> {
205 public:
206 explicit AutoLock(GCRuntime* gc);
207 explicit AutoLock(BufferAllocator* allocator);
208 friend class UnlockGuard<AutoLock>;
209 };
210
211 // A lock guard that is locked only when needed.
212 using MaybeLock = mozilla::Maybe<AutoLock>;
213
214 private:
215 using BufferChunkList = SlimLinkedList<BufferChunk>;
216
217 struct FreeRegion;
218 using FreeList = SlimLinkedList<FreeRegion>;
219
220 // Segregated free list: an array of free lists, one per size class.
221 class FreeLists {
222 using FreeListArray = mozilla::Array<FreeList, MediumAllocClasses>;
223 FreeListArray lists;
224 mozilla::BitSet<MediumAllocClasses, uint32_t> available;
225
226 public:
227 FreeLists() = default;
228
229 FreeLists(FreeLists&& other);
230 FreeLists& operator=(FreeLists&& other);
231
232 using const_iterator = FreeListArray::const_iterator;
233 auto begin() const { return lists.begin(); }
234 auto end() const { return lists.end(); }
235
236 // Returns SIZE_MAX if none available.
237 size_t getFirstAvailableSizeClass(size_t minSizeClass) const;
238
239 FreeRegion* getFirstRegion(size_t sizeClass);
240
241 void pushFront(size_t sizeClass, FreeRegion* region);
242 void pushBack(size_t sizeClass, FreeRegion* region);
243
244 void append(FreeLists&& other);
245 void prepend(FreeLists&& other);
246
247 void remove(size_t sizeClass, FreeRegion* region);
248
249 void clear();
250
251 template <typename Pred>
252 void eraseIf(Pred&& pred);
253
254 void assertEmpty() const;
255 void assertContains(size_t sizeClass, FreeRegion* region) const;
256 void checkAvailable() const;
257 };
258
259 using LargeAllocList = SlimLinkedList<LargeBuffer>;
260
261 using LargeAllocMap =
262 mozilla::HashMap<void*, LargeBuffer*, PointerHasher<void*>>;
263
264 enum class State : uint8_t { NotCollecting, Marking, Sweeping };
265
266 enum class OwnerKind : uint8_t { Tenured = 0, Nursery, None };
267
268 // The zone this allocator is associated with.
269 MainThreadOrGCTaskData<JS::Zone*> zone;
270
271 // Chunks that contain medium buffers. May contain both nursery-owned and
272 // tenured-owned buffers.
273 MainThreadData<BufferChunkList> mediumMixedChunks;
274
275 // Chunks that contain only tenured-owned medium sized buffers.
276 MainThreadData<BufferChunkList> mediumTenuredChunks;
277
278 // Free lists for medium sized buffers. Used for allocation.
279 MainThreadData<FreeLists> mediumFreeLists;
280
281 // Chunks that may contain nursery-owned buffers waiting to be swept during a
282 // minor GC. Populated from |mediumMixedChunks|.
283 MainThreadOrGCTaskData<BufferChunkList> mediumMixedChunksToSweep;
284
285 // Chunks that contain only tenured-owned buffers waiting to be swept during a
286 // major GC. Populated from |mediumTenuredChunks|.
287 MainThreadOrGCTaskData<BufferChunkList> mediumTenuredChunksToSweep;
288
289 // Chunks that have been swept and their associated free lists.
290 MutexData<BufferChunkList> sweptMediumMixedChunks;
291 MutexData<BufferChunkList> sweptMediumTenuredChunks;
292 MutexData<FreeLists> sweptMediumNurseryFreeLists;
293 MutexData<FreeLists> sweptMediumTenuredFreeLists;
294
295 // List of large nursery-owned buffers.
296 MainThreadData<LargeAllocList> largeNurseryAllocs;
297
298 // List of large tenured-owned buffers.
299 MainThreadData<LargeAllocList> largeTenuredAllocs;
300
301 // Map from allocation pointer to buffer metadata for large buffers.
302 // Access requires holding the mutex during sweeping.
303 MainThreadOrGCTaskData<LargeAllocMap> largeAllocMap;
304
305 // Large buffers waiting to be swept.
306 MainThreadOrGCTaskData<LargeAllocList> largeNurseryAllocsToSweep;
307 MainThreadOrGCTaskData<LargeAllocList> largeTenuredAllocsToSweep;
308
309 // Large buffers that have been swept.
310 MutexData<LargeAllocList> sweptLargeTenuredAllocs;
311
312 // Flag to indicate that data from minor sweeping is available to be
313 // merged. This includes chunks in the sweptMediumMixedChunks or
314 // sweptMediumTenuredChunks lists and the minorSweepingFinished flag.
315 mozilla::Atomic<bool, mozilla::Relaxed> hasMinorSweepDataToMerge;
316
317 // GC state for minor and major GC.
318 MainThreadData<State> minorState;
319 MainThreadData<State> majorState;
320
321 // Flags to tell the main thread that sweeping has finished and the state
322 // should be updated.
323 MutexData<bool> minorSweepingFinished;
324 MutexData<bool> majorSweepingFinished;
325
326 // A major GC was started while a minor GC was still sweeping. Chunks by the
327 // minor GC will be moved directly to the list of chunks to sweep for the
328 // major GC. This happens for the minor GC at the start of every major GC.
329 MainThreadData<bool> majorStartedWhileMinorSweeping;
330
331 // A major GC finished while a minor GC was still sweeping. Some post major GC
332 // cleanup will be deferred to the end of the minor sweeping.
333 MainThreadData<bool> majorFinishedWhileMinorSweeping;
334
335 #ifdef DEBUG
336 MainThreadData<bool> movingGCInProgress;
337 #endif
338
339 public:
340 explicit BufferAllocator(JS::Zone* zone);
341 ~BufferAllocator();
342
343 static inline size_t GetGoodAllocSize(size_t requiredBytes);
344 static inline size_t GetGoodElementCount(size_t requiredElements,
345 size_t elementSize);
346 static inline size_t GetGoodPower2AllocSize(size_t requiredBytes);
347 static inline size_t GetGoodPower2ElementCount(size_t requiredElements,
348 size_t elementSize);
349 static bool IsBufferAlloc(void* alloc);
350
351 void* alloc(size_t bytes, bool nurseryOwned);
352 void* allocInGC(size_t bytes, bool nurseryOwned);
353 void* realloc(void* alloc, size_t bytes, bool nurseryOwned);
354 void free(void* alloc);
355 size_t getAllocSize(void* alloc);
356 bool isNurseryOwned(void* alloc);
357
358 void startMinorCollection(MaybeLock& lock);
359 bool startMinorSweeping();
360 void sweepForMinorCollection();
361
362 void startMajorCollection(MaybeLock& lock);
363 void startMajorSweeping(MaybeLock& lock);
364 void sweepForMajorCollection(bool shouldDecommit);
365 void finishMajorCollection(const AutoLock& lock);
366 void prepareForMovingGC();
367 void fixupAfterMovingGC();
368 void clearMarkStateAfterBarrierVerification();
369
370 bool isEmpty() const;
371
372 void traceEdge(JSTracer* trc, Cell* owner, void** bufferp, const char* name);
373 bool markTenuredAlloc(void* alloc);
374 bool isMarkedBlack(void* alloc);
375
376 // For debugging, used to implement GetMarkInfo. Returns false for allocations
377 // being swept on another thread.
378 bool isPointerWithinMediumOrLargeBuffer(void* ptr);
379
380 Mutex& lock() const;
381
382 size_t getSizeOfNurseryBuffers();
383
384 void addSizeOfExcludingThis(size_t* usedBytesOut, size_t* freeBytesOut,
385 size_t* adminBytesOut);
386
387 static void printStatsHeader(FILE* file);
388 static void printStats(GCRuntime* gc, mozilla::TimeStamp creationTime,
389 bool isMajorGC, FILE* file);
390 void getStats(size_t& usedBytes, size_t& freeBytes, size_t& adminBytes,
391 size_t& mediumNurseryChunkCount,
392 size_t& mediumTenuredChunkCount, size_t& freeRegions,
393 size_t& largeNurseryAllocCount, size_t& largeTenuredAllocCount);
394
395 #ifdef DEBUG
396 void checkGCStateNotInUse();
397 void checkGCStateNotInUse(MaybeLock& lock);
398 void checkGCStateNotInUse(const AutoLock& lock);
399 #endif
400
401 private:
402 void markNurseryOwnedAlloc(void* alloc, bool ownerWasTenured);
403 friend class js::Nursery;
404
405 void maybeMergeSweptData();
406 void maybeMergeSweptData(MaybeLock& lock);
407 void mergeSweptData();
408 void mergeSweptData(const AutoLock& lock);
409 void abortMajorSweeping(const AutoLock& lock);
410 void clearAllocatedDuringCollectionState(const AutoLock& lock);
411
412 // Small allocation methods:
413
414 static inline bool IsSmallAllocSize(size_t bytes);
415 static bool IsSmallAlloc(void* alloc);
416
417 static SmallBuffer* GetSmallBuffer(void* alloc);
418 friend struct LargeBuffer;
419
420 void* allocSmall(size_t bytes, bool nurseryOwned);
421 void* allocSmallInGC(size_t bytes, bool nurseryOwned);
422 void traceSmallAlloc(JSTracer* trc, Cell* owner, void** allocp,
423 const char* name);
424 void markSmallNurseryOwnedBuffer(SmallBuffer* buffer, bool ownerWasTenured);
425 bool markSmallTenuredAlloc(void* alloc);
426
427 static AllocKind AllocKindForSmallAlloc(size_t bytes);
428
429 // Medium allocation methods:
430
431 static bool IsMediumAlloc(void* alloc);
432
433 void* allocMedium(size_t bytes, bool nurseryOwned, bool inGC);
434 void* bumpAllocOrRetry(size_t sizeClass, bool inGC);
435 void* bumpAlloc(size_t sizeClass);
436 void* allocFromRegion(FreeRegion* region, size_t requestedBytes,
437 size_t sizeClass);
438 void updateFreeListsAfterAlloc(FreeLists* freeLists, FreeRegion* region,
439 size_t sizeClass);
440 void recommitRegion(FreeRegion* region);
441 bool allocNewChunk(bool inGC);
442 bool sweepChunk(BufferChunk* chunk, OwnerKind ownerKindToSweep,
443 bool shouldDecommit, FreeLists& freeLists);
444 void addSweptRegion(BufferChunk* chunk, uintptr_t freeStart,
445 uintptr_t freeEnd, bool shouldDecommit,
446 bool expectUnchanged, FreeLists& freeLists);
447 void freeMedium(void* alloc);
448 bool growMedium(void* alloc, size_t newBytes);
449 bool shrinkMedium(void* alloc, size_t newBytes);
450 FreeRegion* findFollowingFreeRegion(uintptr_t start);
451 FreeRegion* findPrecedingFreeRegion(uintptr_t start);
452 enum class ListPosition { Front, Back };
453 FreeRegion* addFreeRegion(FreeLists* freeLists, size_t sizeClass,
454 uintptr_t start, uintptr_t end, bool anyDecommitted,
455 ListPosition position,
456 bool expectUnchanged = false);
457 void updateFreeRegionStart(FreeLists* freeLists, FreeRegion* region,
458 uintptr_t newStart);
459 FreeLists* getChunkFreeLists(BufferChunk* chunk);
460 bool isSweepingChunk(BufferChunk* chunk);
461 void traceMediumAlloc(JSTracer* trc, Cell* owner, void** allocp,
462 const char* name);
463 bool isMediumBufferNurseryOwned(void* alloc) const;
464 void markMediumNurseryOwnedBuffer(void* alloc, bool ownerWasTenured);
465 bool markMediumTenuredAlloc(void* alloc);
466
467 // Get the size class for an allocation. This rounds up to a class that is
468 // large enough to hold the required size.
469 static size_t SizeClassForAlloc(size_t bytes);
470
471 // Get the maximum size class of allocations that can use a free region. This
472 // rounds down to the largest class that can fit in this region.
473 static size_t SizeClassForFreeRegion(size_t bytes);
474
475 static size_t SizeClassBytes(size_t sizeClass);
476 friend struct BufferChunk;
477
478 // Large allocation methods:
479
480 static inline bool IsLargeAllocSize(size_t bytes);
481 static bool IsLargeAlloc(void* alloc);
482
483 void* allocLarge(size_t bytes, bool nurseryOwned, bool inGC);
484 bool sweepLargeTenured(LargeBuffer* buffer);
485 void freeLarge(void* alloc);
486 bool shrinkLarge(LargeBuffer* buffer, size_t newBytes);
487 void unmapLarge(LargeBuffer* buffer, bool isSweeping, MaybeLock& lock);
488 void traceLargeAlloc(JSTracer* trc, Cell* owner, void** allocp,
489 const char* name);
490 void markLargeNurseryOwnedBuffer(LargeBuffer* buffer, bool ownerWasTenured);
491 bool markLargeTenuredBuffer(LargeBuffer* buffer);
492 bool isLargeAllocMarked(void* alloc);
493
494 // Lookup a large buffer by pointer in the map.
495 LargeBuffer* lookupLargeBuffer(void* alloc);
496 LargeBuffer* lookupLargeBuffer(void* alloc, MaybeLock& lock);
497 bool needLockToAccessBufferMap() const;
498
499 void updateHeapSize(size_t bytes, bool checkThresholds,
500 bool updateRetainedSize);
501
502 #ifdef DEBUG
503 void checkChunkListGCStateNotInUse(BufferChunkList& chunks,
504 bool hasNurseryOwnedAllocs,
505 bool allowAllocatedDuringCollection);
506 void checkChunkGCStateNotInUse(BufferChunk* chunk,
507 bool allowAllocatedDuringCollection);
508 void checkAllocListGCStateNotInUse(LargeAllocList& list, bool isNurseryOwned);
509 void verifyChunk(BufferChunk* chunk, bool hasNurseryOwnedAllocs);
510 void verifyFreeRegion(BufferChunk* chunk, uintptr_t endOffset,
511 size_t expectedSize);
512 #endif
513 };
514
515 // Internal data structures defined here so that users can get their size.
516
517 #ifdef DEBUG
518 // Magic check values used debug builds.
519 static constexpr uint32_t LargeBufferCheckValue = 0xBFA110C2;
520 static constexpr uint32_t FreeRegionCheckValue = 0xBFA110C3;
521 #endif
522
523 } // namespace gc
524 } // namespace js
525
526 #endif // gc_BufferAllocator_h