Debian Codegraph @

js/src/gc/BufferAllocator.cpp

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 #include "gc/BufferAllocator-inl.h"
8
9 #include "mozilla/PodOperations.h"
10 #include "mozilla/ScopeExit.h"
11
12 #ifdef XP_DARWIN
13 # include <mach/mach_init.h>
14 # include <mach/vm_map.h>
15 #endif
16
17 #include "gc/GCInternals.h"
18 #include "gc/GCLock.h"
19 #include "gc/PublicIterators.h"
20 #include "gc/Zone.h"
21 #include "js/HeapAPI.h"
22 #include "util/Poison.h"
23
24 #include "gc/Heap-inl.h"
25 #include "gc/Marking-inl.h"
26
27 using namespace js;
28 using namespace js::gc;
29
30 namespace js::gc {
31
32 struct alignas(CellAlignBytes) LargeBuffer
33 : public SlimLinkedListElement<LargeBuffer> {
34 void* alloc;
35 size_t bytes;
36 bool isNurseryOwned;
37 bool allocatedDuringCollection = false;
38
39 #ifdef DEBUG
40 uint32_t checkValue = LargeBufferCheckValue;
41 #endif
42
43 LargeBuffer(void* alloc, size_t bytes, bool nurseryOwned)
44 : alloc(alloc), bytes(bytes), isNurseryOwned(nurseryOwned) {
45 MOZ_ASSERT((bytes % ChunkSize) == 0);
46 }
47
48 inline void check() const;
49
50 inline SmallBuffer* headerCell();
51
52 #ifdef DEBUG
53 inline Zone* zone();
54 inline Zone* zoneFromAnyThread();
55 #endif
56
57 void* data() { return alloc; }
58 size_t allocBytes() const { return bytes; }
59 bool isPointerWithinAllocation(void* ptr) const;
60 };
61
62 bool SmallBuffer::isNurseryOwned() const {
63 return header_.get() & NURSERY_OWNED_BIT;
64 }
65
66 void SmallBuffer::setNurseryOwned(bool value) {
67 header_.set(value ? NURSERY_OWNED_BIT : 0);
68 }
69
70 size_t SmallBuffer::allocBytes() const {
71 return arena()->getThingSize() - sizeof(SmallBuffer);
72 }
73
74 inline void LargeBuffer::check() const {
75 MOZ_ASSERT(checkValue == LargeBufferCheckValue);
76 }
77
78 BufferAllocator::AutoLock::AutoLock(GCRuntime* gc)
79 : LockGuard(gc->bufferAllocatorLock) {}
80
81 BufferAllocator::AutoLock::AutoLock(BufferAllocator* allocator)
82 : LockGuard(allocator->lock()) {}
83
84 // Describes a free region in a buffer chunk. This structure is stored at the
85 // end of the region.
86 //
87 // Medium allocations are made in FreeRegions in increasing address order. The
88 // final allocation will contain the now empty and unused FreeRegion structure.
89 // FreeRegions are stored in buckets based on their size in FreeLists. Each
90 // bucket is a linked list of FreeRegions.
91 struct BufferAllocator::FreeRegion
92 : public SlimLinkedListElement<BufferAllocator::FreeRegion> {
93 uintptr_t startAddr;
94 bool hasDecommittedPages;
95
96 #ifdef DEBUG
97 uint32_t checkValue = FreeRegionCheckValue;
98 #endif
99
100 explicit FreeRegion(uintptr_t startAddr, bool decommitted = false)
101 : startAddr(startAddr), hasDecommittedPages(decommitted) {}
102
103 static FreeRegion* fromEndOffset(BufferChunk* chunk, uintptr_t endOffset) {
104 MOZ_ASSERT(endOffset <= ChunkSize);
105 return fromEndAddr(uintptr_t(chunk) + endOffset);
106 }
107 static FreeRegion* fromEndAddr(uintptr_t endAddr) {
108 MOZ_ASSERT((endAddr % MinMediumAllocSize) == 0);
109 auto* region = reinterpret_cast<FreeRegion*>(endAddr - sizeof(FreeRegion));
110 region->check();
111 return region;
112 }
113
114 void check() const { MOZ_ASSERT(checkValue == FreeRegionCheckValue); }
115
116 uintptr_t getEnd() const { return uintptr_t(this + 1); }
117 size_t size() const { return getEnd() - startAddr; }
118 };
119
120 // A chunk containing medium buffer allocations for a single zone. Unlike
121 // ArenaChunk, allocations from different zones do not share chunks.
122 struct BufferChunk : public ChunkBase,
123 public SlimLinkedListElement<BufferChunk> {
124 #ifdef DEBUG
125 MainThreadData<Zone*> zone;
126 #endif
127
128 MainThreadOrGCTaskData<bool> allocatedDuringCollection;
129 MainThreadData<bool> hasNurseryOwnedAllocs;
130 MainThreadOrGCTaskData<bool> hasNurseryOwnedAllocsAfterSweep;
131
132 static constexpr size_t MaxAllocsPerChunk = ChunkSize / MinMediumAllocSize;
133 using PerAllocByteArray = uint8_t[MaxAllocsPerChunk];
134 PerAllocByteArray sizeClassArray;
135
136 // Mark bitmap: one bit minimum per allocation, no gray bits.
137 static constexpr size_t BytesPerMarkBit = MinMediumAllocSize;
138 using BufferMarkBitmap = MarkBitmap<BytesPerMarkBit, 0>;
139 MainThreadOrGCTaskData<BufferMarkBitmap> markBits;
140
141 using PerAllocBitmap = mozilla::BitSet<MaxAllocsPerChunk>;
142 using AtomicPerAllocBitmap =
143 mozilla::BitSet<MaxAllocsPerChunk,
144 mozilla::Atomic<size_t, mozilla::Relaxed>>;
145
146 MainThreadOrGCTaskData<PerAllocBitmap> allocBitmap;
147 MainThreadOrGCTaskData<AtomicPerAllocBitmap> nurseryOwnedBitmap;
148
149 static constexpr size_t PagesPerChunk = ChunkSize / PageSize;
150 using PerPageBitmap = mozilla::BitSet<PagesPerChunk, uint32_t>;
151 MainThreadOrGCTaskData<PerPageBitmap> decommittedPages;
152
153 static BufferChunk* from(void* alloc) {
154 ChunkBase* chunk = js::gc::detail::GetGCAddressChunkBase(alloc);
155 MOZ_ASSERT(chunk->kind == ChunkKind::MediumBuffers);
156 return static_cast<BufferChunk*>(chunk);
157 }
158
159 explicit BufferChunk(Zone* zone);
160 ~BufferChunk();
161
162 void checkAlloc(const void* alloc) const;
163
164 const void* ptrFromOffset(uintptr_t offset) const;
165
166 void setAllocated(void* alloc, bool allocated);
167 bool isAllocated(const void* alloc) const;
168 bool isAllocated(uintptr_t offset) const;
169
170 void setNurseryOwned(void* alloc, bool nurseryOwned);
171 bool isNurseryOwned(const void* alloc) const;
172
173 void setSizeClass(void* alloc, size_t sizeClass);
174 size_t sizeClass(const void* alloc) const;
175 size_t allocBytes(const void* alloc) const;
176
177 // Find next/previous allocations from |offset|. Return ChunkSize on failure.
178 size_t findNextAllocated(uintptr_t offset) const;
179 size_t findPrevAllocated(uintptr_t offset) const;
180
181 bool isPointerWithinAllocation(void* ptr) const;
182
183 private:
184 uintptr_t ptrToOffset(const void* alloc) const;
185 };
186
187 constexpr size_t FirstMediumAllocOffset =
188 RoundUp(sizeof(BufferChunk), MinMediumAllocSize);
189
190 // Iterate allocations in a BufferChunk.
191 class BufferChunkIter {
192 BufferChunk* chunk;
193 size_t offset = FirstMediumAllocOffset;
194 size_t size = 0;
195
196 public:
197 explicit BufferChunkIter(BufferChunk* chunk) : chunk(chunk) { settle(); }
198 bool done() const { return offset == ChunkSize; }
199 void next() {
200 MOZ_ASSERT(!done());
201 offset += size;
202 MOZ_ASSERT(offset <= ChunkSize);
203 if (!done()) {
204 settle();
205 }
206 }
207 size_t getOffset() const {
208 MOZ_ASSERT(!done());
209 return offset;
210 }
211 void* get() const {
212 MOZ_ASSERT(!done());
213 MOZ_ASSERT(offset < ChunkSize);
214 MOZ_ASSERT((offset % MinMediumAllocSize) == 0);
215 return reinterpret_cast<void*>(uintptr_t(chunk) + offset);
216 }
217 operator void*() { return get(); }
218
219 private:
220 void settle() {
221 offset = chunk->findNextAllocated(offset);
222 if (!done()) {
223 size = chunk->allocBytes(get());
224 }
225 }
226 };
227
228 static void CheckHighBitsOfPointer(void* ptr) {
229 #ifdef JS_64BIT
230 // We require bit 48 and higher be clear.
231 MOZ_DIAGNOSTIC_ASSERT((uintptr_t(ptr) >> 47) == 0);
232 #endif
233 }
234
235 BufferAllocator::FreeLists::FreeLists(FreeLists&& other) {
236 MOZ_ASSERT(this != &other);
237 assertEmpty();
238 std::swap(lists, other.lists);
239 std::swap(available, other.available);
240 other.assertEmpty();
241 }
242
243 BufferAllocator::FreeLists& BufferAllocator::FreeLists::operator=(
244 FreeLists&& other) {
245 MOZ_ASSERT(this != &other);
246 assertEmpty();
247 std::swap(lists, other.lists);
248 std::swap(available, other.available);
249 other.assertEmpty();
250 return *this;
251 }
252
253 size_t BufferAllocator::FreeLists::getFirstAvailableSizeClass(
254 size_t minSizeClass) const {
255 size_t result = available.FindNext(minSizeClass);
256 MOZ_ASSERT(result >= minSizeClass);
257 MOZ_ASSERT_IF(result != SIZE_MAX, !lists[result].isEmpty());
258 return result;
259 }
260
261 BufferAllocator::FreeRegion* BufferAllocator::FreeLists::getFirstRegion(
262 size_t sizeClass) {
263 MOZ_ASSERT(!lists[sizeClass].isEmpty());
264 return lists[sizeClass].getFirst();
265 }
266
267 void BufferAllocator::FreeLists::pushFront(size_t sizeClass,
268 FreeRegion* region) {
269 MOZ_ASSERT(sizeClass < MediumAllocClasses);
270 lists[sizeClass].pushFront(region);
271 available[sizeClass] = true;
272 }
273
274 void BufferAllocator::FreeLists::pushBack(size_t sizeClass,
275 FreeRegion* region) {
276 MOZ_ASSERT(sizeClass < MediumAllocClasses);
277 lists[sizeClass].pushBack(region);
278 available[sizeClass] = true;
279 }
280
281 void BufferAllocator::FreeLists::append(FreeLists&& other) {
282 for (size_t i = 0; i < MediumAllocClasses; i++) {
283 if (!other.lists[i].isEmpty()) {
284 lists[i].append(std::move(other.lists[i]));
285 available[i] = true;
286 }
287 }
288 other.available.ResetAll();
289 other.assertEmpty();
290 }
291
292 void BufferAllocator::FreeLists::prepend(FreeLists&& other) {
293 for (size_t i = 0; i < MediumAllocClasses; i++) {
294 if (!other.lists[i].isEmpty()) {
295 lists[i].prepend(std::move(other.lists[i]));
296 available[i] = true;
297 }
298 }
299 other.available.ResetAll();
300 other.assertEmpty();
301 }
302
303 void BufferAllocator::FreeLists::remove(size_t sizeClass, FreeRegion* region) {
304 MOZ_ASSERT(sizeClass < MediumAllocClasses);
305 lists[sizeClass].remove(region);
306 available[sizeClass] = !lists[sizeClass].isEmpty();
307 }
308
309 void BufferAllocator::FreeLists::clear() {
310 for (auto& freeList : lists) {
311 new (&freeList) FreeList; // clear() is less efficient.
312 }
313 available.ResetAll();
314 }
315
316 template <typename Pred>
317 void BufferAllocator::FreeLists::eraseIf(Pred&& pred) {
318 for (size_t i = 0; i < MediumAllocClasses; i++) {
319 FreeList& freeList = lists[i];
320 FreeRegion* region = freeList.getFirst();
321 while (region) {
322 FreeRegion* next = region->getNext();
323 if (pred(region)) {
324 freeList.remove(region);
325 }
326 region = next;
327 }
328 available[i] = !freeList.isEmpty();
329 }
330 }
331
332 inline void BufferAllocator::FreeLists::assertEmpty() const {
333 #ifdef DEBUG
334 for (size_t i = 0; i < MediumAllocClasses; i++) {
335 MOZ_ASSERT(lists[i].isEmpty());
336 }
337 MOZ_ASSERT(available.IsEmpty());
338 #endif
339 }
340
341 inline void BufferAllocator::FreeLists::assertContains(
342 size_t sizeClass, FreeRegion* region) const {
343 #ifdef DEBUG
344 MOZ_ASSERT(available[sizeClass]);
345 MOZ_ASSERT(lists[sizeClass].contains(region));
346 #endif
347 }
348
349 inline void BufferAllocator::FreeLists::checkAvailable() const {
350 #ifdef DEBUG
351 for (size_t i = 0; i < MediumAllocClasses; i++) {
352 MOZ_ASSERT(available[i] == !lists[i].isEmpty());
353 }
354 #endif
355 }
356
357 } // namespace js::gc
358
359 MOZ_ALWAYS_INLINE void PoisonAlloc(void* alloc, uint8_t value, size_t bytes,
360 MemCheckKind kind) {
361 #ifndef EARLY_BETA_OR_EARLIER
362 // Limit poisoning in release builds.
363 bytes = std::min(bytes, size_t(256));
364 #endif
365 AlwaysPoison(alloc, value, bytes, kind);
366 }
367
368 BufferChunk::BufferChunk(Zone* zone)
369 : ChunkBase(zone->runtimeFromMainThread(), ChunkKind::MediumBuffers) {
370 mozilla::PodArrayZero(sizeClassArray);
371 #ifdef DEBUG
372 this->zone = zone;
373 MOZ_ASSERT(allocBitmap.ref().IsEmpty());
374 MOZ_ASSERT(nurseryOwnedBitmap.ref().IsEmpty());
375 MOZ_ASSERT(decommittedPages.ref().IsEmpty());
376 #endif
377 }
378
379 BufferChunk::~BufferChunk() {
380 #ifdef DEBUG
381 MOZ_ASSERT(allocBitmap.ref().IsEmpty());
382 MOZ_ASSERT(nurseryOwnedBitmap.ref().IsEmpty());
383 for (const auto& sizeClass : sizeClassArray) {
384 MOZ_ASSERT(sizeClass == 0);
385 }
386 #endif
387 }
388
389 uintptr_t BufferChunk::ptrToOffset(const void* alloc) const {
390 checkAlloc(alloc);
391
392 uintptr_t offset = uintptr_t(alloc) & ChunkMask;
393 MOZ_ASSERT(offset >= FirstMediumAllocOffset);
394
395 return offset;
396 }
397
398 const void* BufferChunk::ptrFromOffset(uintptr_t offset) const {
399 void* alloc = reinterpret_cast<void*>(uintptr_t(this) + offset);
400 checkAlloc(alloc);
401 return alloc;
402 }
403
404 void BufferChunk::checkAlloc(const void* alloc) const {
405 MOZ_ASSERT((uintptr_t(alloc) & ~ChunkMask) == uintptr_t(this));
406 MOZ_ASSERT((uintptr_t(alloc) % MinMediumAllocSize) == 0);
407 }
408
409 void BufferChunk::setAllocated(void* alloc, bool allocated) {
410 uintptr_t offset = ptrToOffset(alloc);
411 size_t bit = offset / MinMediumAllocSize;
412 MOZ_ASSERT(allocBitmap.ref()[bit] != allocated);
413 allocBitmap.ref()[bit] = allocated;
414 }
415
416 bool BufferChunk::isAllocated(const void* alloc) const {
417 return isAllocated(ptrToOffset(alloc));
418 }
419
420 bool BufferChunk::isAllocated(uintptr_t offset) const {
421 MOZ_ASSERT(offset >= FirstMediumAllocOffset);
422 MOZ_ASSERT(offset < ChunkSize);
423
424 size_t bit = offset / MinMediumAllocSize;
425 return allocBitmap.ref()[bit];
426 }
427
428 size_t BufferChunk::findNextAllocated(uintptr_t offset) const {
429 MOZ_ASSERT(offset >= FirstMediumAllocOffset);
430 MOZ_ASSERT(offset < ChunkSize);
431
432 size_t bit = offset / MinMediumAllocSize;
433 size_t next = allocBitmap.ref().FindNext(bit);
434 if (next == SIZE_MAX) {
435 return ChunkSize;
436 }
437
438 return next * MinMediumAllocSize;
439 }
440
441 size_t BufferChunk::findPrevAllocated(uintptr_t offset) const {
442 MOZ_ASSERT(offset >= FirstMediumAllocOffset);
443 MOZ_ASSERT(offset < ChunkSize);
444
445 size_t bit = offset / MinMediumAllocSize;
446 size_t prev = allocBitmap.ref().FindPrev(bit);
447 if (prev == SIZE_MAX) {
448 return ChunkSize;
449 }
450
451 return prev * MinMediumAllocSize;
452 }
453
454 void BufferChunk::setNurseryOwned(void* alloc, bool nurseryOwned) {
455 MOZ_ASSERT(isAllocated(alloc));
456 uintptr_t offset = ptrToOffset(alloc);
457 size_t bit = offset / MinMediumAllocSize;
458 nurseryOwnedBitmap.ref()[bit] = nurseryOwned;
459 }
460
461 bool BufferChunk::isNurseryOwned(const void* alloc) const {
462 MOZ_ASSERT(isAllocated(alloc));
463 uintptr_t offset = ptrToOffset(alloc);
464 size_t bit = offset / MinMediumAllocSize;
465 return nurseryOwnedBitmap.ref()[bit];
466 }
467
468 void BufferChunk::setSizeClass(void* alloc, size_t sizeClass) {
469 MOZ_ASSERT(isAllocated(alloc));
470 uintptr_t offset = ptrToOffset(alloc);
471 size_t index = offset / MinMediumAllocSize;
472 MOZ_ASSERT(index < std::size(sizeClassArray));
473 sizeClassArray[index] = sizeClass;
474 }
475
476 size_t BufferChunk::sizeClass(const void* alloc) const {
477 MOZ_ASSERT(isAllocated(alloc));
478 uintptr_t offset = ptrToOffset(alloc);
479 size_t index = offset / MinMediumAllocSize;
480 MOZ_ASSERT(index < std::size(sizeClassArray));
481 return sizeClassArray[index];
482 }
483
484 size_t BufferChunk::allocBytes(const void* alloc) const {
485 return BufferAllocator::SizeClassBytes(sizeClass(alloc));
486 }
487
488 BufferAllocator::BufferAllocator(Zone* zone)
489 : zone(zone),
490 sweptMediumMixedChunks(lock()),
491 sweptMediumTenuredChunks(lock()),
492 sweptMediumNurseryFreeLists(lock()),
493 sweptMediumTenuredFreeLists(lock()),
494 sweptLargeTenuredAllocs(lock()),
495 minorState(State::NotCollecting),
496 majorState(State::NotCollecting),
497 minorSweepingFinished(lock()),
498 majorSweepingFinished(lock()) {}
499
500 BufferAllocator::~BufferAllocator() {
501 #ifdef DEBUG
502 checkGCStateNotInUse();
503 MOZ_ASSERT(mediumMixedChunks.ref().isEmpty());
504 MOZ_ASSERT(mediumTenuredChunks.ref().isEmpty());
505 mediumFreeLists.ref().assertEmpty();
506 MOZ_ASSERT(largeNurseryAllocs.ref().isEmpty());
507 MOZ_ASSERT(largeTenuredAllocs.ref().isEmpty());
508 #endif
509 }
510
511 bool BufferAllocator::isEmpty() const {
512 MOZ_ASSERT(!zone->wasGCStarted() || zone->isGCFinished());
513 MOZ_ASSERT(minorState == State::NotCollecting);
514 MOZ_ASSERT(majorState == State::NotCollecting);
515 return mediumMixedChunks.ref().isEmpty() &&
516 mediumTenuredChunks.ref().isEmpty() &&
517 largeNurseryAllocs.ref().isEmpty() &&
518 largeTenuredAllocs.ref().isEmpty();
519 }
520
521 Mutex& BufferAllocator::lock() const {
522 return zone->runtimeFromAnyThread()->gc.bufferAllocatorLock;
523 }
524
525 void* BufferAllocator::alloc(size_t bytes, bool nurseryOwned) {
526 MOZ_ASSERT_IF(zone->isGCMarkingOrSweeping(), majorState == State::Marking);
527
528 if (IsLargeAllocSize(bytes)) {
529 return allocLarge(bytes, nurseryOwned, false);
530 }
531
532 if (IsSmallAllocSize(bytes)) {
533 return allocSmall(bytes, nurseryOwned);
534 }
535
536 return allocMedium(bytes, nurseryOwned, false);
537 }
538
539 void* BufferAllocator::allocInGC(size_t bytes, bool nurseryOwned) {
540 // Currently this is used during tenuring only.
541 MOZ_ASSERT(minorState == State::Marking);
542
543 MOZ_ASSERT_IF(zone->isGCMarkingOrSweeping(), majorState == State::Marking);
544
545 void* result;
546 if (IsLargeAllocSize(bytes)) {
547 result = allocLarge(bytes, nurseryOwned, true);
548 } else if (IsSmallAllocSize(bytes)) {
549 result = allocSmallInGC(bytes, nurseryOwned);
550 } else {
551 result = allocMedium(bytes, nurseryOwned, true);
552 }
553
554 if (!result) {
555 return nullptr;
556 }
557
558 // Barrier to mark nursery-owned allocations that happen during collection. We
559 // don't need to do this for tenured-owned allocations because we don't sweep
560 // tenured-owned allocations that happened after the start of a major
561 // collection.
562 if (nurseryOwned) {
563 markNurseryOwnedAlloc(result, false);
564 }
565
566 return result;
567 }
568
569 /* static */
570 SmallBuffer* BufferAllocator::GetSmallBuffer(void* alloc) {
571 MOZ_ASSERT(BufferAllocator::IsSmallAlloc(alloc));
572 auto* buffer =
573 reinterpret_cast<SmallBuffer*>(uintptr_t(alloc) - sizeof(SmallBuffer));
574 buffer->check();
575 return buffer;
576 }
577
578 inline SmallBuffer* LargeBuffer::headerCell() {
579 return BufferAllocator::GetSmallBuffer(this);
580 }
581
582 #ifdef DEBUG
583
584 inline Zone* LargeBuffer::zone() { return headerCell()->zone(); }
585
586 inline Zone* LargeBuffer::zoneFromAnyThread() {
587 return headerCell()->zoneFromAnyThread();
588 }
589
590 #endif
591
592 #ifdef XP_DARWIN
593 static inline void VirtualCopyPages(void* dst, const void* src, size_t bytes) {
594 MOZ_ASSERT((uintptr_t(dst) & PageMask) == 0);
595 MOZ_ASSERT((uintptr_t(src) & PageMask) == 0);
596 MOZ_ASSERT(bytes >= ChunkSize);
597
598 kern_return_t r = vm_copy(mach_task_self(), vm_address_t(src),
599 vm_size_t(bytes), vm_address_t(dst));
600 if (r != KERN_SUCCESS) {
601 MOZ_CRASH("vm_copy() failed");
602 }
603 }
604 #endif
605
606 void* BufferAllocator::realloc(void* alloc, size_t bytes, bool nurseryOwned) {
607 // Reallocate a buffer. This has the same semantics as standard libarary
608 // realloc: if |ptr| is null it creates a new allocation, and if it fails it
609 // returns |nullptr| and the original |ptr| is still valid.
610
611 if (!alloc) {
612 return this->alloc(bytes, nurseryOwned);
613 }
614
615 MOZ_ASSERT(isNurseryOwned(alloc) == nurseryOwned);
616 MOZ_ASSERT_IF(zone->isGCMarkingOrSweeping(), majorState == State::Marking);
617
618 bytes = GetGoodAllocSize(bytes);
619
620 size_t currentBytes;
621 if (IsLargeAlloc(alloc)) {
622 LargeBuffer* buffer = lookupLargeBuffer(alloc);
623 currentBytes = buffer->allocBytes();
624
625 // We can shrink large allocations (on some platforms).
626 if (bytes < buffer->allocBytes() && IsLargeAllocSize(bytes)) {
627 if (shrinkLarge(buffer, bytes)) {
628 return alloc;
629 }
630 }
631 } else if (IsMediumAlloc(alloc)) {
632 BufferChunk* chunk = BufferChunk::from(alloc);
633 currentBytes = chunk->allocBytes(alloc);
634
635 // We can grow or shrink medium allocations.
636 if (bytes < currentBytes && !IsSmallAllocSize(bytes)) {
637 if (shrinkMedium(alloc, bytes)) {
638 return alloc;
639 }
640 }
641
642 if (bytes > currentBytes && !IsLargeAllocSize(bytes)) {
643 if (growMedium(alloc, bytes)) {
644 return alloc;
645 }
646 }
647 } else {
648 SmallBuffer* buffer = GetSmallBuffer(alloc);
649 currentBytes = buffer->allocBytes();
650 }
651
652 if (bytes == currentBytes) {
653 return alloc;
654 }
655
656 void* newAlloc = this->alloc(bytes, nurseryOwned);
657 if (!newAlloc) {
658 return nullptr;
659 }
660
661 auto freeGuard = mozilla::MakeScopeExit([&]() { free(alloc); });
662
663 size_t bytesToCopy = std::min(bytes, currentBytes);
664
665 #ifdef XP_DARWIN
666 if (bytesToCopy >= ChunkSize) {
667 MOZ_ASSERT(IsLargeAlloc(alloc));
668 MOZ_ASSERT(IsLargeAlloc(newAlloc));
669 VirtualCopyPages(newAlloc, alloc, bytesToCopy);
670 return newAlloc;
671 }
672 #endif
673
674 memcpy(newAlloc, alloc, bytesToCopy);
675 return newAlloc;
676 }
677
678 void BufferAllocator::free(void* alloc) {
679 MOZ_ASSERT(alloc);
680
681 if (IsLargeAlloc(alloc)) {
682 freeLarge(alloc);
683 return;
684 }
685
686 if (IsMediumAlloc(alloc)) {
687 freeMedium(alloc);
688 return;
689 }
690
691 // Can't free small allocations.
692 }
693
694 /* static */
695 bool BufferAllocator::IsBufferAlloc(void* alloc) {
696 // Precondition: |alloc| is a pointer to a buffer allocation, a GC thing or a
697 // direct nursery allocation returned by Nursery::allocateBuffer.
698
699 if (IsLargeAlloc(alloc)) {
700 return true;
701 }
702
703 ChunkKind chunkKind = detail::GetGCAddressChunkBase(alloc)->getKind();
704 if (chunkKind == ChunkKind::MediumBuffers) {
705 return true;
706 }
707
708 if (chunkKind == ChunkKind::TenuredArenas) {
709 auto* arena = reinterpret_cast<Arena*>(uintptr_t(alloc) & ~ArenaMask);
710 return IsBufferAllocKind(arena->getAllocKind());
711 }
712
713 return false;
714 }
715
716 size_t BufferAllocator::getAllocSize(void* alloc) {
717 if (IsLargeAlloc(alloc)) {
718 LargeBuffer* buffer = lookupLargeBuffer(alloc);
719 return buffer->allocBytes();
720 }
721
722 if (IsSmallAlloc(alloc)) {
723 SmallBuffer* cell = GetSmallBuffer(alloc);
724 return cell->allocBytes();
725 }
726
727 MOZ_ASSERT(IsMediumAlloc(alloc));
728 BufferChunk* chunk = BufferChunk::from(alloc);
729 return chunk->allocBytes(alloc);
730 }
731
732 bool BufferAllocator::isNurseryOwned(void* alloc) {
733 if (IsLargeAlloc(alloc)) {
734 LargeBuffer* buffer = lookupLargeBuffer(alloc);
735 return buffer->isNurseryOwned;
736 }
737
738 if (IsSmallAlloc(alloc)) {
739 // This is always false because we currently make such allocations directly
740 // in the nursery.
741 SmallBuffer* cell = GetSmallBuffer(alloc);
742 return cell->isNurseryOwned();
743 }
744
745 BufferChunk* chunk = BufferChunk::from(alloc);
746 return chunk->isNurseryOwned(alloc);
747 }
748
749 void BufferAllocator::markNurseryOwnedAlloc(void* alloc, bool ownerWasTenured) {
750 MOZ_ASSERT(alloc);
751 MOZ_ASSERT(isNurseryOwned(alloc));
752 MOZ_ASSERT(minorState == State::Marking);
753
754 if (IsLargeAlloc(alloc)) {
755 LargeBuffer* buffer = lookupLargeBuffer(alloc);
756 MOZ_ASSERT(buffer->zone() == zone);
757 markLargeNurseryOwnedBuffer(buffer, ownerWasTenured);
758 return;
759 }
760
761 if (IsSmallAlloc(alloc)) {
762 SmallBuffer* buffer = GetSmallBuffer(alloc);
763 markSmallNurseryOwnedBuffer(buffer, ownerWasTenured);
764 return;
765 }
766
767 MOZ_ASSERT(IsMediumAlloc(alloc));
768 markMediumNurseryOwnedBuffer(alloc, ownerWasTenured);
769 }
770
771 void BufferAllocator::markSmallNurseryOwnedBuffer(SmallBuffer* buffer,
772 bool ownerWasTenured) {
773 MOZ_ASSERT(buffer->zone() == zone);
774
775 if (ownerWasTenured) {
776 buffer->setNurseryOwned(false);
777 }
778
779 // Heap size is tracked as part of GC heap for small allocations.
780 }
781
782 void BufferAllocator::markMediumNurseryOwnedBuffer(void* alloc,
783 bool ownerWasTenured) {
784 BufferChunk* chunk = BufferChunk::from(alloc);
785 MOZ_ASSERT(chunk->zone == zone);
786 MOZ_ASSERT(chunk->hasNurseryOwnedAllocs);
787 MOZ_ASSERT(chunk->isAllocated(alloc));
788
789 if (ownerWasTenured) {
790 // Change the allocation to a tenured owned one. This prevents sweeping in a
791 // minor collection.
792 chunk->setNurseryOwned(alloc, false);
793 size_t size = chunk->allocBytes(alloc);
794 updateHeapSize(size, false, false);
795 return;
796 }
797
798 chunk->markBits.ref().markIfUnmarked(alloc, MarkColor::Black);
799 }
800
801 void BufferAllocator::markLargeNurseryOwnedBuffer(LargeBuffer* buffer,
802 bool ownerWasTenured) {
803 largeNurseryAllocsToSweep.ref().remove(buffer);
804
805 if (ownerWasTenured) {
806 buffer->isNurseryOwned = false;
807 buffer->allocatedDuringCollection = majorState != State::NotCollecting;
808 largeTenuredAllocs.ref().pushBack(buffer);
809 size_t usableSize = buffer->allocBytes();
810 updateHeapSize(usableSize, false, false);
811 return;
812 }
813
814 largeNurseryAllocs.ref().pushBack(buffer);
815 }
816
817 bool BufferAllocator::isMarkedBlack(void* alloc) {
818 if (IsLargeAlloc(alloc)) {
819 return isLargeAllocMarked(alloc);
820 }
821
822 if (IsSmallAlloc(alloc)) {
823 SmallBuffer* cell = GetSmallBuffer(alloc);
824 MOZ_ASSERT(!cell->isMarkedGray());
825 return cell->isMarkedBlack();
826 }
827
828 MOZ_ASSERT(IsMediumAlloc(alloc));
829 BufferChunk* chunk = BufferChunk::from(alloc);
830 MOZ_ASSERT(chunk->isAllocated(alloc));
831 return chunk->markBits.ref().isMarkedBlack(alloc);
832 }
833
834 void BufferAllocator::traceEdge(JSTracer* trc, Cell* owner, void** bufferp,
835 const char* name) {
836 // Buffers are conceptually part of the owning cell and are not reported to
837 // the tracer.
838
839 // TODO: This should be unified with the rest of the tracing system.
840
841 MOZ_ASSERT(owner);
842 MOZ_ASSERT(bufferp);
843
844 void* buffer = *bufferp;
845 MOZ_ASSERT(buffer);
846
847 if (!IsLargeAlloc(buffer) &&
848 js::gc::detail::GetGCAddressChunkBase(buffer)->isNurseryChunk()) {
849 // JSObject slots and elements can be allocated in the nursery and this is
850 // handled separately.
851 return;
852 }
853
854 MOZ_ASSERT(IsBufferAlloc(buffer));
855
856 if (IsLargeAlloc(buffer)) {
857 traceLargeAlloc(trc, owner, bufferp, name);
858 return;
859 }
860
861 if (IsSmallAlloc(buffer)) {
862 traceSmallAlloc(trc, owner, bufferp, name);
863 return;
864 }
865
866 traceMediumAlloc(trc, owner, bufferp, name);
867 }
868
869 void BufferAllocator::traceSmallAlloc(JSTracer* trc, Cell* owner, void** allocp,
870 const char* name) {
871 void* alloc = *allocp;
872 SmallBuffer* cell = GetSmallBuffer(alloc);
873 TraceManuallyBarrieredEdge(trc, &cell, name);
874 if (cell != GetSmallBuffer(alloc)) {
875 *allocp = cell->data();
876 }
877 }
878
879 void BufferAllocator::traceMediumAlloc(JSTracer* trc, Cell* owner,
880 void** allocp, const char* name) {
881 void* alloc = *allocp;
882 BufferChunk* chunk = BufferChunk::from(alloc);
883
884 if (trc->isTenuringTracer()) {
885 if (chunk->isNurseryOwned(alloc)) {
886 markMediumNurseryOwnedBuffer(alloc, owner->isTenured());
887 }
888 return;
889 }
890
891 if (trc->isMarkingTracer()) {
892 if (!chunk->isNurseryOwned(alloc)) {
893 markMediumTenuredAlloc(alloc);
894 }
895 return;
896 }
897 }
898
899 void BufferAllocator::traceLargeAlloc(JSTracer* trc, Cell* owner, void** allocp,
900 const char* name) {
901 void* alloc = *allocp;
902 LargeBuffer* buffer = lookupLargeBuffer(alloc);
903
904 // Trace small buffer that holds large buffer metadata.
905 // For moving GC the table is updated in fixupAfterMovingGC().
906 traceSmallAlloc(trc, owner, reinterpret_cast<void**>(&buffer), "LargeBuffer");
907
908 if (trc->isTenuringTracer()) {
909 if (isNurseryOwned(alloc)) {
910 markLargeNurseryOwnedBuffer(buffer, owner->isTenured());
911 }
912 return;
913 }
914
915 if (trc->isMarkingTracer()) {
916 if (!isNurseryOwned(alloc)) {
917 markLargeTenuredBuffer(buffer);
918 }
919 return;
920 }
921 }
922
923 bool BufferAllocator::markTenuredAlloc(void* alloc) {
924 MOZ_ASSERT(alloc);
925 MOZ_ASSERT(!isNurseryOwned(alloc));
926
927 if (IsLargeAlloc(alloc)) {
928 LargeBuffer* buffer = lookupLargeBuffer(alloc);
929 return markLargeTenuredBuffer(buffer);
930 }
931
932 if (IsSmallAlloc(alloc)) {
933 return markSmallTenuredAlloc(alloc);
934 }
935
936 return markMediumTenuredAlloc(alloc);
937 }
938
939 bool BufferAllocator::markSmallTenuredAlloc(void* alloc) {
940 SmallBuffer* cell = GetSmallBuffer(alloc);
941 return cell->markIfUnmarkedThreadSafe(MarkColor::Black);
942 }
943
944 bool BufferAllocator::markMediumTenuredAlloc(void* alloc) {
945 BufferChunk* chunk = BufferChunk::from(alloc);
946 MOZ_ASSERT(chunk->isAllocated(alloc));
947 if (chunk->allocatedDuringCollection) {
948 // Will not be swept, already counted as marked.
949 return false;
950 }
951
952 return chunk->markBits.ref().markIfUnmarkedThreadSafe(alloc,
953 MarkColor::Black);
954 }
955
956 void BufferAllocator::startMinorCollection(MaybeLock& lock) {
957 maybeMergeSweptData(lock);
958
959 #ifdef DEBUG
960 MOZ_ASSERT(minorState == State::NotCollecting);
961 if (majorState == State::NotCollecting) {
962 checkGCStateNotInUse(lock);
963 }
964 #endif
965
966 // Large allocations that are marked when tracing the nursery will be moved
967 // back to the main list.
968 MOZ_ASSERT(largeNurseryAllocsToSweep.ref().isEmpty());
969 std::swap(largeNurseryAllocs.ref(), largeNurseryAllocsToSweep.ref());
970
971 minorState = State::Marking;
972 }
973
974 bool BufferAllocator::startMinorSweeping() {
975 // Called during minor GC. Operates on the active allocs/chunks lists. The 'to
976 // sweep' lists do not contain nursery owned allocations.
977
978 #ifdef DEBUG
979 MOZ_ASSERT(minorState == State::Marking);
980 {
981 AutoLock lock(this);
982 MOZ_ASSERT(!minorSweepingFinished);
983 MOZ_ASSERT(sweptMediumMixedChunks.ref().isEmpty());
984 }
985 for (LargeBuffer* buffer : largeNurseryAllocs.ref()) {
986 MOZ_ASSERT(buffer->isNurseryOwned);
987 }
988 for (LargeBuffer* buffer : largeNurseryAllocsToSweep.ref()) {
989 MOZ_ASSERT(buffer->isNurseryOwned);
990 }
991 #endif
992
993 // Check whether there are any medium chunks containing nursery owned
994 // allocations that need to be swept.
995 if (mediumMixedChunks.ref().isEmpty() &&
996 largeNurseryAllocsToSweep.ref().isEmpty()) {
997 // Nothing more to do. Don't transition to sweeping state.
998 minorState = State::NotCollecting;
999 return false;
1000 }
1001
1002 // TODO: There are more efficient ways to remove the free regions in nursery
1003 // chunks from the free lists, but all require some more bookkeeping. I don't
1004 // know how much difference such a change would make.
1005 //
1006 // Some possibilities are:
1007 // - maintain a separate list of free regions in each chunk and use that to
1008 // remove those regions in nursery chunks
1009 // - have separate free lists for nursery/tenured chunks
1010 // - keep free regions at different ends of the free list depending on chunk
1011 // kind
1012 mediumFreeLists.ref().eraseIf([](FreeRegion* region) {
1013 return BufferChunk::from(region)->hasNurseryOwnedAllocs;
1014 });
1015
1016 mediumMixedChunksToSweep.ref() = std::move(mediumMixedChunks.ref());
1017
1018 minorState = State::Sweeping;
1019
1020 return true;
1021 }
1022
1023 void BufferAllocator::sweepForMinorCollection() {
1024 // Called on a background thread.
1025
1026 MOZ_ASSERT(minorState.refNoCheck() == State::Sweeping);
1027 {
1028 AutoLock lock(this);
1029 MOZ_ASSERT(sweptMediumMixedChunks.ref().isEmpty());
1030 }
1031
1032 while (!mediumMixedChunksToSweep.ref().isEmpty()) {
1033 BufferChunk* chunk = mediumMixedChunksToSweep.ref().popFirst();
1034 FreeLists sweptFreeLists;
1035 if (sweepChunk(chunk, OwnerKind::Nursery, false, sweptFreeLists)) {
1036 {
1037 AutoLock lock(this);
1038 sweptMediumMixedChunks.ref().pushBack(chunk);
1039 if (chunk->hasNurseryOwnedAllocsAfterSweep) {
1040 sweptMediumNurseryFreeLists.ref().append(std::move(sweptFreeLists));
1041 } else {
1042 sweptMediumTenuredFreeLists.ref().append(std::move(sweptFreeLists));
1043 }
1044 }
1045
1046 // Signal to the main thread that swept data is available by setting this
1047 // relaxed atomic flag.
1048 hasMinorSweepDataToMerge = true;
1049 }
1050 }
1051
1052 // Bug 1961749: Freeing large buffers can be slow so it might be worth
1053 // splitting sweeping into two phases so that all zones get their medium
1054 // buffers swept and made available for allocation before any large buffers
1055 // are freed.
1056 // Alternatively this could happen in parallel to sweeping medium buffers.
1057
1058 while (!largeNurseryAllocsToSweep.ref().isEmpty()) {
1059 LargeBuffer* buffer = largeNurseryAllocsToSweep.ref().popFirst();
1060 MaybeLock lock(std::in_place, this);
1061 unmapLarge(buffer, true, lock);
1062 }
1063
1064 // Signal to main thread to update minorState.
1065 {
1066 AutoLock lock(this);
1067 MOZ_ASSERT(!minorSweepingFinished);
1068 minorSweepingFinished = true;
1069 hasMinorSweepDataToMerge = true;
1070 }
1071 }
1072
1073 void BufferAllocator::startMajorCollection(MaybeLock& lock) {
1074 maybeMergeSweptData(lock);
1075
1076 #ifdef DEBUG
1077 MOZ_ASSERT(majorState == State::NotCollecting);
1078 checkGCStateNotInUse(lock);
1079
1080 // Everything is tenured since we just evicted the nursery, or will be by the
1081 // time minor sweeping finishes.
1082 MOZ_ASSERT(mediumMixedChunks.ref().isEmpty());
1083 MOZ_ASSERT(largeNurseryAllocs.ref().isEmpty());
1084 #endif
1085
1086 mediumTenuredChunksToSweep.ref() = std::move(mediumTenuredChunks.ref());
1087 largeTenuredAllocsToSweep.ref() = std::move(largeTenuredAllocs.ref());
1088
1089 // Clear the active free lists to prevent further allocation in chunks that
1090 // will be swept.
1091 mediumFreeLists.ref().clear();
1092
1093 if (minorState == State::Sweeping) {
1094 // Ensure swept nursery chunks are moved to the mediumTenuredChunks lists in
1095 // mergeSweptData.
1096 majorStartedWhileMinorSweeping = true;
1097 }
1098
1099 #ifdef DEBUG
1100 MOZ_ASSERT(mediumTenuredChunks.ref().isEmpty());
1101 mediumFreeLists.ref().assertEmpty();
1102 MOZ_ASSERT(largeTenuredAllocs.ref().isEmpty());
1103 #endif
1104
1105 majorState = State::Marking;
1106 }
1107
1108 void BufferAllocator::startMajorSweeping(MaybeLock& lock) {
1109 // Called when a zone transitions from marking to sweeping.
1110
1111 #ifdef DEBUG
1112 MOZ_ASSERT(majorState == State::Marking);
1113 MOZ_ASSERT(zone->isGCFinished());
1114 MOZ_ASSERT(!majorSweepingFinished.refNoCheck());
1115 #endif
1116
1117 maybeMergeSweptData(lock);
1118 MOZ_ASSERT(!majorStartedWhileMinorSweeping);
1119
1120 majorState = State::Sweeping;
1121 }
1122
1123 void BufferAllocator::sweepForMajorCollection(bool shouldDecommit) {
1124 // Called on a background thread.
1125
1126 MOZ_ASSERT(majorState.refNoCheck() == State::Sweeping);
1127
1128 while (!mediumTenuredChunksToSweep.ref().isEmpty()) {
1129 BufferChunk* chunk = mediumTenuredChunksToSweep.ref().popFirst();
1130 FreeLists sweptFreeLists;
1131 if (sweepChunk(chunk, OwnerKind::Tenured, shouldDecommit, sweptFreeLists)) {
1132 {
1133 AutoLock lock(this);
1134 sweptMediumTenuredChunks.ref().pushBack(chunk);
1135 sweptMediumTenuredFreeLists.ref().append(std::move(sweptFreeLists));
1136 }
1137
1138 // Signal to the main thread that swept data is available by setting this
1139 // relaxed atomic flag.
1140 hasMinorSweepDataToMerge = true;
1141 }
1142 }
1143
1144 // It's tempting to try and optimize this by moving the allocations between
1145 // lists when they are marked, in the same way as for nursery sweeping. This
1146 // would require synchronizing the list modification when marking in parallel,
1147 // so is probably not worth it.
1148 LargeAllocList sweptList;
1149 while (!largeTenuredAllocsToSweep.ref().isEmpty()) {
1150 LargeBuffer* buffer = largeTenuredAllocsToSweep.ref().popFirst();
1151 if (sweepLargeTenured(buffer)) {
1152 sweptList.pushBack(buffer);
1153 }
1154 }
1155
1156 // It would be possible to add these to the output list as we sweep but
1157 // there's currently no advantage to that.
1158 AutoLock lock(this);
1159 sweptLargeTenuredAllocs.ref() = std::move(sweptList);
1160
1161 // Signal to main thread to update majorState.
1162 MOZ_ASSERT(!majorSweepingFinished);
1163 majorSweepingFinished = true;
1164 }
1165
1166 static void ClearAllocatedDuringCollection(SlimLinkedList<BufferChunk>& list) {
1167 for (auto* buffer : list) {
1168 buffer->allocatedDuringCollection = false;
1169 }
1170 }
1171 static void ClearAllocatedDuringCollection(SlimLinkedList<LargeBuffer>& list) {
1172 for (auto* element : list) {
1173 element->allocatedDuringCollection = false;
1174 }
1175 }
1176
1177 void BufferAllocator::finishMajorCollection(const AutoLock& lock) {
1178 // This can be called in any state:
1179 //
1180 // - NotCollecting: after major sweeping has finished and the state has been
1181 // reset to NotCollecting in mergeSweptData.
1182 //
1183 // - Marking: if collection was aborted and startMajorSweeping was not
1184 // called.
1185 //
1186 // - Sweeping: if sweeping has finished and mergeSweptData has not been
1187 // called yet.
1188
1189 MOZ_ASSERT_IF(majorState == State::Sweeping, majorSweepingFinished);
1190
1191 if (minorState == State::Sweeping || majorState == State::Sweeping) {
1192 mergeSweptData(lock);
1193 }
1194
1195 if (majorState == State::Marking) {
1196 abortMajorSweeping(lock);
1197 }
1198
1199 #ifdef DEBUG
1200 checkGCStateNotInUse(lock);
1201 #endif
1202 }
1203
1204 void BufferAllocator::abortMajorSweeping(const AutoLock& lock) {
1205 // We have aborted collection without sweeping this zone. Restore or rebuild
1206 // the original state.
1207
1208 MOZ_ASSERT(majorState == State::Marking);
1209 MOZ_ASSERT(sweptMediumTenuredChunks.ref().isEmpty());
1210
1211 clearAllocatedDuringCollectionState(lock);
1212
1213 if (minorState == State::Sweeping) {
1214 // If we are minor sweeping then chunks with allocatedDuringCollection set
1215 // may be present in |mixedChunksToSweep|. Set a flag so these are cleared
1216 // when they are merged later.
1217 majorFinishedWhileMinorSweeping = true;
1218 }
1219
1220 for (BufferChunk* chunk : mediumTenuredChunksToSweep.ref()) {
1221 chunk->markBits.ref().clear();
1222 }
1223
1224 // Rebuild free lists for chunks we didn't end up sweeping.
1225 for (BufferChunk* chunk : mediumTenuredChunksToSweep.ref()) {
1226 MOZ_ALWAYS_TRUE(
1227 sweepChunk(chunk, OwnerKind::None, false, mediumFreeLists.ref()));
1228 }
1229
1230 mediumTenuredChunks.ref().prepend(
1231 std::move(mediumTenuredChunksToSweep.ref()));
1232 largeTenuredAllocs.ref().prepend(std::move(largeTenuredAllocsToSweep.ref()));
1233
1234 majorState = State::NotCollecting;
1235 }
1236
1237 void BufferAllocator::clearAllocatedDuringCollectionState(
1238 const AutoLock& lock) {
1239 ClearAllocatedDuringCollection(mediumMixedChunks.ref());
1240 ClearAllocatedDuringCollection(mediumTenuredChunks.ref());
1241 // This flag is not set for large nursery-owned allocations.
1242 ClearAllocatedDuringCollection(largeTenuredAllocs.ref());
1243 }
1244
1245 void BufferAllocator::maybeMergeSweptData() {
1246 if (minorState == State::Sweeping || majorState == State::Sweeping) {
1247 mergeSweptData();
1248 }
1249 }
1250
1251 void BufferAllocator::mergeSweptData() {
1252 AutoLock lock(this);
1253 mergeSweptData(lock);
1254 }
1255
1256 void BufferAllocator::maybeMergeSweptData(MaybeLock& lock) {
1257 if (minorState == State::Sweeping || majorState == State::Sweeping) {
1258 if (lock.isNothing()) {
1259 lock.emplace(this);
1260 }
1261 mergeSweptData(lock.ref());
1262 }
1263 }
1264
1265 void BufferAllocator::mergeSweptData(const AutoLock& lock) {
1266 MOZ_ASSERT(minorState == State::Sweeping || majorState == State::Sweeping);
1267
1268 if (majorSweepingFinished) {
1269 clearAllocatedDuringCollectionState(lock);
1270
1271 if (minorState == State::Sweeping) {
1272 majorFinishedWhileMinorSweeping = true;
1273 }
1274 }
1275
1276 // Merge swept chunks that previously contained nursery owned allocations. If
1277 // semispace nursery collection is in use then these chunks may contain both
1278 // nursery and tenured-owned allocations, otherwise all allocations will be
1279 // tenured-owned.
1280 while (!sweptMediumMixedChunks.ref().isEmpty()) {
1281 BufferChunk* chunk = sweptMediumMixedChunks.ref().popLast();
1282 MOZ_ASSERT(chunk->hasNurseryOwnedAllocs);
1283 chunk->hasNurseryOwnedAllocs = chunk->hasNurseryOwnedAllocsAfterSweep;
1284
1285 MOZ_ASSERT_IF(
1286 majorState == State::NotCollecting && !majorFinishedWhileMinorSweeping,
1287 !chunk->allocatedDuringCollection);
1288 if (majorFinishedWhileMinorSweeping) {
1289 chunk->allocatedDuringCollection = false;
1290 }
1291
1292 if (chunk->hasNurseryOwnedAllocs) {
1293 mediumMixedChunks.ref().pushFront(chunk);
1294 } else if (majorStartedWhileMinorSweeping) {
1295 mediumTenuredChunksToSweep.ref().pushFront(chunk);
1296 } else {
1297 mediumTenuredChunks.ref().pushFront(chunk);
1298 }
1299 }
1300
1301 // Merge swept chunks that did not contain nursery owned allocations.
1302 #ifdef DEBUG
1303 for (BufferChunk* chunk : sweptMediumTenuredChunks.ref()) {
1304 MOZ_ASSERT(!chunk->hasNurseryOwnedAllocs);
1305 MOZ_ASSERT(!chunk->hasNurseryOwnedAllocsAfterSweep);
1306 MOZ_ASSERT(!chunk->allocatedDuringCollection);
1307 }
1308 #endif
1309 mediumTenuredChunks.ref().prepend(std::move(sweptMediumTenuredChunks.ref()));
1310
1311 mediumFreeLists.ref().prepend(std::move(sweptMediumNurseryFreeLists.ref()));
1312 if (!majorStartedWhileMinorSweeping) {
1313 mediumFreeLists.ref().prepend(std::move(sweptMediumTenuredFreeLists.ref()));
1314 } else {
1315 sweptMediumTenuredFreeLists.ref().clear();
1316 }
1317
1318 largeTenuredAllocs.ref().prepend(std::move(sweptLargeTenuredAllocs.ref()));
1319
1320 hasMinorSweepDataToMerge = false;
1321
1322 if (minorSweepingFinished) {
1323 MOZ_ASSERT(minorState == State::Sweeping);
1324 minorState = State::NotCollecting;
1325 minorSweepingFinished = false;
1326 majorStartedWhileMinorSweeping = false;
1327 majorFinishedWhileMinorSweeping = false;
1328
1329 #ifdef DEBUG
1330 for (BufferChunk* chunk : mediumMixedChunks.ref()) {
1331 verifyChunk(chunk, true);
1332 }
1333 for (BufferChunk* chunk : mediumTenuredChunks.ref()) {
1334 verifyChunk(chunk, false);
1335 }
1336 #endif
1337 }
1338
1339 if (majorSweepingFinished) {
1340 MOZ_ASSERT(majorState == State::Sweeping);
1341 majorState = State::NotCollecting;
1342 majorSweepingFinished = false;
1343
1344 MOZ_ASSERT(mediumTenuredChunksToSweep.ref().isEmpty());
1345 }
1346 }
1347
1348 void BufferAllocator::prepareForMovingGC() {
1349 maybeMergeSweptData();
1350
1351 MOZ_ASSERT(majorState == State::NotCollecting);
1352 MOZ_ASSERT(minorState == State::NotCollecting);
1353 MOZ_ASSERT(largeNurseryAllocsToSweep.ref().isEmpty());
1354 MOZ_ASSERT(largeTenuredAllocsToSweep.ref().isEmpty());
1355
1356 #ifdef DEBUG
1357 MOZ_ASSERT(!movingGCInProgress);
1358 movingGCInProgress = true;
1359 #endif
1360
1361 // Remove large buffer metadata objects from their linked lists so we can move
1362 // them without breaking the links.
1363 for (auto i = largeAllocMap.ref().iter(); !i.done(); i.next()) {
1364 LargeBuffer* buffer = i.get().value();
1365 if (buffer->isNurseryOwned) {
1366 largeNurseryAllocs.ref().remove(buffer);
1367 } else {
1368 largeTenuredAllocs.ref().remove(buffer);
1369 }
1370 }
1371
1372 MOZ_ASSERT(largeNurseryAllocs.ref().isEmpty());
1373 MOZ_ASSERT(largeTenuredAllocs.ref().isEmpty());
1374 }
1375
1376 void BufferAllocator::fixupAfterMovingGC() {
1377 #ifdef DEBUG
1378 MOZ_ASSERT(movingGCInProgress);
1379 movingGCInProgress = false;
1380 #endif
1381
1382 // Update our pointers to large allocation metadata objects and return them to
1383 // their lists.
1384 for (auto i = largeAllocMap.ref().iter(); !i.done(); i.next()) {
1385 LargeBuffer* buffer = i.get().value();
1386 SmallBuffer* headerCell = buffer->headerCell();
1387 if (IsForwarded(headerCell)) {
1388 headerCell = Forwarded(headerCell);
1389 buffer = static_cast<LargeBuffer*>(headerCell->data());
1390 i.get().value() = buffer;
1391 }
1392
1393 MOZ_ASSERT(!buffer->isInList());
1394 if (buffer->isNurseryOwned) {
1395 largeNurseryAllocs.ref().pushBack(buffer);
1396 } else {
1397 largeTenuredAllocs.ref().pushBack(buffer);
1398 }
1399 }
1400 }
1401
1402 void BufferAllocator::clearMarkStateAfterBarrierVerification() {
1403 MOZ_ASSERT(!zone->wasGCStarted());
1404
1405 maybeMergeSweptData();
1406 MOZ_ASSERT(minorState == State::NotCollecting);
1407 MOZ_ASSERT(majorState == State::NotCollecting);
1408
1409 for (auto* chunks : {&mediumMixedChunks.ref(), &mediumTenuredChunks.ref()}) {
1410 for (auto* chunk : *chunks) {
1411 chunk->markBits.ref().clear();
1412 }
1413 }
1414 }
1415
1416 bool BufferAllocator::isPointerWithinMediumOrLargeBuffer(void* ptr) {
1417 maybeMergeSweptData();
1418
1419 for (const auto* chunks :
1420 {&mediumMixedChunks.ref(), &mediumTenuredChunks.ref()}) {
1421 for (auto* chunk : *chunks) {
1422 if (chunk->isPointerWithinAllocation(ptr)) {
1423 return true;
1424 }
1425 }
1426 }
1427
1428 if (majorState == State::Marking) {
1429 for (auto* chunk : mediumTenuredChunksToSweep.ref()) {
1430 if (chunk->isPointerWithinAllocation(ptr)) {
1431 return true;
1432 }
1433 }
1434 }
1435
1436 // Note we cannot safely access data that is being swept on another thread.
1437
1438 for (const auto* allocs :
1439 {&largeNurseryAllocs.ref(), &largeTenuredAllocs.ref()}) {
1440 for (auto* alloc : *allocs) {
1441 if (alloc->isPointerWithinAllocation(ptr)) {
1442 return true;
1443 }
1444 }
1445 }
1446
1447 return false;
1448 }
1449
1450 bool BufferChunk::isPointerWithinAllocation(void* ptr) const {
1451 uintptr_t offset = uintptr_t(ptr) - uintptr_t(this);
1452 if (offset >= ChunkSize || offset < FirstMediumAllocOffset) {
1453 return false;
1454 }
1455
1456 uintptr_t allocOffset = findPrevAllocated(offset);
1457 MOZ_ASSERT(allocOffset <= ChunkSize);
1458 if (allocOffset == ChunkSize) {
1459 return false;
1460 }
1461
1462 const void* alloc = ptrFromOffset(allocOffset);
1463 size_t size = allocBytes(alloc);
1464
1465 return offset < allocOffset + size;
1466 }
1467
1468 bool LargeBuffer::isPointerWithinAllocation(void* ptr) const {
1469 return uintptr_t(ptr) - uintptr_t(alloc) < bytes;
1470 }
1471
1472 #ifdef DEBUG
1473
1474 void BufferAllocator::checkGCStateNotInUse() {
1475 maybeMergeSweptData();
1476 AutoLock lock(this); // Some fields are protected by this lock.
1477 checkGCStateNotInUse(lock);
1478 }
1479
1480 void BufferAllocator::checkGCStateNotInUse(MaybeLock& maybeLock) {
1481 if (maybeLock.isNothing()) {
1482 // Some fields are protected by this lock.
1483 maybeLock.emplace(this);
1484 }
1485
1486 checkGCStateNotInUse(maybeLock.ref());
1487 }
1488
1489 void BufferAllocator::checkGCStateNotInUse(const AutoLock& lock) {
1490 MOZ_ASSERT(majorState == State::NotCollecting);
1491 bool isNurserySweeping = minorState == State::Sweeping;
1492
1493 checkChunkListGCStateNotInUse(mediumMixedChunks.ref(), true, false);
1494 checkChunkListGCStateNotInUse(mediumTenuredChunks.ref(), false, false);
1495
1496 if (isNurserySweeping) {
1497 checkChunkListGCStateNotInUse(sweptMediumMixedChunks.ref(), true,
1498 majorFinishedWhileMinorSweeping);
1499 checkChunkListGCStateNotInUse(sweptMediumTenuredChunks.ref(), false, false);
1500 } else {
1501 MOZ_ASSERT(mediumMixedChunksToSweep.ref().isEmpty());
1502 MOZ_ASSERT(largeNurseryAllocsToSweep.ref().isEmpty());
1503
1504 MOZ_ASSERT(sweptMediumMixedChunks.ref().isEmpty());
1505 MOZ_ASSERT(sweptMediumTenuredChunks.ref().isEmpty());
1506 sweptMediumNurseryFreeLists.ref().assertEmpty();
1507 sweptMediumTenuredFreeLists.ref().assertEmpty();
1508
1509 MOZ_ASSERT(!majorStartedWhileMinorSweeping);
1510 MOZ_ASSERT(!majorFinishedWhileMinorSweeping);
1511 MOZ_ASSERT(!hasMinorSweepDataToMerge);
1512 MOZ_ASSERT(!minorSweepingFinished);
1513 MOZ_ASSERT(!majorSweepingFinished);
1514 }
1515
1516 MOZ_ASSERT(mediumTenuredChunksToSweep.ref().isEmpty());
1517
1518 checkAllocListGCStateNotInUse(largeNurseryAllocs.ref(), true);
1519 checkAllocListGCStateNotInUse(largeTenuredAllocs.ref(), false);
1520
1521 MOZ_ASSERT(largeTenuredAllocsToSweep.ref().isEmpty());
1522 MOZ_ASSERT(sweptLargeTenuredAllocs.ref().isEmpty());
1523
1524 MOZ_ASSERT(!movingGCInProgress);
1525 }
1526
1527 void BufferAllocator::checkChunkListGCStateNotInUse(
1528 BufferChunkList& chunks, bool hasNurseryOwnedAllocs,
1529 bool allowAllocatedDuringCollection) {
1530 for (BufferChunk* chunk : chunks) {
1531 checkChunkGCStateNotInUse(chunk, allowAllocatedDuringCollection);
1532 verifyChunk(chunk, hasNurseryOwnedAllocs);
1533 }
1534 }
1535
1536 void BufferAllocator::checkChunkGCStateNotInUse(
1537 BufferChunk* chunk, bool allowAllocatedDuringCollection) {
1538 MOZ_ASSERT_IF(!allowAllocatedDuringCollection,
1539 !chunk->allocatedDuringCollection);
1540
1541 static constexpr size_t StepBytes = MinMediumAllocSize;
1542
1543 // Check nothing's marked.
1544 uintptr_t chunkAddr = uintptr_t(chunk);
1545 auto& markBits = chunk->markBits.ref();
1546 for (size_t offset = 0; offset < ChunkSize; offset += StepBytes) {
1547 void* alloc = reinterpret_cast<void*>(chunkAddr + offset);
1548 MOZ_ASSERT(!markBits.isMarkedBlack(alloc));
1549 }
1550 }
1551
1552 void BufferAllocator::verifyChunk(BufferChunk* chunk,
1553 bool hasNurseryOwnedAllocs) {
1554 MOZ_ASSERT(chunk->hasNurseryOwnedAllocs == hasNurseryOwnedAllocs);
1555
1556 static constexpr size_t StepBytes = MinMediumAllocSize;
1557
1558 size_t freeOffset = FirstMediumAllocOffset;
1559
1560 for (BufferChunkIter iter(chunk); !iter.done(); iter.next()) {
1561 // Check any free region preceding this allocation.
1562 size_t offset = iter.getOffset();
1563 MOZ_ASSERT(offset >= FirstMediumAllocOffset);
1564 if (offset > freeOffset) {
1565 verifyFreeRegion(chunk, offset, offset - freeOffset);
1566 }
1567
1568 // Check this allocation.
1569 void* alloc = iter.get();
1570 MOZ_ASSERT_IF(chunk->isNurseryOwned(alloc), hasNurseryOwnedAllocs);
1571 size_t bytes = SizeClassBytes(chunk->sizeClass(alloc));
1572 uintptr_t endOffset = offset + bytes;
1573 MOZ_ASSERT(endOffset <= ChunkSize);
1574 for (size_t i = offset + StepBytes; i < endOffset; i += StepBytes) {
1575 MOZ_ASSERT(!chunk->isAllocated(i));
1576 }
1577
1578 freeOffset = endOffset;
1579 }
1580
1581 // Check any free region following the last allocation.
1582 if (freeOffset < ChunkSize) {
1583 verifyFreeRegion(chunk, ChunkSize, ChunkSize - freeOffset);
1584 }
1585 }
1586
1587 void BufferAllocator::verifyFreeRegion(BufferChunk* chunk, uintptr_t endOffset,
1588 size_t expectedSize) {
1589 auto* freeRegion = FreeRegion::fromEndOffset(chunk, endOffset);
1590 MOZ_ASSERT(freeRegion->isInList());
1591 MOZ_ASSERT(freeRegion->size() == expectedSize);
1592 }
1593
1594 void BufferAllocator::checkAllocListGCStateNotInUse(LargeAllocList& list,
1595 bool isNurseryOwned) {
1596 for (LargeBuffer* buffer : list) {
1597 MOZ_ASSERT(buffer->isNurseryOwned == isNurseryOwned);
1598 MOZ_ASSERT_IF(!isNurseryOwned, !buffer->allocatedDuringCollection);
1599 }
1600 }
1601
1602 #endif
1603
1604 void* BufferAllocator::allocSmall(size_t bytes, bool nurseryOwned) {
1605 AllocKind kind = AllocKindForSmallAlloc(bytes);
1606
1607 void* ptr = CellAllocator::AllocTenuredCellUnchecked<NoGC>(zone, kind);
1608 if (!ptr) {
1609 return nullptr;
1610 }
1611
1612 auto* cell = new (ptr) SmallBuffer();
1613 cell->setNurseryOwned(nurseryOwned);
1614 MOZ_ASSERT(cell->isNurseryOwned() == nurseryOwned);
1615 void* alloc = cell->data();
1616
1617 MOZ_ASSERT(IsSmallAlloc(alloc));
1618 MOZ_ASSERT(getAllocSize(alloc) >= bytes);
1619 MOZ_ASSERT(getAllocSize(alloc) < 2 * bytes);
1620
1621 return alloc;
1622 }
1623
1624 /* static */
1625 void* BufferAllocator::allocSmallInGC(size_t bytes, bool nurseryOwned) {
1626 AllocKind kind = AllocKindForSmallAlloc(bytes);
1627
1628 void* ptr = AllocateTenuredCellInGC(zone, kind);
1629 if (!ptr) {
1630 return nullptr;
1631 }
1632
1633 auto* cell = new (ptr) SmallBuffer();
1634 cell->setNurseryOwned(nurseryOwned);
1635 void* alloc = cell->data();
1636
1637 MOZ_ASSERT(IsSmallAlloc(alloc));
1638 MOZ_ASSERT(getAllocSize(alloc) >= bytes);
1639 MOZ_ASSERT(getAllocSize(alloc) < 2 * bytes);
1640
1641 return alloc;
1642 }
1643
1644 /* static */
1645 AllocKind BufferAllocator::AllocKindForSmallAlloc(size_t bytes) {
1646 bytes = std::max(bytes, MinAllocSize);
1647 MOZ_ASSERT(bytes <= MaxSmallAllocSize);
1648
1649 size_t logBytes = mozilla::CeilingLog2(bytes);
1650 MOZ_ASSERT(bytes <= (size_t(1) << logBytes));
1651
1652 MOZ_ASSERT(logBytes >= mozilla::CeilingLog2(MinAllocSize));
1653 size_t kindIndex = logBytes - mozilla::CeilingLog2(MinAllocSize);
1654
1655 AllocKind kind = AllocKind(size_t(AllocKind::BUFFER_FIRST) + kindIndex);
1656 MOZ_ASSERT(IsBufferAllocKind(kind));
1657
1658 return kind;
1659 }
1660
1661 /* static */
1662 bool BufferAllocator::IsSmallAlloc(void* alloc) {
1663 MOZ_ASSERT(IsBufferAlloc(alloc));
1664
1665 // Test for large buffers before calling this so we can assume |alloc| is
1666 // inside a chunk.
1667 MOZ_ASSERT(!IsLargeAlloc(alloc));
1668
1669 ChunkBase* chunk = detail::GetGCAddressChunkBase(alloc);
1670 return chunk->getKind() == ChunkKind::TenuredArenas;
1671 }
1672
1673 void* BufferAllocator::allocMedium(size_t bytes, bool nurseryOwned, bool inGC) {
1674 MOZ_ASSERT(!IsSmallAllocSize(bytes));
1675 MOZ_ASSERT(!IsLargeAllocSize(bytes));
1676 bytes = mozilla::RoundUpPow2(std::max(bytes, MinMediumAllocSize));
1677
1678 // Get size class from |bytes|.
1679 size_t sizeClass = SizeClassForAlloc(bytes);
1680 MOZ_ASSERT(SizeClassBytes(sizeClass) == GetGoodAllocSize(bytes));
1681
1682 void* alloc = bumpAllocOrRetry(sizeClass, inGC);
1683 if (!alloc) {
1684 return nullptr;
1685 }
1686
1687 BufferChunk* chunk = BufferChunk::from(alloc);
1688 chunk->setAllocated(alloc, true);
1689
1690 MOZ_ASSERT(!chunk->isNurseryOwned(alloc));
1691 chunk->setNurseryOwned(alloc, nurseryOwned);
1692
1693 MOZ_ASSERT(chunk->sizeClass(alloc) == 0);
1694 chunk->setSizeClass(alloc, sizeClass);
1695
1696 if (nurseryOwned && !chunk->hasNurseryOwnedAllocs) {
1697 mediumTenuredChunks.ref().remove(chunk);
1698 chunk->hasNurseryOwnedAllocs = true;
1699 mediumMixedChunks.ref().pushBack(chunk);
1700 }
1701
1702 MOZ_ASSERT(!chunk->markBits.ref().isMarkedBlack(alloc));
1703
1704 if (!nurseryOwned) {
1705 bool checkThresholds = !inGC;
1706 updateHeapSize(bytes, checkThresholds, false);
1707 }
1708
1709 chunk->checkAlloc(alloc);
1710 return alloc;
1711 }
1712
1713 void* BufferAllocator::bumpAllocOrRetry(size_t sizeClass, bool inGC) {
1714 void* ptr = bumpAlloc(sizeClass);
1715 if (ptr) {
1716 return ptr;
1717 }
1718
1719 if (hasMinorSweepDataToMerge) {
1720 // Avoid taking the lock unless we know there is data to merge. This reduces
1721 // context switches.
1722 mergeSweptData();
1723 ptr = bumpAlloc(sizeClass);
1724 if (ptr) {
1725 return ptr;
1726 }
1727 }
1728
1729 if (!allocNewChunk(inGC)) {
1730 return nullptr;
1731 }
1732
1733 ptr = bumpAlloc(sizeClass);
1734 MOZ_ASSERT(ptr);
1735 return ptr;
1736 }
1737
1738 void* BufferAllocator::bumpAlloc(size_t sizeClass) {
1739 size_t requestedBytes = SizeClassBytes(sizeClass);
1740
1741 mediumFreeLists.ref().checkAvailable();
1742
1743 // Find smallest suitable size class that has free regions.
1744 sizeClass = mediumFreeLists.ref().getFirstAvailableSizeClass(sizeClass);
1745 if (sizeClass == SIZE_MAX) {
1746 return nullptr;
1747 }
1748
1749 FreeRegion* region = mediumFreeLists.ref().getFirstRegion(sizeClass);
1750 void* ptr = allocFromRegion(region, requestedBytes, sizeClass);
1751 updateFreeListsAfterAlloc(&mediumFreeLists.ref(), region, sizeClass);
1752 return ptr;
1753 }
1754
1755 void* BufferAllocator::allocFromRegion(FreeRegion* region,
1756 size_t requestedBytes,
1757 size_t sizeClass) {
1758 uintptr_t start = region->startAddr;
1759 MOZ_ASSERT(region->getEnd() > start);
1760 MOZ_ASSERT(region->size() >= SizeClassBytes(sizeClass));
1761 MOZ_ASSERT((region->size() % MinMediumAllocSize) == 0);
1762
1763 // Ensure whole region is commited.
1764 if (region->hasDecommittedPages) {
1765 recommitRegion(region);
1766 }
1767
1768 // Allocate from start of region.
1769 void* ptr = reinterpret_cast<void*>(start);
1770 start += requestedBytes;
1771 MOZ_ASSERT(region->getEnd() >= start);
1772
1773 // Update region start.
1774 region->startAddr = start;
1775
1776 return ptr;
1777 }
1778
1779 void BufferAllocator::updateFreeListsAfterAlloc(FreeLists* freeLists,
1780 FreeRegion* region,
1781 size_t sizeClass) {
1782 // Updates |freeLists| after an allocation of class |sizeClass| from |region|.
1783
1784 freeLists->assertContains(sizeClass, region);
1785
1786 // If the region is still valid for further allocations of this size class
1787 // then there's nothing to do.
1788 size_t classBytes = SizeClassBytes(sizeClass);
1789 size_t newSize = region->size();
1790 MOZ_ASSERT((newSize % MinMediumAllocSize) == 0);
1791 if (newSize >= classBytes) {
1792 return;
1793 }
1794
1795 // Remove region from this free list.
1796 freeLists->remove(sizeClass, region);
1797
1798 // If the region is now empty then we're done.
1799 if (newSize == 0) {
1800 return;
1801 }
1802
1803 // Otherwise region is now too small. Move it to the appropriate bucket for
1804 // its reduced size.
1805 size_t newSizeClass = SizeClassForFreeRegion(newSize);
1806 MOZ_ASSERT(newSize >= SizeClassBytes(newSizeClass));
1807 MOZ_ASSERT(newSizeClass < sizeClass);
1808 freeLists->pushFront(newSizeClass, region);
1809 }
1810
1811 void BufferAllocator::recommitRegion(FreeRegion* region) {
1812 MOZ_ASSERT(region->hasDecommittedPages);
1813 MOZ_ASSERT(DecommitEnabled());
1814
1815 BufferChunk* chunk = BufferChunk::from(region);
1816 uintptr_t startAddr = RoundUp(region->startAddr, PageSize);
1817 uintptr_t endAddr = RoundDown(uintptr_t(region), PageSize);
1818
1819 size_t startPage = (startAddr - uintptr_t(chunk)) / PageSize;
1820 size_t endPage = (endAddr - uintptr_t(chunk)) / PageSize;
1821
1822 // If the start of the region does not lie on a page boundary the page it is
1823 // in should be committed as it must either contain the start of the chunk, a
1824 // FreeRegion or an allocation.
1825 MOZ_ASSERT_IF((region->startAddr % PageSize) != 0,
1826 !chunk->decommittedPages.ref()[startPage - 1]);
1827
1828 // The end of the region should be committed as it holds FreeRegion |region|.
1829 MOZ_ASSERT(!chunk->decommittedPages.ref()[endPage]);
1830
1831 MarkPagesInUseSoft(reinterpret_cast<void*>(startAddr), endAddr - startAddr);
1832 for (size_t i = startPage; i != endPage; i++) {
1833 chunk->decommittedPages.ref()[i] = false;
1834 }
1835
1836 region->hasDecommittedPages = false;
1837 }
1838
1839 static inline StallAndRetry ShouldStallAndRetry(bool inGC) {
1840 return inGC ? StallAndRetry::Yes : StallAndRetry::No;
1841 }
1842
1843 bool BufferAllocator::allocNewChunk(bool inGC) {
1844 GCRuntime* gc = &zone->runtimeFromMainThread()->gc;
1845 AutoLockGCBgAlloc lock(gc);
1846 ArenaChunk* baseChunk = gc->takeOrAllocChunk(ShouldStallAndRetry(inGC), lock);
1847 if (!baseChunk) {
1848 return false;
1849 }
1850
1851 CheckHighBitsOfPointer(baseChunk);
1852
1853 // Ensure all memory is initially committed.
1854 if (!baseChunk->decommittedPages.IsEmpty()) {
1855 MOZ_ASSERT(DecommitEnabled());
1856 MarkPagesInUseSoft(baseChunk, ChunkSize);
1857 }
1858
1859 // Unpoison past the ChunkBase header.
1860 void* ptr = reinterpret_cast<void*>(uintptr_t(baseChunk) + sizeof(ChunkBase));
1861 size_t size = ChunkSize - sizeof(ChunkBase);
1862 SetMemCheckKind(ptr, size, MemCheckKind::MakeUndefined);
1863
1864 BufferChunk* chunk = new (baseChunk) BufferChunk(zone);
1865 chunk->allocatedDuringCollection = majorState != State::NotCollecting;
1866
1867 mediumTenuredChunks.ref().pushBack(chunk);
1868
1869 uintptr_t freeStart = uintptr_t(chunk) + FirstMediumAllocOffset;
1870 uintptr_t freeEnd = uintptr_t(chunk) + ChunkSize;
1871
1872 size_t sizeClass = SizeClassForFreeRegion(freeEnd - freeStart);
1873
1874 ptr = reinterpret_cast<void*>(freeEnd - sizeof(FreeRegion));
1875 FreeRegion* region = new (ptr) FreeRegion(freeStart);
1876 MOZ_ASSERT(region->getEnd() == freeEnd);
1877 mediumFreeLists.ref().pushFront(sizeClass, region);
1878
1879 return true;
1880 }
1881
1882 bool BufferAllocator::sweepChunk(BufferChunk* chunk, OwnerKind ownerKindToSweep,
1883 bool shouldDecommit, FreeLists& freeLists) {
1884 // Find all regions of free space in |chunk| and add them to the swept free
1885 // lists.
1886
1887 // TODO: Ideally we'd arrange things so we allocate from most-full chunks
1888 // first. This could happen by sweeping all chunks and then sorting them by
1889 // how much free space they had and then adding their free regions to the free
1890 // lists in that order.
1891
1892 GCRuntime* gc = &zone->runtimeFromAnyThread()->gc;
1893
1894 bool hasNurseryOwnedAllocs = false;
1895
1896 size_t freeStart = FirstMediumAllocOffset;
1897 bool sweptAny = false;
1898 size_t mallocHeapBytesFreed = 0;
1899
1900 for (BufferChunkIter iter(chunk); !iter.done(); iter.next()) {
1901 void* alloc = iter.get();
1902
1903 size_t bytes = chunk->allocBytes(alloc);
1904 uintptr_t allocEnd = iter.getOffset() + bytes;
1905
1906 bool nurseryOwned = chunk->isNurseryOwned(alloc);
1907 OwnerKind ownerKind = OwnerKind(uint8_t(nurseryOwned));
1908 MOZ_ASSERT_IF(nurseryOwned, ownerKind == OwnerKind::Nursery);
1909 MOZ_ASSERT_IF(!nurseryOwned, ownerKind == OwnerKind::Tenured);
1910 bool canSweep = ownerKind == ownerKindToSweep;
1911 bool shouldSweep = canSweep && !chunk->markBits.ref().isMarkedBlack(alloc);
1912
1913 if (shouldSweep) {
1914 // Dead. Update allocated bitmap, metadata and heap size accounting.
1915 if (!nurseryOwned) {
1916 mallocHeapBytesFreed += bytes;
1917 }
1918 chunk->setNurseryOwned(alloc, false);
1919 chunk->setSizeClass(alloc, 0);
1920 chunk->setAllocated(alloc, false);
1921 PoisonAlloc(alloc, JS_SWEPT_TENURED_PATTERN, bytes,
1922 MemCheckKind::MakeUndefined);
1923 sweptAny = true;
1924 } else {
1925 // Alive. Add any free space before this allocation.
1926 uintptr_t allocStart = iter.getOffset();
1927 if (freeStart != allocStart) {
1928 addSweptRegion(chunk, freeStart, allocStart, shouldDecommit, !sweptAny,
1929 freeLists);
1930 }
1931 freeStart = allocEnd;
1932 if (canSweep) {
1933 chunk->markBits.ref().unmarkOneBit(alloc, ColorBit::BlackBit);
1934 }
1935 if (nurseryOwned) {
1936 MOZ_ASSERT(ownerKindToSweep == OwnerKind::Nursery);
1937 hasNurseryOwnedAllocs = true;
1938 }
1939 sweptAny = false;
1940 }
1941 }
1942
1943 if (mallocHeapBytesFreed) {
1944 zone->mallocHeapSize.removeBytes(mallocHeapBytesFreed, true);
1945 }
1946
1947 if (freeStart == FirstMediumAllocOffset &&
1948 ownerKindToSweep != OwnerKind::None) {
1949 // Chunk is empty. Give it back to the system.
1950 bool allMemoryCommitted = chunk->decommittedPages.ref().IsEmpty();
1951 chunk->~BufferChunk();
1952 ArenaChunk* tenuredChunk =
1953 ArenaChunk::emplace(chunk, gc, allMemoryCommitted);
1954 AutoLockGC lock(gc);
1955 gc->recycleChunk(tenuredChunk, lock);
1956 return false;
1957 }
1958
1959 // Add any free space from the last allocation to the end of the chunk.
1960 if (freeStart != ChunkSize) {
1961 addSweptRegion(chunk, freeStart, ChunkSize, shouldDecommit, !sweptAny,
1962 freeLists);
1963 }
1964
1965 chunk->hasNurseryOwnedAllocsAfterSweep = hasNurseryOwnedAllocs;
1966
1967 return true;
1968 }
1969
1970 void BufferAllocator::addSweptRegion(BufferChunk* chunk, uintptr_t freeStart,
1971 uintptr_t freeEnd, bool shouldDecommit,
1972 bool expectUnchanged,
1973 FreeLists& freeLists) {
1974 // Add the region from |freeStart| to |freeEnd| to the appropriate swept free
1975 // list based on its size.
1976
1977 MOZ_ASSERT(freeStart >= FirstMediumAllocOffset);
1978 MOZ_ASSERT(freeStart < freeEnd);
1979 MOZ_ASSERT(freeEnd <= ChunkSize);
1980 MOZ_ASSERT((freeStart % MinMediumAllocSize) == 0);
1981 MOZ_ASSERT((freeEnd % MinMediumAllocSize) == 0);
1982 MOZ_ASSERT_IF(shouldDecommit, DecommitEnabled());
1983
1984 // Decommit pages if |shouldDecommit| was specified, but leave space for
1985 // the FreeRegion structure at the end.
1986 bool anyDecommitted = false;
1987 uintptr_t decommitStart = RoundUp(freeStart, PageSize);
1988 uintptr_t decommitEnd = RoundDown(freeEnd - sizeof(FreeRegion), PageSize);
1989 size_t endPage = decommitEnd / PageSize;
1990 if (shouldDecommit && decommitEnd > decommitStart) {
1991 void* ptr = reinterpret_cast<void*>(decommitStart + uintptr_t(chunk));
1992 MarkPagesUnusedSoft(ptr, decommitEnd - decommitStart);
1993 size_t startPage = decommitStart / PageSize;
1994 for (size_t i = startPage; i != endPage; i++) {
1995 chunk->decommittedPages.ref()[i] = true;
1996 }
1997 anyDecommitted = true;
1998 } else {
1999 // Check for any previously decommitted pages.
2000 uintptr_t startPage = RoundDown(freeStart, PageSize) / PageSize;
2001 for (size_t i = startPage; i != endPage; i++) {
2002 if (chunk->decommittedPages.ref()[i]) {
2003 anyDecommitted = true;
2004 }
2005 }
2006 }
2007
2008 // The last page must have previously been either a live allocation or a
2009 // FreeRegion, so it must already be committed.
2010 MOZ_ASSERT(!chunk->decommittedPages.ref()[endPage]);
2011
2012 freeStart += uintptr_t(chunk);
2013 freeEnd += uintptr_t(chunk);
2014
2015 size_t sizeClass = SizeClassForFreeRegion(freeEnd - freeStart);
2016 addFreeRegion(&freeLists, sizeClass, freeStart, freeEnd, anyDecommitted,
2017 ListPosition::Back, expectUnchanged);
2018 }
2019
2020 void BufferAllocator::freeMedium(void* alloc) {
2021 // Free a medium sized allocation. This coalesces the free space with any
2022 // neighboring free regions. Coalescing is necessary for resize to work
2023 // properly.
2024
2025 BufferChunk* chunk = BufferChunk::from(alloc);
2026 MOZ_ASSERT(chunk->zone == zone);
2027
2028 size_t bytes = chunk->allocBytes(alloc);
2029 PoisonAlloc(alloc, JS_FREED_BUFFER_PATTERN, bytes,
2030 MemCheckKind::MakeUndefined);
2031
2032 if (isSweepingChunk(chunk)) {
2033 return; // We can't free if the chunk is currently being swept.
2034 }
2035
2036 // Update heap size for tenured owned allocations.
2037 if (!chunk->isNurseryOwned(alloc)) {
2038 bool updateRetained =
2039 majorState == State::Marking && !chunk->allocatedDuringCollection;
2040 zone->mallocHeapSize.removeBytes(bytes, updateRetained);
2041 }
2042
2043 // Update metadata.
2044 chunk->setNurseryOwned(alloc, false);
2045 chunk->setSizeClass(alloc, 0);
2046
2047 // Set region as not allocated and then clear mark bit.
2048 chunk->setAllocated(alloc, false);
2049
2050 // TODO: Since the mark bits are atomic, it's probably OK to unmark even if
2051 // the chunk is currently being swept. If we get lucky the memory will be
2052 // freed sooner.
2053 chunk->markBits.ref().unmarkOneBit(alloc, ColorBit::BlackBit);
2054
2055 FreeLists* freeLists = getChunkFreeLists(chunk);
2056
2057 uintptr_t startAddr = uintptr_t(alloc);
2058 uintptr_t endAddr = startAddr + bytes;
2059
2060 // First check whether there is a free region following the allocation.
2061 FreeRegion* region;
2062 uintptr_t endOffset = endAddr & ChunkMask;
2063 if (endOffset == 0 || chunk->isAllocated(endOffset)) {
2064 // The allocation abuts the end of the chunk or another allocation. Add the
2065 // allocation as a new free region.
2066 //
2067 // The new region is added to the front of relevant list so as to reuse
2068 // recently freed memory preferentially. This may reduce fragmentation. See
2069 // "The Memory Fragmentation Problem: Solved?" by Johnstone et al.
2070 size_t sizeClass = SizeClassForFreeRegion(bytes);
2071 region = addFreeRegion(freeLists, sizeClass, startAddr, endAddr, false,
2072 ListPosition::Front);
2073 } else {
2074 // There is a free region following this allocation. Expand the existing
2075 // region down to cover the newly freed space.
2076 region = findFollowingFreeRegion(endAddr);
2077 MOZ_ASSERT(region->startAddr == endAddr);
2078 updateFreeRegionStart(freeLists, region, startAddr);
2079 }
2080
2081 // Next check for any preceding free region and coalesce.
2082 FreeRegion* precRegion = findPrecedingFreeRegion(startAddr);
2083 if (precRegion) {
2084 if (freeLists) {
2085 size_t sizeClass = SizeClassForFreeRegion(precRegion->size());
2086 freeLists->remove(sizeClass, precRegion);
2087 }
2088
2089 updateFreeRegionStart(freeLists, region, precRegion->startAddr);
2090 if (precRegion->hasDecommittedPages) {
2091 region->hasDecommittedPages = true;
2092 }
2093 }
2094 }
2095
2096 bool BufferAllocator::isSweepingChunk(BufferChunk* chunk) {
2097 if (minorState == State::Sweeping && chunk->hasNurseryOwnedAllocs) {
2098 // We are currently sweeping nursery owned allocations.
2099
2100 // TODO: We could set a flag for nursery chunks allocated during minor
2101 // collection to allow operations on chunks that are not being swept here.
2102
2103 if (!hasMinorSweepDataToMerge) {
2104 #ifdef DEBUG
2105 {
2106 AutoLock lock(this);
2107 MOZ_ASSERT_IF(!hasMinorSweepDataToMerge, !minorSweepingFinished);
2108 }
2109 #endif
2110
2111 // Likely no data to merge so don't bother taking the lock.
2112 return true;
2113 }
2114
2115 // Merge swept data and recheck.
2116 //
2117 // TODO: It would be good to know how often this helps and if it is
2118 // worthwhile.
2119 mergeSweptData();
2120 if (minorState == State::Sweeping && chunk->hasNurseryOwnedAllocs) {
2121 return true;
2122 }
2123 }
2124
2125 if (majorState == State::Sweeping && !chunk->allocatedDuringCollection) {
2126 // We are currently sweeping tenured owned allocations.
2127 return true;
2128 }
2129
2130 return false;
2131 }
2132
2133 BufferAllocator::FreeRegion* BufferAllocator::addFreeRegion(
2134 FreeLists* freeLists, size_t sizeClass, uintptr_t start, uintptr_t end,
2135 bool anyDecommitted, ListPosition position,
2136 bool expectUnchanged /* = false */) {
2137 #ifdef DEBUG
2138 MOZ_ASSERT(end - start >= SizeClassBytes(sizeClass));
2139 if (expectUnchanged) {
2140 // We didn't free any allocations so there should already be a FreeRegion
2141 // from |start| to |end|.
2142 auto* region = FreeRegion::fromEndAddr(end);
2143 region->check();
2144 MOZ_ASSERT(region->startAddr == start);
2145 }
2146 #endif
2147
2148 void* ptr = reinterpret_cast<void*>(end - sizeof(FreeRegion));
2149 FreeRegion* region = new (ptr) FreeRegion(start, anyDecommitted);
2150 MOZ_ASSERT(region->getEnd() == end);
2151
2152 if (freeLists) {
2153 if (position == ListPosition::Front) {
2154 freeLists->pushFront(sizeClass, region);
2155 } else {
2156 freeLists->pushBack(sizeClass, region);
2157 }
2158 }
2159
2160 return region;
2161 }
2162
2163 void BufferAllocator::updateFreeRegionStart(FreeLists* freeLists,
2164 FreeRegion* region,
2165 uintptr_t newStart) {
2166 MOZ_ASSERT((newStart & ~ChunkMask) == (uintptr_t(region) & ~ChunkMask));
2167 MOZ_ASSERT(region->startAddr != newStart);
2168
2169 size_t oldSize = region->size();
2170 region->startAddr = newStart;
2171
2172 if (!freeLists) {
2173 return;
2174 }
2175
2176 size_t currentSizeClass = SizeClassForFreeRegion(oldSize);
2177 size_t newSizeClass = SizeClassForFreeRegion(region->size());
2178 if (currentSizeClass != newSizeClass) {
2179 freeLists->remove(currentSizeClass, region);
2180 freeLists->pushFront(newSizeClass, region);
2181 }
2182 }
2183
2184 bool BufferAllocator::growMedium(void* alloc, size_t newBytes) {
2185 MOZ_ASSERT(!IsSmallAllocSize(newBytes));
2186 MOZ_ASSERT(!IsLargeAllocSize(newBytes));
2187 newBytes = std::max(newBytes, MinMediumAllocSize);
2188 MOZ_ASSERT(newBytes == GetGoodAllocSize(newBytes));
2189
2190 BufferChunk* chunk = BufferChunk::from(alloc);
2191 MOZ_ASSERT(chunk->zone == zone);
2192
2193 if (isSweepingChunk(chunk)) {
2194 return false; // We can't grow if the chunk is currently being swept.
2195 }
2196
2197 size_t currentBytes = SizeClassBytes(chunk->sizeClass(alloc));
2198 MOZ_ASSERT(newBytes > currentBytes);
2199
2200 uintptr_t endOffset = (uintptr_t(alloc) & ChunkMask) + currentBytes;
2201 MOZ_ASSERT(endOffset <= ChunkSize);
2202 if (endOffset == ChunkSize) {
2203 return false; // Can't extend because we're at the end of the chunk.
2204 }
2205
2206 size_t endAddr = uintptr_t(chunk) + endOffset;
2207 if (chunk->isAllocated(endOffset)) {
2208 return false; // Can't extend because we abut another allocation.
2209 }
2210
2211 FreeRegion* region = findFollowingFreeRegion(endAddr);
2212 MOZ_ASSERT(region->startAddr == endAddr);
2213
2214 size_t extraBytes = newBytes - currentBytes;
2215 if (region->size() < extraBytes) {
2216 return false; // Can't extend because following free region is too small.
2217 }
2218
2219 size_t sizeClass = SizeClassForFreeRegion(region->size());
2220
2221 allocFromRegion(region, extraBytes, sizeClass);
2222
2223 // If the allocation is in a chunk where we've cleared the free lists before
2224 // sweeping we don't need to update the free lists.
2225 if (FreeLists* freeLists = getChunkFreeLists(chunk)) {
2226 updateFreeListsAfterAlloc(freeLists, region, sizeClass);
2227 }
2228
2229 chunk->setSizeClass(alloc, SizeClassForAlloc(newBytes));
2230 if (!chunk->isNurseryOwned(alloc)) {
2231 bool updateRetained =
2232 majorState == State::Marking && !chunk->allocatedDuringCollection;
2233 updateHeapSize(extraBytes, true, updateRetained);
2234 }
2235
2236 return true;
2237 }
2238
2239 bool BufferAllocator::shrinkMedium(void* alloc, size_t newBytes) {
2240 MOZ_ASSERT(!IsSmallAllocSize(newBytes));
2241 MOZ_ASSERT(!IsLargeAllocSize(newBytes));
2242 newBytes = std::max(newBytes, MinMediumAllocSize);
2243 MOZ_ASSERT(newBytes == GetGoodAllocSize(newBytes));
2244
2245 BufferChunk* chunk = BufferChunk::from(alloc);
2246 MOZ_ASSERT(chunk->zone == zone);
2247
2248 if (isSweepingChunk(chunk)) {
2249 return false; // We can't shrink if the chunk is currently being swept.
2250 }
2251
2252 size_t currentBytes = chunk->allocBytes(alloc);
2253 if (newBytes == currentBytes) {
2254 // Requested size is the same after adjusting to a valid medium alloc size.
2255 return false;
2256 }
2257
2258 MOZ_ASSERT(newBytes < currentBytes);
2259 size_t sizeChange = currentBytes - newBytes;
2260
2261 // Update allocation size.
2262 chunk->setSizeClass(alloc, SizeClassForAlloc(newBytes));
2263 if (!chunk->isNurseryOwned(alloc)) {
2264 bool updateRetained =
2265 majorState == State::Marking && !chunk->allocatedDuringCollection;
2266 zone->mallocHeapSize.removeBytes(sizeChange, updateRetained);
2267 }
2268
2269 uintptr_t startOffset = uintptr_t(alloc) & ChunkMask;
2270 uintptr_t oldEndOffset = startOffset + currentBytes;
2271 uintptr_t newEndOffset = startOffset + newBytes;
2272 MOZ_ASSERT(oldEndOffset <= ChunkSize);
2273
2274 // Poison freed memory.
2275 uintptr_t chunkAddr = uintptr_t(chunk);
2276 PoisonAlloc(reinterpret_cast<void*>(chunkAddr + newEndOffset),
2277 JS_SWEPT_TENURED_PATTERN, sizeChange,
2278 MemCheckKind::MakeUndefined);
2279
2280 FreeLists* freeLists = getChunkFreeLists(chunk);
2281
2282 // If we abut another allocation then add a new free region.
2283 if (oldEndOffset == ChunkSize || chunk->isAllocated(oldEndOffset)) {
2284 size_t sizeClass = SizeClassForFreeRegion(sizeChange);
2285 uintptr_t freeStart = chunkAddr + newEndOffset;
2286 uintptr_t freeEnd = chunkAddr + oldEndOffset;
2287 addFreeRegion(freeLists, sizeClass, freeStart, freeEnd, false,
2288 ListPosition::Front);
2289 return true;
2290 }
2291
2292 // Otherwise find the following free region and extend it down.
2293 FreeRegion* region = findFollowingFreeRegion(chunkAddr + oldEndOffset);
2294 MOZ_ASSERT(region->startAddr == chunkAddr + oldEndOffset);
2295 updateFreeRegionStart(freeLists, region, chunkAddr + newEndOffset);
2296
2297 return true;
2298 }
2299
2300 BufferAllocator::FreeLists* BufferAllocator::getChunkFreeLists(
2301 BufferChunk* chunk) {
2302 MOZ_ASSERT_IF(majorState == State::Sweeping,
2303 chunk->allocatedDuringCollection);
2304
2305 if (majorState == State::Marking && !chunk->allocatedDuringCollection) {
2306 // The chunk has been queued for sweeping and the free lists cleared.
2307 return nullptr;
2308 }
2309
2310 return &mediumFreeLists.ref();
2311 }
2312
2313 BufferAllocator::FreeRegion* BufferAllocator::findFollowingFreeRegion(
2314 uintptr_t startAddr) {
2315 // Find the free region that starts at |startAddr|, which is not allocated and
2316 // not at the end of the chunk. Always returns a region.
2317
2318 uintptr_t offset = uintptr_t(startAddr) & ChunkMask;
2319 MOZ_ASSERT(offset >= FirstMediumAllocOffset);
2320 MOZ_ASSERT(offset < ChunkSize);
2321 MOZ_ASSERT((offset % MinMediumAllocSize) == 0);
2322
2323 BufferChunk* chunk = BufferChunk::from(reinterpret_cast<void*>(startAddr));
2324 MOZ_ASSERT(!chunk->isAllocated(offset)); // Already marked as not allocated.
2325 offset = chunk->findNextAllocated(offset);
2326 MOZ_ASSERT(offset <= ChunkSize);
2327
2328 auto* region = FreeRegion::fromEndOffset(chunk, offset);
2329 MOZ_ASSERT(region->startAddr == startAddr);
2330
2331 return region;
2332 }
2333
2334 BufferAllocator::FreeRegion* BufferAllocator::findPrecedingFreeRegion(
2335 uintptr_t endAddr) {
2336 // Find the free region, if any, that ends at |endAddr|, which may be
2337 // allocated or at the start of the chunk.
2338
2339 uintptr_t offset = uintptr_t(endAddr) & ChunkMask;
2340 MOZ_ASSERT(offset >= FirstMediumAllocOffset);
2341 MOZ_ASSERT(offset < ChunkSize);
2342 MOZ_ASSERT((offset % MinMediumAllocSize) == 0);
2343
2344 if (offset == FirstMediumAllocOffset) {
2345 return nullptr; // Already at start of chunk.
2346 }
2347
2348 BufferChunk* chunk = BufferChunk::from(reinterpret_cast<void*>(endAddr));
2349 MOZ_ASSERT(!chunk->isAllocated(offset));
2350 offset = chunk->findPrevAllocated(offset);
2351
2352 if (offset != ChunkSize) {
2353 // Found a preceding allocation.
2354 const void* alloc = chunk->ptrFromOffset(offset);
2355 size_t bytes = SizeClassBytes(chunk->sizeClass(alloc));
2356 MOZ_ASSERT(uintptr_t(alloc) + bytes <= endAddr);
2357 if (uintptr_t(alloc) + bytes == endAddr) {
2358 // No free space between preceding allocation and |endAddr|.
2359 return nullptr;
2360 }
2361 }
2362
2363 auto* region = FreeRegion::fromEndAddr(endAddr);
2364
2365 #ifdef DEBUG
2366 region->check();
2367 if (offset != ChunkSize) {
2368 const void* alloc = chunk->ptrFromOffset(offset);
2369 size_t bytes = chunk->allocBytes(alloc);
2370 MOZ_ASSERT(region->startAddr == uintptr_t(alloc) + bytes);
2371 } else {
2372 MOZ_ASSERT(region->startAddr == uintptr_t(chunk) + FirstMediumAllocOffset);
2373 }
2374 #endif
2375
2376 return region;
2377 }
2378
2379 /* static */
2380 size_t BufferAllocator::SizeClassForAlloc(size_t bytes) {
2381 MOZ_ASSERT(bytes >= MinMediumAllocSize);
2382 MOZ_ASSERT(bytes <= MaxMediumAllocSize);
2383
2384 size_t log2Size = mozilla::CeilingLog2(bytes);
2385 MOZ_ASSERT((size_t(1) << log2Size) >= bytes);
2386 MOZ_ASSERT(MinMediumAllocShift == mozilla::CeilingLog2(MinMediumAllocSize));
2387 MOZ_ASSERT(log2Size >= MinMediumAllocShift);
2388 size_t sizeClass = log2Size - MinMediumAllocShift;
2389 MOZ_ASSERT(sizeClass < MediumAllocClasses);
2390 return sizeClass;
2391 }
2392
2393 /* static */
2394 size_t BufferAllocator::SizeClassForFreeRegion(size_t bytes) {
2395 MOZ_ASSERT(bytes >= MinMediumAllocSize);
2396 MOZ_ASSERT(bytes < ChunkSize);
2397
2398 size_t log2Size = mozilla::FloorLog2(bytes);
2399 MOZ_ASSERT((size_t(1) << log2Size) <= bytes);
2400 MOZ_ASSERT(log2Size >= MinMediumAllocShift);
2401 size_t sizeClass =
2402 std::min(log2Size - MinMediumAllocShift, MediumAllocClasses - 1);
2403 MOZ_ASSERT(sizeClass < MediumAllocClasses);
2404
2405 return sizeClass;
2406 }
2407
2408 /* static */
2409 inline size_t BufferAllocator::SizeClassBytes(size_t sizeClass) {
2410 MOZ_ASSERT(sizeClass < MediumAllocClasses);
2411 return 1 << (sizeClass + MinMediumAllocShift);
2412 }
2413
2414 /* static */
2415 bool BufferAllocator::IsMediumAlloc(void* alloc) {
2416 ChunkBase* chunk = js::gc::detail::GetGCAddressChunkBase(alloc);
2417 return chunk->getKind() == ChunkKind::MediumBuffers;
2418 }
2419
2420 bool BufferAllocator::needLockToAccessBufferMap() const {
2421 MOZ_ASSERT(CurrentThreadCanAccessZone(zone) || CurrentThreadIsPerformingGC());
2422 return minorState.refNoCheck() == State::Sweeping ||
2423 majorState.refNoCheck() == State::Sweeping;
2424 }
2425
2426 LargeBuffer* BufferAllocator::lookupLargeBuffer(void* alloc) {
2427 MaybeLock lock;
2428 return lookupLargeBuffer(alloc, lock);
2429 }
2430
2431 LargeBuffer* BufferAllocator::lookupLargeBuffer(void* alloc, MaybeLock& lock) {
2432 MOZ_ASSERT(lock.isNothing());
2433 if (needLockToAccessBufferMap()) {
2434 lock.emplace(this);
2435 }
2436
2437 auto ptr = largeAllocMap.ref().lookup(alloc);
2438 MOZ_ASSERT(ptr);
2439 LargeBuffer* buffer = ptr->value();
2440 MOZ_ASSERT(buffer->data() == alloc);
2441 MOZ_ASSERT(buffer->zoneFromAnyThread() == zone);
2442 return buffer;
2443 }
2444
2445 void* BufferAllocator::allocLarge(size_t bytes, bool nurseryOwned, bool inGC) {
2446 bytes = RoundUp(bytes, ChunkSize);
2447 MOZ_ASSERT(bytes > MaxMediumAllocSize);
2448 MOZ_ASSERT(bytes >= bytes);
2449
2450 // Allocate a small buffer the size of a LargeBuffer to hold the metadata.
2451 static_assert(sizeof(LargeBuffer) <= MaxSmallAllocSize);
2452 void* bufferPtr = allocSmall(sizeof(LargeBuffer), nurseryOwned);
2453 if (!bufferPtr) {
2454 return nullptr;
2455 }
2456
2457 // Large allocations are aligned to the chunk size, even if they are smaller
2458 // than a chunk. This allows us to tell large buffer allocations apart by
2459 // looking at the pointer alignment.
2460 void* alloc = MapAlignedPages(bytes, ChunkSize, ShouldStallAndRetry(inGC));
2461 if (!alloc) {
2462 return nullptr;
2463 }
2464 auto freeGuard = mozilla::MakeScopeExit([&]() { UnmapPages(alloc, bytes); });
2465
2466 CheckHighBitsOfPointer(alloc);
2467
2468 auto* buffer = new (bufferPtr) LargeBuffer(alloc, bytes, nurseryOwned);
2469
2470 {
2471 MaybeLock lock;
2472 if (needLockToAccessBufferMap()) {
2473 lock.emplace(this);
2474 }
2475 if (!largeAllocMap.ref().putNew(alloc, buffer)) {
2476 return nullptr;
2477 }
2478 }
2479
2480 freeGuard.release();
2481
2482 if (nurseryOwned) {
2483 largeNurseryAllocs.ref().pushBack(buffer);
2484 } else {
2485 buffer->allocatedDuringCollection = majorState != State::NotCollecting;
2486 largeTenuredAllocs.ref().pushBack(buffer);
2487 }
2488
2489 // Update memory accounting and trigger an incremental slice if needed.
2490 if (!nurseryOwned) {
2491 bool checkThresholds = !inGC;
2492 updateHeapSize(bytes, checkThresholds, false);
2493 }
2494
2495 MOZ_ASSERT(IsLargeAlloc(alloc));
2496 return alloc;
2497 }
2498
2499 void BufferAllocator::updateHeapSize(size_t bytes, bool checkThresholds,
2500 bool updateRetainedSize) {
2501 // Update memory accounting and trigger an incremental slice if needed.
2502 // TODO: This will eventually be attributed to gcHeapSize.
2503 zone->mallocHeapSize.addBytes(bytes, updateRetainedSize);
2504 if (checkThresholds) {
2505 GCRuntime* gc = &zone->runtimeFromAnyThread()->gc;
2506 gc->maybeTriggerGCAfterMalloc(zone);
2507 }
2508 }
2509
2510 /* static */
2511 bool BufferAllocator::IsLargeAlloc(void* alloc) {
2512 return (uintptr_t(alloc) & ChunkMask) == 0;
2513 }
2514
2515 bool BufferAllocator::isLargeAllocMarked(void* alloc) {
2516 LargeBuffer* buffer = lookupLargeBuffer(alloc);
2517 return buffer->headerCell()->isMarkedAny();
2518 }
2519
2520 bool BufferAllocator::markLargeTenuredBuffer(LargeBuffer* buffer) {
2521 MOZ_ASSERT(!buffer->isNurseryOwned);
2522
2523 if (buffer->allocatedDuringCollection) {
2524 return false;
2525 }
2526
2527 // Bug 1961755: This method can return false positives. A fully atomic version
2528 // would be preferable in this case.
2529 return buffer->headerCell()->markIfUnmarkedThreadSafe(MarkColor::Black);
2530 }
2531
2532 bool BufferAllocator::sweepLargeTenured(LargeBuffer* buffer) {
2533 MOZ_ASSERT(!buffer->isNurseryOwned);
2534 MOZ_ASSERT(buffer->zoneFromAnyThread() == zone);
2535 MOZ_ASSERT(!buffer->isInList());
2536
2537 if (buffer->headerCell()->isMarkedAny()) {
2538 return true;
2539 }
2540
2541 MaybeLock lock(std::in_place, this);
2542 unmapLarge(buffer, true, lock);
2543 return false;
2544 }
2545
2546 void BufferAllocator::freeLarge(void* alloc) {
2547 MaybeLock lock;
2548 LargeBuffer* buffer = lookupLargeBuffer(alloc, lock);
2549 MOZ_ASSERT(buffer->zone() == zone);
2550
2551 DebugOnlyPoison(alloc, JS_FREED_BUFFER_PATTERN, buffer->allocBytes(),
2552 MemCheckKind::MakeUndefined);
2553
2554 if (!buffer->isNurseryOwned && majorState == State::Sweeping &&
2555 !buffer->allocatedDuringCollection) {
2556 return; // Large allocations are currently being swept.
2557 }
2558
2559 MOZ_ASSERT(buffer->isInList());
2560
2561 if (buffer->isNurseryOwned) {
2562 largeNurseryAllocs.ref().remove(buffer);
2563 } else if (majorState == State::Marking &&
2564 !buffer->allocatedDuringCollection) {
2565 largeTenuredAllocsToSweep.ref().remove(buffer);
2566 } else {
2567 largeTenuredAllocs.ref().remove(buffer);
2568 }
2569
2570 unmapLarge(buffer, false, lock);
2571 }
2572
2573 bool BufferAllocator::shrinkLarge(LargeBuffer* buffer, size_t newBytes) {
2574 MOZ_ASSERT(IsLargeAllocSize(newBytes));
2575 #ifdef XP_WIN
2576 // Can't unmap part of a region mapped with VirtualAlloc on Windows.
2577 //
2578 // It is possible to decommit the physical pages so we could do that and
2579 // track virtual size as well as committed size. This would also allow us to
2580 // grow the allocation again if necessary.
2581 return false;
2582 #else
2583 MOZ_ASSERT(buffer->zone() == zone);
2584
2585 if (!buffer->isNurseryOwned && majorState == State::Sweeping &&
2586 !buffer->allocatedDuringCollection) {
2587 return false; // Large allocations are currently being swept.
2588 }
2589
2590 MOZ_ASSERT(buffer->isInList());
2591
2592 newBytes = RoundUp(newBytes, ChunkSize);
2593 size_t oldBytes = buffer->bytes;
2594 MOZ_ASSERT(oldBytes > newBytes);
2595 size_t shrinkBytes = oldBytes - newBytes;
2596
2597 if (!buffer->isNurseryOwned) {
2598 zone->mallocHeapSize.removeBytes(shrinkBytes, false);
2599 }
2600
2601 buffer->bytes = newBytes;
2602
2603 void* endPtr = reinterpret_cast<void*>(uintptr_t(buffer->data()) + newBytes);
2604 UnmapPages(endPtr, shrinkBytes);
2605
2606 return true;
2607 #endif
2608 }
2609
2610 void BufferAllocator::unmapLarge(LargeBuffer* buffer, bool isSweeping,
2611 MaybeLock& lock) {
2612 MOZ_ASSERT(buffer->zoneFromAnyThread() == zone);
2613 MOZ_ASSERT(!buffer->isInList());
2614 MOZ_ASSERT_IF(isSweeping || needLockToAccessBufferMap(), lock.isSome());
2615
2616 #ifdef DEBUG
2617 auto ptr = largeAllocMap.ref().lookup(buffer->data());
2618 MOZ_ASSERT(ptr && ptr->value() == buffer);
2619 #endif
2620 largeAllocMap.ref().remove(buffer->data());
2621
2622 // Drop the lock now we've updated the map.
2623 lock.reset();
2624
2625 size_t bytes = buffer->bytes;
2626
2627 if (!buffer->isNurseryOwned) {
2628 zone->mallocHeapSize.removeBytes(bytes, isSweeping);
2629 }
2630
2631 UnmapPages(buffer->data(), bytes);
2632 }
2633
2634 #include "js/Printer.h"
2635 #include "util/GetPidProvider.h"
2636
2637 static const char* const BufferAllocatorStatsPrefix = "BufAllc:";
2638
2639 #define FOR_EACH_BUFFER_STATS_FIELD(_) \
2640 _("PID", 7, "%7zu", pid) \
2641 _("Runtime", 14, "0x%12p", runtime) \
2642 _("Timestamp", 10, "%10.6f", timestamp.ToSeconds()) \
2643 _("Reason", 20, "%-20.20s", reason) \
2644 _("", 2, "%2s", "") \
2645 _("TotalKB", 8, "%8zu", totalBytes / 1024) \
2646 _("UsedKB", 8, "%8zu", usedBytes / 1024) \
2647 _("FreeKB", 8, "%8zu", freeBytes / 1024) \
2648 _("Zs", 3, "%3zu", zoneCount) \
2649 _("", 7, "%7s", "") \
2650 _("MNCs", 6, "%6zu", mediumMixedChunks) \
2651 _("MTCs", 6, "%6zu", mediumTenuredChunks) \
2652 _("FRs", 6, "%6zu", freeRegions) \
2653 _("LNAs", 6, "%6zu", largeNurseryAllocs) \
2654 _("LTAs", 6, "%6zu", largeTenuredAllocs)
2655
2656 /* static */
2657 void BufferAllocator::printStatsHeader(FILE* file) {
2658 Sprinter sprinter;
2659 if (!sprinter.init()) {
2660 return;
2661 }
2662 sprinter.put(BufferAllocatorStatsPrefix);
2663
2664 #define PRINT_METADATA_NAME(name, width, _1, _2) \
2665 sprinter.printf(" %-*s", width, name);
2666
2667 FOR_EACH_BUFFER_STATS_FIELD(PRINT_METADATA_NAME)
2668 #undef PRINT_METADATA_NAME
2669
2670 sprinter.put("\n");
2671
2672 JS::UniqueChars str = sprinter.release();
2673 if (!str) {
2674 return;
2675 }
2676 fputs(str.get(), file);
2677 }
2678
2679 /* static */
2680 void BufferAllocator::printStats(GCRuntime* gc, mozilla::TimeStamp creationTime,
2681 bool isMajorGC, FILE* file) {
2682 Sprinter sprinter;
2683 if (!sprinter.init()) {
2684 return;
2685 }
2686 sprinter.put(BufferAllocatorStatsPrefix);
2687
2688 size_t pid = getpid();
2689 JSRuntime* runtime = gc->rt;
2690 mozilla::TimeDuration timestamp = mozilla::TimeStamp::Now() - creationTime;
2691 const char* reason = isMajorGC ? "post major slice" : "pre minor GC";
2692
2693 size_t zoneCount = 0;
2694 size_t usedBytes = 0;
2695 size_t freeBytes = 0;
2696 size_t adminBytes = 0;
2697 size_t mediumMixedChunks = 0;
2698 size_t mediumTenuredChunks = 0;
2699 size_t freeRegions = 0;
2700 size_t largeNurseryAllocs = 0;
2701 size_t largeTenuredAllocs = 0;
2702 for (AllZonesIter zone(gc); !zone.done(); zone.next()) {
2703 zoneCount++;
2704 zone->bufferAllocator.getStats(usedBytes, freeBytes, adminBytes,
2705 mediumMixedChunks, mediumTenuredChunks,
2706 freeRegions, largeNurseryAllocs,
2707 largeTenuredAllocs);
2708 }
2709
2710 size_t totalBytes = usedBytes + freeBytes + adminBytes;
2711
2712 #define PRINT_FIELD_VALUE(_1, _2, format, value) \
2713 sprinter.printf(" " format, value);
2714
2715 FOR_EACH_BUFFER_STATS_FIELD(PRINT_FIELD_VALUE)
2716 #undef PRINT_FIELD_VALUE
2717
2718 sprinter.put("\n");
2719
2720 JS::UniqueChars str = sprinter.release();
2721 if (!str) {
2722 return;
2723 }
2724
2725 fputs(str.get(), file);
2726 }
2727
2728 size_t BufferAllocator::getSizeOfNurseryBuffers() {
2729 maybeMergeSweptData();
2730
2731 MOZ_ASSERT(minorState == State::NotCollecting);
2732 MOZ_ASSERT(majorState == State::NotCollecting);
2733
2734 size_t bytes = 0;
2735
2736 for (BufferChunk* chunk : mediumMixedChunks.ref()) {
2737 for (BufferChunkIter alloc(chunk); !alloc.done(); alloc.next()) {
2738 if (chunk->isNurseryOwned(alloc)) {
2739 bytes += chunk->allocBytes(alloc);
2740 }
2741 }
2742 }
2743
2744 for (const LargeBuffer* buffer : largeNurseryAllocs.ref()) {
2745 bytes += buffer->allocBytes();
2746 }
2747
2748 return bytes;
2749 }
2750
2751 void BufferAllocator::addSizeOfExcludingThis(size_t* usedBytesOut,
2752 size_t* freeBytesOut,
2753 size_t* adminBytesOut) {
2754 maybeMergeSweptData();
2755
2756 MOZ_ASSERT(minorState == State::NotCollecting);
2757 MOZ_ASSERT(majorState == State::NotCollecting);
2758
2759 size_t usedBytes = 0;
2760 size_t freeBytes = 0;
2761 size_t adminBytes = 0;
2762 size_t mediumMixedChunks = 0;
2763 size_t mediumTenuredChunks = 0;
2764 size_t freeRegions = 0;
2765 size_t largeNurseryAllocs = 0;
2766 size_t largeTenuredAllocs = 0;
2767 getStats(usedBytes, freeBytes, adminBytes, mediumMixedChunks,
2768 mediumTenuredChunks, freeRegions, largeNurseryAllocs,
2769 largeTenuredAllocs);
2770
2771 *usedBytesOut += usedBytes;
2772 *freeBytesOut += freeBytes;
2773 *adminBytesOut += adminBytes;
2774 }
2775
2776 void BufferAllocator::getStats(size_t& usedBytes, size_t& freeBytes,
2777 size_t& adminBytes,
2778 size_t& mediumNurseryChunkCount,
2779 size_t& mediumTenuredChunkCount,
2780 size_t& freeRegions,
2781 size_t& largeNurseryAllocCount,
2782 size_t& largeTenuredAllocCount) {
2783 maybeMergeSweptData();
2784
2785 MOZ_ASSERT(minorState == State::NotCollecting);
2786
2787 for (const BufferChunk* chunk : mediumMixedChunks.ref()) {
2788 (void)chunk;
2789 mediumNurseryChunkCount++;
2790 usedBytes += ChunkSize - FirstMediumAllocOffset;
2791 adminBytes += FirstMediumAllocOffset;
2792 }
2793 for (const BufferChunk* chunk : mediumTenuredChunks.ref()) {
2794 (void)chunk;
2795 mediumTenuredChunkCount++;
2796 usedBytes += ChunkSize - FirstMediumAllocOffset;
2797 adminBytes += FirstMediumAllocOffset;
2798 }
2799 for (const LargeBuffer* buffer : largeNurseryAllocs.ref()) {
2800 largeNurseryAllocCount++;
2801 usedBytes += buffer->allocBytes();
2802 adminBytes += sizeof(LargeBuffer);
2803 }
2804 for (const LargeBuffer* buffer : largeTenuredAllocs.ref()) {
2805 largeTenuredAllocCount++;
2806 usedBytes += buffer->allocBytes();
2807 adminBytes += sizeof(LargeBuffer);
2808 }
2809 for (const FreeList& freeList : mediumFreeLists.ref()) {
2810 for (const FreeRegion* region : freeList) {
2811 freeRegions++;
2812 size_t size = region->size();
2813 MOZ_ASSERT(usedBytes >= size);
2814 usedBytes -= size;
2815 freeBytes += size;
2816 }
2817 }
2818 }
2819
2820 JS::ubi::Node::Size JS::ubi::Concrete<SmallBuffer>::size(
2821 mozilla::MallocSizeOf mallocSizeOf) const {
2822 return get().allocBytes();
2823 }
2824
2825 const char16_t JS::ubi::Concrete<SmallBuffer>::concreteTypeName[] =
2826 u"SmallBuffer";