1 /*
  2  * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "gc/g1/g1CollectedHeap.inline.hpp"
 27 #include "gc/g1/g1GCParPhaseTimesTracker.hpp"
 28 #include "gc/g1/g1GCPhaseTimes.hpp"
 29 #include "gc/g1/g1ParScanThreadState.inline.hpp"
 30 #include "gc/shared/gcTimer.hpp"
 31 #include "gc/shared/oopStorage.hpp"
 32 #include "gc/shared/oopStorageSet.hpp"
 33 #include "gc/shared/tlab_globals.hpp"
 34 #include "gc/shared/workerDataArray.inline.hpp"
 35 #include "memory/resourceArea.hpp"
 36 #include "logging/log.hpp"
 37 #include "logging/logStream.hpp"
 38 #include "runtime/timer.hpp"
 39 #include "runtime/os.hpp"
 40 #include "utilities/enumIterator.hpp"
 41 #include "utilities/macros.hpp"
 42 
 43 constexpr const char* G1GCPhaseTimes::GCMergeRSWorkItemsStrings[];
 44 
 45 G1GCPhaseTimes::G1GCPhaseTimes(STWGCTimer* gc_timer, uint max_gc_threads) :
 46   _max_gc_threads(max_gc_threads),
 47   _gc_start_counter(0),
 48   _gc_pause_time_ms(0.0),
 49   _ref_phase_times(gc_timer, max_gc_threads),
 50   _weak_phase_times(max_gc_threads)
 51 {
 52   assert(max_gc_threads > 0, "Must have some GC threads");
 53 
 54   _gc_par_phases[RetireTLABsAndFlushLogs] = new WorkerDataArray<double>("RetireTLABsAndFlushLogs", "JT Retire TLABs And Flush Logs (ms):", max_gc_threads);
 55   _gc_par_phases[NonJavaThreadFlushLogs] = new WorkerDataArray<double>("NonJavaThreadFlushLogs", "Non-JT Flush Logs (ms):", max_gc_threads);
 56 
 57   _gc_par_phases[GCWorkerStart] = new WorkerDataArray<double>("GCWorkerStart", "GC Worker Start (ms):", max_gc_threads);
 58   _gc_par_phases[ExtRootScan] = new WorkerDataArray<double>("ExtRootScan", "Ext Root Scanning (ms):", max_gc_threads);
 59 
 60   // Root scanning phases
 61   _gc_par_phases[ThreadRoots] = new WorkerDataArray<double>("ThreadRoots", "Thread Roots (ms):", max_gc_threads);
 62   _gc_par_phases[CLDGRoots] = new WorkerDataArray<double>("CLDGRoots", "CLDG Roots (ms):", max_gc_threads);
 63   _gc_par_phases[CMRefRoots] = new WorkerDataArray<double>("CMRefRoots", "CM RefProcessor Roots (ms):", max_gc_threads);
 64 
 65   for (auto id : EnumRange<OopStorageSet::StrongId>()) {
 66     GCParPhases phase = strong_oopstorage_phase(id);
 67     const char* phase_name_postfix = " Roots (ms):";
 68     const char* storage_name = OopStorageSet::storage(id)->name();
 69     char* oop_storage_phase_name = NEW_C_HEAP_ARRAY(char, strlen(phase_name_postfix) + strlen(storage_name) + 1, mtGC);
 70     strcpy(oop_storage_phase_name, storage_name);
 71     strcat(oop_storage_phase_name, phase_name_postfix);
 72     _gc_par_phases[phase] = new WorkerDataArray<double>(storage_name, oop_storage_phase_name, max_gc_threads);
 73   }
 74 
 75   _gc_par_phases[MergeER] = new WorkerDataArray<double>("MergeER", "Eager Reclaim (ms):", max_gc_threads);
 76 
 77   _gc_par_phases[MergeRS] = new WorkerDataArray<double>("MergeRS", "Remembered Sets (ms):", max_gc_threads);
 78   for (uint i = 0; i < MergeRSContainersSentinel; i++) {
 79     _gc_par_phases[MergeRS]->create_thread_work_items(GCMergeRSWorkItemsStrings[i], i);
 80   }
 81 
 82   _gc_par_phases[OptMergeRS] = new WorkerDataArray<double>("OptMergeRS", "Optional Remembered Sets (ms):", max_gc_threads);
 83   for (uint i = 0; i < MergeRSContainersSentinel; i++) {
 84     _gc_par_phases[OptMergeRS]->create_thread_work_items(GCMergeRSWorkItemsStrings[i], i);
 85   }
 86 
 87   _gc_par_phases[MergeLB] = new WorkerDataArray<double>("MergeLB", "Log Buffers (ms):", max_gc_threads);
 88   _gc_par_phases[ScanHR] = new WorkerDataArray<double>("ScanHR", "Scan Heap Roots (ms):", max_gc_threads);
 89   _gc_par_phases[OptScanHR] = new WorkerDataArray<double>("OptScanHR", "Optional Scan Heap Roots (ms):", max_gc_threads);
 90   _gc_par_phases[CodeRoots] = new WorkerDataArray<double>("CodeRoots", "Code Root Scan (ms):", max_gc_threads);
 91   _gc_par_phases[OptCodeRoots] = new WorkerDataArray<double>("OptCodeRoots", "Optional Code Root Scan (ms):", max_gc_threads);
 92   _gc_par_phases[ObjCopy] = new WorkerDataArray<double>("ObjCopy", "Object Copy (ms):", max_gc_threads);
 93   _gc_par_phases[OptObjCopy] = new WorkerDataArray<double>("OptObjCopy", "Optional Object Copy (ms):", max_gc_threads);
 94   _gc_par_phases[Termination] = new WorkerDataArray<double>("Termination", "Termination (ms):", max_gc_threads);
 95   _gc_par_phases[OptTermination] = new WorkerDataArray<double>("OptTermination", "Optional Termination (ms):", max_gc_threads);
 96   _gc_par_phases[GCWorkerTotal] = new WorkerDataArray<double>("GCWorkerTotal", "GC Worker Total (ms):", max_gc_threads);
 97   _gc_par_phases[GCWorkerEnd] = new WorkerDataArray<double>("GCWorkerEnd", "GC Worker End (ms):", max_gc_threads);
 98   _gc_par_phases[Other] = new WorkerDataArray<double>("Other", "GC Worker Other (ms):", max_gc_threads);
 99   _gc_par_phases[MergePSS] = new WorkerDataArray<double>("MergePSS", "Merge Per-Thread State (ms):", max_gc_threads);
100   _gc_par_phases[RestoreEvacuationFailedRegions] = new WorkerDataArray<double>("RestoreEvacuationFailedRegions", "Restore Evacuation Failed Regions (ms):", max_gc_threads);
101   _gc_par_phases[RemoveSelfForwards] = new WorkerDataArray<double>("RemoveSelfForwards", "Remove Self Forwards (ms):", max_gc_threads);
102   _gc_par_phases[ClearCardTable] = new WorkerDataArray<double>("ClearLoggedCards", "Clear Logged Cards (ms):", max_gc_threads);
103   _gc_par_phases[RecalculateUsed] = new WorkerDataArray<double>("RecalculateUsed", "Recalculate Used Memory (ms):", max_gc_threads);
104 #if COMPILER2_OR_JVMCI
105   _gc_par_phases[UpdateDerivedPointers] = new WorkerDataArray<double>("UpdateDerivedPointers", "Update Derived Pointers (ms):", max_gc_threads);
106 #endif
107   _gc_par_phases[EagerlyReclaimHumongousObjects] = new WorkerDataArray<double>("EagerlyReclaimHumongousObjects", "Eagerly Reclaim Humongous Objects (ms):", max_gc_threads);
108   _gc_par_phases[ProcessEvacuationFailedRegions] = new WorkerDataArray<double>("ProcessEvacuationFailedRegions", "Process Evacuation Failed Regions (ms):", max_gc_threads);
109 
110   _gc_par_phases[ScanHR]->create_thread_work_items("Scanned Cards:", ScanHRScannedCards);
111   _gc_par_phases[ScanHR]->create_thread_work_items("Scanned Blocks:", ScanHRScannedBlocks);
112   _gc_par_phases[ScanHR]->create_thread_work_items("Claimed Chunks:", ScanHRClaimedChunks);
113   _gc_par_phases[ScanHR]->create_thread_work_items("Found Roots:", ScanHRFoundRoots);
114 
115   _gc_par_phases[OptScanHR]->create_thread_work_items("Scanned Cards:", ScanHRScannedCards);
116   _gc_par_phases[OptScanHR]->create_thread_work_items("Scanned Blocks:", ScanHRScannedBlocks);
117   _gc_par_phases[OptScanHR]->create_thread_work_items("Claimed Chunks:", ScanHRClaimedChunks);
118   _gc_par_phases[OptScanHR]->create_thread_work_items("Found Roots:", ScanHRFoundRoots);
119   _gc_par_phases[OptScanHR]->create_thread_work_items("Scanned Refs:", ScanHRScannedOptRefs);
120   _gc_par_phases[OptScanHR]->create_thread_work_items("Used Memory:", ScanHRUsedMemory);
121 
122   _gc_par_phases[MergeLB]->create_thread_work_items("Dirty Cards:", MergeLBDirtyCards);
123   _gc_par_phases[MergeLB]->create_thread_work_items("Skipped Cards:", MergeLBSkippedCards);
124 
125   _gc_par_phases[CodeRoots]->create_thread_work_items("Scanned Nmethods:", CodeRootsScannedNMethods);
126 
127   _gc_par_phases[OptCodeRoots]->create_thread_work_items("Scanned Nmethods:", CodeRootsScannedNMethods);
128 
129   _gc_par_phases[MergePSS]->create_thread_work_items("Copied Bytes:", MergePSSCopiedBytes);
130   _gc_par_phases[MergePSS]->create_thread_work_items("LAB Waste:", MergePSSLABWasteBytes);
131   _gc_par_phases[MergePSS]->create_thread_work_items("LAB Undo Waste:", MergePSSLABUndoWasteBytes);
132   _gc_par_phases[MergePSS]->create_thread_work_items("Evac Fail Extra Cards:", MergePSSEvacFailExtra);
133 
134   _gc_par_phases[RestoreEvacuationFailedRegions]->create_thread_work_items("Evacuation Failed Regions:", RestoreEvacFailureRegionsEvacFailedNum);
135   _gc_par_phases[RestoreEvacuationFailedRegions]->create_thread_work_items("Pinned Regions:", RestoreEvacFailureRegionsPinnedNum);
136   _gc_par_phases[RestoreEvacuationFailedRegions]->create_thread_work_items("Allocation Failed Regions:", RestoreEvacFailureRegionsAllocFailedNum);
137 
138   _gc_par_phases[RemoveSelfForwards]->create_thread_work_items("Forward Chunks:", RemoveSelfForwardChunksNum);
139   _gc_par_phases[RemoveSelfForwards]->create_thread_work_items("Empty Forward Chunks:", RemoveSelfForwardEmptyChunksNum);
140   _gc_par_phases[RemoveSelfForwards]->create_thread_work_items("Forward Objects:", RemoveSelfForwardObjectsNum);
141   _gc_par_phases[RemoveSelfForwards]->create_thread_work_items("Forward Bytes:", RemoveSelfForwardObjectsBytes);
142 
143   _gc_par_phases[EagerlyReclaimHumongousObjects]->create_thread_work_items("Humongous Total:", EagerlyReclaimNumTotal);
144   _gc_par_phases[EagerlyReclaimHumongousObjects]->create_thread_work_items("Humongous Candidates:", EagerlyReclaimNumCandidates);
145   _gc_par_phases[EagerlyReclaimHumongousObjects]->create_thread_work_items("Humongous Reclaimed:", EagerlyReclaimNumReclaimed);
146 
147   _gc_par_phases[SampleCollectionSetCandidates] = new WorkerDataArray<double>("SampleCandidates", "Sample CSet Candidates (ms):", max_gc_threads);
148 
149   _gc_par_phases[Termination]->create_thread_work_items("Termination Attempts:");
150 
151   _gc_par_phases[OptTermination]->create_thread_work_items("Optional Termination Attempts:");
152 
153   _gc_par_phases[RedirtyCards] = new WorkerDataArray<double>("RedirtyCards", "Redirty Logged Cards (ms):", max_gc_threads);
154   _gc_par_phases[RedirtyCards]->create_thread_work_items("Redirtied Cards:");
155 
156   _gc_par_phases[ResizeThreadLABs] = new WorkerDataArray<double>("ResizeTLABs", "Resize TLABs (ms):", max_gc_threads);
157 
158   _gc_par_phases[FreeCollectionSet] = new WorkerDataArray<double>("FreeCSet", "Free Collection Set (ms):", max_gc_threads);
159   _gc_par_phases[YoungFreeCSet] = new WorkerDataArray<double>("YoungFreeCSet", "Young Free Collection Set (ms):", max_gc_threads);
160   _gc_par_phases[NonYoungFreeCSet] = new WorkerDataArray<double>("NonYoungFreeCSet", "Non-Young Free Collection Set (ms):", max_gc_threads);
161   _gc_par_phases[RebuildFreeList] = new WorkerDataArray<double>("RebuildFreeList", "Parallel Rebuild Free List (ms):", max_gc_threads);
162 
163   _gc_par_phases[ResetMarkingState] = new WorkerDataArray<double>("ResetMarkingState", "Reset Marking State (ms):", max_gc_threads);
164   _gc_par_phases[NoteStartOfMark] = new WorkerDataArray<double>("NoteStartOfMark", "Note Start Of Mark (ms):", max_gc_threads);
165 
166   reset();
167 }
168 
169 void G1GCPhaseTimes::reset() {
170   _cur_collection_initial_evac_time_ms = 0.0;
171   _cur_optional_evac_time_ms = 0.0;
172   _cur_collection_nmethod_list_cleanup_time_ms = 0.0;
173   _cur_merge_heap_roots_time_ms = 0.0;
174   _cur_optional_merge_heap_roots_time_ms = 0.0;
175   _cur_prepare_merge_heap_roots_time_ms = 0.0;
176   _cur_distribute_log_buffers_time_ms = 0.0;
177   _cur_optional_prepare_merge_heap_roots_time_ms = 0.0;
178   _cur_pre_evacuate_prepare_time_ms = 0.0;
179   _cur_post_evacuate_cleanup_1_time_ms = 0.0;
180   _cur_post_evacuate_cleanup_2_time_ms = 0.0;
181   _cur_expand_heap_time_ms = 0.0;
182   _cur_ref_proc_time_ms = 0.0;
183   _cur_collection_start_sec = 0.0;
184   _root_region_scan_wait_time_ms = 0.0;
185   _external_accounted_time_ms = 0.0;
186   _recorded_prepare_heap_roots_time_ms = 0.0;
187   _recorded_young_cset_choice_time_ms = 0.0;
188   _recorded_non_young_cset_choice_time_ms = 0.0;
189   _recorded_prepare_for_mutator_time_ms = 0.0;
190   _recorded_serial_free_cset_time_ms = 0.0;
191   _recorded_total_rebuild_freelist_time_ms = 0.0;
192   _recorded_serial_rebuild_freelist_time_ms = 0.0;
193   _cur_region_register_time = 0.0;
194   _cur_verify_before_time_ms = 0.0;
195   _cur_verify_after_time_ms = 0.0;
196 
197   for (int i = 0; i < GCParPhasesSentinel; i++) {
198     if (_gc_par_phases[i] != nullptr) {
199       _gc_par_phases[i]->reset();
200     }
201   }
202 
203   _ref_phase_times.reset();
204   _weak_phase_times.reset();
205 }
206 
207 void G1GCPhaseTimes::record_gc_pause_start() {
208   _gc_start_counter = os::elapsed_counter();
209   reset();
210 }
211 
212 #define ASSERT_PHASE_UNINITIALIZED(phase) \
213     assert(_gc_par_phases[phase] == nullptr || _gc_par_phases[phase]->get(i) == uninitialized, "Phase " #phase " reported for thread that was not started");
214 
215 double G1GCPhaseTimes::worker_time(GCParPhases phase, uint worker) {
216   if (_gc_par_phases[phase] == nullptr) {
217     return 0.0;
218   }
219   double value = _gc_par_phases[phase]->get(worker);
220   if (value != WorkerDataArray<double>::uninitialized()) {
221     return value;
222   }
223   return 0.0;
224 }
225 
226 void G1GCPhaseTimes::record_gc_pause_end() {
227   _gc_pause_time_ms = TimeHelper::counter_to_millis(os::elapsed_counter() - _gc_start_counter);
228 
229   double uninitialized = WorkerDataArray<double>::uninitialized();
230 
231   for (uint i = 0; i < _max_gc_threads; i++) {
232     double worker_start = _gc_par_phases[GCWorkerStart]->get(i);
233     if (worker_start != uninitialized) {
234       assert(_gc_par_phases[GCWorkerEnd]->get(i) != uninitialized, "Worker started but not ended.");
235       double total_worker_time = _gc_par_phases[GCWorkerEnd]->get(i) - _gc_par_phases[GCWorkerStart]->get(i);
236       record_time_secs(GCWorkerTotal, i , total_worker_time);
237 
238       double worker_known_time = worker_time(ExtRootScan, i) +
239                                  worker_time(ScanHR, i) +
240                                  worker_time(CodeRoots, i) +
241                                  worker_time(ObjCopy, i) +
242                                  worker_time(Termination, i);
243 
244       record_time_secs(Other, i, total_worker_time - worker_known_time);
245     } else {
246       // Make sure all slots are uninitialized since this thread did not seem to have been started
247       ASSERT_PHASE_UNINITIALIZED(GCWorkerEnd);
248       ASSERT_PHASE_UNINITIALIZED(ExtRootScan);
249       ASSERT_PHASE_UNINITIALIZED(MergeER);
250       ASSERT_PHASE_UNINITIALIZED(MergeRS);
251       ASSERT_PHASE_UNINITIALIZED(OptMergeRS);
252       ASSERT_PHASE_UNINITIALIZED(MergeLB);
253       ASSERT_PHASE_UNINITIALIZED(ScanHR);
254       ASSERT_PHASE_UNINITIALIZED(CodeRoots);
255       ASSERT_PHASE_UNINITIALIZED(OptCodeRoots);
256       ASSERT_PHASE_UNINITIALIZED(ObjCopy);
257       ASSERT_PHASE_UNINITIALIZED(OptObjCopy);
258       ASSERT_PHASE_UNINITIALIZED(Termination);
259     }
260   }
261 }
262 
263 #undef ASSERT_PHASE_UNINITIALIZED
264 
265 // record the time a phase took in seconds
266 void G1GCPhaseTimes::record_time_secs(GCParPhases phase, uint worker_id, double secs) {
267   _gc_par_phases[phase]->set(worker_id, secs);
268 }
269 
270 // add a number of seconds to a phase
271 void G1GCPhaseTimes::add_time_secs(GCParPhases phase, uint worker_id, double secs) {
272   _gc_par_phases[phase]->add(worker_id, secs);
273 }
274 
275 void G1GCPhaseTimes::record_or_add_time_secs(GCParPhases phase, uint worker_id, double secs) {
276   _gc_par_phases[phase]->set_or_add(worker_id, secs);
277 }
278 
279 double G1GCPhaseTimes::get_time_secs(GCParPhases phase, uint worker_id) {
280   return _gc_par_phases[phase]->get(worker_id);
281 }
282 
283 void G1GCPhaseTimes::record_thread_work_item(GCParPhases phase, uint worker_id, size_t count, uint index) {
284   _gc_par_phases[phase]->set_thread_work_item(worker_id, count, index);
285 }
286 
287 void G1GCPhaseTimes::record_or_add_thread_work_item(GCParPhases phase, uint worker_id, size_t count, uint index) {
288   _gc_par_phases[phase]->set_or_add_thread_work_item(worker_id, count, index);
289 }
290 
291 size_t G1GCPhaseTimes::get_thread_work_item(GCParPhases phase, uint worker_id, uint index) {
292   return _gc_par_phases[phase]->get_thread_work_item(worker_id, index);
293 }
294 
295 // return the average time for a phase in milliseconds
296 double G1GCPhaseTimes::average_time_ms(GCParPhases phase) const {
297   if (_gc_par_phases[phase] == nullptr) {
298     return 0.0;
299   }
300   return _gc_par_phases[phase]->average() * 1000.0;
301 }
302 
303 size_t G1GCPhaseTimes::sum_thread_work_items(GCParPhases phase, uint index) {
304   if (_gc_par_phases[phase] == nullptr) {
305     return 0;
306   }
307   assert(_gc_par_phases[phase]->thread_work_items(index) != nullptr, "No sub count");
308   return _gc_par_phases[phase]->thread_work_items(index)->sum();
309 }
310 
311 template <class T>
312 void G1GCPhaseTimes::details(T* phase, uint indent_level) const {
313   LogTarget(Trace, gc, phases, task) lt;
314   if (lt.is_enabled()) {
315     LogStream ls(lt);
316     ls.sp(indent_level * 2);
317     phase->print_details_on(&ls);
318   }
319 }
320 
321 void G1GCPhaseTimes::print_thread_work_items(WorkerDataArray<double>* phase, uint indent_level, outputStream* out) const {
322   for (uint i = 0; i < phase->MaxThreadWorkItems; i++) {
323     WorkerDataArray<size_t>* work_items = phase->thread_work_items(i);
324     if (work_items != nullptr) {
325       out->sp((indent_level + 1) * 2);
326       work_items->print_summary_on(out, true);
327       details(work_items, indent_level + 1);
328     }
329   }
330 }
331 
332 void G1GCPhaseTimes::debug_phase_merge_remset() const {
333   LogTarget(Debug, gc, phases) lt;
334   if (!lt.is_enabled()) {
335     return;
336   }
337 
338   ResourceMark rm;
339   LogStream ls(lt);
340 
341   WorkerDataArray<double>* phase = _gc_par_phases[MergeRS];
342   WorkerDataArray<double>* sub_phase = _gc_par_phases[MergeER];
343 
344   uint indent_level = 2;
345 
346   ls.sp(indent_level * 2);
347   phase->print_summary_on(&ls, true);
348   details(phase, indent_level);
349 
350   log_phase(sub_phase, (indent_level + 1), &ls, true);
351 
352   print_thread_work_items(phase, indent_level, &ls);
353 }
354 
355 void G1GCPhaseTimes::log_phase(WorkerDataArray<double>* phase, uint indent_level, outputStream* out, bool print_sum) const {
356   out->sp(indent_level * 2);
357   phase->print_summary_on(out, print_sum);
358   details(phase, indent_level);
359 
360   print_thread_work_items(phase, indent_level, out);
361 }
362 
363 void G1GCPhaseTimes::debug_phase(WorkerDataArray<double>* phase, uint extra_indent) const {
364   LogTarget(Debug, gc, phases) lt;
365   if (lt.is_enabled()) {
366     LogStream ls(lt);
367     log_phase(phase, 2 + extra_indent, &ls, true);
368   }
369 }
370 
371 void G1GCPhaseTimes::trace_phase(WorkerDataArray<double>* phase, bool print_sum, uint extra_indent) const {
372   LogTarget(Trace, gc, phases) lt;
373   if (lt.is_enabled()) {
374     LogStream ls(lt);
375     log_phase(phase, 3 + extra_indent, &ls, print_sum);
376   }
377 }
378 
379 #define TIME_FORMAT "%.2lfms"
380 
381 void G1GCPhaseTimes::info_time(const char* name, double value) const {
382   log_info(gc, phases)("  %s: " TIME_FORMAT, name, value);
383 }
384 
385 void G1GCPhaseTimes::debug_time(const char* name, double value) const {
386   log_debug(gc, phases)("    %s: " TIME_FORMAT, name, value);
387 }
388 
389 void G1GCPhaseTimes::debug_time_for_reference(const char* name, double value) const {
390   LogTarget(Debug, gc, phases) lt;
391   LogTarget(Debug, gc, phases, ref) lt2;
392 
393   if (lt.is_enabled()) {
394     LogStream ls(lt);
395     ls.print_cr("    %s: " TIME_FORMAT, name, value);
396   } else if (lt2.is_enabled()) {
397     LogStream ls(lt2);
398     ls.print_cr("    %s: " TIME_FORMAT, name, value);
399   }
400 }
401 
402 void G1GCPhaseTimes::trace_time(const char* name, double value) const {
403   log_trace(gc, phases)("      %s: " TIME_FORMAT, name, value);
404 }
405 
406 void G1GCPhaseTimes::trace_count(const char* name, size_t value) const {
407   log_trace(gc, phases)("      %s: " SIZE_FORMAT, name, value);
408 }
409 
410 double G1GCPhaseTimes::print_pre_evacuate_collection_set() const {
411   const double pre_concurrent_start_ms = average_time_ms(ResetMarkingState) +
412                                          average_time_ms(NoteStartOfMark);
413 
414   const double sum_ms = pre_concurrent_start_ms +
415                         _cur_pre_evacuate_prepare_time_ms +
416                         _recorded_young_cset_choice_time_ms +
417                         _recorded_non_young_cset_choice_time_ms +
418                         _cur_region_register_time +
419                         _recorded_prepare_heap_roots_time_ms;
420 
421   info_time("Pre Evacuate Collection Set", sum_ms);
422 
423   if (pre_concurrent_start_ms > 0.0) {
424     debug_phase(_gc_par_phases[ResetMarkingState]);
425     debug_phase(_gc_par_phases[NoteStartOfMark]);
426   }
427 
428   debug_time("Pre Evacuate Prepare", _cur_pre_evacuate_prepare_time_ms);
429   debug_phase(_gc_par_phases[RetireTLABsAndFlushLogs], 1);
430   debug_phase(_gc_par_phases[NonJavaThreadFlushLogs], 1);
431   debug_time("Choose Collection Set", (_recorded_young_cset_choice_time_ms + _recorded_non_young_cset_choice_time_ms));
432   debug_time("Region Register", _cur_region_register_time);
433 
434   debug_time("Prepare Heap Roots", _recorded_prepare_heap_roots_time_ms);
435 
436   return sum_ms;
437 }
438 
439 double G1GCPhaseTimes::print_evacuate_optional_collection_set() const {
440   const double sum_ms = _cur_optional_evac_time_ms + _cur_optional_merge_heap_roots_time_ms;
441   if (sum_ms > 0) {
442     info_time("Merge Optional Heap Roots", _cur_optional_merge_heap_roots_time_ms);
443 
444     debug_time("Prepare Optional Merge Heap Roots", _cur_optional_prepare_merge_heap_roots_time_ms);
445     debug_phase(_gc_par_phases[OptMergeRS]);
446 
447     info_time("Evacuate Optional Collection Set", _cur_optional_evac_time_ms);
448     debug_phase(_gc_par_phases[OptScanHR]);
449     debug_phase(_gc_par_phases[OptObjCopy]);
450     debug_phase(_gc_par_phases[OptCodeRoots]);
451     debug_phase(_gc_par_phases[OptTermination]);
452   }
453   return sum_ms;
454 }
455 
456 double G1GCPhaseTimes::print_evacuate_initial_collection_set() const {
457   info_time("Merge Heap Roots", _cur_merge_heap_roots_time_ms);
458 
459   debug_time("Prepare Merge Heap Roots", _cur_prepare_merge_heap_roots_time_ms);
460   debug_phase_merge_remset();
461 
462   debug_time("Distribute Log Buffers", _cur_distribute_log_buffers_time_ms);
463   debug_phase(_gc_par_phases[MergeLB]);
464 
465   info_time("Evacuate Collection Set", _cur_collection_initial_evac_time_ms);
466 
467   trace_phase(_gc_par_phases[GCWorkerStart], false);
468   debug_phase(_gc_par_phases[ExtRootScan]);
469   for (int i = ExtRootScanSubPhasesFirst; i <= ExtRootScanSubPhasesLast; i++) {
470     trace_phase(_gc_par_phases[i]);
471   }
472   debug_phase(_gc_par_phases[ScanHR]);
473   debug_phase(_gc_par_phases[CodeRoots]);
474   debug_phase(_gc_par_phases[ObjCopy]);
475   debug_phase(_gc_par_phases[Termination]);
476   debug_phase(_gc_par_phases[Other]);
477   debug_phase(_gc_par_phases[GCWorkerTotal]);
478   trace_phase(_gc_par_phases[GCWorkerEnd], false);
479 
480   return _cur_collection_initial_evac_time_ms + _cur_merge_heap_roots_time_ms;
481 }
482 
483 double G1GCPhaseTimes::print_post_evacuate_collection_set(bool evacuation_failed) const {
484   const double sum_ms = _cur_collection_nmethod_list_cleanup_time_ms +
485                         _cur_ref_proc_time_ms +
486                         (_weak_phase_times.total_time_sec() * MILLIUNITS) +
487                         _cur_post_evacuate_cleanup_1_time_ms +
488                         _cur_post_evacuate_cleanup_2_time_ms +
489                         _recorded_total_rebuild_freelist_time_ms +
490                         _recorded_prepare_for_mutator_time_ms +
491                         _cur_expand_heap_time_ms;
492 
493   info_time("Post Evacuate Collection Set", sum_ms);
494 
495   debug_time("NMethod List Cleanup", _cur_collection_nmethod_list_cleanup_time_ms);
496 
497   debug_time_for_reference("Reference Processing", _cur_ref_proc_time_ms);
498   _ref_phase_times.print_all_references(2, false);
499   _weak_phase_times.log_total(2);
500   _weak_phase_times.log_subtotals(3);
501 
502   debug_time("Post Evacuate Cleanup 1", _cur_post_evacuate_cleanup_1_time_ms);
503   debug_phase(_gc_par_phases[MergePSS], 1);
504   debug_phase(_gc_par_phases[ClearCardTable], 1);
505   debug_phase(_gc_par_phases[RecalculateUsed], 1);
506   if (evacuation_failed) {
507     debug_phase(_gc_par_phases[RestoreEvacuationFailedRegions], 1);
508     debug_phase(_gc_par_phases[RemoveSelfForwards], 2);
509   }
510 
511   debug_time("Post Evacuate Cleanup 2", _cur_post_evacuate_cleanup_2_time_ms);
512   if (evacuation_failed) {
513     debug_phase(_gc_par_phases[RecalculateUsed], 1);
514     debug_phase(_gc_par_phases[ProcessEvacuationFailedRegions], 1);
515   }
516 #if COMPILER2_OR_JVMCI
517   debug_phase(_gc_par_phases[UpdateDerivedPointers], 1);
518 #endif
519   debug_phase(_gc_par_phases[EagerlyReclaimHumongousObjects], 1);
520 
521   if (G1CollectedHeap::heap()->should_sample_collection_set_candidates()) {
522     debug_phase(_gc_par_phases[SampleCollectionSetCandidates], 1);
523   }
524   debug_phase(_gc_par_phases[RedirtyCards], 1);
525   if (UseTLAB && ResizeTLAB) {
526     debug_phase(_gc_par_phases[ResizeThreadLABs], 1);
527   }
528   debug_phase(_gc_par_phases[FreeCollectionSet], 1);
529   trace_phase(_gc_par_phases[YoungFreeCSet], true, 1);
530   trace_phase(_gc_par_phases[NonYoungFreeCSet], true, 1);
531 
532   trace_time("Serial Free Collection Set", _recorded_serial_free_cset_time_ms);
533 
534   debug_time("Rebuild Free List", _recorded_total_rebuild_freelist_time_ms);
535   trace_time("Serial Rebuild Free List", _recorded_serial_rebuild_freelist_time_ms);
536   trace_phase(_gc_par_phases[RebuildFreeList]);
537 
538   debug_time("Prepare For Mutator", _recorded_prepare_for_mutator_time_ms);
539   debug_time("Expand Heap After Collection", _cur_expand_heap_time_ms);
540 
541   return sum_ms;
542 }
543 
544 void G1GCPhaseTimes::print_other(double accounted_ms) const {
545   info_time("Other", _gc_pause_time_ms - accounted_ms);
546 }
547 
548 void G1GCPhaseTimes::print(bool evacuation_failed) {
549   if (_root_region_scan_wait_time_ms > 0.0) {
550     debug_time("Root Region Scan Waiting", _root_region_scan_wait_time_ms);
551   }
552 
553   // Check if some time has been recorded for verification and only then print
554   // the message. We do not use Verify*GC here to print because VerifyGCType
555   // further limits actual verification.
556   if (_cur_verify_before_time_ms > 0.0) {
557     debug_time("Verify Before", _cur_verify_before_time_ms);
558   }
559 
560   double accounted_ms = 0.0;
561 
562   accounted_ms += _root_region_scan_wait_time_ms;
563   accounted_ms += _cur_verify_before_time_ms;
564 
565   accounted_ms += print_pre_evacuate_collection_set();
566   accounted_ms += print_evacuate_initial_collection_set();
567   accounted_ms += print_evacuate_optional_collection_set();
568   accounted_ms += print_post_evacuate_collection_set(evacuation_failed);
569 
570   accounted_ms += _cur_verify_after_time_ms;
571 
572   print_other(accounted_ms);
573 
574   // See above comment on the _cur_verify_before_time_ms check.
575   if (_cur_verify_after_time_ms > 0.0) {
576     debug_time("Verify After", _cur_verify_after_time_ms);
577   }
578 }
579 
580 const char* G1GCPhaseTimes::phase_name(GCParPhases phase) {
581   G1GCPhaseTimes* phase_times = G1CollectedHeap::heap()->phase_times();
582   return phase_times->_gc_par_phases[phase]->short_name();
583 }
584 
585 G1EvacPhaseWithTrimTimeTracker::G1EvacPhaseWithTrimTimeTracker(G1ParScanThreadState* pss, Tickspan& total_time, Tickspan& trim_time) :
586   _pss(pss),
587   _start(Ticks::now()),
588   _total_time(total_time),
589   _trim_time(trim_time),
590   _stopped(false) {
591 
592   assert(_pss->trim_ticks().value() == 0, "Possibly remaining trim ticks left over from previous use");
593 }
594 
595 G1EvacPhaseWithTrimTimeTracker::~G1EvacPhaseWithTrimTimeTracker() {
596   if (!_stopped) {
597     stop();
598   }
599 }
600 
601 void G1EvacPhaseWithTrimTimeTracker::stop() {
602   assert(!_stopped, "Should only be called once");
603   _total_time += (Ticks::now() - _start) - _pss->trim_ticks();
604   _trim_time += _pss->trim_ticks();
605   _pss->reset_trim_ticks();
606   _stopped = true;
607 }
608 
609 G1GCParPhaseTimesTracker::G1GCParPhaseTimesTracker(G1GCPhaseTimes* phase_times, G1GCPhaseTimes::GCParPhases phase, uint worker_id, bool allow_multiple_record) :
610   _start_time(), _phase(phase), _phase_times(phase_times), _worker_id(worker_id), _event(), _allow_multiple_record(allow_multiple_record) {
611   if (_phase_times != nullptr) {
612     _start_time = Ticks::now();
613   }
614 }
615 
616 G1GCParPhaseTimesTracker::~G1GCParPhaseTimesTracker() {
617   if (_phase_times != nullptr) {
618     if (_allow_multiple_record) {
619       _phase_times->record_or_add_time_secs(_phase, _worker_id, (Ticks::now() - _start_time).seconds());
620     } else {
621       _phase_times->record_time_secs(_phase, _worker_id, (Ticks::now() - _start_time).seconds());
622     }
623     _event.commit(GCId::current(), _worker_id, G1GCPhaseTimes::phase_name(_phase));
624   }
625 }
626 
627 G1EvacPhaseTimesTracker::G1EvacPhaseTimesTracker(G1GCPhaseTimes* phase_times,
628                                                  G1ParScanThreadState* pss,
629                                                  G1GCPhaseTimes::GCParPhases phase,
630                                                  uint worker_id) :
631   G1GCParPhaseTimesTracker(phase_times, phase, worker_id),
632   _total_time(),
633   _trim_time(),
634   _trim_tracker(pss, _total_time, _trim_time) {
635 }
636 
637 G1EvacPhaseTimesTracker::~G1EvacPhaseTimesTracker() {
638   if (_phase_times != nullptr) {
639     // Explicitly stop the trim tracker since it's not yet destructed.
640     _trim_tracker.stop();
641     // Exclude trim time by increasing the start time.
642     _start_time += _trim_time;
643     _phase_times->record_or_add_time_secs(G1GCPhaseTimes::ObjCopy, _worker_id, _trim_time.seconds());
644   }
645 }