-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathStatistics.cpp
1613 lines (1369 loc) · 50.1 KB
/
Statistics.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "gc/Statistics.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Sprintf.h"
#include "mozilla/TimeStamp.h"
#include <algorithm>
#include <stdarg.h>
#include <stdio.h>
#include <type_traits>
#include "debugger/DebugAPI.h"
#include "gc/GC.h"
#include "gc/Memory.h"
#include "util/Text.h"
#include "vm/HelperThreads.h"
#include "vm/Runtime.h"
#include "vm/Time.h"
#include "gc/PrivateIterators-inl.h"
using namespace js;
using namespace js::gc;
using namespace js::gcstats;
using mozilla::DebugOnly;
using mozilla::EnumeratedArray;
using mozilla::TimeDuration;
using mozilla::TimeStamp;
/*
* If this fails, then you can either delete this assertion and allow all
* larger-numbered reasons to pile up in the last telemetry bucket, or switch
* to GC_REASON_3 and bump the max value.
*/
static_assert(JS::GCReason::NUM_TELEMETRY_REASONS >= JS::GCReason::NUM_REASONS);
static inline auto AllPhaseKinds() {
return mozilla::MakeEnumeratedRange(PhaseKind::FIRST, PhaseKind::LIMIT);
}
static inline auto MajorGCPhaseKinds() {
return mozilla::MakeEnumeratedRange(PhaseKind::GC_BEGIN,
PhaseKind(size_t(PhaseKind::GC_END) + 1));
}
const char* js::gcstats::ExplainInvocationKind(JSGCInvocationKind gckind) {
MOZ_ASSERT(gckind == GC_NORMAL || gckind == GC_SHRINK);
if (gckind == GC_NORMAL) {
return "Normal";
} else {
return "Shrinking";
}
}
JS_PUBLIC_API const char* JS::ExplainGCReason(JS::GCReason reason) {
switch (reason) {
#define SWITCH_REASON(name, _) \
case JS::GCReason::name: \
return #name;
GCREASONS(SWITCH_REASON)
#undef SWITCH_REASON
case JS::GCReason::NO_REASON:
return "NO_REASON";
default:
MOZ_CRASH("bad GC reason");
}
}
JS_PUBLIC_API bool JS::InternalGCReason(JS::GCReason reason) {
return reason < JS::GCReason::FIRST_FIREFOX_REASON;
}
const char* js::gcstats::ExplainAbortReason(gc::AbortReason reason) {
switch (reason) {
#define SWITCH_REASON(name, _) \
case gc::AbortReason::name: \
return #name;
GC_ABORT_REASONS(SWITCH_REASON)
default:
MOZ_CRASH("bad GC abort reason");
#undef SWITCH_REASON
}
}
static FILE* MaybeOpenFileFromEnv(const char* env) {
FILE* file;
const char* value = getenv(env);
if (!value) {
return nullptr;
}
if (strcmp(value, "none") == 0) {
file = nullptr;
} else if (strcmp(value, "stdout") == 0) {
file = stdout;
} else if (strcmp(value, "stderr") == 0) {
file = stderr;
} else {
char path[300];
if (value[0] != '/') {
const char* dir = getenv("MOZ_UPLOAD_DIR");
if (dir) {
SprintfLiteral(path, "%s/%s", dir, value);
value = path;
}
}
file = fopen(value, "a");
if (!file) {
perror("opening log file");
MOZ_CRASH("Failed to open log file.");
}
}
return file;
}
struct PhaseKindInfo {
Phase firstPhase;
uint8_t telemetryBucket;
};
// PhaseInfo objects form a tree.
struct PhaseInfo {
Phase parent;
Phase firstChild;
Phase nextSibling;
Phase nextWithPhaseKind;
PhaseKind phaseKind;
uint8_t depth;
const char* name;
const char* path;
};
// A table of PhaseInfo indexed by Phase.
using PhaseTable = EnumeratedArray<Phase, Phase::LIMIT, PhaseInfo>;
// A table of PhaseKindInfo indexed by PhaseKind.
using PhaseKindTable =
EnumeratedArray<PhaseKind, PhaseKind::LIMIT, PhaseKindInfo>;
#include "gc/StatsPhasesGenerated.inc"
static double t(TimeDuration duration) { return duration.ToMilliseconds(); }
inline JSContext* Statistics::context() {
return gc->rt->mainContextFromOwnThread();
}
inline Phase Statistics::currentPhase() const {
return phaseStack.empty() ? Phase::NONE : phaseStack.back();
}
PhaseKind Statistics::currentPhaseKind() const {
// Public API to get the current phase kind, suppressing the synthetic
// PhaseKind::MUTATOR phase.
Phase phase = currentPhase();
MOZ_ASSERT_IF(phase == Phase::MUTATOR, phaseStack.length() == 1);
if (phase == Phase::NONE || phase == Phase::MUTATOR) {
return PhaseKind::NONE;
}
return phases[phase].phaseKind;
}
Phase Statistics::lookupChildPhase(PhaseKind phaseKind) const {
if (phaseKind == PhaseKind::IMPLICIT_SUSPENSION) {
return Phase::IMPLICIT_SUSPENSION;
}
if (phaseKind == PhaseKind::EXPLICIT_SUSPENSION) {
return Phase::EXPLICIT_SUSPENSION;
}
MOZ_ASSERT(phaseKind < PhaseKind::LIMIT);
// Search all expanded phases that correspond to the required
// phase to find the one whose parent is the current expanded phase.
Phase phase;
for (phase = phaseKinds[phaseKind].firstPhase; phase != Phase::NONE;
phase = phases[phase].nextWithPhaseKind) {
if (phases[phase].parent == currentPhase()) {
break;
}
}
if (phase == Phase::NONE) {
MOZ_CRASH_UNSAFE_PRINTF(
"Child phase kind %u not found under current phase kind %u",
unsigned(phaseKind), unsigned(currentPhaseKind()));
}
return phase;
}
inline auto AllPhases() {
return mozilla::MakeEnumeratedRange(Phase::FIRST, Phase::LIMIT);
}
void Statistics::gcDuration(TimeDuration* total, TimeDuration* maxPause) const {
*total = *maxPause = 0;
for (auto& slice : slices_) {
*total += slice.duration();
if (slice.duration() > *maxPause) {
*maxPause = slice.duration();
}
}
if (*maxPause > maxPauseInInterval) {
maxPauseInInterval = *maxPause;
}
}
void Statistics::sccDurations(TimeDuration* total,
TimeDuration* maxPause) const {
*total = *maxPause = 0;
for (size_t i = 0; i < sccTimes.length(); i++) {
*total += sccTimes[i];
*maxPause = std::max(*maxPause, sccTimes[i]);
}
}
typedef Vector<UniqueChars, 8, SystemAllocPolicy> FragmentVector;
static UniqueChars Join(const FragmentVector& fragments,
const char* separator = "") {
const size_t separatorLength = strlen(separator);
size_t length = 0;
for (size_t i = 0; i < fragments.length(); ++i) {
length += fragments[i] ? strlen(fragments[i].get()) : 0;
if (i < (fragments.length() - 1)) {
length += separatorLength;
}
}
char* joined = js_pod_malloc<char>(length + 1);
if (!joined) {
return UniqueChars();
}
joined[length] = '\0';
char* cursor = joined;
for (size_t i = 0; i < fragments.length(); ++i) {
if (fragments[i]) {
strcpy(cursor, fragments[i].get());
}
cursor += fragments[i] ? strlen(fragments[i].get()) : 0;
if (i < (fragments.length() - 1)) {
if (separatorLength) {
strcpy(cursor, separator);
}
cursor += separatorLength;
}
}
return UniqueChars(joined);
}
static TimeDuration SumChildTimes(
Phase phase, const Statistics::PhaseTimeTable& phaseTimes) {
TimeDuration total = 0;
for (phase = phases[phase].firstChild; phase != Phase::NONE;
phase = phases[phase].nextSibling) {
total += phaseTimes[phase];
}
return total;
}
UniqueChars Statistics::formatCompactSliceMessage() const {
// Skip if we OOM'ed.
if (slices_.length() == 0) {
return UniqueChars(nullptr);
}
const size_t index = slices_.length() - 1;
const SliceData& slice = slices_.back();
char budgetDescription[200];
slice.budget.describe(budgetDescription, sizeof(budgetDescription) - 1);
const char* format =
"GC Slice %u - Pause: %.3fms of %s budget (@ %.3fms); Reason: %s; Reset: "
"%s%s; Times: ";
char buffer[1024];
SprintfLiteral(buffer, format, index, t(slice.duration()), budgetDescription,
t(slice.start - slices_[0].start),
ExplainGCReason(slice.reason),
slice.wasReset() ? "yes - " : "no",
slice.wasReset() ? ExplainAbortReason(slice.resetReason) : "");
FragmentVector fragments;
if (!fragments.append(DuplicateString(buffer)) ||
!fragments.append(
formatCompactSlicePhaseTimes(slices_[index].phaseTimes))) {
return UniqueChars(nullptr);
}
return Join(fragments);
}
UniqueChars Statistics::formatCompactSummaryMessage() const {
const double bytesPerMiB = 1024 * 1024;
FragmentVector fragments;
if (!fragments.append(DuplicateString("Summary - "))) {
return UniqueChars(nullptr);
}
TimeDuration total, longest;
gcDuration(&total, &longest);
const double mmu20 = computeMMU(TimeDuration::FromMilliseconds(20));
const double mmu50 = computeMMU(TimeDuration::FromMilliseconds(50));
char buffer[1024];
if (!nonincremental()) {
SprintfLiteral(buffer,
"Max Pause: %.3fms; MMU 20ms: %.1f%%; MMU 50ms: %.1f%%; "
"Total: %.3fms; ",
t(longest), mmu20 * 100., mmu50 * 100., t(total));
} else {
SprintfLiteral(buffer, "Non-Incremental: %.3fms (%s); ", t(total),
ExplainAbortReason(nonincrementalReason_));
}
if (!fragments.append(DuplicateString(buffer))) {
return UniqueChars(nullptr);
}
SprintfLiteral(buffer,
"Zones: %d of %d (-%d); Compartments: %d of %d (-%d); "
"HeapSize: %.3f MiB; "
"HeapChange (abs): %+d (%u); ",
zoneStats.collectedZoneCount, zoneStats.zoneCount,
zoneStats.sweptZoneCount, zoneStats.collectedCompartmentCount,
zoneStats.compartmentCount, zoneStats.sweptCompartmentCount,
double(preTotalHeapBytes) / bytesPerMiB,
int32_t(counts[COUNT_NEW_CHUNK] - counts[COUNT_DESTROY_CHUNK]),
counts[COUNT_NEW_CHUNK] + counts[COUNT_DESTROY_CHUNK]);
if (!fragments.append(DuplicateString(buffer))) {
return UniqueChars(nullptr);
}
MOZ_ASSERT_IF(counts[COUNT_ARENA_RELOCATED], gckind == GC_SHRINK);
if (gckind == GC_SHRINK) {
SprintfLiteral(
buffer, "Kind: %s; Relocated: %.3f MiB; ",
ExplainInvocationKind(gckind),
double(ArenaSize * counts[COUNT_ARENA_RELOCATED]) / bytesPerMiB);
if (!fragments.append(DuplicateString(buffer))) {
return UniqueChars(nullptr);
}
}
return Join(fragments);
}
UniqueChars Statistics::formatCompactSlicePhaseTimes(
const PhaseTimeTable& phaseTimes) const {
static const TimeDuration MaxUnaccountedTime =
TimeDuration::FromMicroseconds(100);
FragmentVector fragments;
char buffer[128];
for (auto phase : AllPhases()) {
DebugOnly<uint8_t> level = phases[phase].depth;
MOZ_ASSERT(level < 4);
TimeDuration ownTime = phaseTimes[phase];
TimeDuration childTime = SumChildTimes(phase, phaseTimes);
if (ownTime > MaxUnaccountedTime) {
SprintfLiteral(buffer, "%s: %.3fms", phases[phase].name, t(ownTime));
if (!fragments.append(DuplicateString(buffer))) {
return UniqueChars(nullptr);
}
if (childTime && (ownTime - childTime) > MaxUnaccountedTime) {
MOZ_ASSERT(level < 3);
SprintfLiteral(buffer, "%s: %.3fms", "Other", t(ownTime - childTime));
if (!fragments.append(DuplicateString(buffer))) {
return UniqueChars(nullptr);
}
}
}
}
return Join(fragments, ", ");
}
UniqueChars Statistics::formatDetailedMessage() const {
FragmentVector fragments;
if (!fragments.append(formatDetailedDescription())) {
return UniqueChars(nullptr);
}
if (!slices_.empty()) {
for (unsigned i = 0; i < slices_.length(); i++) {
if (!fragments.append(formatDetailedSliceDescription(i, slices_[i]))) {
return UniqueChars(nullptr);
}
if (!fragments.append(formatDetailedPhaseTimes(slices_[i].phaseTimes))) {
return UniqueChars(nullptr);
}
}
}
if (!fragments.append(formatDetailedTotals())) {
return UniqueChars(nullptr);
}
if (!fragments.append(formatDetailedPhaseTimes(phaseTimes))) {
return UniqueChars(nullptr);
}
return Join(fragments);
}
UniqueChars Statistics::formatDetailedDescription() const {
const double bytesPerMiB = 1024 * 1024;
TimeDuration sccTotal, sccLongest;
sccDurations(&sccTotal, &sccLongest);
const double mmu20 = computeMMU(TimeDuration::FromMilliseconds(20));
const double mmu50 = computeMMU(TimeDuration::FromMilliseconds(50));
const char* format =
"=================================================================\n\
Invocation Kind: %s\n\
Reason: %s\n\
Incremental: %s%s\n\
Zones Collected: %d of %d (-%d)\n\
Compartments Collected: %d of %d (-%d)\n\
MinorGCs since last GC: %d\n\
Store Buffer Overflows: %d\n\
MMU 20ms:%.1f%%; 50ms:%.1f%%\n\
SCC Sweep Total (MaxPause): %.3fms (%.3fms)\n\
HeapSize: %.3f MiB\n\
Chunk Delta (magnitude): %+d (%d)\n\
Arenas Relocated: %.3f MiB\n\
Trigger: %s\n\
";
char thresholdBuffer[100] = "n/a";
if (thresholdTriggered) {
SprintfLiteral(thresholdBuffer, "%.3f MiB of %.3f MiB threshold\n",
triggerAmount / 1024.0 / 1024.0,
triggerThreshold / 1024.0 / 1024.0);
}
char buffer[1024];
SprintfLiteral(
buffer, format, ExplainInvocationKind(gckind),
ExplainGCReason(slices_[0].reason), nonincremental() ? "no - " : "yes",
nonincremental() ? ExplainAbortReason(nonincrementalReason_) : "",
zoneStats.collectedZoneCount, zoneStats.zoneCount,
zoneStats.sweptZoneCount, zoneStats.collectedCompartmentCount,
zoneStats.compartmentCount, zoneStats.sweptCompartmentCount,
getCount(COUNT_MINOR_GC), getCount(COUNT_STOREBUFFER_OVERFLOW),
mmu20 * 100., mmu50 * 100., t(sccTotal), t(sccLongest),
double(preTotalHeapBytes) / bytesPerMiB,
getCount(COUNT_NEW_CHUNK) - getCount(COUNT_DESTROY_CHUNK),
getCount(COUNT_NEW_CHUNK) + getCount(COUNT_DESTROY_CHUNK),
double(ArenaSize * getCount(COUNT_ARENA_RELOCATED)) / bytesPerMiB,
thresholdBuffer);
return DuplicateString(buffer);
}
UniqueChars Statistics::formatDetailedSliceDescription(
unsigned i, const SliceData& slice) const {
char budgetDescription[200];
slice.budget.describe(budgetDescription, sizeof(budgetDescription) - 1);
const char* format =
"\
---- Slice %u ----\n\
Reason: %s\n\
Reset: %s%s\n\
State: %s -> %s\n\
Page Faults: %" PRIu64
"\n\
Pause: %.3fms of %s budget (@ %.3fms)\n\
";
char buffer[1024];
SprintfLiteral(
buffer, format, i, ExplainGCReason(slice.reason),
slice.wasReset() ? "yes - " : "no",
slice.wasReset() ? ExplainAbortReason(slice.resetReason) : "",
gc::StateName(slice.initialState), gc::StateName(slice.finalState),
uint64_t(slice.endFaults - slice.startFaults), t(slice.duration()),
budgetDescription, t(slice.start - slices_[0].start));
return DuplicateString(buffer);
}
static bool IncludePhase(TimeDuration duration) {
// Don't include durations that will print as "0.000ms".
return duration.ToMilliseconds() >= 0.001;
}
UniqueChars Statistics::formatDetailedPhaseTimes(
const PhaseTimeTable& phaseTimes) const {
static const TimeDuration MaxUnaccountedChildTime =
TimeDuration::FromMicroseconds(50);
FragmentVector fragments;
char buffer[128];
for (auto phase : AllPhases()) {
uint8_t level = phases[phase].depth;
TimeDuration ownTime = phaseTimes[phase];
TimeDuration childTime = SumChildTimes(phase, phaseTimes);
if (IncludePhase(ownTime)) {
SprintfLiteral(buffer, " %*s%s: %.3fms\n", level * 2, "",
phases[phase].name, t(ownTime));
if (!fragments.append(DuplicateString(buffer))) {
return UniqueChars(nullptr);
}
if (childTime && (ownTime - childTime) > MaxUnaccountedChildTime) {
SprintfLiteral(buffer, " %*s%s: %.3fms\n", (level + 1) * 2, "",
"Other", t(ownTime - childTime));
if (!fragments.append(DuplicateString(buffer))) {
return UniqueChars(nullptr);
}
}
}
}
return Join(fragments);
}
UniqueChars Statistics::formatDetailedTotals() const {
TimeDuration total, longest;
gcDuration(&total, &longest);
const char* format =
"\
---- Totals ----\n\
Total Time: %.3fms\n\
Max Pause: %.3fms\n\
";
char buffer[1024];
SprintfLiteral(buffer, format, t(total), t(longest));
return DuplicateString(buffer);
}
void Statistics::formatJsonSlice(size_t sliceNum, JSONPrinter& json) const {
/*
* We number each of the slice properties to keep the code in
* GCTelemetry.jsm in sync. See MAX_SLICE_KEYS.
*/
json.beginObject();
formatJsonSliceDescription(sliceNum, slices_[sliceNum], json); // # 1-11
json.beginObjectProperty("times"); // # 12
formatJsonPhaseTimes(slices_[sliceNum].phaseTimes, json);
json.endObject();
json.endObject();
}
UniqueChars Statistics::renderJsonSlice(size_t sliceNum) const {
Sprinter printer(nullptr, false);
if (!printer.init()) {
return UniqueChars(nullptr);
}
JSONPrinter json(printer);
formatJsonSlice(sliceNum, json);
return printer.release();
}
UniqueChars Statistics::renderNurseryJson() const {
Sprinter printer(nullptr, false);
if (!printer.init()) {
return UniqueChars(nullptr);
}
JSONPrinter json(printer);
gc->nursery().renderProfileJSON(json);
return printer.release();
}
#ifdef DEBUG
void Statistics::writeLogMessage(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
if (gcDebugFile) {
TimeDuration sinceStart = TimeStamp::Now() - TimeStamp::ProcessCreation();
fprintf(gcDebugFile, "%12.3f: ", sinceStart.ToMicroseconds());
vfprintf(gcDebugFile, fmt, args);
fprintf(gcDebugFile, "\n");
fflush(gcDebugFile);
}
va_end(args);
}
#endif
UniqueChars Statistics::renderJsonMessage(uint64_t timestamp,
Statistics::JSONUse use) const {
/*
* The format of the JSON message is specified by the GCMajorMarkerPayload
* type in profiler.firefox.com
* https://github.com/firefox-devtools/profiler/blob/master/src/types/markers.js#L62
*
* All the properties listed here are created within the timings property
* of the GCMajor marker.
*/
if (aborted) {
return DuplicateString("{status:\"aborted\"}"); // May return nullptr
}
Sprinter printer(nullptr, false);
if (!printer.init()) {
return UniqueChars(nullptr);
}
JSONPrinter json(printer);
json.beginObject();
json.property("status", "completed"); // JSON Key #1
formatJsonDescription(timestamp, json, use); // #2-22
if (use == Statistics::JSONUse::TELEMETRY) {
json.beginListProperty("slices_list"); // #23
for (unsigned i = 0; i < slices_.length(); i++) {
formatJsonSlice(i, json);
}
json.endList();
}
json.beginObjectProperty("totals"); // #24
formatJsonPhaseTimes(phaseTimes, json);
json.endObject();
json.endObject();
return printer.release();
}
void Statistics::formatJsonDescription(uint64_t timestamp, JSONPrinter& json,
JSONUse use) const {
// If you change JSON properties here, please update:
// Telemetry ping code:
// toolkit/components/telemetry/other/GCTelemetry.jsm
// Telemetry documentation:
// toolkit/components/telemetry/docs/data/main-ping.rst
// Telemetry tests:
// toolkit/components/telemetry/tests/browser/browser_TelemetryGC.js,
// toolkit/components/telemetry/tests/unit/test_TelemetryGC.js
// Firefox Profiler:
// https://github.com/firefox-devtools/profiler
//
// Please also number each property to help correctly maintain the Telemetry
// ping code
json.property("timestamp", timestamp); // # JSON Key #2
TimeDuration total, longest;
gcDuration(&total, &longest);
json.property("max_pause", longest, JSONPrinter::MILLISECONDS); // #3
json.property("total_time", total, JSONPrinter::MILLISECONDS); // #4
// We might be able to omit reason if profiler.firefox.com was able to retrive
// it from the first slice. But it doesn't do this yet.
json.property("reason", ExplainGCReason(slices_[0].reason)); // #5
json.property("zones_collected", zoneStats.collectedZoneCount); // #6
json.property("total_zones", zoneStats.zoneCount); // #7
json.property("total_compartments", zoneStats.compartmentCount); // #8
json.property("minor_gcs", getCount(COUNT_MINOR_GC)); // #9
uint32_t storebufferOverflows = getCount(COUNT_STOREBUFFER_OVERFLOW);
if (storebufferOverflows) {
json.property("store_buffer_overflows", storebufferOverflows); // #10
}
json.property("slices", slices_.length()); // #11
const double mmu20 = computeMMU(TimeDuration::FromMilliseconds(20));
const double mmu50 = computeMMU(TimeDuration::FromMilliseconds(50));
json.property("mmu_20ms", int(mmu20 * 100)); // #12
json.property("mmu_50ms", int(mmu50 * 100)); // #13
TimeDuration sccTotal, sccLongest;
sccDurations(&sccTotal, &sccLongest);
json.property("scc_sweep_total", sccTotal, JSONPrinter::MILLISECONDS); // #14
json.property("scc_sweep_max_pause", sccLongest,
JSONPrinter::MILLISECONDS); // #15
if (nonincrementalReason_ != AbortReason::None) {
json.property("nonincremental_reason",
ExplainAbortReason(nonincrementalReason_)); // #16
}
json.property("allocated_bytes", preTotalHeapBytes); // #17
if (use == Statistics::JSONUse::PROFILER) {
json.property("post_heap_size", postTotalHeapBytes);
}
uint32_t addedChunks = getCount(COUNT_NEW_CHUNK);
if (addedChunks) {
json.property("added_chunks", addedChunks); // #18
}
uint32_t removedChunks = getCount(COUNT_DESTROY_CHUNK);
if (removedChunks) {
json.property("removed_chunks", removedChunks); // #19
}
json.property("major_gc_number", startingMajorGCNumber); // #20
json.property("minor_gc_number", startingMinorGCNumber); // #21
json.property("slice_number", startingSliceNumber); // #22
}
void Statistics::formatJsonSliceDescription(unsigned i, const SliceData& slice,
JSONPrinter& json) const {
// If you change JSON properties here, please update:
// Telemetry ping code:
// toolkit/components/telemetry/other/GCTelemetry.jsm
// Telemetry documentation:
// toolkit/components/telemetry/docs/data/main-ping.rst
// Telemetry tests:
// toolkit/components/telemetry/tests/browser/browser_TelemetryGC.js,
// toolkit/components/telemetry/tests/unit/test_TelemetryGC.js
// Firefox Profiler:
// https://github.com/firefox-devtools/profiler
//
char budgetDescription[200];
slice.budget.describe(budgetDescription, sizeof(budgetDescription) - 1);
TimeStamp originTime = TimeStamp::ProcessCreation();
json.property("slice", i); // JSON Property #1
json.property("pause", slice.duration(), JSONPrinter::MILLISECONDS); // #2
json.property("reason", ExplainGCReason(slice.reason)); // #3
json.property("initial_state", gc::StateName(slice.initialState)); // #4
json.property("final_state", gc::StateName(slice.finalState)); // #5
json.property("budget", budgetDescription); // #6
json.property("major_gc_number", startingMajorGCNumber); // #7
if (thresholdTriggered) {
json.floatProperty("trigger_amount", triggerAmount, 0); // #8
json.floatProperty("trigger_threshold", triggerThreshold, 0); // #9
}
int64_t numFaults = slice.endFaults - slice.startFaults;
if (numFaults != 0) {
json.property("page_faults", numFaults); // #10
}
json.property("start_timestamp", slice.start - originTime,
JSONPrinter::SECONDS); // #11
}
void Statistics::formatJsonPhaseTimes(const PhaseTimeTable& phaseTimes,
JSONPrinter& json) const {
for (auto phase : AllPhases()) {
TimeDuration ownTime = phaseTimes[phase];
if (!ownTime.IsZero()) {
json.property(phases[phase].path, ownTime, JSONPrinter::MILLISECONDS);
}
}
}
Statistics::Statistics(GCRuntime* gc)
: gc(gc),
gcTimerFile(nullptr),
gcDebugFile(nullptr),
nonincrementalReason_(gc::AbortReason::None),
allocsSinceMinorGC({0, 0}),
preTotalHeapBytes(0),
postTotalHeapBytes(0),
preCollectedHeapBytes(0),
thresholdTriggered(false),
triggerAmount(0.0),
triggerThreshold(0.0),
startingMinorGCNumber(0),
startingMajorGCNumber(0),
startingSliceNumber(0),
maxPauseInInterval(0),
sliceCallback(nullptr),
nurseryCollectionCallback(nullptr),
aborted(false),
enableProfiling_(false),
sliceCount_(0) {
for (auto& count : counts) {
count = 0;
}
for (auto& stat : stats) {
stat = 0;
}
#ifdef DEBUG
for (const auto& duration : totalTimes_) {
using ElementType = std::remove_reference_t<decltype(duration)>;
static_assert(!std::is_trivially_constructible<ElementType>::value,
"Statistics::Statistics will only initialize "
"totalTimes_'s elements if their default constructor is "
"non-trivial");
MOZ_ASSERT(duration.IsZero(),
"totalTimes_ default-initialization should have "
"default-initialized every element of totalTimes_ to zero");
}
#endif
MOZ_ALWAYS_TRUE(phaseStack.reserve(MAX_PHASE_NESTING));
MOZ_ALWAYS_TRUE(suspendedPhases.reserve(MAX_SUSPENDED_PHASES));
gcTimerFile = MaybeOpenFileFromEnv("MOZ_GCTIMER");
gcDebugFile = MaybeOpenFileFromEnv("JS_GC_DEBUG");
const char* env = getenv("JS_GC_PROFILE");
if (env) {
if (0 == strcmp(env, "help")) {
fprintf(stderr,
"JS_GC_PROFILE=N\n"
"\tReport major GC's taking more than N milliseconds.\n");
exit(0);
}
enableProfiling_ = true;
profileThreshold_ = TimeDuration::FromMilliseconds(atoi(env));
}
}
Statistics::~Statistics() {
if (gcTimerFile && gcTimerFile != stdout && gcTimerFile != stderr) {
fclose(gcTimerFile);
}
if (gcDebugFile && gcDebugFile != stdout && gcDebugFile != stderr) {
fclose(gcDebugFile);
}
}
/* static */
bool Statistics::initialize() {
#ifdef DEBUG
// Sanity check generated tables.
for (auto i : AllPhases()) {
auto parent = phases[i].parent;
if (parent != Phase::NONE) {
MOZ_ASSERT(phases[i].depth == phases[parent].depth + 1);
}
auto firstChild = phases[i].firstChild;
if (firstChild != Phase::NONE) {
MOZ_ASSERT(i == phases[firstChild].parent);
MOZ_ASSERT(phases[i].depth == phases[firstChild].depth - 1);
}
auto nextSibling = phases[i].nextSibling;
if (nextSibling != Phase::NONE) {
MOZ_ASSERT(parent == phases[nextSibling].parent);
MOZ_ASSERT(phases[i].depth == phases[nextSibling].depth);
}
auto nextWithPhaseKind = phases[i].nextWithPhaseKind;
if (nextWithPhaseKind != Phase::NONE) {
MOZ_ASSERT(phases[i].phaseKind == phases[nextWithPhaseKind].phaseKind);
MOZ_ASSERT(parent != phases[nextWithPhaseKind].parent);
}
}
for (auto i : AllPhaseKinds()) {
MOZ_ASSERT(phases[phaseKinds[i].firstPhase].phaseKind == i);
for (auto j : AllPhaseKinds()) {
MOZ_ASSERT_IF(i != j, phaseKinds[i].telemetryBucket !=
phaseKinds[j].telemetryBucket);
}
}
#endif
return true;
}
JS::GCSliceCallback Statistics::setSliceCallback(
JS::GCSliceCallback newCallback) {
JS::GCSliceCallback oldCallback = sliceCallback;
sliceCallback = newCallback;
return oldCallback;
}
JS::GCNurseryCollectionCallback Statistics::setNurseryCollectionCallback(
JS::GCNurseryCollectionCallback newCallback) {
auto oldCallback = nurseryCollectionCallback;
nurseryCollectionCallback = newCallback;
return oldCallback;
}
TimeDuration Statistics::clearMaxGCPauseAccumulator() {
TimeDuration prior = maxPauseInInterval;
maxPauseInInterval = 0;
return prior;
}
TimeDuration Statistics::getMaxGCPauseSinceClear() {
return maxPauseInInterval;
}
// Sum up the time for a phase, including instances of the phase with different
// parents.
static TimeDuration SumPhase(PhaseKind phaseKind,
const Statistics::PhaseTimeTable& times) {
TimeDuration sum = 0;
for (Phase phase = phaseKinds[phaseKind].firstPhase; phase != Phase::NONE;
phase = phases[phase].nextWithPhaseKind) {
sum += times[phase];
}
return sum;
}
static bool CheckSelfTime(Phase parent, Phase child,
const Statistics::PhaseTimeTable& times,
const Statistics::PhaseTimeTable& selfTimes,
TimeDuration childTime) {
if (selfTimes[parent] < childTime) {
fprintf(
stderr,
"Parent %s time = %.3fms with %.3fms remaining, child %s time %.3fms\n",
phases[parent].name, times[parent].ToMilliseconds(),
selfTimes[parent].ToMilliseconds(), phases[child].name,
childTime.ToMilliseconds());
fflush(stderr);
return false;
}
return true;
}
static PhaseKind LongestPhaseSelfTimeInMajorGC(
const Statistics::PhaseTimeTable& times) {
// Start with total times per expanded phase, including children's times.
Statistics::PhaseTimeTable selfTimes(times);
// We have the total time spent in each phase, including descendant times.
// Loop over the children and subtract their times from their parent's self
// time.
for (auto i : AllPhases()) {
Phase parent = phases[i].parent;
if (parent != Phase::NONE) {
bool ok = CheckSelfTime(parent, i, times, selfTimes, times[i]);
// This happens very occasionally in release builds and frequently
// in Windows debug builds. Skip collecting longest phase telemetry
// if it does.
#ifndef XP_WIN
MOZ_ASSERT(ok, "Inconsistent time data; see bug 1400153");
#endif
if (!ok) {
return PhaseKind::NONE;
}
selfTimes[parent] -= times[i];
}
}
// Sum expanded phases corresponding to the same phase.
EnumeratedArray<PhaseKind, PhaseKind::LIMIT, TimeDuration> phaseTimes;
for (auto i : AllPhaseKinds()) {
phaseTimes[i] = SumPhase(i, selfTimes);
}
// Loop over this table to find the longest phase.
TimeDuration longestTime = 0;
PhaseKind longestPhase = PhaseKind::NONE;
for (auto i : MajorGCPhaseKinds()) {
if (phaseTimes[i] > longestTime) {
longestTime = phaseTimes[i];
longestPhase = i;
}
}
return longestPhase;
}
void Statistics::printStats() {
if (aborted) {
fprintf(gcTimerFile,
"OOM during GC statistics collection. The report is unavailable "
"for this GC.\n");
} else {
UniqueChars msg = formatDetailedMessage();
if (msg) {
double secSinceStart =
(slices_[0].start - TimeStamp::ProcessCreation()).ToSeconds();
fprintf(gcTimerFile, "GC(T+%.3fs) %s\n", secSinceStart, msg.get());
}
}
fflush(gcTimerFile);
}
void Statistics::beginGC(JSGCInvocationKind kind,
const TimeStamp& currentTime) {
slices_.clearAndFree();
sccTimes.clearAndFree();
gckind = kind;
nonincrementalReason_ = gc::AbortReason::None;
preTotalHeapBytes = gc->heapSize.bytes();
preCollectedHeapBytes = 0;
startingMajorGCNumber = gc->majorGCCount();
startingSliceNumber = gc->gcNumber();
if (gc->lastGCEndTime()) {
timeSinceLastGC = currentTime - gc->lastGCEndTime();
}
}