Debian Codegraph @

js/src/gc/Nursery.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sw=2 et tw=80:
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
6 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7
8 #include "gc/Nursery-inl.h"
9
10 #include "mozilla/DebugOnly.h"
11 #include "mozilla/IntegerPrintfMacros.h"
12 #include "mozilla/Maybe.h"
13 #include "mozilla/ScopeExit.h"
14 #include "mozilla/Sprintf.h"
15 #include "mozilla/TimeStamp.h"
16
17 #include <algorithm>
18 #include <cmath>
19 #include <utility>
20
21 #include "builtin/MapObject.h"
22 #include "debugger/DebugAPI.h"
23 #include "gc/Allocator.h"
24 #include "gc/GCInternals.h"
25 #include "gc/GCLock.h"
26 #include "gc/GCParallelTask.h"
27 #include "gc/Memory.h"
28 #include "gc/PublicIterators.h"
29 #include "gc/Tenuring.h"
30 #include "jit/JitFrames.h"
31 #include "jit/JitZone.h"
32 #include "js/Printer.h"
33 #include "util/DifferentialTesting.h"
34 #include "util/GetPidProvider.h" // getpid()
35 #include "util/Poison.h"
36 #include "vm/JSONPrinter.h"
37 #include "vm/Realm.h"
38 #include "vm/Time.h"
39
40 #include "gc/BufferAllocator-inl.h"
41 #include "gc/Heap-inl.h"
42 #include "gc/Marking-inl.h"
43 #include "gc/StableCellHasher-inl.h"
44 #include "gc/StoreBuffer-inl.h"
45 #include "vm/GeckoProfiler-inl.h"
46
47 using namespace js;
48 using namespace js::gc;
49
50 using mozilla::DebugOnly;
51 using mozilla::PodCopy;
52 using mozilla::TimeDuration;
53 using mozilla::TimeStamp;
54
55 namespace js {
56
57 static constexpr size_t NurseryChunkHeaderSize =
58 RoundUp(sizeof(ChunkBase), CellAlignBytes);
59
60 // The amount of space in a nursery chunk available to allocations.
61 static constexpr size_t NurseryChunkUsableSize =
62 ChunkSize - NurseryChunkHeaderSize;
63
64 struct NurseryChunk : public ChunkBase {
65 alignas(CellAlignBytes) uint8_t data[NurseryChunkUsableSize];
66
67 static NurseryChunk* fromChunk(ArenaChunk* chunk, ChunkKind kind,
68 uint8_t index);
69
70 explicit NurseryChunk(JSRuntime* runtime, ChunkKind kind, uint8_t chunkIndex)
71 : ChunkBase(runtime, &runtime->gc.storeBuffer(), kind, chunkIndex) {}
72
73 void poisonRange(size_t start, size_t end, uint8_t value,
74 MemCheckKind checkKind);
75 void poisonAfterEvict(size_t extent = ChunkSize);
76
77 // Mark pages from startOffset to the end of the chunk as unused. The start
78 // offset must be after the first page, which contains the chunk header and is
79 // not marked as unused.
80 void markPagesUnusedHard(size_t startOffset);
81
82 // Mark pages from the second page of the chunk to endOffset as in use,
83 // following a call to markPagesUnusedHard.
84 [[nodiscard]] bool markPagesInUseHard(size_t endOffset);
85
86 uintptr_t start() const { return uintptr_t(&data); }
87 uintptr_t end() const { return uintptr_t(this) + ChunkSize; }
88 };
89 static_assert(sizeof(NurseryChunk) == ChunkSize,
90 "Nursery chunk size must match Chunk size.");
91 static_assert(offsetof(NurseryChunk, data) == NurseryChunkHeaderSize);
92
93 class NurserySweepTask : public GCParallelTask {
94 SlimLinkedList<BufferAllocator> allocatorsToSweep;
95
96 public:
97 explicit NurserySweepTask(gc::GCRuntime* gc)
98 : GCParallelTask(gc, gcstats::PhaseKind::NONE) {}
99
100 bool isEmpty(AutoLockHelperThreadState& lock) const {
101 return allocatorsToSweep.isEmpty();
102 }
103
104 void queueAllocatorToSweep(BufferAllocator& allocator) {
105 MOZ_ASSERT(isIdle());
106 allocatorsToSweep.pushBack(&allocator);
107 }
108
109 private:
110 void run(AutoLockHelperThreadState& lock) override;
111 };
112
113 class NurseryDecommitTask : public GCParallelTask {
114 public:
115 explicit NurseryDecommitTask(gc::GCRuntime* gc);
116 bool reserveSpaceForChunks(size_t nchunks);
117
118 bool isEmpty(const AutoLockHelperThreadState& lock) const;
119
120 void queueChunk(NurseryChunk* chunk, const AutoLockHelperThreadState& lock);
121 void queueRange(size_t newCapacity, NurseryChunk* chunk,
122 const AutoLockHelperThreadState& lock);
123
124 private:
125 struct Region {
126 NurseryChunk* chunk;
127 size_t startOffset;
128 };
129
130 using NurseryChunkVector = Vector<NurseryChunk*, 0, SystemAllocPolicy>;
131 using RegionVector = Vector<Region, 2, SystemAllocPolicy>;
132
133 void run(AutoLockHelperThreadState& lock) override;
134
135 NurseryChunkVector& chunksToDecommit() { return chunksToDecommit_.ref(); }
136 const NurseryChunkVector& chunksToDecommit() const {
137 return chunksToDecommit_.ref();
138 }
139 RegionVector& regionsToDecommit() { return regionsToDecommit_.ref(); }
140 const RegionVector& regionsToDecommit() const {
141 return regionsToDecommit_.ref();
142 }
143
144 MainThreadOrGCTaskData<NurseryChunkVector> chunksToDecommit_;
145 MainThreadOrGCTaskData<RegionVector> regionsToDecommit_;
146 };
147
148 } // namespace js
149
150 inline void js::NurseryChunk::poisonRange(size_t start, size_t end,
151 uint8_t value,
152 MemCheckKind checkKind) {
153 MOZ_ASSERT(start >= NurseryChunkHeaderSize);
154 MOZ_ASSERT((start % gc::CellAlignBytes) == 0);
155 MOZ_ASSERT((end % gc::CellAlignBytes) == 0);
156 MOZ_ASSERT(end >= start);
157 MOZ_ASSERT(end <= ChunkSize);
158
159 auto* ptr = reinterpret_cast<uint8_t*>(this) + start;
160 size_t size = end - start;
161
162 // We can poison the same chunk more than once, so first make sure memory
163 // sanitizers will let us poison it.
164 MOZ_MAKE_MEM_UNDEFINED(ptr, size);
165 Poison(ptr, value, size, checkKind);
166 }
167
168 inline void js::NurseryChunk::poisonAfterEvict(size_t extent) {
169 poisonRange(NurseryChunkHeaderSize, extent, JS_SWEPT_NURSERY_PATTERN,
170 MemCheckKind::MakeNoAccess);
171 }
172
173 inline void js::NurseryChunk::markPagesUnusedHard(size_t startOffset) {
174 MOZ_ASSERT(startOffset >= NurseryChunkHeaderSize); // Don't touch the header.
175 MOZ_ASSERT(startOffset >= SystemPageSize());
176 MOZ_ASSERT(startOffset <= ChunkSize);
177 uintptr_t start = uintptr_t(this) + startOffset;
178 size_t length = ChunkSize - startOffset;
179 MarkPagesUnusedHard(reinterpret_cast<void*>(start), length);
180 }
181
182 inline bool js::NurseryChunk::markPagesInUseHard(size_t endOffset) {
183 MOZ_ASSERT(endOffset >= NurseryChunkHeaderSize);
184 MOZ_ASSERT(endOffset >= SystemPageSize());
185 MOZ_ASSERT(endOffset <= ChunkSize);
186 uintptr_t start = uintptr_t(this) + SystemPageSize();
187 size_t length = endOffset - SystemPageSize();
188 return MarkPagesInUseHard(reinterpret_cast<void*>(start), length);
189 }
190
191 // static
192 inline js::NurseryChunk* js::NurseryChunk::fromChunk(ArenaChunk* chunk,
193 ChunkKind kind,
194 uint8_t index) {
195 return new (chunk) NurseryChunk(chunk->runtime, kind, index);
196 }
197
198 void js::NurserySweepTask::run(AutoLockHelperThreadState& lock) {
199 SlimLinkedList<BufferAllocator> allocators;
200 std::swap(allocators, allocatorsToSweep);
201 AutoUnlockHelperThreadState unlock(lock);
202
203 while (!allocators.isEmpty()) {
204 BufferAllocator* allocator = allocators.popFirst();
205 allocator->sweepForMinorCollection();
206 }
207 }
208
209 js::NurseryDecommitTask::NurseryDecommitTask(gc::GCRuntime* gc)
210 : GCParallelTask(gc, gcstats::PhaseKind::NONE) {
211 // This can occur outside GCs so doesn't have a stats phase.
212 MOZ_ALWAYS_TRUE(regionsToDecommit().reserve(2));
213 }
214
215 bool js::NurseryDecommitTask::isEmpty(
216 const AutoLockHelperThreadState& lock) const {
217 return chunksToDecommit().empty() && regionsToDecommit().empty();
218 }
219
220 bool js::NurseryDecommitTask::reserveSpaceForChunks(size_t nchunks) {
221 MOZ_ASSERT(isIdle());
222 return chunksToDecommit().reserve(nchunks);
223 }
224
225 void js::NurseryDecommitTask::queueChunk(
226 NurseryChunk* chunk, const AutoLockHelperThreadState& lock) {
227 MOZ_ASSERT(isIdle(lock));
228 MOZ_ALWAYS_TRUE(chunksToDecommit().append(chunk));
229 }
230
231 void js::NurseryDecommitTask::queueRange(
232 size_t newCapacity, NurseryChunk* chunk,
233 const AutoLockHelperThreadState& lock) {
234 MOZ_ASSERT(isIdle(lock));
235 MOZ_ASSERT(regionsToDecommit_.ref().length() < 2);
236 MOZ_ASSERT(newCapacity < ChunkSize);
237 MOZ_ASSERT(newCapacity % SystemPageSize() == 0);
238
239 regionsToDecommit().infallibleAppend(Region{chunk, newCapacity});
240 }
241
242 void js::NurseryDecommitTask::run(AutoLockHelperThreadState& lock) {
243 while (!chunksToDecommit().empty()) {
244 NurseryChunk* nurseryChunk = chunksToDecommit().popCopy();
245 AutoUnlockHelperThreadState unlock(lock);
246 nurseryChunk->~NurseryChunk();
247 ArenaChunk* tenuredChunk =
248 ArenaChunk::emplace(nurseryChunk, gc, /* allMemoryCommitted = */ false);
249 AutoLockGC lock(gc);
250 gc->recycleChunk(tenuredChunk, lock);
251 }
252
253 while (!regionsToDecommit().empty()) {
254 Region region = regionsToDecommit().popCopy();
255 AutoUnlockHelperThreadState unlock(lock);
256 region.chunk->markPagesUnusedHard(region.startOffset);
257 }
258 }
259
260 js::Nursery::Nursery(GCRuntime* gc)
261 : toSpace(ChunkKind::NurseryToSpace),
262 fromSpace(ChunkKind::NurseryFromSpace),
263 gc(gc),
264 capacity_(0),
265 enableProfiling_(false),
266 semispaceEnabled_(gc::TuningDefaults::SemispaceNurseryEnabled),
267 canAllocateStrings_(true),
268 canAllocateBigInts_(true),
269 reportDeduplications_(false),
270 minorGCTriggerReason_(JS::GCReason::NO_REASON),
271 prevPosition_(0),
272 hasRecentGrowthData(false),
273 smoothedTargetSize(0.0) {
274 // Try to keep fields used by allocation fast path together at the start of
275 // the nursery.
276 static_assert(offsetof(Nursery, toSpace.position_) < TypicalCacheLineSize);
277 static_assert(offsetof(Nursery, toSpace.currentEnd_) < TypicalCacheLineSize);
278
279 const char* env = getenv("MOZ_NURSERY_STRINGS");
280 if (env && *env) {
281 canAllocateStrings_ = (*env == '1');
282 }
283 env = getenv("MOZ_NURSERY_BIGINTS");
284 if (env && *env) {
285 canAllocateBigInts_ = (*env == '1');
286 }
287 }
288
289 static void PrintAndExit(const char* message) {
290 fprintf(stderr, "%s", message);
291 exit(0);
292 }
293
294 static const char* GetEnvVar(const char* name, const char* helpMessage) {
295 const char* value = getenv(name);
296 if (!value) {
297 return nullptr;
298 }
299
300 if (strcmp(value, "help") == 0) {
301 PrintAndExit(helpMessage);
302 }
303
304 return value;
305 }
306
307 static bool GetBoolEnvVar(const char* name, const char* helpMessage) {
308 const char* env = GetEnvVar(name, helpMessage);
309 return env && bool(atoi(env));
310 }
311
312 static void ReadReportPretenureEnv(const char* name, const char* helpMessage,
313 AllocSiteFilter* filter) {
314 const char* env = GetEnvVar(name, helpMessage);
315 if (!env) {
316 return;
317 }
318
319 if (!AllocSiteFilter::readFromString(env, filter)) {
320 PrintAndExit(helpMessage);
321 }
322 }
323
324 bool js::Nursery::init(AutoLockGCBgAlloc& lock) {
325 ReadProfileEnv("JS_GC_PROFILE_NURSERY",
326 "Report minor GCs taking at least N microseconds.\n",
327 &enableProfiling_, &profileWorkers_, &profileThreshold_);
328
329 reportDeduplications_ = GetBoolEnvVar(
330 "JS_GC_REPORT_STATS",
331 "JS_GC_REPORT_STATS=1\n"
332 "\tAfter a minor GC, report how many strings were deduplicated.\n");
333
334 #ifdef JS_GC_ZEAL
335 reportPromotion_ = GetBoolEnvVar(
336 "JS_GC_REPORT_PROMOTE",
337 "JS_GC_REPORT_PROMOTE=1\n"
338 "\tAfter a minor GC, report what kinds of things were promoted.\n");
339 #endif
340
341 ReadReportPretenureEnv(
342 "JS_GC_REPORT_PRETENURE",
343 "JS_GC_REPORT_PRETENURE=FILTER\n"
344 "\tAfter a minor GC, report information about pretenuring, including\n"
345 "\tallocation sites which match the filter specification. This is comma\n"
346 "\tseparated list of one or more elements which can include:\n"
347 "\t\tinteger N: report sites with at least N allocations\n"
348 "\t\t'normal': report normal sites used for pretenuring\n"
349 "\t\t'unknown': report catch-all sites for allocations without a\n"
350 "\t\t specific site associated with them\n"
351 "\t\t'optimized': report catch-all sites for allocations from\n"
352 "\t\t optimized JIT code\n"
353 "\t\t'missing': report automatically generated missing sites\n"
354 "\t\t'object': report sites associated with JS objects\n"
355 "\t\t'string': report sites associated with JS strings\n"
356 "\t\t'bigint': report sites associated with JS big ints\n"
357 "\t\t'longlived': report sites in the LongLived state (ignored for\n"
358 "\t\t catch-all sites)\n"
359 "\t\t'shortlived': report sites in the ShortLived state (ignored for\n"
360 "\t\t catch-all sites)\n"
361 "\tFilters of the same kind are combined with OR and of different kinds\n"
362 "\twith AND. Prefixes of the keywords above are accepted.\n",
363 &pretenuringReportFilter_);
364
365 sweepTask = MakeUnique<NurserySweepTask>(gc);
366 if (!sweepTask) {
367 return false;
368 }
369
370 decommitTask = MakeUnique<NurseryDecommitTask>(gc);
371 if (!decommitTask) {
372 return false;
373 }
374
375 if (!gc->storeBuffer().enable()) {
376 return false;
377 }
378
379 return initFirstChunk(lock);
380 }
381
382 js::Nursery::~Nursery() { disable(); }
383
384 void js::Nursery::enable() {
385 MOZ_ASSERT(TlsContext.get()->generationalDisabled == 0);
386
387 if (isEnabled()) {
388 return;
389 }
390
391 MOZ_ASSERT(isEmpty());
392 MOZ_ASSERT(!gc->isVerifyPreBarriersEnabled());
393
394 {
395 AutoLockGCBgAlloc lock(gc);
396 if (!initFirstChunk(lock)) {
397 // If we fail to allocate memory, the nursery will not be enabled.
398 return;
399 }
400 }
401
402 #ifdef JS_GC_ZEAL
403 if (gc->hasZealMode(ZealMode::GenerationalGC)) {
404 enterZealMode();
405 }
406 #endif
407
408 updateAllZoneAllocFlags();
409
410 // This should always succeed after the first time it's called.
411 MOZ_ALWAYS_TRUE(gc->storeBuffer().enable());
412 }
413
414 bool js::Nursery::initFirstChunk(AutoLockGCBgAlloc& lock) {
415 MOZ_ASSERT(!isEnabled());
416 MOZ_ASSERT(toSpace.chunks_.length() == 0);
417 MOZ_ASSERT(fromSpace.chunks_.length() == 0);
418
419 setCapacity(minSpaceSize());
420
421 size_t nchunks = toSpace.maxChunkCount_ + fromSpace.maxChunkCount_;
422 if (!decommitTask->reserveSpaceForChunks(nchunks) ||
423 !allocateNextChunk(lock)) {
424 setCapacity(0);
425 MOZ_ASSERT(toSpace.isEmpty());
426 MOZ_ASSERT(fromSpace.isEmpty());
427 return false;
428 }
429
430 toSpace.moveToStartOfChunk(this, 0);
431 toSpace.setStartToCurrentPosition();
432
433 if (semispaceEnabled_) {
434 fromSpace.moveToStartOfChunk(this, 0);
435 fromSpace.setStartToCurrentPosition();
436 }
437
438 MOZ_ASSERT(toSpace.isEmpty());
439 MOZ_ASSERT(fromSpace.isEmpty());
440
441 poisonAndInitCurrentChunk();
442
443 // Clear any information about previous collections.
444 clearRecentGrowthData();
445
446 tenureThreshold_ = 0;
447
448 #ifdef DEBUG
449 toSpace.checkKind(ChunkKind::NurseryToSpace);
450 fromSpace.checkKind(ChunkKind::NurseryFromSpace);
451 #endif
452
453 return true;
454 }
455
456 size_t RequiredChunkCount(size_t nbytes) {
457 return nbytes <= ChunkSize ? 1 : nbytes / ChunkSize;
458 }
459
460 void js::Nursery::setCapacity(size_t newCapacity) {
461 MOZ_ASSERT(newCapacity == roundSize(newCapacity));
462 capacity_ = newCapacity;
463 size_t count = RequiredChunkCount(newCapacity);
464 toSpace.maxChunkCount_ = count;
465 if (semispaceEnabled_) {
466 fromSpace.maxChunkCount_ = count;
467 }
468 }
469
470 void js::Nursery::disable() {
471 MOZ_ASSERT(isEmpty());
472 if (!isEnabled()) {
473 return;
474 }
475
476 // Wait for any background tasks.
477 sweepTask->join();
478 decommitTask->join();
479
480 // Free all chunks.
481 freeChunksFrom(toSpace, 0);
482 freeChunksFrom(fromSpace, 0);
483 decommitTask->runFromMainThread();
484
485 setCapacity(0);
486
487 // We must reset currentEnd_ so that there is no space for anything in the
488 // nursery. JIT'd code uses this even if the nursery is disabled.
489 toSpace = Space(ChunkKind::NurseryToSpace);
490 fromSpace = Space(ChunkKind::NurseryFromSpace);
491 MOZ_ASSERT(toSpace.isEmpty());
492 MOZ_ASSERT(fromSpace.isEmpty());
493
494 gc->storeBuffer().disable();
495
496 if (gc->wasInitialized()) {
497 // This assumes there is an atoms zone.
498 updateAllZoneAllocFlags();
499 }
500 }
501
502 void js::Nursery::enableStrings() {
503 MOZ_ASSERT(isEmpty());
504 canAllocateStrings_ = true;
505 updateAllZoneAllocFlags();
506 }
507
508 void js::Nursery::disableStrings() {
509 MOZ_ASSERT(isEmpty());
510 canAllocateStrings_ = false;
511 updateAllZoneAllocFlags();
512 }
513
514 void js::Nursery::enableBigInts() {
515 MOZ_ASSERT(isEmpty());
516 canAllocateBigInts_ = true;
517 updateAllZoneAllocFlags();
518 }
519
520 void js::Nursery::disableBigInts() {
521 MOZ_ASSERT(isEmpty());
522 canAllocateBigInts_ = false;
523 updateAllZoneAllocFlags();
524 }
525
526 void js::Nursery::updateAllZoneAllocFlags() {
527 // The alloc flags are not relevant for the atoms zone, and flushing
528 // jit-related information can be problematic for the atoms zone.
529 for (ZonesIter zone(gc, SkipAtoms); !zone.done(); zone.next()) {
530 updateAllocFlagsForZone(zone);
531 }
532 }
533
534 void js::Nursery::getAllocFlagsForZone(JS::Zone* zone, bool* allocObjectsOut,
535 bool* allocStringsOut,
536 bool* allocBigIntsOut) {
537 *allocObjectsOut = isEnabled();
538 *allocStringsOut =
539 isEnabled() && canAllocateStrings() && !zone->nurseryStringsDisabled;
540 *allocBigIntsOut =
541 isEnabled() && canAllocateBigInts() && !zone->nurseryBigIntsDisabled;
542 }
543
544 void js::Nursery::setAllocFlagsForZone(JS::Zone* zone) {
545 bool allocObjects;
546 bool allocStrings;
547 bool allocBigInts;
548
549 getAllocFlagsForZone(zone, &allocObjects, &allocStrings, &allocBigInts);
550 zone->setNurseryAllocFlags(allocObjects, allocStrings, allocBigInts);
551 }
552
553 void js::Nursery::updateAllocFlagsForZone(JS::Zone* zone) {
554 bool allocObjects;
555 bool allocStrings;
556 bool allocBigInts;
557
558 getAllocFlagsForZone(zone, &allocObjects, &allocStrings, &allocBigInts);
559
560 if (allocObjects != zone->allocNurseryObjects() ||
561 allocStrings != zone->allocNurseryStrings() ||
562 allocBigInts != zone->allocNurseryBigInts()) {
563 CancelOffThreadIonCompile(zone);
564 zone->setNurseryAllocFlags(allocObjects, allocStrings, allocBigInts);
565 discardCodeAndSetJitFlagsForZone(zone);
566 }
567 }
568
569 void js::Nursery::discardCodeAndSetJitFlagsForZone(JS::Zone* zone) {
570 zone->forceDiscardJitCode(runtime()->gcContext());
571
572 if (jit::JitZone* jitZone = zone->jitZone()) {
573 jitZone->discardStubs();
574 jitZone->setStringsCanBeInNursery(zone->allocNurseryStrings());
575 }
576 }
577
578 void js::Nursery::setSemispaceEnabled(bool enabled) {
579 if (semispaceEnabled() == enabled) {
580 return;
581 }
582
583 bool wasEnabled = isEnabled();
584 if (wasEnabled) {
585 if (!isEmpty()) {
586 gc->minorGC(JS::GCReason::EVICT_NURSERY);
587 }
588 disable();
589 }
590
591 semispaceEnabled_ = enabled;
592
593 if (wasEnabled) {
594 enable();
595 }
596 }
597
598 bool js::Nursery::isEmpty() const {
599 MOZ_ASSERT(fromSpace.isEmpty());
600
601 if (!isEnabled()) {
602 return true;
603 }
604
605 if (!gc->hasZealMode(ZealMode::GenerationalGC)) {
606 MOZ_ASSERT(startChunk() == 0);
607 MOZ_ASSERT(startPosition() == chunk(0).start());
608 }
609
610 return toSpace.isEmpty();
611 }
612
613 bool js::Nursery::Space::isEmpty() const { return position_ == startPosition_; }
614
615 static size_t AdjustSizeForSemispace(size_t size, bool semispaceEnabled) {
616 if (!semispaceEnabled) {
617 return size;
618 }
619
620 return Nursery::roundSize(size / 2);
621 }
622
623 size_t js::Nursery::maxSpaceSize() const {
624 return AdjustSizeForSemispace(tunables().gcMaxNurseryBytes(),
625 semispaceEnabled_);
626 }
627
628 size_t js::Nursery::minSpaceSize() const {
629 return AdjustSizeForSemispace(tunables().gcMinNurseryBytes(),
630 semispaceEnabled_);
631 }
632
633 #ifdef JS_GC_ZEAL
634 void js::Nursery::enterZealMode() {
635 if (!isEnabled()) {
636 return;
637 }
638
639 MOZ_ASSERT(isEmpty());
640
641 decommitTask->join();
642
643 AutoEnterOOMUnsafeRegion oomUnsafe;
644
645 if (isSubChunkMode()) {
646 {
647 if (!chunk(0).markPagesInUseHard(ChunkSize)) {
648 oomUnsafe.crash("Out of memory trying to extend chunk for zeal mode");
649 }
650 }
651
652 // It'd be simpler to poison the whole chunk, but we can't do that
653 // because the nursery might be partially used.
654 chunk(0).poisonRange(capacity_, ChunkSize, JS_FRESH_NURSERY_PATTERN,
655 MemCheckKind::MakeUndefined);
656 }
657
658 setCapacity(maxSpaceSize());
659
660 size_t nchunks = toSpace.maxChunkCount_ + fromSpace.maxChunkCount_;
661 if (!decommitTask->reserveSpaceForChunks(nchunks)) {
662 oomUnsafe.crash("Nursery::enterZealMode");
663 }
664
665 setCurrentEnd();
666 }
667
668 void js::Nursery::leaveZealMode() {
669 if (!isEnabled()) {
670 return;
671 }
672
673 MOZ_ASSERT(isEmpty());
674
675 // Reset the nursery size.
676 setCapacity(minSpaceSize());
677
678 toSpace.moveToStartOfChunk(this, 0);
679 toSpace.setStartToCurrentPosition();
680
681 if (semispaceEnabled_) {
682 fromSpace.moveToStartOfChunk(this, 0);
683 fromSpace.setStartToCurrentPosition();
684 }
685
686 poisonAndInitCurrentChunk();
687 }
688 #endif // JS_GC_ZEAL
689
690 void* js::Nursery::allocateCell(gc::AllocSite* site, size_t size,
691 JS::TraceKind kind) {
692 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime()));
693
694 void* ptr = tryAllocateCell(site, size, kind);
695 if (MOZ_LIKELY(ptr)) {
696 return ptr;
697 }
698
699 if (handleAllocationFailure() != JS::GCReason::NO_REASON) {
700 return nullptr;
701 }
702
703 ptr = tryAllocateCell(site, size, kind);
704 MOZ_ASSERT(ptr);
705 return ptr;
706 }
707
708 inline void* js::Nursery::allocate(size_t size) {
709 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime()));
710
711 void* ptr = tryAllocate(size);
712 if (MOZ_LIKELY(ptr)) {
713 return ptr;
714 }
715
716 if (handleAllocationFailure() != JS::GCReason::NO_REASON) {
717 return nullptr;
718 }
719
720 ptr = tryAllocate(size);
721 MOZ_ASSERT(ptr);
722 return ptr;
723 }
724
725 MOZ_NEVER_INLINE JS::GCReason Nursery::handleAllocationFailure() {
726 if (minorGCRequested()) {
727 // If a minor GC was requested then fail the allocation. The collection is
728 // then run in GCRuntime::tryNewNurseryCell.
729 return minorGCTriggerReason_;
730 }
731
732 if (!moveToNextChunk()) {
733 return JS::GCReason::OUT_OF_NURSERY;
734 }
735
736 return JS::GCReason::NO_REASON;
737 }
738
739 bool Nursery::moveToNextChunk() {
740 unsigned chunkno = currentChunk() + 1;
741 MOZ_ASSERT(chunkno <= maxChunkCount());
742 MOZ_ASSERT(chunkno <= allocatedChunkCount());
743 if (chunkno == maxChunkCount()) {
744 return false;
745 }
746
747 if (chunkno == allocatedChunkCount()) {
748 TimeStamp start = TimeStamp::Now();
749 {
750 AutoLockGCBgAlloc lock(gc);
751 if (!allocateNextChunk(lock)) {
752 return false;
753 }
754 }
755 timeInChunkAlloc_ += TimeStamp::Now() - start;
756 MOZ_ASSERT(chunkno < allocatedChunkCount());
757 }
758
759 moveToStartOfChunk(chunkno);
760 poisonAndInitCurrentChunk();
761 return true;
762 }
763
764 std::tuple<void*, bool> js::Nursery::allocNurseryOrMallocBuffer(
765 Zone* zone, size_t nbytes, arena_id_t arenaId) {
766 MOZ_ASSERT(nbytes > 0);
767 MOZ_ASSERT(nbytes <= SIZE_MAX - gc::CellAlignBytes);
768 nbytes = RoundUp(nbytes, gc::CellAlignBytes);
769
770 if (nbytes <= MaxNurseryBufferSize) {
771 void* buffer = allocate(nbytes);
772 if (buffer) {
773 return {buffer, false};
774 }
775 }
776
777 void* buffer = zone->pod_arena_malloc<uint8_t>(arenaId, nbytes);
778 return {buffer, bool(buffer)};
779 }
780
781 std::tuple<void*, bool> js::Nursery::allocateBuffer(Zone* zone, size_t nbytes) {
782 MOZ_ASSERT(nbytes > 0);
783 MOZ_ASSERT(nbytes <= SIZE_MAX - gc::CellAlignBytes);
784 nbytes = RoundUp(nbytes, gc::CellAlignBytes);
785
786 if (nbytes <= MaxNurseryBufferSize) {
787 void* buffer = allocate(nbytes);
788 if (buffer) {
789 return {buffer, false};
790 }
791 }
792
793 void* buffer = AllocBuffer(zone, nbytes, true);
794 return {buffer, bool(buffer)};
795 }
796
797 void* js::Nursery::tryAllocateNurseryBuffer(JS::Zone* zone, size_t nbytes,
798 arena_id_t arenaId) {
799 MOZ_ASSERT(nbytes > 0);
800 MOZ_ASSERT(nbytes <= SIZE_MAX - gc::CellAlignBytes);
801 nbytes = RoundUp(nbytes, gc::CellAlignBytes);
802
803 if (nbytes <= MaxNurseryBufferSize) {
804 return allocate(nbytes);
805 }
806
807 return nullptr;
808 }
809
810 void* js::Nursery::allocNurseryOrMallocBuffer(Zone* zone, Cell* owner,
811 size_t nbytes,
812 arena_id_t arenaId) {
813 MOZ_ASSERT(owner);
814 MOZ_ASSERT(nbytes > 0);
815
816 if (!IsInsideNursery(owner)) {
817 return zone->pod_arena_malloc<uint8_t>(arenaId, nbytes);
818 }
819
820 auto [buffer, isMalloced] = allocNurseryOrMallocBuffer(zone, nbytes, arenaId);
821 if (isMalloced && !registerMallocedBuffer(buffer, nbytes)) {
822 js_free(buffer);
823 return nullptr;
824 }
825 return buffer;
826 }
827
828 void* js::Nursery::allocateBuffer(Zone* zone, Cell* owner, size_t nbytes) {
829 MOZ_ASSERT(owner);
830 MOZ_ASSERT(zone == owner->zone());
831 MOZ_ASSERT(nbytes > 0);
832
833 if (!IsInsideNursery(owner)) {
834 return AllocBuffer(zone, nbytes, false);
835 }
836
837 auto [buffer, isExternal] = allocateBuffer(zone, nbytes);
838 if (isExternal) {
839 registerBuffer(buffer, nbytes);
840 }
841 return buffer;
842 }
843
844 std::tuple<void*, bool> js::Nursery::allocateZeroedBuffer(Zone* zone,
845 size_t nbytes,
846 arena_id_t arena) {
847 MOZ_ASSERT(nbytes > 0);
848
849 if (nbytes <= MaxNurseryBufferSize) {
850 void* buffer = allocate(nbytes);
851 if (buffer) {
852 memset(buffer, 0, nbytes);
853 return {buffer, false};
854 }
855 }
856
857 void* buffer = zone->pod_arena_calloc<uint8_t>(arena, nbytes);
858 return {buffer, bool(buffer)};
859 }
860
861 void* js::Nursery::allocateZeroedBuffer(Cell* owner, size_t nbytes,
862 arena_id_t arena) {
863 MOZ_ASSERT(owner);
864 MOZ_ASSERT(nbytes > 0);
865
866 if (!IsInsideNursery(owner)) {
867 return owner->asTenured().zone()->pod_arena_calloc<uint8_t>(arena, nbytes);
868 }
869 auto [buffer, isMalloced] =
870 allocateZeroedBuffer(owner->nurseryZone(), nbytes, arena);
871 if (isMalloced && !registerMallocedBuffer(buffer, nbytes)) {
872 js_free(buffer);
873 return nullptr;
874 }
875 return buffer;
876 }
877
878 void* js::Nursery::reallocNurseryOrMallocBuffer(Zone* zone, Cell* cell,
879 void* oldBuffer,
880 size_t oldBytes,
881 size_t newBytes,
882 arena_id_t arena) {
883 if (!IsInsideNursery(cell)) {
884 MOZ_ASSERT(!isInside(oldBuffer));
885 return zone->pod_realloc<uint8_t>((uint8_t*)oldBuffer, oldBytes, newBytes);
886 }
887
888 if (!isInside(oldBuffer)) {
889 MOZ_ASSERT(toSpace.mallocedBufferBytes >= oldBytes);
890 void* newBuffer =
891 zone->pod_realloc<uint8_t>((uint8_t*)oldBuffer, oldBytes, newBytes);
892 if (newBuffer) {
893 if (oldBuffer != newBuffer) {
894 MOZ_ALWAYS_TRUE(
895 toSpace.mallocedBuffers.rekeyAs(oldBuffer, newBuffer, newBuffer));
896 }
897 toSpace.mallocedBufferBytes -= oldBytes;
898 toSpace.mallocedBufferBytes += newBytes;
899 }
900 return newBuffer;
901 }
902
903 // The nursery cannot make use of the returned slots data.
904 if (newBytes < oldBytes) {
905 return oldBuffer;
906 }
907
908 auto newBuffer =
909 allocNurseryOrMallocBuffer(zone, cell, newBytes, js::MallocArena);
910 if (newBuffer) {
911 PodCopy((uint8_t*)newBuffer, (uint8_t*)oldBuffer, oldBytes);
912 }
913 return newBuffer;
914 }
915
916 void* js::Nursery::reallocateBuffer(Zone* zone, Cell* cell, void* oldBuffer,
917 size_t oldBytes, size_t newBytes) {
918 if (!IsInsideNursery(cell)) {
919 MOZ_ASSERT(IsBufferAlloc(oldBuffer));
920 MOZ_ASSERT(!IsNurseryOwned(zone, oldBuffer));
921 return ReallocBuffer(zone, oldBuffer, newBytes, false);
922 }
923
924 if (IsBufferAlloc(oldBuffer)) {
925 MOZ_ASSERT(IsNurseryOwned(zone, oldBuffer));
926 MOZ_ASSERT(toSpace.mallocedBufferBytes >= oldBytes);
927
928 void* newBuffer = ReallocBuffer(zone, oldBuffer, newBytes, true);
929 if (!newBuffer) {
930 return nullptr;
931 }
932
933 toSpace.mallocedBufferBytes -= oldBytes;
934 toSpace.mallocedBufferBytes += newBytes;
935 return newBuffer;
936 }
937
938 // The nursery cannot make use of the returned slots data.
939 if (newBytes < oldBytes) {
940 return oldBuffer;
941 }
942
943 auto newBuffer = allocateBuffer(zone, cell, newBytes);
944 if (newBuffer) {
945 PodCopy((uint8_t*)newBuffer, (uint8_t*)oldBuffer, oldBytes);
946 }
947 return newBuffer;
948 }
949
950 void js::Nursery::freeBuffer(void* buffer, size_t nbytes) {
951 if (!isInside(buffer)) {
952 removeMallocedBuffer(buffer, nbytes);
953 js_free(buffer);
954 }
955 }
956
957 #ifdef DEBUG
958 /* static */
959 inline bool Nursery::checkForwardingPointerInsideNursery(void* ptr) {
960 // If a zero-capacity elements header lands right at the end of a chunk then
961 // elements data will appear to be in the next chunk. If we have a pointer to
962 // the very start of a chunk, check the previous chunk.
963 if ((uintptr_t(ptr) & ChunkMask) == 0) {
964 return isInside(reinterpret_cast<uint8_t*>(ptr) - 1);
965 }
966
967 return isInside(ptr);
968 }
969 #endif
970
971 void Nursery::setIndirectForwardingPointer(void* oldData, void* newData) {
972 MOZ_ASSERT(checkForwardingPointerInsideNursery(oldData));
973 // |newData| may be either in the nursery or in the malloc heap.
974
975 AutoEnterOOMUnsafeRegion oomUnsafe;
976 #ifdef DEBUG
977 if (ForwardedBufferMap::Ptr p = forwardedBuffers.lookup(oldData)) {
978 MOZ_ASSERT(p->value() == newData);
979 }
980 #endif
981 if (!forwardedBuffers.put(oldData, newData)) {
982 oomUnsafe.crash("Nursery::setForwardingPointer");
983 }
984 }
985
986 #ifdef DEBUG
987 static bool IsWriteableAddress(void* ptr) {
988 auto* vPtr = reinterpret_cast<volatile uint64_t*>(ptr);
989 *vPtr = *vPtr;
990 return true;
991 }
992 #endif
993
994 void js::Nursery::forwardBufferPointer(uintptr_t* pSlotsElems) {
995 // Read the current pointer value which may be one of:
996 // - Non-nursery pointer
997 // - Nursery-allocated buffer
998 // - A BufferRelocationOverlay inside the nursery
999 //
1000 // Note: The buffer has already been relocated. We are just patching stale
1001 // pointers now.
1002 auto* buffer = reinterpret_cast<void*>(*pSlotsElems);
1003
1004 // If the pointer is to the beginning of a chunk, then that chunk cannot be a
1005 // nursery chunk due to the chunk header. Also, the pointer cannot be to the
1006 // end of a previous nursery chunk since the last word is never allocated.
1007 if ((uintptr_t(buffer) & ChunkMask) == 0) {
1008 return;
1009 }
1010
1011 if (!isInside(buffer)) {
1012 return;
1013 }
1014
1015 // The new location for this buffer is either stored inline with it or in
1016 // the forwardedBuffers table.
1017 if (ForwardedBufferMap::Ptr p = forwardedBuffers.lookup(buffer)) {
1018 buffer = p->value();
1019 // It's not valid to assert IsWriteableAddress for indirect forwarding
1020 // pointers because the size of the allocation could be less than a word.
1021 } else {
1022 BufferRelocationOverlay* reloc =
1023 static_cast<BufferRelocationOverlay*>(buffer);
1024 buffer = *reloc;
1025 MOZ_ASSERT(IsWriteableAddress(buffer));
1026 }
1027
1028 MOZ_ASSERT_IF(isInside(buffer), !inCollectedRegion(buffer));
1029 *pSlotsElems = reinterpret_cast<uintptr_t>(buffer);
1030 }
1031
1032 inline double js::Nursery::calcPromotionRate(bool* validForTenuring) const {
1033 MOZ_ASSERT(validForTenuring);
1034
1035 if (previousGC.nurseryUsedBytes == 0) {
1036 *validForTenuring = false;
1037 return 0.0;
1038 }
1039
1040 double used = double(previousGC.nurseryUsedBytes);
1041 double capacity = double(previousGC.nurseryCapacity);
1042 double tenured = double(previousGC.tenuredBytes);
1043
1044 // We should only use the promotion rate to make tenuring decisions if it's
1045 // likely to be valid. The criterion we use is that the nursery was at least
1046 // 90% full.
1047 *validForTenuring = used > capacity * 0.9;
1048
1049 MOZ_ASSERT(tenured <= used);
1050 return tenured / used;
1051 }
1052
1053 void js::Nursery::renderProfileJSON(JSONPrinter& json) const {
1054 if (!isEnabled()) {
1055 json.beginObject();
1056 json.property("status", "nursery disabled");
1057 json.endObject();
1058 return;
1059 }
1060
1061 if (previousGC.reason == JS::GCReason::NO_REASON) {
1062 // If the nursery was empty when the last minorGC was requested, then
1063 // no nursery collection will have been performed but JSON may still be
1064 // requested. (And as a public API, this function should not crash in
1065 // such a case.)
1066 json.beginObject();
1067 json.property("status", "nursery empty");
1068 json.endObject();
1069 return;
1070 }
1071
1072 // The profiler data uses the term 'tenured' for compatibility with the
1073 // existing data format, although 'promoted' would be more accurate given
1074 // support for semispace nursery.
1075
1076 json.beginObject();
1077
1078 json.property("status", "complete");
1079
1080 json.property("reason", JS::ExplainGCReason(previousGC.reason));
1081 json.property("bytes_tenured", previousGC.tenuredBytes);
1082 json.property("cells_tenured", previousGC.tenuredCells);
1083 json.property("strings_tenured",
1084 stats().getStat(gcstats::STAT_STRINGS_PROMOTED));
1085 json.property("strings_deduplicated",
1086 stats().getStat(gcstats::STAT_STRINGS_DEDUPLICATED));
1087 json.property("bigints_tenured",
1088 stats().getStat(gcstats::STAT_BIGINTS_PROMOTED));
1089 json.property("bytes_used", previousGC.nurseryUsedBytes);
1090 json.property("cur_capacity", previousGC.nurseryCapacity);
1091 const size_t newCapacity = capacity();
1092 if (newCapacity != previousGC.nurseryCapacity) {
1093 json.property("new_capacity", newCapacity);
1094 }
1095 if (previousGC.nurseryCommitted != previousGC.nurseryCapacity) {
1096 json.property("lazy_capacity", previousGC.nurseryCommitted);
1097 }
1098 if (!timeInChunkAlloc_.IsZero()) {
1099 json.property("chunk_alloc_us", timeInChunkAlloc_, json.MICROSECONDS);
1100 }
1101
1102 // This calculation includes the whole collection time, not just the time
1103 // spent promoting.
1104 double totalTime = profileDurations_[ProfileKey::Total].ToSeconds();
1105 if (totalTime > 0.0) {
1106 double tenuredAllocRate = double(previousGC.tenuredBytes) / totalTime;
1107 json.property("tenured_allocation_rate", size_t(tenuredAllocRate));
1108 }
1109
1110 // These counters only contain consistent data if the profiler is enabled,
1111 // and then there's no guarentee.
1112 if (runtime()->geckoProfiler().enabled()) {
1113 json.property("cells_allocated_nursery",
1114 pretenuringNursery.totalAllocCount());
1115 json.property("cells_allocated_tenured",
1116 stats().allocsSinceMinorGCTenured());
1117 }
1118
1119 json.beginObjectProperty("phase_times");
1120
1121 #define EXTRACT_NAME(name, text) #name,
1122 static const char* const names[] = {
1123 FOR_EACH_NURSERY_PROFILE_TIME(EXTRACT_NAME)
1124 #undef EXTRACT_NAME
1125 ""};
1126
1127 size_t i = 0;
1128 for (auto time : profileDurations_) {
1129 json.property(names[i++], time, json.MICROSECONDS);
1130 }
1131
1132 json.endObject(); // timings value
1133
1134 json.endObject();
1135 }
1136
1137 // The following macros define nursery GC profile metadata fields that are
1138 // printed before the timing information defined by
1139 // FOR_EACH_NURSERY_PROFILE_TIME.
1140
1141 #define FOR_EACH_NURSERY_PROFILE_COMMON_METADATA(_) \
1142 _("PID", 7, "%7zu", pid) \
1143 _("Runtime", 14, "0x%12p", runtime)
1144
1145 #define FOR_EACH_NURSERY_PROFILE_SLICE_METADATA(_) \
1146 _("Timestamp", 10, "%10.6f", timestamp.ToSeconds()) \
1147 _("Reason", 20, "%-20.20s", reasonStr) \
1148 _("PRate", 6, "%5.1f%%", promotionRatePercent) \
1149 _("OldKB", 6, "%6zu", oldSizeKB) \
1150 _("NewKB", 6, "%6zu", newSizeKB) \
1151 _("Dedup", 6, "%6zu", dedupCount)
1152
1153 #define FOR_EACH_NURSERY_PROFILE_METADATA(_) \
1154 FOR_EACH_NURSERY_PROFILE_COMMON_METADATA(_) \
1155 FOR_EACH_NURSERY_PROFILE_SLICE_METADATA(_)
1156
1157 void js::Nursery::printCollectionProfile(JS::GCReason reason,
1158 double promotionRate) {
1159 stats().maybePrintProfileHeaders();
1160
1161 Sprinter sprinter;
1162 if (!sprinter.init()) {
1163 return;
1164 }
1165 sprinter.put(gcstats::MinorGCProfilePrefix);
1166
1167 size_t pid = getpid();
1168 JSRuntime* runtime = gc->rt;
1169 TimeDuration timestamp = collectionStartTime() - stats().creationTime();
1170 const char* reasonStr = ExplainGCReason(reason);
1171 double promotionRatePercent = promotionRate * 100;
1172 size_t oldSizeKB = previousGC.nurseryCapacity / 1024;
1173 size_t newSizeKB = capacity() / 1024;
1174 size_t dedupCount = stats().getStat(gcstats::STAT_STRINGS_DEDUPLICATED);
1175
1176 #define PRINT_FIELD_VALUE(_1, _2, format, value) \
1177 sprinter.printf(" " format, value);
1178
1179 FOR_EACH_NURSERY_PROFILE_METADATA(PRINT_FIELD_VALUE)
1180 #undef PRINT_FIELD_VALUE
1181
1182 printProfileDurations(profileDurations_, sprinter);
1183
1184 JS::UniqueChars str = sprinter.release();
1185 if (!str) {
1186 return;
1187 }
1188 fputs(str.get(), stats().profileFile());
1189 }
1190
1191 void js::Nursery::printProfileHeader() {
1192 Sprinter sprinter;
1193 if (!sprinter.init()) {
1194 return;
1195 }
1196 sprinter.put(gcstats::MinorGCProfilePrefix);
1197
1198 #define PRINT_FIELD_NAME(name, width, _1, _2) \
1199 sprinter.printf(" %-*s", width, name);
1200
1201 FOR_EACH_NURSERY_PROFILE_METADATA(PRINT_FIELD_NAME)
1202 #undef PRINT_FIELD_NAME
1203
1204 #define PRINT_PROFILE_NAME(_1, text) sprinter.printf(" %-6.6s", text);
1205
1206 FOR_EACH_NURSERY_PROFILE_TIME(PRINT_PROFILE_NAME)
1207 #undef PRINT_PROFILE_NAME
1208
1209 sprinter.put("\n");
1210
1211 JS::UniqueChars str = sprinter.release();
1212 if (!str) {
1213 return;
1214 }
1215 fputs(str.get(), stats().profileFile());
1216 }
1217
1218 // static
1219 void js::Nursery::printProfileDurations(const ProfileDurations& times,
1220 Sprinter& sprinter) {
1221 for (auto time : times) {
1222 int64_t micros = int64_t(time.ToMicroseconds());
1223 sprinter.printf(" %6" PRIi64, micros);
1224 }
1225
1226 sprinter.put("\n");
1227 }
1228
1229 static constexpr size_t NurserySliceMetadataFormatWidth() {
1230 size_t fieldCount = 0;
1231 size_t totalWidth = 0;
1232
1233 #define UPDATE_COUNT_AND_WIDTH(_1, width, _2, _3) \
1234 fieldCount++; \
1235 totalWidth += width;
1236 FOR_EACH_NURSERY_PROFILE_SLICE_METADATA(UPDATE_COUNT_AND_WIDTH)
1237 #undef UPDATE_COUNT_AND_WIDTH
1238
1239 // Add padding between fields.
1240 totalWidth += fieldCount - 1;
1241
1242 return totalWidth;
1243 }
1244
1245 void js::Nursery::printTotalProfileTimes() {
1246 if (!enableProfiling_) {
1247 return;
1248 }
1249
1250 Sprinter sprinter;
1251 if (!sprinter.init()) {
1252 return;
1253 }
1254 sprinter.put(gcstats::MinorGCProfilePrefix);
1255
1256 size_t pid = getpid();
1257 JSRuntime* runtime = gc->rt;
1258
1259 char collections[32];
1260 DebugOnly<int> r = SprintfLiteral(
1261 collections, "TOTALS: %7" PRIu64 " collections:", gc->minorGCCount());
1262 MOZ_ASSERT(r > 0 && r < int(sizeof(collections)));
1263
1264 #define PRINT_FIELD_VALUE(_1, _2, format, value) \
1265 sprinter.printf(" " format, value);
1266
1267 FOR_EACH_NURSERY_PROFILE_COMMON_METADATA(PRINT_FIELD_VALUE)
1268 #undef PRINT_FIELD_VALUE
1269
1270 // Use whole width of per-slice metadata to print total slices so the profile
1271 // totals that follow line up.
1272 size_t width = NurserySliceMetadataFormatWidth();
1273 sprinter.printf(" %-*s", int(width), collections);
1274
1275 printProfileDurations(totalDurations_, sprinter);
1276
1277 JS::UniqueChars str = sprinter.release();
1278 if (!str) {
1279 return;
1280 }
1281 fputs(str.get(), stats().profileFile());
1282 }
1283
1284 void js::Nursery::maybeClearProfileDurations() {
1285 for (auto& duration : profileDurations_) {
1286 duration = mozilla::TimeDuration::Zero();
1287 }
1288 }
1289
1290 inline void js::Nursery::startProfile(ProfileKey key) {
1291 startTimes_[key] = TimeStamp::Now();
1292 }
1293
1294 inline void js::Nursery::endProfile(ProfileKey key) {
1295 profileDurations_[key] = TimeStamp::Now() - startTimes_[key];
1296 totalDurations_[key] += profileDurations_[key];
1297 }
1298
1299 inline TimeStamp js::Nursery::collectionStartTime() const {
1300 return startTimes_[ProfileKey::Total];
1301 }
1302
1303 TimeStamp js::Nursery::lastCollectionEndTime() const {
1304 return previousGC.endTime;
1305 }
1306
1307 bool js::Nursery::wantEagerCollection() const {
1308 if (!isEnabled()) {
1309 return false;
1310 }
1311
1312 if (isEmpty() && capacity() == minSpaceSize()) {
1313 return false;
1314 }
1315
1316 if (minorGCRequested()) {
1317 return true;
1318 }
1319
1320 if (freeSpaceIsBelowEagerThreshold()) {
1321 return true;
1322 }
1323
1324 // If the nursery is not being collected often then it may be taking up more
1325 // space than necessary.
1326 return isUnderused();
1327 }
1328
1329 inline bool js::Nursery::freeSpaceIsBelowEagerThreshold() const {
1330 // The threshold is specified in terms of free space so that it doesn't depend
1331 // on the size of the nursery.
1332 //
1333 // There two thresholds, an absolute free bytes threshold and a free space
1334 // fraction threshold. Two thresholds are used so that we don't collect too
1335 // eagerly for small nurseries (or even all the time if nursery size is less
1336 // than the free bytes threshold) or too eagerly for large nurseries (where a
1337 // fractional threshold may leave a significant amount of nursery unused).
1338 //
1339 // Since the aim is making this less eager we require both thresholds to be
1340 // met.
1341
1342 size_t freeBytes = freeSpace();
1343 double freeFraction = double(freeBytes) / double(capacity());
1344
1345 size_t bytesThreshold = tunables().nurseryEagerCollectionThresholdBytes();
1346 double fractionThreshold =
1347 tunables().nurseryEagerCollectionThresholdPercent();
1348
1349 return freeBytes < bytesThreshold && freeFraction < fractionThreshold;
1350 }
1351
1352 inline bool js::Nursery::isUnderused() const {
1353 if (js::SupportDifferentialTesting() || !previousGC.endTime) {
1354 return false;
1355 }
1356
1357 if (capacity() == minSpaceSize()) {
1358 return false;
1359 }
1360
1361 // If the nursery is above its minimum size, collect it every so often if we
1362 // have idle time. This allows the nursery to shrink when it's not being
1363 // used. There are other heuristics we could use for this, but this is the
1364 // simplest.
1365 TimeDuration timeSinceLastCollection =
1366 TimeStamp::NowLoRes() - previousGC.endTime;
1367 return timeSinceLastCollection > tunables().nurseryEagerCollectionTimeout();
1368 }
1369
1370 void js::Nursery::collect(JS::GCOptions options, JS::GCReason reason) {
1371 JSRuntime* rt = runtime();
1372 MOZ_ASSERT(!rt->mainContextFromOwnThread()->suppressGC);
1373
1374 if (minorGCRequested()) {
1375 MOZ_ASSERT(position() == chunk(currentChunk()).end());
1376 toSpace.position_ = prevPosition_;
1377 prevPosition_ = 0;
1378 minorGCTriggerReason_ = JS::GCReason::NO_REASON;
1379 rt->mainContextFromOwnThread()->clearPendingInterrupt(
1380 InterruptReason::MinorGC);
1381 }
1382
1383 if (!isEnabled() || isEmpty()) {
1384 // Our barriers are not always exact, and there may be entries in the
1385 // storebuffer even when the nursery is disabled or empty. It's not safe
1386 // to keep these entries as they may refer to tenured cells which may be
1387 // freed after this point.
1388 gc->storeBuffer().clear();
1389
1390 MOZ_ASSERT_IF(!semispaceEnabled_, !pretenuringNursery.hasAllocatedSites());
1391 }
1392
1393 if (!isEnabled()) {
1394 return;
1395 }
1396
1397 AutoGCSession session(gc, JS::HeapState::MinorCollecting);
1398
1399 stats().beginNurseryCollection();
1400 gcprobes::MinorGCStart();
1401
1402 if (stats().bufferAllocStatsEnabled() && runtime()->isMainRuntime()) {
1403 stats().maybePrintProfileHeaders();
1404 BufferAllocator::printStats(gc, gc->stats().creationTime(), false,
1405 gc->stats().profileFile());
1406 }
1407
1408 gc->callNurseryCollectionCallbacks(
1409 JS::GCNurseryProgress::GC_NURSERY_COLLECTION_START, reason);
1410
1411 maybeClearProfileDurations();
1412 startProfile(ProfileKey::Total);
1413
1414 previousGC.reason = JS::GCReason::NO_REASON;
1415 previousGC.nurseryUsedBytes = usedSpace();
1416 previousGC.nurseryCapacity = capacity();
1417 previousGC.nurseryCommitted = totalCommitted();
1418 previousGC.nurseryUsedChunkCount = currentChunk() + 1;
1419 previousGC.tenuredBytes = 0;
1420 previousGC.tenuredCells = 0;
1421 tenuredEverything = true;
1422
1423 // Wait for any previous buffer sweeping to finish. This happens even if the
1424 // nursery is empty because we track whether this has happened by checking the
1425 // minor GC number, which is incremented regardless. See the call to
1426 // joinSweepTask in GCRuntime::endSweepingSweepGroup.
1427 joinSweepTask();
1428
1429 // If it isn't empty, it will call doCollection, and possibly after that
1430 // isEmpty() will become true, so use another variable to keep track of the
1431 // old empty state.
1432 bool wasEmpty = isEmpty();
1433 if (!wasEmpty) {
1434 CollectionResult result = doCollection(session, options, reason);
1435 // Don't include chunk headers when calculating nursery space, since this
1436 // space does not represent data that can be tenured
1437 MOZ_ASSERT(result.tenuredBytes <=
1438 (previousGC.nurseryUsedBytes -
1439 (NurseryChunkHeaderSize * previousGC.nurseryUsedChunkCount)));
1440
1441 previousGC.reason = reason;
1442 previousGC.tenuredBytes = result.tenuredBytes;
1443 previousGC.tenuredCells = result.tenuredCells;
1444 previousGC.nurseryUsedChunkCount = currentChunk() + 1;
1445 }
1446
1447 // Resize the nursery.
1448 maybeResizeNursery(options, reason);
1449
1450 if (!semispaceEnabled()) {
1451 poisonAndInitCurrentChunk();
1452 }
1453
1454 bool validPromotionRate;
1455 const double promotionRate = calcPromotionRate(&validPromotionRate);
1456
1457 startProfile(ProfileKey::Pretenure);
1458 size_t sitesPretenured = 0;
1459 sitesPretenured =
1460 doPretenuring(rt, reason, validPromotionRate, promotionRate);
1461 endProfile(ProfileKey::Pretenure);
1462
1463 previousGC.endTime =
1464 TimeStamp::Now(); // Must happen after maybeResizeNursery.
1465 endProfile(ProfileKey::Total);
1466 gc->incMinorGcNumber();
1467
1468 TimeDuration totalTime = profileDurations_[ProfileKey::Total];
1469 sendTelemetry(reason, totalTime, wasEmpty, promotionRate, sitesPretenured);
1470
1471 gc->callNurseryCollectionCallbacks(
1472 JS::GCNurseryProgress::GC_NURSERY_COLLECTION_END, reason);
1473
1474 stats().endNurseryCollection();
1475 gcprobes::MinorGCEnd();
1476
1477 timeInChunkAlloc_ = mozilla::TimeDuration::Zero();
1478
1479 js::StringStats prevStats = gc->stringStats;
1480 js::StringStats& currStats = gc->stringStats;
1481 currStats = js::StringStats();
1482 for (ZonesIter zone(gc, WithAtoms); !zone.done(); zone.next()) {
1483 currStats += zone->stringStats;
1484 zone->previousGCStringStats = zone->stringStats;
1485 }
1486 stats().setStat(
1487 gcstats::STAT_STRINGS_DEDUPLICATED,
1488 currStats.deduplicatedStrings - prevStats.deduplicatedStrings);
1489 if (ShouldPrintProfile(runtime(), enableProfiling_, profileWorkers_,
1490 profileThreshold_, totalTime)) {
1491 printCollectionProfile(reason, promotionRate);
1492 }
1493
1494 if (reportDeduplications_) {
1495 printDeduplicationData(prevStats, currStats);
1496 }
1497 }
1498
1499 void js::Nursery::sendTelemetry(JS::GCReason reason, TimeDuration totalTime,
1500 bool wasEmpty, double promotionRate,
1501 size_t sitesPretenured) {
1502 JSRuntime* rt = runtime();
1503 rt->metrics().GC_MINOR_REASON(uint32_t(reason));
1504
1505 // Long minor GCs are those that take more than 1ms.
1506 bool wasLongMinorGC = totalTime.ToMilliseconds() > 1.0;
1507 if (wasLongMinorGC) {
1508 rt->metrics().GC_MINOR_REASON_LONG(uint32_t(reason));
1509 }
1510 rt->metrics().GC_MINOR_US(totalTime);
1511 rt->metrics().GC_NURSERY_BYTES_2(totalCommitted());
1512
1513 if (!wasEmpty) {
1514 rt->metrics().GC_PRETENURE_COUNT_2(sitesPretenured);
1515 rt->metrics().GC_NURSERY_PROMOTION_RATE(promotionRate * 100);
1516 }
1517 }
1518
1519 void js::Nursery::printDeduplicationData(js::StringStats& prev,
1520 js::StringStats& curr) {
1521 if (curr.deduplicatedStrings > prev.deduplicatedStrings) {
1522 fprintf(stderr,
1523 "pid %zu: deduplicated %" PRIi64 " strings, %" PRIu64
1524 " chars, %" PRIu64 " malloc bytes\n",
1525 size_t(getpid()),
1526 curr.deduplicatedStrings - prev.deduplicatedStrings,
1527 curr.deduplicatedChars - prev.deduplicatedChars,
1528 curr.deduplicatedBytes - prev.deduplicatedBytes);
1529 }
1530 }
1531
1532 void js::Nursery::freeTrailerBlocks(JS::GCOptions options,
1533 JS::GCReason reason) {
1534 fromSpace.freeTrailerBlocks(mallocedBlockCache_);
1535
1536 if (options == JS::GCOptions::Shrink || gc::IsOOMReason(reason)) {
1537 mallocedBlockCache_.clear();
1538 return;
1539 }
1540
1541 // Discard blocks from the cache at 0.05% per megabyte of nursery capacity,
1542 // that is, 0.8% of blocks for a 16-megabyte nursery. This allows the cache
1543 // to gradually discard unneeded blocks in long running applications.
1544 mallocedBlockCache_.preen(0.05 * double(capacity()) / (1024.0 * 1024.0));
1545 }
1546
1547 void js::Nursery::Space::freeTrailerBlocks(
1548 MallocedBlockCache& mallocedBlockCache) {
1549 // This routine frees those blocks denoted by the set
1550 //
1551 // trailersAdded_ (all of it)
1552 // - trailersRemoved_ (entries with index below trailersRemovedUsed_)
1553 //
1554 // For each block, places it back on the nursery's small-malloced-block pool
1555 // by calling mallocedBlockCache.free.
1556
1557 MOZ_ASSERT(trailersAdded_.length() == trailersRemoved_.length());
1558 MOZ_ASSERT(trailersRemovedUsed_ <= trailersRemoved_.length());
1559
1560 // Sort the removed entries.
1561 std::sort(trailersRemoved_.begin(),
1562 trailersRemoved_.begin() + trailersRemovedUsed_,
1563 [](const void* block1, const void* block2) {
1564 return uintptr_t(block1) < uintptr_t(block2);
1565 });
1566
1567 // Use one of two schemes to enumerate the set subtraction.
1568 if (trailersRemovedUsed_ < 1000) {
1569 // If the number of removed items is relatively small, it isn't worth the
1570 // cost of sorting `trailersAdded_`. Instead, walk through the vector in
1571 // whatever order it is and use binary search to establish whether each
1572 // item is present in trailersRemoved_[0 .. trailersRemovedUsed_ - 1].
1573 const size_t nAdded = trailersAdded_.length();
1574 for (size_t i = 0; i < nAdded; i++) {
1575 const PointerAndUint7 block = trailersAdded_[i];
1576 const void* blockPointer = block.pointer();
1577 if (!std::binary_search(trailersRemoved_.begin(),
1578 trailersRemoved_.begin() + trailersRemovedUsed_,
1579 blockPointer)) {
1580 mallocedBlockCache.free(block);
1581 }
1582 }
1583 } else {
1584 // The general case, which is algorithmically safer for large inputs.
1585 // Sort the added entries, and then walk through both them and the removed
1586 // entries in lockstep.
1587 std::sort(trailersAdded_.begin(), trailersAdded_.end(),
1588 [](const PointerAndUint7& block1, const PointerAndUint7& block2) {
1589 return uintptr_t(block1.pointer()) <
1590 uintptr_t(block2.pointer());
1591 });
1592 // Enumerate the set subtraction. This is somewhat simplified by the fact
1593 // that all elements of the removed set must also be present in the added
1594 // set. (the "inclusion property").
1595 const size_t nAdded = trailersAdded_.length();
1596 const size_t nRemoved = trailersRemovedUsed_;
1597 size_t iAdded;
1598 size_t iRemoved = 0;
1599 for (iAdded = 0; iAdded < nAdded; iAdded++) {
1600 if (iRemoved == nRemoved) {
1601 // We've run out of items to skip, so move on to the next loop.
1602 break;
1603 }
1604 const PointerAndUint7 blockAdded = trailersAdded_[iAdded];
1605 const void* blockRemoved = trailersRemoved_[iRemoved];
1606 if (blockAdded.pointer() < blockRemoved) {
1607 mallocedBlockCache.free(blockAdded);
1608 continue;
1609 }
1610 // If this doesn't hold
1611 // (that is, if `blockAdded.pointer() > blockRemoved`),
1612 // then the abovementioned inclusion property doesn't hold.
1613 MOZ_RELEASE_ASSERT(blockAdded.pointer() == blockRemoved);
1614 iRemoved++;
1615 }
1616 MOZ_ASSERT(iRemoved == nRemoved);
1617 // We've used up the removed set, so now finish up the remainder of the
1618 // added set.
1619 for (/*keep going*/; iAdded < nAdded; iAdded++) {
1620 const PointerAndUint7 block = trailersAdded_[iAdded];
1621 mallocedBlockCache.free(block);
1622 }
1623 }
1624
1625 // And empty out both sets, but preserve the underlying storage.
1626 trailersAdded_.clear();
1627 trailersRemoved_.clear();
1628 trailersRemovedUsed_ = 0;
1629 trailerBytes_ = 0;
1630 }
1631
1632 size_t Nursery::sizeOfTrailerBlockSets(
1633 mozilla::MallocSizeOf mallocSizeOf) const {
1634 MOZ_ASSERT(fromSpace.trailersAdded_.empty());
1635 MOZ_ASSERT(fromSpace.trailersRemoved_.empty());
1636 return toSpace.trailersAdded_.sizeOfExcludingThis(mallocSizeOf) +
1637 toSpace.trailersRemoved_.sizeOfExcludingThis(mallocSizeOf);
1638 }
1639
1640 js::Nursery::CollectionResult js::Nursery::doCollection(AutoGCSession& session,
1641 JS::GCOptions options,
1642 JS::GCReason reason) {
1643 JSRuntime* rt = runtime();
1644 AutoSetThreadIsPerformingGC performingGC(rt->gcContext());
1645 AutoStopVerifyingBarriers av(rt, false);
1646 AutoDisableProxyCheck disableStrictProxyChecking;
1647 mozilla::DebugOnly<AutoEnterOOMUnsafeRegion> oomUnsafeRegion;
1648
1649 #ifdef JS_GC_ZEAL
1650 if (gc->hasZealMode(ZealMode::CheckHeapBeforeMinorGC)) {
1651 gc->checkHeapBeforeMinorGC(session);
1652 }
1653 #endif
1654
1655 // Swap nursery spaces.
1656 swapSpaces();
1657 MOZ_ASSERT(toSpace.isEmpty());
1658 MOZ_ASSERT(toSpace.mallocedBuffers.empty());
1659 if (semispaceEnabled_) {
1660 poisonAndInitCurrentChunk();
1661 }
1662
1663 clearMapAndSetNurseryIterators();
1664
1665 MOZ_ASSERT(sweepTask->isIdle());
1666 {
1667 BufferAllocator::MaybeLock lock;
1668 for (ZonesIter zone(runtime(), WithAtoms); !zone.done(); zone.next()) {
1669 zone->bufferAllocator.startMinorCollection(lock);
1670 }
1671 }
1672
1673 // Move objects pointed to by roots from the nursery to the major heap.
1674 tenuredEverything = shouldTenureEverything(reason);
1675 TenuringTracer mover(rt, this, tenuredEverything);
1676 #ifdef JS_GC_ZEAL
1677 if (reportPromotion_) {
1678 mover.initPromotionReport();
1679 }
1680 #endif
1681
1682 // Trace everything considered as a root by a minor GC.
1683 traceRoots(session, mover);
1684
1685 startProfile(ProfileKey::SweepCaches);
1686 gc->purgeRuntimeForMinorGC();
1687 endProfile(ProfileKey::SweepCaches);
1688
1689 // Most of the work is done here. This loop iterates over objects that have
1690 // been moved to the major heap. If these objects have any outgoing pointers
1691 // to the nursery, then those nursery objects get moved as well, until no
1692 // objects are left to move. That is, we iterate to a fixed point.
1693 startProfile(ProfileKey::CollectToObjFP);
1694 mover.collectToObjectFixedPoint();
1695 endProfile(ProfileKey::CollectToObjFP);
1696
1697 startProfile(ProfileKey::CollectToStrFP);
1698 mover.collectToStringFixedPoint();
1699 endProfile(ProfileKey::CollectToStrFP);
1700
1701 #ifdef JS_GC_ZEAL
1702 if (reportPromotion_ && options != JS::GCOptions::Shutdown) {
1703 JSContext* cx = runtime()->mainContextFromOwnThread();
1704 JS::AutoAssertNoGC nogc(cx);
1705 mover.printPromotionReport(cx, reason, nogc);
1706 }
1707 #endif
1708
1709 // Sweep to update any pointers to nursery objects that have now been
1710 // tenured.
1711 startProfile(ProfileKey::Sweep);
1712 sweep();
1713 endProfile(ProfileKey::Sweep);
1714
1715 // Update any slot or element pointers whose destination has been tenured.
1716 startProfile(ProfileKey::UpdateJitActivations);
1717 js::jit::UpdateJitActivationsForMinorGC(rt);
1718 forwardedBuffers.clearAndCompact();
1719 endProfile(ProfileKey::UpdateJitActivations);
1720
1721 startProfile(ProfileKey::ObjectsTenuredCallback);
1722 gc->callObjectsTenuredCallback();
1723 endProfile(ProfileKey::ObjectsTenuredCallback);
1724
1725 // Sweep malloced buffers.
1726 startProfile(ProfileKey::FreeMallocedBuffers);
1727 gc->queueBuffersForFreeAfterMinorGC(fromSpace.mallocedBuffers,
1728 stringBuffersToReleaseAfterMinorGC_);
1729 fromSpace.mallocedBufferBytes = 0;
1730 endProfile(ProfileKey::FreeMallocedBuffers);
1731
1732 // Give trailer blocks associated with non-tenured Wasm{Struct,Array}Objects
1733 // back to our `mallocedBlockCache_`.
1734 startProfile(ProfileKey::FreeTrailerBlocks);
1735 freeTrailerBlocks(options, reason);
1736 endProfile(ProfileKey::FreeTrailerBlocks);
1737
1738 startProfile(ProfileKey::ClearNursery);
1739 clear();
1740 endProfile(ProfileKey::ClearNursery);
1741
1742 // Purge the StringToAtomCache. This has to happen at the end because the
1743 // cache is used when tenuring strings.
1744 startProfile(ProfileKey::PurgeStringToAtomCache);
1745 runtime()->caches().stringToAtomCache.purge();
1746 endProfile(ProfileKey::PurgeStringToAtomCache);
1747
1748 #ifdef JS_GC_ZEAL
1749 // Make sure hashtables have been updated after the collection.
1750 startProfile(ProfileKey::CheckHashTables);
1751 if (gc->hasZealMode(ZealMode::CheckHashTablesOnMinorGC)) {
1752 runtime()->caches().checkEvalCacheAfterMinorGC();
1753 gc->checkHashTablesAfterMovingGC();
1754 }
1755 endProfile(ProfileKey::CheckHashTables);
1756
1757 // Check for missing post barriers.
1758 if (gc->hasZealMode(ZealMode::VerifierPost)) {
1759 gc->verifyPostBarriers(session);
1760 }
1761 #endif
1762
1763 if (semispaceEnabled_) {
1764 // On the next collection, tenure everything before |tenureThreshold_|.
1765 tenureThreshold_ = toSpace.offsetFromExclusiveAddress(position());
1766 } else {
1767 // Swap nursery spaces back because we only use one.
1768 swapSpaces();
1769 MOZ_ASSERT(toSpace.isEmpty());
1770 }
1771
1772 MOZ_ASSERT(fromSpace.isEmpty());
1773
1774 if (semispaceEnabled_) {
1775 poisonAndInitCurrentChunk();
1776 }
1777
1778 return {mover.getPromotedSize(), mover.getPromotedCells()};
1779 }
1780
1781 void js::Nursery::swapSpaces() {
1782 std::swap(toSpace, fromSpace);
1783 toSpace.setKind(ChunkKind::NurseryToSpace);
1784 fromSpace.setKind(ChunkKind::NurseryFromSpace);
1785 }
1786
1787 void js::Nursery::traceRoots(AutoGCSession& session, TenuringTracer& mover) {
1788 {
1789 // Suppress the sampling profiler to prevent it observing moved functions.
1790 AutoSuppressProfilerSampling suppressProfiler(
1791 runtime()->mainContextFromOwnThread());
1792
1793 // Trace the store buffer, which must happen first.
1794
1795 // Create an empty store buffer on the stack and swap it with the main store
1796 // buffer, clearing it.
1797 StoreBuffer sb(runtime());
1798 {
1799 AutoEnterOOMUnsafeRegion oomUnsafe;
1800 if (!sb.enable()) {
1801 oomUnsafe.crash("Nursery::traceRoots");
1802 }
1803 }
1804 std::swap(sb, gc->storeBuffer());
1805 MOZ_ASSERT(gc->storeBuffer().isEnabled());
1806 MOZ_ASSERT(gc->storeBuffer().isEmpty());
1807
1808 startProfile(ProfileKey::TraceWholeCells);
1809 sb.traceWholeCells(mover);
1810 endProfile(ProfileKey::TraceWholeCells);
1811
1812 startProfile(ProfileKey::TraceValues);
1813 sb.traceValues(mover);
1814 endProfile(ProfileKey::TraceValues);
1815
1816 startProfile(ProfileKey::TraceWasmAnyRefs);
1817 sb.traceWasmAnyRefs(mover);
1818 endProfile(ProfileKey::TraceWasmAnyRefs);
1819
1820 startProfile(ProfileKey::TraceCells);
1821 sb.traceCells(mover);
1822 endProfile(ProfileKey::TraceCells);
1823
1824 startProfile(ProfileKey::TraceSlots);
1825 sb.traceSlots(mover);
1826 endProfile(ProfileKey::TraceSlots);
1827
1828 startProfile(ProfileKey::TraceGenericEntries);
1829 sb.traceGenericEntries(&mover);
1830 endProfile(ProfileKey::TraceGenericEntries);
1831
1832 startProfile(ProfileKey::MarkRuntime);
1833 gc->traceRuntimeForMinorGC(&mover, session);
1834 endProfile(ProfileKey::MarkRuntime);
1835 }
1836
1837 startProfile(ProfileKey::MarkDebugger);
1838 {
1839 gcstats::AutoPhase ap(stats(), gcstats::PhaseKind::MARK_ROOTS);
1840 DebugAPI::traceAllForMovingGC(&mover);
1841 }
1842 endProfile(ProfileKey::MarkDebugger);
1843 }
1844
1845 bool js::Nursery::shouldTenureEverything(JS::GCReason reason) {
1846 if (!semispaceEnabled()) {
1847 return true;
1848 }
1849
1850 return reason == JS::GCReason::EVICT_NURSERY ||
1851 reason == JS::GCReason::DISABLE_GENERATIONAL_GC;
1852 }
1853
1854 size_t js::Nursery::doPretenuring(JSRuntime* rt, JS::GCReason reason,
1855 bool validPromotionRate,
1856 double promotionRate) {
1857 size_t sitesPretenured = pretenuringNursery.doPretenuring(
1858 gc, reason, validPromotionRate, promotionRate, pretenuringReportFilter_);
1859
1860 size_t zonesWhereStringsDisabled = 0;
1861 size_t zonesWhereBigIntsDisabled = 0;
1862
1863 uint32_t numStringsPromoted = 0;
1864 uint32_t numBigIntsPromoted = 0;
1865 for (ZonesIter zone(gc, SkipAtoms); !zone.done(); zone.next()) {
1866 bool disableNurseryStrings =
1867 zone->allocNurseryStrings() &&
1868 zone->unknownAllocSite(JS::TraceKind::String)->state() ==
1869 AllocSite::State::LongLived;
1870
1871 bool disableNurseryBigInts =
1872 zone->allocNurseryBigInts() &&
1873 zone->unknownAllocSite(JS::TraceKind::BigInt)->state() ==
1874 AllocSite::State::LongLived;
1875
1876 if (disableNurseryStrings || disableNurseryBigInts) {
1877 if (disableNurseryStrings) {
1878 zone->nurseryStringsDisabled = true;
1879 zonesWhereStringsDisabled++;
1880 }
1881 if (disableNurseryBigInts) {
1882 zone->nurseryBigIntsDisabled = true;
1883 zonesWhereStringsDisabled++;
1884 }
1885 updateAllocFlagsForZone(zone);
1886 }
1887
1888 numStringsPromoted += zone->nurseryPromotedCount(JS::TraceKind::String);
1889 numBigIntsPromoted += zone->nurseryPromotedCount(JS::TraceKind::BigInt);
1890 }
1891
1892 stats().setStat(gcstats::STAT_STRINGS_PROMOTED, numStringsPromoted);
1893 stats().setStat(gcstats::STAT_BIGINTS_PROMOTED, numBigIntsPromoted);
1894
1895 if (reportPretenuring() && zonesWhereStringsDisabled) {
1896 fprintf(stderr,
1897 "Pretenuring disabled nursery string allocation in %zu zones\n",
1898 zonesWhereStringsDisabled);
1899 }
1900 if (reportPretenuring() && zonesWhereBigIntsDisabled) {
1901 fprintf(stderr,
1902 "Pretenuring disabled nursery big int allocation in %zu zones\n",
1903 zonesWhereBigIntsDisabled);
1904 }
1905
1906 return sitesPretenured;
1907 }
1908
1909 bool js::Nursery::registerMallocedBuffer(void* buffer, size_t nbytes) {
1910 MOZ_ASSERT(buffer);
1911 MOZ_ASSERT(nbytes > 0);
1912 MOZ_ASSERT(!isInside(buffer));
1913
1914 if (!toSpace.mallocedBuffers.putNew(buffer)) {
1915 return false;
1916 }
1917
1918 addMallocedBufferBytes(nbytes);
1919 return true;
1920 }
1921
1922 void js::Nursery::registerBuffer(void* buffer, size_t nbytes) {
1923 MOZ_ASSERT(buffer);
1924 MOZ_ASSERT(nbytes > 0);
1925 MOZ_ASSERT(!isInside(buffer));
1926
1927 addMallocedBufferBytes(nbytes);
1928 }
1929
1930 /*
1931 * Several things may need to happen when a nursery allocated cell with an
1932 * external buffer is promoted:
1933 * - the buffer may need to be moved if it is currently in the nursery
1934 * - the buffer may need to be removed from the list of buffers that will be
1935 * freed after nursery collection if it is malloced
1936 * - memory accounting for the buffer needs to be updated
1937 */
1938 Nursery::WasBufferMoved js::Nursery::maybeMoveRawBufferOnPromotion(
1939 void** bufferp, gc::Cell* owner, size_t bytesUsed, size_t bytesCapacity,
1940 MemoryUse use, arena_id_t arena) {
1941 MOZ_ASSERT(bytesUsed <= bytesCapacity);
1942
1943 void* buffer = *bufferp;
1944 if (!isInside(buffer)) {
1945 // This is a malloced buffer. Remove it from the nursery's previous list of
1946 // buffers so we don't free it.
1947 removeMallocedBufferDuringMinorGC(buffer);
1948 trackMallocedBufferOnPromotion(buffer, owner, bytesCapacity, use);
1949 return BufferNotMoved;
1950 }
1951
1952 // Copy the nursery-allocated buffer into a new malloc allocation.
1953
1954 AutoEnterOOMUnsafeRegion oomUnsafe;
1955 Zone* zone = owner->zone();
1956 void* movedBuffer = zone->pod_arena_malloc<uint8_t>(arena, bytesCapacity);
1957 if (!movedBuffer) {
1958 oomUnsafe.crash("Nursery::maybeMoveRawNurseryOrMallocBufferOnPromotion");
1959 }
1960
1961 memcpy(movedBuffer, buffer, bytesUsed);
1962
1963 trackMallocedBufferOnPromotion(movedBuffer, owner, bytesCapacity, use);
1964
1965 *bufferp = movedBuffer;
1966 return BufferMoved;
1967 }
1968
1969 void js::Nursery::trackMallocedBufferOnPromotion(void* buffer, gc::Cell* owner,
1970 size_t nbytes, MemoryUse use) {
1971 if (owner->isTenured()) {
1972 // If we tenured the owner then account for the memory.
1973 AddCellMemory(owner, nbytes, use);
1974 return;
1975 }
1976
1977 // Otherwise add it to the nursery's new buffer list.
1978 AutoEnterOOMUnsafeRegion oomUnsafe;
1979 if (!registerMallocedBuffer(buffer, nbytes)) {
1980 oomUnsafe.crash("Nursery::trackMallocedBufferOnPromotion");
1981 }
1982 }
1983
1984 void js::Nursery::trackTrailerOnPromotion(void* buffer, gc::Cell* owner,
1985 size_t nbytes, size_t overhead,
1986 MemoryUse use) {
1987 MOZ_ASSERT(!isInside(buffer));
1988 unregisterTrailer(buffer);
1989
1990 if (owner->isTenured()) {
1991 // If we tenured the owner then account for the memory.
1992 AddCellMemory(owner, nbytes + overhead, use);
1993 return;
1994 }
1995
1996 // Otherwise add it to the nursery's new buffer list.
1997 PointerAndUint7 blockAndListID(buffer,
1998 MallocedBlockCache::listIDForSize(nbytes));
1999 AutoEnterOOMUnsafeRegion oomUnsafe;
2000 if (!registerTrailer(blockAndListID, nbytes)) {
2001 oomUnsafe.crash("Nursery::trackTrailerOnPromotion");
2002 }
2003 }
2004
2005 Nursery::WasBufferMoved js::Nursery::maybeMoveRawBufferOnPromotion(
2006 void** bufferp, gc::Cell* owner, size_t nbytes) {
2007 bool nurseryOwned = IsInsideNursery(owner);
2008
2009 void* buffer = *bufferp;
2010 if (IsBufferAlloc(buffer)) {
2011 // This is an external buffer allocation owned by a nursery GC thing.
2012 Zone* zone = owner->zone();
2013 MOZ_ASSERT(IsNurseryOwned(zone, buffer));
2014 bool ownerWasTenured = !nurseryOwned;
2015 zone->bufferAllocator.markNurseryOwnedAlloc(buffer, ownerWasTenured);
2016 if (nurseryOwned) {
2017 registerBuffer(buffer, nbytes);
2018 }
2019 return BufferNotMoved;
2020 }
2021
2022 // Copy the nursery-allocated buffer into a new allocation.
2023
2024 // todo: only necessary for copying inline elements data where we didn't
2025 // calculate this on allocation.
2026 size_t dstBytes = GetGoodAllocSize(nbytes);
2027
2028 AutoEnterOOMUnsafeRegion oomUnsafe;
2029 void* movedBuffer = AllocBufferInGC(owner->zone(), dstBytes, nurseryOwned);
2030 if (!movedBuffer) {
2031 oomUnsafe.crash("Nursery::maybeMoveRawBufferOnPromotion");
2032 }
2033
2034 memcpy(movedBuffer, buffer, nbytes);
2035
2036 if (nurseryOwned) {
2037 registerBuffer(movedBuffer, nbytes);
2038 }
2039
2040 *bufferp = movedBuffer;
2041 return BufferMoved;
2042 }
2043
2044 void js::Nursery::sweepBuffers() {
2045 for (ZonesIter zone(runtime(), WithAtoms); !zone.done(); zone.next()) {
2046 if (zone->bufferAllocator.startMinorSweeping()) {
2047 sweepTask->queueAllocatorToSweep(zone->bufferAllocator);
2048 }
2049 }
2050
2051 AutoLockHelperThreadState lock;
2052 if (!sweepTask->isEmpty(lock)) {
2053 sweepTask->startOrRunIfIdle(lock);
2054 }
2055 }
2056
2057 void Nursery::requestMinorGC(JS::GCReason reason) {
2058 JS::HeapState heapState = runtime()->heapState();
2059 #ifdef DEBUG
2060 if (heapState == JS::HeapState::Idle ||
2061 heapState == JS::HeapState::MinorCollecting) {
2062 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime()));
2063 } else if (heapState == JS::HeapState::MajorCollecting) {
2064 // The GC runs sweeping tasks that may access the storebuffer in parallel
2065 // and these require taking the store buffer lock.
2066 MOZ_ASSERT(!CurrentThreadIsGCMarking());
2067 runtime()->gc.assertCurrentThreadHasLockedStoreBuffer();
2068 } else {
2069 MOZ_CRASH("Unexpected heap state");
2070 }
2071 #endif
2072
2073 MOZ_ASSERT(reason != JS::GCReason::NO_REASON);
2074 MOZ_ASSERT(isEnabled());
2075
2076 if (minorGCRequested()) {
2077 return;
2078 }
2079
2080 if (heapState == JS::HeapState::MinorCollecting) {
2081 // This can happen when we promote a lot of data to the second generation in
2082 // a semispace collection. This can trigger a GC due to the amount of store
2083 // buffer entries added.
2084 return;
2085 }
2086
2087 // Set position to end of chunk to block further allocation.
2088 MOZ_ASSERT(prevPosition_ == 0);
2089 prevPosition_ = position();
2090 toSpace.position_ = chunk(currentChunk()).end();
2091
2092 minorGCTriggerReason_ = reason;
2093 runtime()->mainContextFromAnyThread()->requestInterrupt(
2094 InterruptReason::MinorGC);
2095 }
2096
2097 size_t SemispaceSizeFactor(bool semispaceEnabled) {
2098 return semispaceEnabled ? 2 : 1;
2099 }
2100
2101 size_t js::Nursery::totalCapacity() const {
2102 return capacity() * SemispaceSizeFactor(semispaceEnabled_);
2103 }
2104
2105 size_t js::Nursery::totalCommitted() const {
2106 size_t size = std::min(capacity_, allocatedChunkCount() * gc::ChunkSize);
2107 return size * SemispaceSizeFactor(semispaceEnabled_);
2108 }
2109
2110 size_t Nursery::sizeOfMallocedBuffers(
2111 mozilla::MallocSizeOf mallocSizeOf) const {
2112 MOZ_ASSERT(fromSpace.mallocedBuffers.empty());
2113
2114 size_t total = 0;
2115 for (BufferSet::Range r = toSpace.mallocedBuffers.all(); !r.empty();
2116 r.popFront()) {
2117 total += mallocSizeOf(r.front());
2118 }
2119 total += toSpace.mallocedBuffers.shallowSizeOfExcludingThis(mallocSizeOf);
2120
2121 for (AllZonesIter zone(runtime()); !zone.done(); zone.next()) {
2122 total += zone->bufferAllocator.getSizeOfNurseryBuffers();
2123 }
2124
2125 return total;
2126 }
2127
2128 void js::Nursery::sweepStringsWithBuffer() {
2129 // Add StringBuffers to stringBuffersToReleaseAfterMinorGC_. Strings we
2130 // tenured must have an additional refcount at this point.
2131
2132 MOZ_ASSERT(stringBuffersToReleaseAfterMinorGC_.empty());
2133
2134 auto sweep = [&](JSLinearString* str,
2135 mozilla::StringBuffer* buffer) -> JSLinearString* {
2136 MOZ_ASSERT(inCollectedRegion(str));
2137
2138 if (!IsForwarded(str)) {
2139 MOZ_ASSERT(str->hasStringBuffer() || str->isAtomRef());
2140 MOZ_ASSERT_IF(str->hasStringBuffer(), str->stringBuffer() == buffer);
2141 if (!stringBuffersToReleaseAfterMinorGC_.append(buffer)) {
2142 // Release on the main thread on OOM.
2143 buffer->Release();
2144 }
2145 return nullptr;
2146 }
2147
2148 JSLinearString* dst = Forwarded(str);
2149 if (!IsInsideNursery(dst)) {
2150 MOZ_ASSERT_IF(dst->hasStringBuffer() && dst->stringBuffer() == buffer,
2151 buffer->RefCount() > 1);
2152 if (!stringBuffersToReleaseAfterMinorGC_.append(buffer)) {
2153 // Release on the main thread on OOM.
2154 buffer->Release();
2155 }
2156 return nullptr;
2157 }
2158
2159 return dst;
2160 };
2161
2162 stringBuffers_.mutableEraseIf([&](StringAndBuffer& entry) {
2163 if (JSLinearString* dst = sweep(entry.first, entry.second)) {
2164 entry.first = dst;
2165 // See comment in Nursery::addStringBuffer.
2166 if (!entry.second->HasMultipleReferences()) {
2167 addMallocedBufferBytes(entry.second->AllocationSize());
2168 }
2169 return false;
2170 }
2171 return true;
2172 });
2173
2174 AutoEnterOOMUnsafeRegion oomUnsafe;
2175
2176 ExtensibleStringBuffers buffers(std::move(extensibleStringBuffers_));
2177 MOZ_ASSERT(extensibleStringBuffers_.empty());
2178
2179 for (ExtensibleStringBuffers::Enum e(buffers); !e.empty(); e.popFront()) {
2180 if (JSLinearString* dst = sweep(e.front().key(), e.front().value())) {
2181 if (!extensibleStringBuffers_.putNew(dst, e.front().value())) {
2182 oomUnsafe.crash("sweepStringsWithBuffer");
2183 }
2184 // Ensure mallocedBufferBytes includes the buffer size for
2185 // removeExtensibleStringBuffer.
2186 addMallocedBufferBytes(e.front().value()->AllocationSize());
2187 }
2188 }
2189 }
2190
2191 void js::Nursery::sweep() {
2192 // It's important that the context's GCUse is not Finalizing at this point,
2193 // otherwise we will miscount memory attached to nursery objects with
2194 // CellAllocPolicy.
2195 AutoSetThreadIsSweeping setThreadSweeping(runtime()->gcContext());
2196
2197 // Start sweeping buffers off-thread as soon as possible.
2198 sweepBuffers();
2199
2200 MinorSweepingTracer trc(runtime());
2201
2202 // Sweep unique IDs first before we sweep any tables that may be keyed based
2203 // on them.
2204 cellsWithUid_.mutableEraseIf([](Cell*& cell) {
2205 auto* obj = static_cast<JSObject*>(cell);
2206 if (!IsForwarded(obj)) {
2207 gc::RemoveUniqueId(obj);
2208 return true;
2209 }
2210
2211 JSObject* dst = Forwarded(obj);
2212 gc::TransferUniqueId(dst, obj);
2213
2214 if (!IsInsideNursery(dst)) {
2215 return true;
2216 }
2217
2218 cell = dst;
2219 return false;
2220 });
2221
2222 sweepStringsWithBuffer();
2223
2224 for (ZonesIter zone(runtime(), SkipAtoms); !zone.done(); zone.next()) {
2225 zone->sweepAfterMinorGC(&trc);
2226 }
2227
2228 sweepMapAndSetObjects();
2229
2230 runtime()->caches().sweepAfterMinorGC(&trc);
2231 }
2232
2233 void js::Nursery::clear() {
2234 fromSpace.clear(this);
2235 MOZ_ASSERT(fromSpace.isEmpty());
2236 }
2237
2238 void js::Nursery::Space::clear(Nursery* nursery) {
2239 GCRuntime* gc = nursery->gc;
2240
2241 // Poison the nursery contents so touching a freed object will crash.
2242 unsigned firstClearChunk;
2243 if (gc->hasZealMode(ZealMode::GenerationalGC) || nursery->semispaceEnabled_) {
2244 // Poison all the chunks used in this cycle.
2245 firstClearChunk = startChunk_;
2246 } else {
2247 // Poison from the second chunk onwards as the first one will be used
2248 // in the next cycle and poisoned in Nusery::collect();
2249 MOZ_ASSERT(startChunk_ == 0);
2250 firstClearChunk = 1;
2251 }
2252 for (unsigned i = firstClearChunk; i < currentChunk_; ++i) {
2253 chunks_[i]->poisonAfterEvict();
2254 }
2255 // Clear only the used part of the chunk because that's the part we touched,
2256 // but only if it's not going to be re-used immediately (>= firstClearChunk).
2257 if (currentChunk_ >= firstClearChunk) {
2258 size_t usedBytes = position_ - chunks_[currentChunk_]->start();
2259 chunks_[currentChunk_]->poisonAfterEvict(NurseryChunkHeaderSize +
2260 usedBytes);
2261 }
2262
2263 // Reset the start chunk & position if we're not in this zeal mode, or we're
2264 // in it and close to the end of the nursery.
2265 MOZ_ASSERT(maxChunkCount_ > 0);
2266 if (!gc->hasZealMode(ZealMode::GenerationalGC) ||
2267 currentChunk_ + 1 == maxChunkCount_) {
2268 moveToStartOfChunk(nursery, 0);
2269 }
2270
2271 // Set current start position for isEmpty checks.
2272 setStartToCurrentPosition();
2273 }
2274
2275 void js::Nursery::moveToStartOfChunk(unsigned chunkno) {
2276 toSpace.moveToStartOfChunk(this, chunkno);
2277 }
2278
2279 void js::Nursery::Space::moveToStartOfChunk(Nursery* nursery,
2280 unsigned chunkno) {
2281 MOZ_ASSERT(chunkno < chunks_.length());
2282
2283 currentChunk_ = chunkno;
2284 position_ = chunks_[chunkno]->start();
2285 setCurrentEnd(nursery);
2286
2287 MOZ_ASSERT(position_ != 0);
2288 MOZ_ASSERT(currentEnd_ > position_); // Check this cannot wrap.
2289 }
2290
2291 void js::Nursery::poisonAndInitCurrentChunk() {
2292 NurseryChunk& chunk = this->chunk(currentChunk());
2293 size_t start = position() - uintptr_t(&chunk);
2294 size_t end = isSubChunkMode() ? capacity_ : ChunkSize;
2295 chunk.poisonRange(start, end, JS_FRESH_NURSERY_PATTERN,
2296 MemCheckKind::MakeUndefined);
2297 new (&chunk)
2298 NurseryChunk(runtime(), ChunkKind::NurseryToSpace, currentChunk());
2299 }
2300
2301 void js::Nursery::setCurrentEnd() { toSpace.setCurrentEnd(this); }
2302
2303 void js::Nursery::Space::setCurrentEnd(Nursery* nursery) {
2304 size_t chunkBytesToUse = ChunkSize;
2305
2306 // To avoid problems with inline object elements abutting the end of a chunk,
2307 // reduce the size used slightly. This wastes 8 bytes per chunk.
2308 chunkBytesToUse -= gc::CellAlignBytes;
2309
2310 currentEnd_ = uintptr_t(chunks_[currentChunk_]) +
2311 std::min(nursery->capacity(), chunkBytesToUse);
2312 }
2313
2314 bool js::Nursery::allocateNextChunk(AutoLockGCBgAlloc& lock) {
2315 // Allocate a new nursery chunk. If semispace collection is enabled, we have
2316 // to allocate one for both spaces.
2317
2318 const unsigned priorCount = toSpace.chunks_.length();
2319 const unsigned newCount = priorCount + 1;
2320
2321 MOZ_ASSERT(newCount <= maxChunkCount());
2322 MOZ_ASSERT(fromSpace.chunks_.length() ==
2323 (semispaceEnabled_ ? priorCount : 0));
2324
2325 if (!toSpace.chunks_.reserve(newCount) ||
2326 (semispaceEnabled_ && !fromSpace.chunks_.reserve(newCount))) {
2327 return false;
2328 }
2329
2330 ArenaChunk* toSpaceChunk = gc->takeOrAllocChunk(StallAndRetry::No, lock);
2331 if (!toSpaceChunk) {
2332 return false;
2333 }
2334
2335 ArenaChunk* fromSpaceChunk = nullptr;
2336 if (semispaceEnabled_ &&
2337 !(fromSpaceChunk = gc->takeOrAllocChunk(StallAndRetry::No, lock))) {
2338 gc->recycleChunk(toSpaceChunk, lock);
2339 return false;
2340 }
2341
2342 uint8_t index = toSpace.chunks_.length();
2343 NurseryChunk* nurseryChunk =
2344 NurseryChunk::fromChunk(toSpaceChunk, ChunkKind::NurseryToSpace, index);
2345 toSpace.chunks_.infallibleAppend(nurseryChunk);
2346
2347 if (semispaceEnabled_) {
2348 MOZ_ASSERT(index == fromSpace.chunks_.length());
2349 nurseryChunk = NurseryChunk::fromChunk(fromSpaceChunk,
2350 ChunkKind::NurseryFromSpace, index);
2351 fromSpace.chunks_.infallibleAppend(nurseryChunk);
2352 }
2353
2354 return true;
2355 }
2356
2357 void js::Nursery::setStartToCurrentPosition() {
2358 toSpace.setStartToCurrentPosition();
2359 }
2360
2361 void js::Nursery::Space::setStartToCurrentPosition() {
2362 startChunk_ = currentChunk_;
2363 startPosition_ = position_;
2364 MOZ_ASSERT(isEmpty());
2365 }
2366
2367 void js::Nursery::maybeResizeNursery(JS::GCOptions options,
2368 JS::GCReason reason) {
2369 #ifdef JS_GC_ZEAL
2370 // This zeal mode disabled nursery resizing.
2371 if (gc->hasZealMode(ZealMode::GenerationalGC)) {
2372 return;
2373 }
2374 #endif
2375
2376 decommitTask->join();
2377
2378 size_t newCapacity =
2379 std::clamp(targetSize(options, reason), minSpaceSize(), maxSpaceSize());
2380
2381 MOZ_ASSERT(roundSize(newCapacity) == newCapacity);
2382 MOZ_ASSERT(newCapacity >= SystemPageSize());
2383
2384 if (newCapacity > capacity()) {
2385 growAllocableSpace(newCapacity);
2386 } else if (newCapacity < capacity()) {
2387 shrinkAllocableSpace(newCapacity);
2388 }
2389
2390 AutoLockHelperThreadState lock;
2391 if (!decommitTask->isEmpty(lock)) {
2392 decommitTask->startOrRunIfIdle(lock);
2393 }
2394 }
2395
2396 static inline bool ClampDouble(double* value, double min, double max) {
2397 MOZ_ASSERT(!std::isnan(*value) && !std::isnan(min) && !std::isnan(max));
2398 MOZ_ASSERT(max >= min);
2399
2400 if (*value <= min) {
2401 *value = min;
2402 return true;
2403 }
2404
2405 if (*value >= max) {
2406 *value = max;
2407 return true;
2408 }
2409
2410 return false;
2411 }
2412
2413 size_t js::Nursery::targetSize(JS::GCOptions options, JS::GCReason reason) {
2414 // Shrink the nursery as much as possible if purging was requested or in low
2415 // memory situations.
2416 if (options == JS::GCOptions::Shrink || gc::IsOOMReason(reason) ||
2417 gc->systemHasLowMemory()) {
2418 clearRecentGrowthData();
2419 return 0;
2420 }
2421
2422 // Don't resize the nursery during shutdown.
2423 if (options == JS::GCOptions::Shutdown) {
2424 clearRecentGrowthData();
2425 return capacity();
2426 }
2427
2428 TimeStamp now = TimeStamp::Now();
2429
2430 if (reason == JS::GCReason::PREPARE_FOR_PAGELOAD) {
2431 return roundSize(maxSpaceSize());
2432 }
2433
2434 // If the nursery is completely unused then minimise it.
2435 if (hasRecentGrowthData && previousGC.nurseryUsedBytes == 0 &&
2436 now - lastCollectionEndTime() >
2437 tunables().nurseryEagerCollectionTimeout() &&
2438 !js::SupportDifferentialTesting()) {
2439 clearRecentGrowthData();
2440 return 0;
2441 }
2442
2443 // Calculate the fraction of the nursery promoted out of its entire
2444 // capacity. This gives better results than using the promotion rate (based on
2445 // the amount of nursery used) in cases where we collect before the nursery is
2446 // full.
2447 double fractionPromoted =
2448 double(previousGC.tenuredBytes) / double(previousGC.nurseryCapacity);
2449
2450 // Calculate the duty factor, the fraction of time spent collecting the
2451 // nursery.
2452 double dutyFactor = 0.0;
2453 TimeDuration collectorTime = now - collectionStartTime();
2454 if (hasRecentGrowthData && !js::SupportDifferentialTesting()) {
2455 TimeDuration totalTime = now - lastCollectionEndTime();
2456 dutyFactor = collectorTime.ToSeconds() / totalTime.ToSeconds();
2457 }
2458
2459 // Calculate a growth factor to try to achieve target promotion rate and duty
2460 // factor goals.
2461 static const double PromotionGoal = 0.02;
2462 static const double DutyFactorGoal = 0.01;
2463 double promotionGrowth = fractionPromoted / PromotionGoal;
2464 double dutyGrowth = dutyFactor / DutyFactorGoal;
2465 double growthFactor = std::max(promotionGrowth, dutyGrowth);
2466
2467 #ifndef DEBUG
2468 // In optimized builds, decrease the growth factor to try to keep collections
2469 // shorter than a target maximum time. Don't do this during page load.
2470 //
2471 // Debug builds are so much slower and more unpredictable that doing this
2472 // would cause very different nursery behaviour to an equivalent release
2473 // build.
2474 double maxTimeGoalMS = tunables().nurseryMaxTimeGoalMS().ToMilliseconds();
2475 if (!gc->isInPageLoad() && maxTimeGoalMS != 0.0 &&
2476 !js::SupportDifferentialTesting()) {
2477 double timeGrowth = maxTimeGoalMS / collectorTime.ToMilliseconds();
2478 growthFactor = std::min(growthFactor, timeGrowth);
2479 }
2480 #endif
2481
2482 // Limit the range of the growth factor to prevent transient high promotion
2483 // rates from affecting the nursery size too far into the future.
2484 static const double GrowthRange = 2.0;
2485 bool wasClamped = ClampDouble(&growthFactor, 1.0 / GrowthRange, GrowthRange);
2486
2487 // Calculate the target size based on data from this collection.
2488 double target = double(capacity()) * growthFactor;
2489
2490 // Use exponential smoothing on the target size to take into account data from
2491 // recent previous collections.
2492 if (hasRecentGrowthData &&
2493 now - lastCollectionEndTime() < TimeDuration::FromMilliseconds(200) &&
2494 !js::SupportDifferentialTesting()) {
2495 // Pay more attention to large changes.
2496 double fraction = wasClamped ? 0.5 : 0.25;
2497 smoothedTargetSize =
2498 (1 - fraction) * smoothedTargetSize + fraction * target;
2499 } else {
2500 smoothedTargetSize = target;
2501 }
2502 hasRecentGrowthData = true;
2503
2504 // Leave size untouched if we are close to the target.
2505 static const double GoalWidth = 1.5;
2506 growthFactor = smoothedTargetSize / double(capacity());
2507 if (growthFactor > (1.0 / GoalWidth) && growthFactor < GoalWidth) {
2508 return capacity();
2509 }
2510
2511 return roundSize(size_t(smoothedTargetSize));
2512 }
2513
2514 void js::Nursery::clearRecentGrowthData() {
2515 if (js::SupportDifferentialTesting()) {
2516 return;
2517 }
2518
2519 hasRecentGrowthData = false;
2520 smoothedTargetSize = 0.0;
2521 }
2522
2523 /* static */
2524 size_t js::Nursery::roundSize(size_t size) {
2525 size_t step = size >= ChunkSize ? ChunkSize : SystemPageSize();
2526 return Round(size, step);
2527 }
2528
2529 void js::Nursery::growAllocableSpace(size_t newCapacity) {
2530 MOZ_ASSERT_IF(!isSubChunkMode(), newCapacity > currentChunk() * ChunkSize);
2531 MOZ_ASSERT(newCapacity <= maxSpaceSize());
2532 MOZ_ASSERT(newCapacity > capacity());
2533
2534 size_t nchunks =
2535 RequiredChunkCount(newCapacity) * SemispaceSizeFactor(semispaceEnabled_);
2536 if (!decommitTask->reserveSpaceForChunks(nchunks)) {
2537 return;
2538 }
2539
2540 if (isSubChunkMode()) {
2541 if (!toSpace.commitSubChunkRegion(capacity(), newCapacity) ||
2542 (semispaceEnabled_ &&
2543 !fromSpace.commitSubChunkRegion(capacity(), newCapacity))) {
2544 return;
2545 }
2546 }
2547
2548 setCapacity(newCapacity);
2549
2550 toSpace.setCurrentEnd(this);
2551 if (semispaceEnabled_) {
2552 fromSpace.setCurrentEnd(this);
2553 }
2554 }
2555
2556 bool js::Nursery::Space::commitSubChunkRegion(size_t oldCapacity,
2557 size_t newCapacity) {
2558 MOZ_ASSERT(currentChunk_ == 0);
2559 MOZ_ASSERT(oldCapacity < ChunkSize);
2560 MOZ_ASSERT(newCapacity > oldCapacity);
2561
2562 size_t newChunkEnd = std::min(newCapacity, ChunkSize);
2563
2564 // The remainder of the chunk may have been decommitted.
2565 if (!chunks_[0]->markPagesInUseHard(newChunkEnd)) {
2566 // The OS won't give us the memory we need, we can't grow.
2567 return false;
2568 }
2569
2570 // The capacity has changed and since we were in sub-chunk mode we need to
2571 // update the poison values / asan information for the now-valid region of
2572 // this chunk.
2573 chunks_[0]->poisonRange(oldCapacity, newChunkEnd, JS_FRESH_NURSERY_PATTERN,
2574 MemCheckKind::MakeUndefined);
2575 return true;
2576 }
2577
2578 void js::Nursery::freeChunksFrom(Space& space, const unsigned firstFreeChunk) {
2579 if (firstFreeChunk >= space.chunks_.length()) {
2580 return;
2581 }
2582
2583 // The loop below may need to skip the first chunk, so we may use this so we
2584 // can modify it.
2585 unsigned firstChunkToDecommit = firstFreeChunk;
2586
2587 if ((firstChunkToDecommit == 0) && isSubChunkMode()) {
2588 // Part of the first chunk may be hard-decommitted, un-decommit it so that
2589 // the GC's normal chunk-handling doesn't segfault.
2590 MOZ_ASSERT(space.currentChunk_ == 0);
2591 if (!space.chunks_[0]->markPagesInUseHard(ChunkSize)) {
2592 // Free the chunk if we can't allocate its pages.
2593 UnmapPages(space.chunks_[0], ChunkSize);
2594 firstChunkToDecommit = 1;
2595 }
2596 }
2597
2598 {
2599 AutoLockHelperThreadState lock;
2600 for (size_t i = firstChunkToDecommit; i < space.chunks_.length(); i++) {
2601 decommitTask->queueChunk(space.chunks_[i], lock);
2602 }
2603 }
2604
2605 space.chunks_.shrinkTo(firstFreeChunk);
2606 }
2607
2608 void js::Nursery::shrinkAllocableSpace(size_t newCapacity) {
2609 MOZ_ASSERT(!gc->hasZealMode(ZealMode::GenerationalGC));
2610 MOZ_ASSERT(newCapacity < capacity_);
2611
2612 if (semispaceEnabled() && usedSpace() >= newCapacity) {
2613 // Can't shrink below what we've already used.
2614 return;
2615 }
2616
2617 unsigned newCount = HowMany(newCapacity, ChunkSize);
2618 if (newCount < allocatedChunkCount()) {
2619 freeChunksFrom(toSpace, newCount);
2620 freeChunksFrom(fromSpace, newCount);
2621 }
2622
2623 size_t oldCapacity = capacity_;
2624 setCapacity(newCapacity);
2625
2626 toSpace.setCurrentEnd(this);
2627 if (semispaceEnabled_) {
2628 fromSpace.setCurrentEnd(this);
2629 }
2630
2631 if (isSubChunkMode()) {
2632 toSpace.decommitSubChunkRegion(this, oldCapacity, newCapacity);
2633 if (semispaceEnabled_) {
2634 fromSpace.decommitSubChunkRegion(this, oldCapacity, newCapacity);
2635 }
2636 }
2637 }
2638
2639 void js::Nursery::Space::decommitSubChunkRegion(Nursery* nursery,
2640 size_t oldCapacity,
2641 size_t newCapacity) {
2642 MOZ_ASSERT(currentChunk_ == 0);
2643 MOZ_ASSERT(newCapacity < ChunkSize);
2644 MOZ_ASSERT(newCapacity < oldCapacity);
2645
2646 size_t oldChunkEnd = std::min(oldCapacity, ChunkSize);
2647 chunks_[0]->poisonRange(newCapacity, oldChunkEnd, JS_SWEPT_NURSERY_PATTERN,
2648 MemCheckKind::MakeNoAccess);
2649
2650 AutoLockHelperThreadState lock;
2651 nursery->decommitTask->queueRange(newCapacity, chunks_[0], lock);
2652 }
2653
2654 js::Nursery::Space::Space(gc::ChunkKind kind) : kind(kind) {
2655 MOZ_ASSERT(kind == ChunkKind::NurseryFromSpace ||
2656 kind == ChunkKind::NurseryToSpace);
2657 }
2658
2659 void js::Nursery::Space::setKind(ChunkKind newKind) {
2660 #ifdef DEBUG
2661 MOZ_ASSERT(newKind == ChunkKind::NurseryFromSpace ||
2662 newKind == ChunkKind::NurseryToSpace);
2663 checkKind(kind);
2664 #endif
2665
2666 kind = newKind;
2667 for (NurseryChunk* chunk : chunks_) {
2668 chunk->kind = newKind;
2669 }
2670
2671 #ifdef DEBUG
2672 checkKind(newKind);
2673 #endif
2674 }
2675
2676 #ifdef DEBUG
2677 void js::Nursery::Space::checkKind(ChunkKind expected) const {
2678 MOZ_ASSERT(kind == expected);
2679 for (NurseryChunk* chunk : chunks_) {
2680 MOZ_ASSERT(chunk->getKind() == expected);
2681 }
2682 }
2683 #endif
2684
2685 #ifdef DEBUG
2686 size_t js::Nursery::Space::findChunkIndex(uintptr_t chunkAddr) const {
2687 for (size_t i = 0; i < chunks_.length(); i++) {
2688 if (uintptr_t(chunks_[i]) == chunkAddr) {
2689 return i;
2690 }
2691 }
2692
2693 MOZ_CRASH("Nursery chunk not found");
2694 }
2695 #endif
2696
2697 gcstats::Statistics& js::Nursery::stats() const { return gc->stats(); }
2698
2699 MOZ_ALWAYS_INLINE const js::gc::GCSchedulingTunables& js::Nursery::tunables()
2700 const {
2701 return gc->tunables;
2702 }
2703
2704 bool js::Nursery::isSubChunkMode() const {
2705 return capacity() <= NurseryChunkUsableSize;
2706 }
2707
2708 void js::Nursery::clearMapAndSetNurseryIterators() {
2709 // Clears the lists of nursery iterators for all Map/Set objects. These lists
2710 // are cleared at the start of minor GC and rebuilt when iterators are
2711 // promoted during minor GC.
2712 for (auto* map : mapsWithNurseryIterators_) {
2713 map->clearNurseryIteratorsBeforeMinorGC();
2714 }
2715 for (auto* set : setsWithNurseryIterators_) {
2716 set->clearNurseryIteratorsBeforeMinorGC();
2717 }
2718 }
2719
2720 void js::Nursery::sweepMapAndSetObjects() {
2721 // This processes all Map and Set objects that are known to have associated
2722 // iterator objects that are nursery allocated.
2723 //
2724 // These objects may die and be finalized or if not their internal state and
2725 // memory tracking are updated.
2726 //
2727 // Finally the lists themselves are rebuilt so as to remove objects that are
2728 // no longer associated with nursery iterators (because all iterators died or
2729 // were promoted to the tenured heap).
2730
2731 auto* gcx = runtime()->gcContext();
2732
2733 AutoEnterOOMUnsafeRegion oomUnsafe;
2734
2735 MapObjectVector maps;
2736 std::swap(mapsWithNurseryIterators_, maps);
2737 for (auto* mapobj : maps) {
2738 mapobj = MapObject::sweepAfterMinorGC(gcx, mapobj);
2739 if (mapobj) {
2740 if (!mapsWithNurseryIterators_.append(mapobj)) {
2741 oomUnsafe.crash("sweepAfterMinorGC");
2742 }
2743 }
2744 }
2745
2746 SetObjectVector sets;
2747 std::swap(setsWithNurseryIterators_, sets);
2748 for (auto* setobj : sets) {
2749 setobj = SetObject::sweepAfterMinorGC(gcx, setobj);
2750 if (setobj) {
2751 if (!setsWithNurseryIterators_.append(setobj)) {
2752 oomUnsafe.crash("sweepAfterMinorGC");
2753 }
2754 }
2755 }
2756 }
2757
2758 void js::Nursery::joinSweepTask() { sweepTask->join(); }
2759 void js::Nursery::joinDecommitTask() { decommitTask->join(); }
2760
2761 #ifdef DEBUG
2762 bool js::Nursery::sweepTaskIsIdle() { return sweepTask->isIdle(); }
2763 #endif