-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathreferenceChains.cpp
More file actions
2677 lines (2494 loc) · 121 KB
/
Copy pathreferenceChains.cpp
File metadata and controls
2677 lines (2494 loc) · 121 KB
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
/*
* Copyright 2026, Datadog, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
#include "referenceChains.h"
#include "common.h"
#include "counters.h"
#include "jniHelper.h"
#include "livenessTracker.h"
#include "log.h"
#include "objectSampler.h"
#include "os.h"
#include "profiler.h"
#include "tsc.h"
#include "vmEntry.h"
#include <algorithm>
#include <cassert>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <unordered_set>
// ---------------------------------------------------------------------------
// FrontierTable (tag-indexed frontier metadata table)
// ---------------------------------------------------------------------------
FrontierTable::FrontierTable(int max_cap)
: _table_size(0), _table_cap(0), _table_max_cap(std::max(max_cap, 0)),
_table(nullptr) {
_table_cap = std::min(INITIAL_TABLE_CAPACITY, _table_max_cap);
if (_table_cap > 0) {
_table = (FrontierEntry *)calloc(_table_cap, sizeof(FrontierEntry));
if (_table == nullptr) {
_table_cap = 0;
}
}
Counters::increment(REFERENCE_CHAIN_FRONTIER_TABLE_BYTES,
(jlong)_table_cap * sizeof(FrontierEntry));
Counters::increment(REFERENCE_CHAIN_FRONTIER_TABLE_CAPACITY, _table_cap);
}
FrontierTable::~FrontierTable() {
Counters::increment(REFERENCE_CHAIN_FRONTIER_TABLE_BYTES,
-(jlong)_table_cap * sizeof(FrontierEntry));
Counters::increment(REFERENCE_CHAIN_FRONTIER_TABLE_CAPACITY, -_table_cap);
free(_table);
}
void FrontierTable::resetCapacityForTest(int max_cap) {
_table_lock.lock();
Counters::increment(REFERENCE_CHAIN_FRONTIER_TABLE_BYTES,
-(jlong)_table_cap * sizeof(FrontierEntry));
Counters::increment(REFERENCE_CHAIN_FRONTIER_TABLE_CAPACITY, -_table_cap);
free(_table);
_table = nullptr;
_table_max_cap = std::max(max_cap, 0);
_table_cap = std::min(INITIAL_TABLE_CAPACITY, _table_max_cap);
if (_table_cap > 0) {
_table = (FrontierEntry *)calloc(_table_cap, sizeof(FrontierEntry));
if (_table == nullptr) {
_table_cap = 0;
}
}
Counters::increment(REFERENCE_CHAIN_FRONTIER_TABLE_BYTES,
(jlong)_table_cap * sizeof(FrontierEntry));
Counters::increment(REFERENCE_CHAIN_FRONTIER_TABLE_CAPACITY, _table_cap);
_table_size.store(0, std::memory_order_relaxed);
_table_lock.unlock();
}
bool FrontierTable::growLocked(int required_cap) {
if (required_cap <= _table_cap) {
return true;
}
if (_table_cap >= _table_max_cap) {
return false;
}
int newcap = _table_cap;
while (newcap < required_cap && newcap < _table_max_cap) {
newcap = newcap == 0 ? std::min(INITIAL_TABLE_CAPACITY, _table_max_cap)
: std::min(newcap * 2, _table_max_cap);
}
if (newcap <= _table_cap) {
return false;
}
FrontierEntry *tmp =
(FrontierEntry *)realloc(_table, sizeof(FrontierEntry) * newcap);
if (tmp == nullptr) {
Log::debug(
"ReferenceChains: frontier table resize to %d entries failed", newcap);
return false;
}
// realloc() does not zero the newly grown region - clear it so lookup()
// never returns garbage state for a slot that hasn't been inserted yet.
memset(tmp + _table_cap, 0, sizeof(FrontierEntry) * (newcap - _table_cap));
Counters::increment(REFERENCE_CHAIN_FRONTIER_TABLE_BYTES,
(jlong)(newcap - _table_cap) * sizeof(FrontierEntry));
Counters::increment(REFERENCE_CHAIN_FRONTIER_TABLE_CAPACITY,
newcap - _table_cap);
_table = tmp;
_table_cap = newcap;
return _table_cap >= required_cap;
}
bool FrontierTable::insert(jlong tag, jlong parent_tag, u32 referrer_klass,
u32 depth, u8 state, u8 root_kind) {
if (tag <= 0 || tag - 1 > (jlong)INT_MAX) {
return false;
}
int idx = (int)(tag - 1);
// Exclusive lock for the whole write (growLocked() already requires it) -
// a shared lock here would not exclude lookup()'s own shared-mode read of
// the same slot, letting a concurrent reader observe a torn entry.
_table_lock.lock();
if (idx >= _table_cap && !growLocked(idx + 1)) {
_table_lock.unlock();
Log::debug("ReferenceChains: frontier table capacity exhausted "
"(cap=%d, max=%d, tag=%lld)",
_table_cap, _table_max_cap, (long long)tag);
return false;
}
_table[idx].parent_tag = parent_tag;
_table[idx].referrer_klass = referrer_klass;
_table[idx].depth = depth;
_table[idx].state = state;
_table[idx].root_kind = root_kind;
_table_lock.unlock();
int sz = _table_size.load(std::memory_order_relaxed);
while (sz < idx + 1 &&
!_table_size.compare_exchange_weak(sz, idx + 1,
std::memory_order_relaxed)) {
// sz reloaded with the current value by compare_exchange_weak on
// failure; retry until either this thread wins or another thread
// already advanced _table_size past idx + 1.
}
return true;
}
bool FrontierTable::lookup(jlong tag, FrontierEntry *out) {
if (tag <= 0 || tag - 1 > (jlong)INT_MAX) {
return false;
}
int idx = (int)(tag - 1);
bool found = false;
_table_lock.lockShared();
if (idx < _table_size) {
*out = _table[idx];
found = true;
}
_table_lock.unlockShared();
return found;
}
bool FrontierTable::lookupLocked(jlong tag, FrontierEntry *out) const {
if (tag <= 0 || tag - 1 > (jlong)INT_MAX) {
return false;
}
int idx = (int)(tag - 1);
if (idx < _table_size) {
*out = _table[idx];
return true;
}
return false;
}
void FrontierTable::clear(jlong tag) {
if (tag <= 0 || tag - 1 > (jlong)INT_MAX) {
return;
}
int idx = (int)(tag - 1);
// Exclusive lock: this mutates a slot lookup() may be reading concurrently
// under its own shared lock (see insert()'s own comment above).
_table_lock.lock();
if (idx < _table_size) {
_table[idx].state = FrontierEntryState::ABANDONED;
}
_table_lock.unlock();
}
void FrontierTable::markEdge(jlong tag) {
if (tag <= 0 || tag - 1 > (jlong)INT_MAX) {
return;
}
int idx = (int)(tag - 1);
_table_lock.lock();
if (idx < _table_size) {
_table[idx].state = FrontierEntryState::EDGE;
}
_table_lock.unlock();
}
void FrontierTable::markExpanded(jlong tag) {
if (tag <= 0 || tag - 1 > (jlong)INT_MAX) {
return;
}
int idx = (int)(tag - 1);
_table_lock.lock();
if (idx < _table_size) {
_table[idx].state = FrontierEntryState::EXPANDED;
}
_table_lock.unlock();
}
void FrontierTable::updateRootKind(jlong tag, u8 root_kind) {
if (tag <= 0 || tag - 1 > (jlong)INT_MAX) {
return;
}
int idx = (int)(tag - 1);
_table_lock.lock();
if (idx < _table_size) {
_table[idx].root_kind = root_kind;
}
_table_lock.unlock();
}
bool FrontierTable::reconstructChain(jlong target_tag,
std::vector<u32> *out_chain,
u8 *out_root_kind) {
FrontierEntry entry{};
if (!lookup(target_tag, &entry)) {
return false;
}
std::vector<u32> chain;
jlong tag = target_tag;
u8 root_kind = 0;
// Bounded by maxCapacity(): every tag maps to a distinct slot (this table's
// "tags/slots are never reused" invariant, see the class comment above),
// so a well-formed parent_tag chain can visit at most maxCapacity() slots
// before either reaching parent_tag == 0 or repeating a slot.
for (int hops = 0; hops <= maxCapacity() && tag != 0; hops++) {
if (!lookup(tag, &entry)) {
// parent_tag pointed at a tag that was never inserted - should not
// happen for a chain built entirely within one BFS pass, but do not
// fabricate a partial chain silently.
return false;
}
chain.push_back(entry.referrer_klass);
markEdge(tag);
root_kind = entry.root_kind;
tag = entry.parent_tag;
}
if (tag != 0) {
// Ran past the defensive hop bound without reaching a root-attached
// entry (parent_tag == 0) - a corrupted/cyclic chain. Report failure
// rather than returning a truncated, possibly-misleading chain.
return false;
}
*out_chain = std::move(chain);
if (out_root_kind != nullptr) {
// The loop's last iteration is always the root-attached entry (the one
// whose parent_tag == 0 that just ended the loop), so root_kind here is
// that entry's own FrontierEntry::root_kind.
*out_root_kind = root_kind;
}
return true;
}
// ---------------------------------------------------------------------------
// ReferenceChainTracker
// ---------------------------------------------------------------------------
// Marks the calling thread as executing inside the GarbageCollectionStart/
// Finish JVMTI callback for the duration of the guard's lifetime. Used by the
// tag helpers below as a debug-only self-consistency check that this class
// never issues a Heap-category JVMTI call (SetTag/GetTag/...) from a context
// where the JVMTI spec forbids it (see referenceChains.h). Thread-local
// because the JVMTI spec only guarantees the callback runs on the VM thread
// delivering the event, and this must not leak across threads.
static thread_local bool t_inGCCallback = false;
namespace {
class GCCallbackGuard {
public:
GCCallbackGuard() { t_inGCCallback = true; }
~GCCallbackGuard() { t_inGCCallback = false; }
};
} // namespace
Error ReferenceChainTracker::start(Arguments &args) {
_enabled = args._reference_chains;
if (!_enabled) {
Log::info("Reference chain tracking is disabled");
return Error::OK;
}
Log::info("Reference chain tracking is enabled (hops=%d, budget=%d, "
"ttl=%ldms, framecap=%d, pausetarget=%ldms, painbudget=%d%%)",
args._reference_chains_hop_cap, args._reference_chains_budget,
args._reference_chains_ttl_ms, args._reference_chains_frontier_cap,
args._reference_chains_pause_target_ms,
args._reference_chains_pain_budget_percent);
// Like LivenessTracker's table (livenessTracker.cpp:225-232), construct the
// frontier table once and keep it across repeated start()/stop() cycles -
// do not reallocate on a second start() with a possibly different cap, for
// the same reason LivenessTracker keeps its first-initialize() result.
// Recorded unconditionally, even on a start() call that finds _frontier
// already constructed (see _configured_frontier_cap's own comment) - this
// is what resetSearchStateForTest() rebuilds the table at, undoing
// whatever cap an earlier test in this same JVM happened to construct it
// with.
_configured_frontier_cap = args._reference_chains_frontier_cap;
if (_frontier == nullptr) {
_frontier = new FrontierTable(_configured_frontier_cap);
}
_hop_cap = args._reference_chains_hop_cap;
_budget = args._reference_chains_budget;
// 0 (unset) auto-scales from _budget instead of falling back to it plainly
// - see this field's own comment (referenceChains.h) for why a
// steady-state per-pass budget is the wrong size for the first pass.
_first_pass_budget = args._reference_chains_first_pass_budget > 0
? args._reference_chains_first_pass_budget
: std::min(_budget * AUTO_FIRST_PASS_BUDGET_MULTIPLIER,
AUTO_FIRST_PASS_BUDGET_CAP);
_ttl_ms = args._reference_chains_ttl_ms;
// Pause-time pacing controller: (re)seed the controller's ceiling and the
// adaptive values it drives. _effective_budget/_effective_cadence_ns start
// exactly at their pre-pacing-controller fixed-constant equivalents
// (_budget/PASS_CADENCE_NS) so a tracker that has not yet measured a pass
// behaves identically to before the controller was added - updatePacing()
// only moves them once a real pass duration is
// available. _pause_pid is reconstructed (not just reset()) because its
// target is only known now, from args - same reason RateLimiter::start()
// reconstructs its own _pid rather than mutating it in place.
_pause_target_ms = args._reference_chains_pause_target_ms;
_effective_budget = _budget;
_effective_cadence_ns = PASS_CADENCE_NS;
// Budget-borrowing (referenceChains.h's _borrowed_budget comment): reset
// alongside the rest of the pacing controller's state, so a restarted
// search never inherits headroom earned by a previous one.
_borrowed_budget = 0;
_consecutive_under_target_passes = 0;
_pause_pid = PidController((u64)std::max(_pause_target_ms, 0L),
10, // proportional gain: reacts to a single
// pass's over/under-ceiling error without
// needing many passes to notice - a
// duration-ms error is typically single/
// low-double-digit in magnitude (unlike
// the shared triple's event-count scale),
// so a smaller P keeps a one-pass
// overshoot from swinging the budget by
// more than a modest fraction of itself
1, // integral gain: small and round -
// pidController.cpp's `_integral_value`
// has no built-in clamp, and this
// controller is invoked once per BFS pass
// rather than on the other three usages'
// roughly-periodic one-call-per-second
// cadence, so windup accumulates faster
// per wall-clock second than it does there
2, // derivative gain: small, matching the
// shared triple's own "the derivational
// gain is rather small" rationale
// (objectSampler.cpp) - a single slow/
// fast pass should not itself trigger a
// large swing
1, // sampling_window=1: one compute() call
// *is* one pass, not a fixed real-time
// window like the other three usages
// assume (see _pause_pid's own comment)
5.0 // cutoff_secs: a round value, halved from
// the shared triple's own "15" since a
// pass-scoped signal is naturally
// noisier per-call than a roughly-1s-
// cadence one
);
// Search restart (this class's own header comment): (re)seed _pain_budget
// from the configured refill rate, mirroring _pause_pid's own
// reconstruct-in-start() pattern above. A search's already-accumulated
// _search_pain_ms is deliberately left untouched here - only restartSearch()
// spends it, so a start()/stop() cycle mid-search (if that ever happens)
// does not erase cost the current search has already incurred.
_pain_budget = PainBudget(
std::max(args._reference_chains_pain_budget_percent, 0) / 100.0);
// Lazy-enable, matching LivenessTracker::start() (livenessTracker.cpp:194-196):
// the GC callbacks are wired unconditionally in vmEntry.cpp, but the events
// themselves are only turned on for this JVMTI env when the flag is on.
jvmtiEnv *jvmti = VM::jvmti();
jvmti->SetEventNotificationMode(
JVMTI_ENABLE, JVMTI_EVENT_GARBAGE_COLLECTION_START, nullptr);
jvmti->SetEventNotificationMode(
JVMTI_ENABLE, JVMTI_EVENT_GARBAGE_COLLECTION_FINISH, nullptr);
// Deliberately does NOT create the BFS thread (threadEntry()/threadLoop()
// below) here - threadLoop()'s VM::attachThread() call dereferences
// VM::_vm unconditionally (vmEntry.h:191-195) and crashes if the VM is not
// yet attached, which is exactly the case in this file's own gtest binary
// (referenceChains_ut.cpp calls start() directly with no live JVM).
// startThread() (referenceChains.h) owns spawning the thread instead, and
// is called from Profiler::start() (profiler.cpp) immediately after this
// method returns Error::OK - by that point in the real profiler lifecycle
// the JVM/JVMTI environment is already fully up, so VM::attachThread() is
// safe there. runPass() - the actual BFS engine - does not depend on the
// thread either way and is called directly by this file's own tests.
return Error::OK;
}
void ReferenceChainTracker::stop() {
if (!_enabled) {
return;
}
Log::info("Reference chain tracking stopped");
// Do not disable GC notifications here - LivenessTracker follows the same
// rule (livenessTracker.cpp:209-210) since the JVMTI env and its tracker
// singletons are expected to survive across multiple start/stop recording
// cycles. The BFS thread itself is stopped separately, by
// Profiler::stop() calling stopThread() (profiler.cpp) - mirroring
// start()'s split between this method and startThread().
}
void ReferenceChainTracker::startThread() {
if (!_enabled || _running.load(std::memory_order_acquire)) {
return;
}
// Create the thread (into a local pthread_t) and only publish _thread /
// flip _running=true once pthread_create() has actually succeeded.
// onGCFinish() (GC callback thread) guards its pthread_kill(_thread, ...)
// call on _running alone - GC-finish notifications are already enabled by
// start() before this method runs, so a GC-finish callback firing between
// "_running=true" and pthread_create() actually initializing _thread would
// previously call pthread_kill() on a still value-initialized (0) or
// stale/joined pthread_t, which is undefined behavior. Publishing _thread
// before _running closes that window.
// Reset from any previous stopThread() call - a dynamic-attach profiler
// can go through multiple start()/stop() cycles in one JVM lifetime (this
// class's own start()/stop() header comments), and a stale abort request
// left set from the prior cycle would make heapReferenceCallback() abort
// this new cycle's very first pass instantly.
_abort_pass_requested.store(false, std::memory_order_relaxed);
// Same reasoning as _abort_pass_requested above, for a different stale-state
// hazard: expandFrontier()'s _cached_object_class[_jni] is keyed on JNIEnv*
// identity to detect a fresh attach, but a new pthread's VM::attachThread()
// (threadLoop(), below) can be handed back a JNIEnv* the JVM already freed
// and is now reusing for this new session - the pointer value alone cannot
// distinguish "still this session" from "coincidentally the same address as
// a prior, already-detached session". A prior session's now-dangling local
// ref would then look "cached and valid" to that identity check and get
// passed straight into NewObjectArray(). stopThread() already joined that
// prior session's thread before this method can run (Profiler::stop()/
// start() always pair stopThread()+start() sequentially), so it is safe to
// force the cache to re-resolve unconditionally on this new session's first
// expandFrontier() call rather than trust the old JNIEnv* comparison.
_cached_object_class = nullptr;
_cached_object_class_jni = nullptr;
pthread_t thread;
if (pthread_create(&thread, NULL, threadEntry, this) != 0) {
Log::warn("Unable to create ReferenceChains BFS thread");
return;
}
_thread = thread;
_running.store(true, std::memory_order_release);
}
void ReferenceChainTracker::stopThread() {
if (!_running.load(std::memory_order_acquire)) {
return;
}
_running.store(false, std::memory_order_release);
// Ask any in-flight JVMTI FollowReferences walk (heapReferenceCallback())
// to abort at its next callback invocation - set before pthread_kill()
// below, since that signal alone cannot interrupt a call already inside
// the JVM/JVMTI implementation.
_abort_pass_requested.store(true, std::memory_order_relaxed);
// Same wake-then-join shape as BaseWallClock::stop() (wallClock.cpp:324-333):
// pthread_kill(WAKEUP_SIGNAL) interrupts threadLoop()'s OS::sleep() early
// (WAKEUP_SIGNAL/SIGIO is installed with a no-op handler unconditionally
// in vmEntry.cpp, so this signal never terminates the thread) so it
// re-checks _running and exits promptly rather than waiting out the rest
// of the current sleep interval.
pthread_kill(_thread, WAKEUP_SIGNAL);
int res = pthread_join(_thread, NULL);
if (res != 0) {
Log::warn("Unable to join ReferenceChains BFS thread on stop %d", res);
}
}
// Not yet started by anything (see start()'s comment above for why) - but
// now implements the real scheduling loop the design doc asks for, matching
// J9WallClock's attach/park/detach lifecycle (j9WallClock.cpp:28-57): each
// wake (adaptive cadence, or earlier via onGCFinish()'s pthread_kill below)
// checks shouldRunPass() and calls runPass() if it says so. The pause-time
// pacing controller sleeps for _effective_cadence_ns rather than the fixed
// PASS_CADENCE_NS, so a
// controller-driven relaxed cadence (updatePacing()) actually shortens how
// long an idle, no-GC-event search waits between passes, not just
// shouldRunPass()'s own comparison.
void ReferenceChainTracker::threadLoop() {
struct Cleanup {
ReferenceChainTracker *tracker;
~Cleanup() {
// Drop the cached java/lang/Object local ref (and the JNIEnv* it was
// resolved on) before detaching: DetachCurrentThread() invalidates
// every local ref this attach ever created, but _cached_object_class
// and _cached_object_class_jni are tracker-lifetime fields that
// survive into the next start()'s brand-new BFS thread/attach. If the
// JVM happens to hand that next attach the same JNIEnv* address (JNIEnv
// structs are heap-allocated per attach and can be reused once freed),
// the "_cached_object_class_jni != jni" check in expandFrontier()
// would wrongly treat the now-dangling local ref as still valid.
// Clearing both here forces an unconditional FindClass() on the first
// expandFrontier() call of the next attach instead.
tracker->_cached_object_class = nullptr;
tracker->_cached_object_class_jni = nullptr;
VM::detachThread();
}
} cleanup{this};
JNIEnv *jni = VM::attachThread("java-profiler ReferenceChains");
jvmtiEnv *jvmti = VM::jvmti();
if (jni == nullptr) {
// AttachCurrentThreadAsDaemon() failed - mirror pollWatchedTargets()'s
// own jni==nullptr early return rather than letting a null JNIEnv flow
// into runPass()/resolveLoadedClasses()/expandFrontier()/
// releaseSearchTags() below: those only guard their DeleteLocalRef()
// calls on `jni != nullptr`, so without this check every
// GetLoadedClasses()/GetObjectsWithTags() local ref returned on this
// (permanently un-attached) thread would leak for the rest of the
// process's lifetime. Nothing this thread does is safe without a live
// JNIEnv, so give up on the whole loop rather than retrying per
// iteration - detachThread() in Cleanup is a safe no-op if attach never
// actually succeeded.
Log::warn("ReferenceChains: VM::attachThread failed; BFS thread exiting");
return;
}
TEST_LOG("ReferenceChainTracker::threadLoop started, cadence=%lluns", (unsigned long long)_effective_cadence_ns);
int iteration = 0;
while (_running.load(std::memory_order_acquire)) {
// Fixed ~1s cadence, no early wake on GC (see onGCFinish()'s own
// comment) - stopThread() still interrupts this via its own
// pthread_kill so shutdown stays prompt.
OS::sleep(_effective_cadence_ns);
if (!_running.load(std::memory_order_acquire)) {
break;
}
// Third trigger for LivenessTracker::cleanup_table() (see
// LivenessTracker::maybeForceCleanup()'s own comment): track()'s
// table-overflow branch and flush_table()'s JFR cadence can both starve
// under ObjectSampler's PID-controlled sampling interval, leaving
// hasLeakSignal() below stuck on a stale population history no matter
// how long a real leak keeps growing. This thread already wakes every
// ~1s with a live JNIEnv, so it doubles as that fallback tick - cheap,
// and a no-op unless 30s have actually elapsed with a GC in between (see
// that method for the exact gate).
u64 wake_now_ns = OS::nanotime();
LivenessTracker::instance()->maybeForceCleanup(wake_now_ns);
// No fast-path skip here: shouldRunPass() below already returns false
// cheaply (a couple of atomic loads/comparisons, no JVMTI call) for a
// RUNNING search with no new GC and cadence not yet elapsed. An earlier
// revision additionally gated this on hasLeakSignal() (LivenessTracker's
// population-trend signal, also used by canAffordNewSearch() below to gate
// the first-ever search and every restart), but that signal answers "is
// there a leak candidate right now", which is unrelated to whether an
// already-RUNNING search's own frontier still has pending work - gating a
// RUNNING search's every pass on it would stall that search's own
// convergence for as long as no leak candidate happens to be visible,
// even with GC epochs advancing or cadence elapsed. hasLeakSignal()
// remains the right gate for starting a *new* search, whether that is the
// first one ever or a restart of a *terminal* one (shouldRunPass()'s own
// canAffordNewSearch() call).
u64 now_ns = OS::nanotime();
bool should_run = shouldRunPass(now_ns);
// Log the loop state only when a pass is actually going to run - the idle
// wakes (should_run == false) are the common steady state and logging them
// every second is pure noise.
if (should_run) {
TEST_LOG("ReferenceChainTracker::threadLoop iteration=%d shouldRunPass=%d searchState=%d "
"passesRun=%d effectiveCadenceNs=%llu effectiveBudget=%d gcFinishEpoch=%llu "
"lastPassGcFinishEpoch=%llu nowMinusLastPassNs=%llu",
++iteration, should_run, (int)_search_state, _passes_run,
(unsigned long long)_effective_cadence_ns, _effective_budget,
(unsigned long long)gcFinishEpoch(), (unsigned long long)_last_pass_gc_finish_epoch,
(unsigned long long)(now_ns - _last_pass_ns));
runPass(jvmti, jni, nullptr);
}
// Target-selection bridging step: poll once per scheduling cycle, after
// runPass() - so this poll always sees the most recent pass's tagging (see
// pollWatchedTargets()'s own comment). Unconditional, not gated on
// shouldRunPass()'s decision above: a candidate discovered by an
// earlier pass may still be waiting for its first poll even on a cycle
// where this cycle's own pass was skipped.
pollWatchedTargets(jvmti, jni);
}
}
void JNICALL ReferenceChainTracker::GarbageCollectionStart(jvmtiEnv *jvmti_env) {
ReferenceChainTracker::instance()->onGCStart();
}
void JNICALL ReferenceChainTracker::GarbageCollectionFinish(jvmtiEnv *jvmti_env) {
ReferenceChainTracker::instance()->onGCFinish();
}
void ReferenceChainTracker::onGCStart() {
if (!_enabled) {
return;
}
// JVMTI spec: only Memory Management category calls (Allocate/Deallocate)
// are allowed from inside this callback - nothing else may run here.
GCCallbackGuard guard;
atomicIncRelaxed(_gc_start_epoch, (u64)1);
}
void ReferenceChainTracker::onGCFinish() {
if (!_enabled) {
return;
}
GCCallbackGuard guard;
// Design doc's Triggering section: GC callbacks are only a scheduling
// *signal*, never a pass's execution vehicle (Heap-category JVMTI calls
// are forbidden here - see this file's header comment). Deliberately just
// bookkeeping - no pthread_kill/early wake here. threadLoop() below wakes
// on its own fixed ~1s cadence and reads this epoch then; waking it early
// on every GC gains at most ~1s of latency but, under any GC-heavy
// workload, collapses the loop's cadence to GC frequency instead (each
// early wake is itself a full iteration's worth of shouldRunPass()/
// pollWatchedTargets() work), which is not worth the latency win.
atomicIncRelaxed(_gc_finish_epoch, (u64)1);
}
bool ReferenceChainTracker::shouldRunPass(u64 now_ns) {
if (!_search_started) {
// Same gate as a restart (canAffordNewSearch() below) - a brand-new
// tracker must not pay for the first whole-heap walk/tagging pass either
// when there is no leak candidate to justify it. The pain-budget half is
// always a no-op here (nothing has ever been spent yet), so this reduces
// to hasLeakSignal() in practice, but sharing the one gate keeps both
// call sites from drifting apart.
if (!canAffordNewSearch(now_ns)) {
return false;
}
TEST_LOG("ReferenceChainTracker::shouldRunPass -> true (search not started yet)");
return true; // nothing has run yet - always worth taking the first pass
}
if (_search_state != SearchState::RUNNING) {
// Terminal outcome already reached (runPass()'s Termination section).
if (!_tags_released) {
// releaseSearchTags() failed to confirm every live tag this search
// owned was actually cleared - restartSearch() must never run until
// that is confirmed (see _tags_released's own comment), so return
// true unconditionally here: that drives threadLoop() to call
// runPass() again, whose terminal-state branch retries the release,
// rather than letting canAffordNewSearch()/restartSearch() below run
// ahead of it.
TEST_LOG("ReferenceChainTracker::shouldRunPass -> true (retrying tag "
"release before restart is allowed)");
return true;
}
// Restart (this class's own header comment) if the pain budget has
// drained and there is still (or again) a leak indication to chase -
// canAffordNewSearch() is always true when LivenessTracker's population
// trends are not in use at all, so this only ever changes behavior for a
// search that already ran once.
if (canAffordNewSearch(now_ns)) {
restartSearch();
TEST_LOG("ReferenceChainTracker::shouldRunPass -> true (restarting search)");
return true;
}
// No log here: a terminal search waiting for a restart to become
// warranted is the common idle state, re-evaluated every second, so
// logging it is pure per-second noise (see threadLoop()).
return false;
}
u64 gc_finish_epoch = gcFinishEpoch();
if (gc_finish_epoch != _last_pass_gc_finish_epoch) {
// Triggering section: "a GC just happened, a pass may be worth running
// soon".
TEST_LOG("ReferenceChainTracker::shouldRunPass -> true (gcFinishEpoch=%llu != "
"lastPassGcFinishEpoch=%llu)",
(unsigned long long)gc_finish_epoch,
(unsigned long long)_last_pass_gc_finish_epoch);
return true;
}
// Pause-time pacing controller: compares against _effective_cadence_ns, not
// the fixed PASS_CADENCE_NS - see that
// field's own comment (referenceChains.h) for how updatePacing() widens or
// relaxes it from the measured pause-time signal.
bool cadence_elapsed = now_ns - _last_pass_ns >= _effective_cadence_ns;
// Only log when the cadence actually elapsed (a pass will run). The
// not-yet-elapsed case is the common idle wake and logging it every second
// is noise.
if (cadence_elapsed) {
TEST_LOG("ReferenceChainTracker::shouldRunPass -> true (now_ns=%llu last_pass_ns=%llu "
"delta=%llu effectiveCadenceNs=%llu)",
(unsigned long long)now_ns, (unsigned long long)_last_pass_ns,
(unsigned long long)(now_ns - _last_pass_ns),
(unsigned long long)_effective_cadence_ns);
}
return cadence_elapsed;
}
// Search restart gate (this class's own header comment). Deliberately a
// probe (max=1) rather than reusing pollWatchedTargets()'s own
// selectLeakCandidates() call - that one runs after runPass() in
// threadLoop()'s own iteration and needs the *list* to poll each candidate's
// tag; this only needs to know whether at least one exists.
bool ReferenceChainTracker::hasLeakSignal() {
if (!LivenessTracker::instance()->gcGenerationsEnabled()) {
// No population-trend signal to gate on at all - see this method's own
// header comment for why that means "always true" here.
return true;
}
KlassCandidate probe[1];
return LivenessTracker::instance()->selectLeakCandidates(probe, 1) > 0;
}
bool ReferenceChainTracker::canAffordNewSearch(u64 now_ns) {
if (!_pain_budget.canStartNow(now_ns)) {
return false; // still cooling down from the last search's own cost
}
return hasLeakSignal();
}
// Search restart (this class's own header comment). Called only from
// shouldRunPass() once canAffordNewSearch() has approved it, immediately
// before returning true for this same iteration - runPass() then sees
// _search_started == false and takes the first-pass branch, exactly like a
// brand-new tracker.
void ReferenceChainTracker::restartSearch() {
// Only called once shouldRunPass() has confirmed _tags_released - never
// while a prior search's release might still be pending (see
// _tags_released's own comment): resetting _next_tag to 1 / the frontier
// table below while some object could still hold this search's now-
// ambiguous tag would let the restarted search's fresh tags collide with
// it.
assert(_tags_released &&
"restartSearch() must not run before releaseSearchTags() has "
"confirmed every live tag was cleared");
// Spend the finishing search's own cost before clearing the accumulator -
// canAffordNewSearch()'s *next* call must see this search's cost, not a
// reset-to-zero balance.
_pain_budget.spend(_search_pain_ms);
_search_pain_ms = 0;
if (_frontier != nullptr) {
_frontier->resetForRestart();
}
_next_tag = 1;
// _next_class_tag_magnitude/_class_tags intentionally untouched - see this
// method's own declaration comment (referenceChains.h).
_search_started = false;
store(_search_state, (u8)SearchState::RUNNING);
store(_abandon_reason, (u8)SearchAbandonReason::NONE);
store(_search_start_ns, (u64)0);
_pending_expand.clear();
_priority_expand.clear();
_last_pass_gc_finish_epoch = 0;
store(_last_pass_ns, (u64)0);
store(_passes_run, 0);
// Reset back to their just-constructed values (0 / -1) like every other
// per-search field this method touches: resolveLoadedClasses() and
// admitStaticFieldRoots() must both run unconditionally on the restarted
// search's first pass, exactly as they do for a brand-new tracker.
_last_resolved_class_count = 0;
_last_static_field_class_count = -1;
// _resolved_chains is intentionally left intact: a chain resolved by the
// finishing search stays cached (and keeps being re-emitted on every dump)
// across the restart, since it describes a sample that is still live. The
// restarted search re-tags that sample under a fresh _search_start_ns, and
// pollWatchedTargets() refreshes the cached entry then (its own comment);
// it prunes the entry if the sample has since been collected.
}
void ReferenceChainTracker::resetSearchStateForTest(jvmtiEnv *jvmti,
JNIEnv *jni) {
// Every field touched below is otherwise only ever mutated by the BFS
// thread itself (threadLoop()/runPass()/pollWatchedTargets()) - without
// stopping it first, a pass already in flight on that thread can observe
// this reset only partially, or overwrite it right back (e.g. finish a
// pass that was already headed for SearchState::ABANDONED after this
// method has just forced SearchState::RUNNING below), a race found in
// practice, not just in theory. stopThread() (now that it can abort an
// in-flight JVMTI walk promptly - see its own comment) makes this a cheap,
// clean stop/reset/restart rather than an indefinite wait.
stopThread();
// Clear every live tag this search still holds before resetting - the
// same ordering restartSearch() itself requires (its own assert), so a
// stale tag from whatever search a previous test left running cannot
// collide with the fresh search's own tags once _next_tag is rewound
// below.
if (jvmti != nullptr && jni != nullptr) {
releaseSearchTags(jvmti, jni);
}
_tags_released = true;
_pain_budget.spend(_search_pain_ms);
_search_pain_ms = 0;
if (_frontier != nullptr) {
// Rebuilds the table at this test's own _configured_frontier_cap,
// undoing any smaller framecap= an earlier test left it permanently
// sized at (this class's own header comment on @TestMethodOrder) -
// restartSearch()'s production path only calls the cheaper
// resetForRestart() since it never needs to change the cap mid-JVM.
_frontier->resetCapacityForTest(_configured_frontier_cap);
}
_next_tag = 1;
_search_started = false;
store(_search_state, (u8)SearchState::RUNNING);
store(_abandon_reason, (u8)SearchAbandonReason::NONE);
store(_search_start_ns, (u64)0);
_pending_expand.clear();
_priority_expand.clear();
_last_pass_gc_finish_epoch = 0;
store(_last_pass_ns, (u64)0);
store(_passes_run, 0);
// Unlike restartSearch(), which deliberately keeps _resolved_chains alive
// across a production restart, a test reset starts from a blank cache so
// one test's resolved chains cannot leak into the next.
_resolved_chains_lock.lock();
_resolved_chains.clear();
_resolved_chains_lock.unlock();
// Restart the BFS thread against this freshly reset state - startThread()
// itself clears _abort_pass_requested, so the new thread's very first
// pass is not instantly aborted by the flag stopThread() just set above.
startThread();
}
long ReferenceChainTracker::pendingExpandPositionForTest(jlong tag) const {
if (tag == 0) {
return -2;
}
// _priority_expand drains first (expandFrontier()'s own comment), so its
// entries are reported as coming before _pending_expand's.
long pos = 0;
for (jlong queued : _priority_expand) {
if (queued == tag) {
return pos;
}
pos++;
}
for (jlong queued : _pending_expand) {
if (queued == tag) {
return pos;
}
pos++;
}
return -1;
}
size_t ReferenceChainTracker::pendingExpandSizeForTest() const {
return _pending_expand.size() + _priority_expand.size();
}
jlong ReferenceChainTracker::tagObject(jvmtiEnv *jvmti, jobject obj) {
assert(!t_inGCCallback &&
"SetTag is a JVMTI Heap-category call and must not be made from "
"GarbageCollectionStart/Finish");
jlong tag = nextTag();
jvmtiError err = jvmti->SetTag(obj, tag);
if (err != JVMTI_ERROR_NONE) {
return 0;
}
return tag;
}
jlong ReferenceChainTracker::getTag(jvmtiEnv *jvmti, jobject obj) {
assert(!t_inGCCallback &&
"GetTag is a JVMTI Heap-category call and must not be made from "
"GarbageCollectionStart/Finish");
jlong tag = 0;
jvmtiError err = jvmti->GetTag(obj, &tag);
if (err != JVMTI_ERROR_NONE) {
return 0;
}
return tag;
}
void ReferenceChainTracker::clearTag(jvmtiEnv *jvmti, jobject obj) {
assert(!t_inGCCallback &&
"SetTag is a JVMTI Heap-category call and must not be made from "
"GarbageCollectionStart/Finish");
jvmti->SetTag(obj, 0);
}
jlong ReferenceChainTracker::tagAsRootForTest(jvmtiEnv *jvmti, JNIEnv *jni,
jobject obj) {
if (_frontier == nullptr || jvmti == nullptr || jni == nullptr ||
obj == nullptr) {
return 0;
}
// Resolves the klass_id the same way LivenessTracker::resolveKlassId()
// does (GetObjectClass + Class.getName() + Profiler::lookupClass()) -
// this is a test-only, off-hot-path call so caching _Class/_Class_getName
// like LivenessTracker does is not worth the extra state.
u32 klass_id = 0;
jclass klass = jni->GetObjectClass(obj);
jclass class_class = jni->FindClass("java/lang/Class");
if (class_class != nullptr) {
jmethodID get_name =
jni->GetMethodID(class_class, "getName", "()Ljava/lang/String;");
if (get_name != nullptr) {
jstring name_str = (jstring)jni->CallObjectMethod(klass, get_name);
if (name_str != nullptr) {
const char *name = jni->GetStringUTFChars(name_str, nullptr);
if (name != nullptr) {
int id = Profiler::instance()->lookupClass(name, strlen(name));
if (id > 0) {
klass_id = (u32)id;
}
jni->ReleaseStringUTFChars(name_str, name);
}
jni->DeleteLocalRef(name_str);
}
}
jni->DeleteLocalRef(class_class);
}
jni->DeleteLocalRef(klass);
// Tags `obj` and inserts it as a frontier root (parent_tag=0, depth=0),
// exactly the convention runPass()'s heap-root callback path already uses
// (referenceChains.cpp's heapReferenceCallback(), referrer_tag_ptr ==
// nullptr branch) - this lets a test drive the real BFS/chain-
// reconstruction logic (runPass()/pollWatchedTargets()/buildChainEvent())
// against a known, caller-chosen live object, decoupled from whether the
// real root-seeded walk or LivenessTracker's probabilistic sampler happens
// to reach/select it on its own.
jlong tag = tagObject(jvmti, obj);
if (tag == 0) {
return 0;
}
if (!_frontier->insert(tag, 0, klass_id, 0)) {
clearTag(jvmti, obj);
return 0;
}
return tag;
}
// ---------------------------------------------------------------------------
// Heap-walk engine
// ---------------------------------------------------------------------------
void ReferenceChainTracker::resolveLoadedClasses(jvmtiEnv *jvmti,
JNIEnv *jni) {
// Profiler::start() resets the class-name StringDictionary
// (_class_map.clearAll(), profiler.cpp) whenever `reset || _start_time ==
// 0` - which restarts its id namespace at 1, but does NOT touch any
// class's JVMTI-level class-object tag (JVM-level state, unrelated to our
// dictionary). Detect that reset via the dictionary's own generation
// counter and drop every id this table cached from the now-gone
// generation before the scan below - see _last_class_map_generation's own
// comment (referenceChains.h) for why leaving them in place would keep
// resolving heap references to the wrong (or nonexistent) class name.
u64 current_generation = Profiler::instance()->classMap()->generation();
bool class_map_reset = current_generation != _last_class_map_generation;
if (class_map_reset) {
_class_tags.clear();
// Force the scan below to run even if GetLoadedClasses()'s count happens
// to match the last-seen count - -1 can never equal `class_count`
// (always >= 0), unlike 0 which is a legitimate "no classes loaded yet"
// starting value.
_last_resolved_class_count = -1;
_last_class_map_generation = current_generation;
}
jclass *classes = nullptr;
jint class_count = 0;
if (jvmti->GetLoadedClasses(&class_count, &classes) != JVMTI_ERROR_NONE ||
classes == nullptr) {
return;
}
// Skip the per-class GetTag()/GetClassSignature() scan entirely once the
// loaded-class count has not CHANGED since the last time this ran it:
// every already-tagged class stays tagged forever (tags are never
// cleared once assigned - see _class_tags' own comment), so a resumed
// pass with no newly-loaded classes has nothing left to resolve. Without
// this, every single pass pays a full GetTag() call per loaded class
// (potentially thousands) even though almost all of them are already
// resolved, and that cost is invisible to the pause-time-SLO pacing
// controller (runPass()'s pass_wall_ticks measurement deliberately scopes