Debian Codegraph @

js/src/gc/Statistics.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef gc_Statistics_h
8 #define gc_Statistics_h
9
10 #include "mozilla/Array.h"
11 #include "mozilla/Atomics.h"
12 #include "mozilla/EnumeratedArray.h"
13 #include "mozilla/Maybe.h"
14 #include "mozilla/TimeStamp.h"
15
16 #include "jspubtd.h"
17 #include "NamespaceImports.h"
18
19 #include "gc/GCEnum.h"
20 #include "js/AllocPolicy.h"
21 #include "js/GCAPI.h"
22 #include "js/SliceBudget.h"
23 #include "js/Vector.h"
24
25 namespace js {
26
27 class JS_PUBLIC_API Sprinter;
28 class JSONPrinter;
29
30 namespace gcstats {
31
32 // Phase data is generated by a script. If you need to add phases, edit
33 // js/src/gc/GenerateStatsPhases.py
34
35 #include "gc/StatsPhasesGenerated.h"
36
37 // Counts can be incremented with Statistics::count(). They're reset at the end
38 // of a Major GC.
39 enum Count {
40 COUNT_NEW_CHUNK,
41 COUNT_DESTROY_CHUNK,
42 COUNT_MINOR_GC,
43
44 // Number of times a 'put' into a storebuffer overflowed, triggering a
45 // compaction
46 COUNT_STOREBUFFER_OVERFLOW,
47
48 // Number of arenas relocated by compacting GC.
49 COUNT_ARENA_RELOCATED,
50
51 // Number of cells marked during the marking phase. Excludes atoms marked when
52 // not collecting the atoms zone.
53 COUNT_CELLS_MARKED,
54
55 // Number of times work was donated to a requesting thread during parallel
56 // marking.
57 COUNT_PARALLEL_MARK_INTERRUPTIONS,
58
59 COUNT_LIMIT
60 };
61
62 // Stats can be set with Statistics::setStat(). They're not reset automatically.
63 enum Stat {
64 // Number of strings promoted.
65 STAT_STRINGS_PROMOTED,
66
67 // Number of strings deduplicated.
68 STAT_STRINGS_DEDUPLICATED,
69
70 // Number of BigInts promoted.
71 STAT_BIGINTS_PROMOTED,
72
73 STAT_LIMIT
74 };
75
76 struct ZoneGCStats {
77 /* Number of zones collected in this GC. */
78 size_t collectedZoneCount = 0;
79
80 /* Total number of zones in the Runtime at the start of this GC. */
81 size_t zoneCount = 0;
82
83 /* Number of zones swept in this GC. */
84 size_t sweptZoneCount = 0;
85
86 /* Total number of compartments in all zones collected. */
87 size_t collectedCompartmentCount = 0;
88
89 /* Total number of compartments in the Runtime at the start of this GC. */
90 size_t compartmentCount = 0;
91
92 /* Total number of compartments swept by this GC. */
93 size_t sweptCompartmentCount = 0;
94
95 /* Total number of realms in the Runtime at the start of this GC. */
96 size_t realmCount = 0;
97
98 ZoneGCStats() = default;
99 };
100
101 struct Trigger {
102 size_t amount = 0;
103 size_t threshold = 0;
104 };
105
106 #define FOR_EACH_GC_PROFILE_TIME(_) \
107 _(Total, "total", PhaseKind::NONE) \
108 _(Background, "bgwrk", PhaseKind::NONE) \
109 _(MinorForMajor, "evct4m", PhaseKind::EVICT_NURSERY_FOR_MAJOR_GC) \
110 _(WaitBgThread, "waitBG", PhaseKind::WAIT_BACKGROUND_THREAD) \
111 _(Prepare, "prep", PhaseKind::PREPARE) \
112 _(Mark, "mark", PhaseKind::MARK) \
113 _(Sweep, "sweep", PhaseKind::SWEEP) \
114 _(Compact, "cmpct", PhaseKind::COMPACT) \
115 _(Decommit, "dcmmt", PhaseKind::DECOMMIT)
116
117 static const char* const MajorGCProfilePrefix = "MajorGC:";
118 static const char* const MinorGCProfilePrefix = "MinorGC:";
119
120 const char* ExplainAbortReason(GCAbortReason reason);
121
122 /*
123 * Struct for collecting timing statistics on a "phase tree". The tree is
124 * specified as a limited DAG, but the timings are collected for the whole tree
125 * that you would get by expanding out the DAG by duplicating subtrees rooted
126 * at nodes with multiple parents.
127 *
128 * During execution, a child phase can be activated multiple times, and the
129 * total time will be accumulated. (So for example, you can start and end
130 * PhaseKind::MARK_ROOTS multiple times before completing the parent phase.)
131 *
132 * Incremental GC is represented by recording separate timing results for each
133 * slice within the overall GC.
134 */
135 struct Statistics {
136 template <typename T, size_t Length>
137 using Array = mozilla::Array<T, Length>;
138
139 template <typename IndexType, typename ValueType, IndexType SizeAsEnumValue>
140 using EnumeratedArray =
141 mozilla::EnumeratedArray<IndexType, ValueType, size_t(SizeAsEnumValue)>;
142
143 using TimeDuration = mozilla::TimeDuration;
144 using TimeStamp = mozilla::TimeStamp;
145
146 // Create types for tables of times, by phase and phase kind.
147 using PhaseTimes = EnumeratedArray<Phase, TimeDuration, Phase::LIMIT>;
148 using PhaseKindTimes =
149 EnumeratedArray<PhaseKind, TimeDuration, PhaseKind::LIMIT>;
150
151 using PhaseTimeStamps = EnumeratedArray<Phase, TimeStamp, Phase::LIMIT>;
152
153 [[nodiscard]] static bool initialize();
154
155 explicit Statistics(gc::GCRuntime* gc);
156 ~Statistics();
157
158 Statistics(const Statistics&) = delete;
159 Statistics& operator=(const Statistics&) = delete;
160
161 void beginPhase(PhaseKind phaseKind);
162 void endPhase(PhaseKind phaseKind);
163 void recordParallelPhase(PhaseKind phaseKind, TimeDuration duration);
164
165 // Occasionally, we may be in the middle of something that is tracked by
166 // this class, and we need to do something unusual (eg evict the nursery)
167 // that doesn't normally nest within the current phase. Suspend the
168 // currently tracked phase stack, at which time the caller is free to do
169 // other tracked operations.
170 //
171 // This also happens internally with the PhaseKind::MUTATOR "phase". While in
172 // this phase, any beginPhase will automatically suspend the non-GC phase,
173 // until that inner stack is complete, at which time it will automatically
174 // resume the non-GC phase. Explicit suspensions do not get auto-resumed.
175 void suspendPhases(PhaseKind suspension = PhaseKind::EXPLICIT_SUSPENSION);
176
177 // Resume a suspended stack of phases.
178 void resumePhases();
179
180 void beginSlice(const ZoneGCStats& zoneStats, JS::GCOptions options,
181 const JS::SliceBudget& budget, JS::GCReason reason,
182 bool budgetWasIncreased);
183 void endSlice();
184
185 [[nodiscard]] bool startTimingMutator();
186 [[nodiscard]] bool stopTimingMutator(double& mutator_ms, double& gc_ms);
187
188 // Note when we sweep a zone or compartment.
189 void sweptZone() { ++zoneStats.sweptZoneCount; }
190 void sweptCompartment() { ++zoneStats.sweptCompartmentCount; }
191
192 void reset(GCAbortReason reason) {
193 MOZ_ASSERT(reason != GCAbortReason::None);
194 if (!aborted) {
195 slices_.back().resetReason = reason;
196 }
197 }
198
199 void measureInitialHeapSizes();
200
201 void nonincremental(GCAbortReason reason) {
202 MOZ_ASSERT(reason != GCAbortReason::None);
203 nonincrementalReason_ = reason;
204 log("Non-incremental reason: %s", nonincrementalReason());
205 }
206
207 bool nonincremental() const {
208 return nonincrementalReason_ != GCAbortReason::None;
209 }
210
211 const char* nonincrementalReason() const {
212 return ExplainAbortReason(nonincrementalReason_);
213 }
214
215 void count(Count s) { counts[s]++; }
216 void addCount(Count s, uint32_t count) { counts[s] += count; }
217
218 uint32_t getCount(Count s) const { return uint32_t(counts[s]); }
219
220 void setStat(Stat s, uint32_t value) { stats[s] = value; }
221
222 uint32_t getStat(Stat s) const { return stats[s]; }
223
224 void recordTrigger(size_t amount, size_t threshold) {
225 recordedTrigger = mozilla::Some(Trigger{amount, threshold});
226 }
227 bool hasTrigger() const { return recordedTrigger.isSome(); }
228
229 // tenured allocs don't include nursery evictions.
230 void setAllocsSinceMinorGCTenured(uint32_t allocs) {
231 tenuredAllocsSinceMinorGC = allocs;
232 }
233
234 uint32_t allocsSinceMinorGCTenured() { return tenuredAllocsSinceMinorGC; }
235
236 void beginNurseryCollection();
237 void endNurseryCollection();
238
239 TimeStamp beginSCC();
240 void endSCC(unsigned scc, TimeStamp start);
241
242 UniqueChars formatCompactSliceMessage() const;
243 UniqueChars formatCompactSummaryMessage() const;
244 UniqueChars formatDetailedMessage() const;
245
246 JS::GCSliceCallback setSliceCallback(JS::GCSliceCallback callback);
247
248 TimeDuration clearMaxGCPauseAccumulator();
249 TimeDuration getMaxGCPauseSinceClear();
250
251 PhaseKind currentPhaseKind() const;
252
253 static const size_t MAX_SUSPENDED_PHASES = MAX_PHASE_NESTING * 3;
254
255 struct SliceData {
256 SliceData(const JS::SliceBudget& budget, mozilla::Maybe<Trigger> trigger,
257 JS::GCReason reason, TimeStamp start, size_t startFaults,
258 gc::State initialState);
259
260 JS::SliceBudget budget;
261 JS::GCReason reason = JS::GCReason::NO_REASON;
262 mozilla::Maybe<Trigger> trigger;
263 gc::State initialState = gc::State::NotActive;
264 gc::State finalState = gc::State::NotActive;
265 GCAbortReason resetReason = GCAbortReason::None;
266 TimeStamp start;
267 TimeStamp end;
268 size_t startFaults = 0;
269 size_t endFaults = 0;
270 PhaseTimes phaseTimes;
271 PhaseKindTimes totalParallelTimes;
272 PhaseKindTimes maxParallelTimes;
273
274 TimeDuration duration() const;
275 bool wasReset() const { return resetReason != GCAbortReason::None; }
276 };
277
278 using SliceDataVector = Vector<SliceData, 8, SystemAllocPolicy>;
279
280 const SliceDataVector& slices() const { return slices_; }
281 const SliceData& sliceAt(size_t index) const { return slices_[index]; }
282
283 const SliceData* lastSlice() const {
284 if (slices_.length() == 0) {
285 return nullptr;
286 }
287
288 return &slices_.back();
289 }
290
291 TimeStamp start() const { return slices_[0].start; }
292
293 TimeStamp end() const { return slices_.back().end; }
294
295 TimeStamp creationTime() const { return creationTime_; }
296
297 TimeDuration totalGCTime() const { return totalGCTime_; }
298 size_t initialCollectedBytes() const { return preCollectedGCHeapBytes; }
299
300 // File to write profiling information to, either stderr or file specified
301 // with JS_GC_PROFILE_FILE.
302 FILE* profileFile() const { return gcProfileFile; }
303
304 // Occasionally print header lines for profiling information.
305 void maybePrintProfileHeaders();
306
307 // Print header line for profile times.
308 void printProfileHeader();
309
310 // Print total profile times on shutdown.
311 void printTotalProfileTimes();
312
313 // These JSON strings are used by the firefox profiler to display the GC
314 // markers.
315
316 // Return JSON for a whole major GC
317 UniqueChars renderJsonMessage() const;
318
319 // Return JSON for the timings of just the given slice.
320 UniqueChars renderJsonSlice(size_t sliceNum) const;
321
322 // Return JSON for the previous nursery collection.
323 UniqueChars renderNurseryJson() const;
324
325 bool bufferAllocStatsEnabled() const { return enableBufferAllocStats_; }
326
327 #ifdef DEBUG
328 // Print a logging message.
329 void log(const char* fmt, ...);
330 #else
331 void log(const char* fmt, ...) {};
332 #endif
333
334 private:
335 gc::GCRuntime* const gc;
336
337 /* File used for MOZ_GCTIMER output. */
338 FILE* gcTimerFile;
339
340 /* File used for JS_GC_DEBUG output. */
341 FILE* gcDebugFile;
342
343 /* File used for JS_GC_PROFILE output. */
344 FILE* gcProfileFile;
345
346 ZoneGCStats zoneStats;
347
348 JS::GCOptions gcOptions = JS::GCOptions::Normal;
349
350 GCAbortReason nonincrementalReason_;
351
352 SliceDataVector slices_;
353
354 /* Most recent time when the given phase started. */
355 PhaseTimeStamps phaseStartTimes;
356
357 #ifdef DEBUG
358 /* Most recent time when the given phase ended. */
359 PhaseTimeStamps phaseEndTimes;
360 #endif
361
362 TimeStamp creationTime_;
363
364 /* Bookkeeping for GC timings when timingMutator is true */
365 TimeStamp timedGCStart;
366 TimeDuration timedGCTime;
367
368 /* Total main thread time in a given phase for this GC. */
369 PhaseTimes phaseTimes;
370
371 /* Total main thread time for this GC. */
372 TimeDuration totalGCTime_;
373
374 /* Number of events of this type for this GC. */
375 EnumeratedArray<Count, mozilla::Atomic<uint32_t, mozilla::ReleaseAcquire>,
376 COUNT_LIMIT>
377 counts;
378
379 /* Other GC statistics. */
380 EnumeratedArray<Stat, uint32_t, STAT_LIMIT> stats;
381
382 /*
383 * These events cannot be kept in the above array, we need to take their
384 * address.
385 */
386 uint32_t tenuredAllocsSinceMinorGC;
387
388 /* Total GC heap size before and after the GC ran. */
389 size_t preTotalGCHeapBytes;
390 size_t postTotalGCHeapBytes;
391
392 /* GC heap size for collected zones before GC ran. */
393 size_t preCollectedGCHeapBytes;
394
395 /* Total malloc heap size before and after the GC ran. */
396 size_t preTotalMallocHeapBytes;
397 size_t postTotalMallocHeapBytes;
398
399 /*
400 * If a GC slice was triggered by exceeding some threshold, record the
401 * threshold and the value that exceeded it. This happens before the slice
402 * starts so this is recorded here first and then transferred to SliceData.
403 */
404 mozilla::Maybe<Trigger> recordedTrigger;
405
406 /* GC numbers as of the beginning of the collection. */
407 uint64_t startingMinorGCNumber;
408 uint64_t startingMajorGCNumber;
409 uint64_t startingSliceNumber;
410
411 /* Records the maximum GC pause in an API-controlled interval. */
412 mutable TimeDuration maxPauseInInterval;
413
414 /* Phases that are currently on stack. */
415 Vector<Phase, MAX_PHASE_NESTING, SystemAllocPolicy> phaseStack;
416
417 /*
418 * Certain phases can interrupt the phase stack, eg callback phases. When
419 * this happens, we move the suspended phases over to a sepearate list,
420 * terminated by a dummy PhaseKind::SUSPENSION phase (so that we can nest
421 * suspensions by suspending multiple stacks with a PhaseKind::SUSPENSION in
422 * between).
423 */
424 Vector<Phase, MAX_SUSPENDED_PHASES, SystemAllocPolicy> suspendedPhases;
425
426 /* Sweep times for SCCs of compartments. */
427 Vector<TimeDuration, 0, SystemAllocPolicy> sccTimes;
428
429 TimeDuration timeSinceLastGC;
430
431 JS::GCSliceCallback sliceCallback;
432
433 /*
434 * True if we saw an OOM while allocating slices or we saw an impossible
435 * timestamp. The statistics for this GC will be invalid.
436 */
437 bool aborted;
438
439 /* Profiling data. */
440
441 enum class ProfileKey {
442 #define DEFINE_PROFILE_KEY(name, _1, _2) name,
443 FOR_EACH_GC_PROFILE_TIME(DEFINE_PROFILE_KEY)
444 #undef DEFINE_PROFILE_KEY
445 KeyCount
446 };
447
448 using ProfileDurations =
449 EnumeratedArray<ProfileKey, TimeDuration, ProfileKey::KeyCount>;
450
451 bool enableProfiling_ = false;
452 bool profileWorkers_ = false;
453 bool enableBufferAllocStats_ = false;
454 TimeDuration profileThreshold_;
455 ProfileDurations totalTimes_;
456 uint64_t sliceCount_;
457
458 char formatBuffer_[32];
459 static constexpr int FormatBufferLength = sizeof(formatBuffer_);
460
461 JSContext* context();
462
463 Phase currentPhase() const;
464 Phase lookupChildPhase(PhaseKind phaseKind) const;
465
466 void beginGC(JS::GCOptions options, const TimeStamp& currentTime);
467 void endGC();
468
469 void sendGCTelemetry();
470 void sendSliceTelemetry(const SliceData& slice);
471
472 TimeDuration sumTotalParallelTime(PhaseKind phaseKind) const;
473
474 void recordPhaseBegin(Phase phase);
475 void recordPhaseEnd(Phase phase);
476
477 void gcDuration(TimeDuration* total, TimeDuration* maxPause) const;
478 void sccDurations(TimeDuration* total, TimeDuration* maxPause) const;
479 void printStats();
480
481 template <typename LegacyFn, typename GleanFn>
482 void reportLongestPhaseInMajorGC(PhaseKind longest, LegacyFn legacyReportFn,
483 GleanFn gleanReportFn);
484
485 UniqueChars formatCompactSlicePhaseTimes(const PhaseTimes& phaseTimes) const;
486
487 UniqueChars formatDetailedDescription() const;
488 UniqueChars formatDetailedSliceDescription(unsigned i,
489 const SliceData& slice) const;
490 UniqueChars formatDetailedPhaseTimes(const PhaseTimes& phaseTimes) const;
491 UniqueChars formatDetailedTotals() const;
492
493 void formatJsonDescription(JSONPrinter&) const;
494 void formatJsonSliceDescription(unsigned i, const SliceData& slice,
495 JSONPrinter&) const;
496 void formatJsonPhaseTimes(const PhaseTimes& phaseTimes, JSONPrinter&) const;
497 void formatJsonSlice(size_t sliceNum, JSONPrinter&) const;
498
499 double computeMMU(TimeDuration window) const;
500
501 void printSliceProfile();
502 ProfileDurations getProfileTimes(const SliceData& slice) const;
503 void updateTotalProfileTimes(const ProfileDurations& times);
504 const char* formatGCStates(const SliceData& slice);
505 const char* formatGCFlags(const SliceData& slice);
506 const char* formatBudget(const SliceData& slice);
507 const char* formatTotalSlices();
508
509 size_t getMallocHeapSize();
510
511 void getBufferedAllocatorStats(Zone* zone, size_t& mediumChunks,
512 size_t& mediumTenuredChunks,
513 size_t& largeNurseryAllocs,
514 size_t& largeTenuredAllocs);
515
516 static void printProfileTimes(const ProfileDurations& times,
517 Sprinter& sprinter);
518 };
519
520 struct MOZ_RAII AutoGCSlice {
521 AutoGCSlice(Statistics& stats, const ZoneGCStats& zoneStats,
522 JS::GCOptions options, const JS::SliceBudget& budget,
523 JS::GCReason reason, bool budgetWasIncreased)
524 : stats(stats) {
525 stats.beginSlice(zoneStats, options, budget, reason, budgetWasIncreased);
526 }
527 ~AutoGCSlice() { stats.endSlice(); }
528
529 Statistics& stats;
530 };
531
532 struct MOZ_RAII AutoPhase {
533 AutoPhase(Statistics& stats, PhaseKind phaseKind)
534 : stats(stats), phaseKind(phaseKind), enabled(true) {
535 stats.beginPhase(phaseKind);
536 }
537
538 AutoPhase(Statistics& stats, bool condition, PhaseKind phaseKind)
539 : stats(stats), phaseKind(phaseKind), enabled(condition) {
540 if (enabled) {
541 stats.beginPhase(phaseKind);
542 }
543 }
544
545 ~AutoPhase() {
546 if (enabled) {
547 stats.endPhase(phaseKind);
548 }
549 }
550
551 Statistics& stats;
552 PhaseKind phaseKind;
553 bool enabled;
554 };
555
556 struct MOZ_RAII AutoSCC {
557 AutoSCC(Statistics& stats, unsigned scc) : stats(stats), scc(scc) {
558 start = stats.beginSCC();
559 }
560 ~AutoSCC() { stats.endSCC(scc, start); }
561
562 Statistics& stats;
563 unsigned scc;
564 mozilla::TimeStamp start;
565 };
566
567 void ReadProfileEnv(const char* envName, const char* helpText, bool* enableOut,
568 bool* workersOut, mozilla::TimeDuration* thresholdOut);
569
570 } /* namespace gcstats */
571
572 struct StringStats {
573 // number of strings that were deduplicated, and their sizes in characters
574 // and bytes
575 uint64_t deduplicatedStrings = 0;
576 uint64_t deduplicatedChars = 0;
577 uint64_t deduplicatedBytes = 0;
578
579 // number of malloced bytes associated with tenured strings (the actual
580 // malloc will have happened when the strings were allocated in the nursery;
581 // the ownership of the bytes will be transferred to the tenured strings)
582 uint64_t tenuredBytes = 0;
583
584 StringStats& operator+=(const StringStats& other) {
585 deduplicatedStrings += other.deduplicatedStrings;
586 deduplicatedChars += other.deduplicatedChars;
587 deduplicatedBytes += other.deduplicatedBytes;
588 tenuredBytes += other.tenuredBytes;
589 return *this;
590 }
591
592 void noteTenured(size_t mallocBytes) { tenuredBytes += mallocBytes; }
593
594 void noteDeduplicated(size_t numChars, size_t mallocBytes) {
595 deduplicatedStrings++;
596 deduplicatedChars += numChars;
597 deduplicatedBytes += mallocBytes;
598 }
599 };
600
601 } /* namespace js */
602
603 #endif /* gc_Statistics_h */