1 /*
   2  * Copyright (c) 2001, 2015, 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 #ifndef __clang_major__
  26 // FIXME, formats have issues.  Disable this macro definition, compile, and study warnings for more information.
  27 #define ATTRIBUTE_PRINTF(x,y)
  28 #endif
  29 
  30 #include "precompiled.hpp"
  31 #include "gc_implementation/g1/concurrentG1Refine.hpp"
  32 #include "gc_implementation/g1/concurrentMark.hpp"
  33 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
  34 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  35 #include "gc_implementation/g1/g1CollectorPolicy.hpp"
  36 #include "gc_implementation/g1/g1ErgoVerbose.hpp"
  37 #include "gc_implementation/g1/g1GCPhaseTimes.hpp"
  38 #include "gc_implementation/g1/g1Log.hpp"
  39 #include "gc_implementation/g1/heapRegionRemSet.hpp"
  40 #include "gc_implementation/shared/gcPolicyCounters.hpp"
  41 #include "runtime/arguments.hpp"
  42 #include "runtime/java.hpp"
  43 #include "runtime/mutexLocker.hpp"
  44 #include "utilities/debug.hpp"
  45 
  46 // Different defaults for different number of GC threads
  47 // They were chosen by running GCOld and SPECjbb on debris with different
  48 //   numbers of GC threads and choosing them based on the results
  49 
  50 // all the same
  51 static double rs_length_diff_defaults[] = {
  52   0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
  53 };
  54 
  55 static double cost_per_card_ms_defaults[] = {
  56   0.01, 0.005, 0.005, 0.003, 0.003, 0.002, 0.002, 0.0015
  57 };
  58 
  59 // all the same
  60 static double young_cards_per_entry_ratio_defaults[] = {
  61   1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
  62 };
  63 
  64 static double cost_per_entry_ms_defaults[] = {
  65   0.015, 0.01, 0.01, 0.008, 0.008, 0.0055, 0.0055, 0.005
  66 };
  67 
  68 static double cost_per_byte_ms_defaults[] = {
  69   0.00006, 0.00003, 0.00003, 0.000015, 0.000015, 0.00001, 0.00001, 0.000009
  70 };
  71 
  72 // these should be pretty consistent
  73 static double constant_other_time_ms_defaults[] = {
  74   5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0
  75 };
  76 
  77 
  78 static double young_other_cost_per_region_ms_defaults[] = {
  79   0.3, 0.2, 0.2, 0.15, 0.15, 0.12, 0.12, 0.1
  80 };
  81 
  82 static double non_young_other_cost_per_region_ms_defaults[] = {
  83   1.0, 0.7, 0.7, 0.5, 0.5, 0.42, 0.42, 0.30
  84 };
  85 
  86 G1CollectorPolicy::G1CollectorPolicy() :
  87   _parallel_gc_threads(ParallelGCThreads),
  88 
  89   _recent_gc_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
  90   _stop_world_start(0.0),
  91 
  92   _concurrent_mark_remark_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
  93   _concurrent_mark_cleanup_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
  94 
  95   _alloc_rate_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
  96   _prev_collection_pause_end_ms(0.0),
  97   _rs_length_diff_seq(new TruncatedSeq(TruncatedSeqLength)),
  98   _cost_per_card_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
  99   _young_cards_per_entry_ratio_seq(new TruncatedSeq(TruncatedSeqLength)),
 100   _mixed_cards_per_entry_ratio_seq(new TruncatedSeq(TruncatedSeqLength)),
 101   _cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 102   _mixed_cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 103   _cost_per_byte_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 104   _cost_per_byte_ms_during_cm_seq(new TruncatedSeq(TruncatedSeqLength)),
 105   _constant_other_time_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 106   _young_other_cost_per_region_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 107   _non_young_other_cost_per_region_ms_seq(
 108                                          new TruncatedSeq(TruncatedSeqLength)),
 109 
 110   _pending_cards_seq(new TruncatedSeq(TruncatedSeqLength)),
 111   _rs_lengths_seq(new TruncatedSeq(TruncatedSeqLength)),
 112 
 113   _pause_time_target_ms((double) MaxGCPauseMillis),
 114 
 115   _gcs_are_young(true),
 116 
 117   _during_marking(false),
 118   _in_marking_window(false),
 119   _in_marking_window_im(false),
 120 
 121   _recent_prev_end_times_for_all_gcs_sec(
 122                                 new TruncatedSeq(NumPrevPausesForHeuristics)),
 123 
 124   _recent_avg_pause_time_ratio(0.0),
 125 
 126   _initiate_conc_mark_if_possible(false),
 127   _during_initial_mark_pause(false),
 128   _last_young_gc(false),
 129   _last_gc_was_young(false),
 130 
 131   _eden_used_bytes_before_gc(0),
 132   _survivor_used_bytes_before_gc(0),
 133   _heap_used_bytes_before_gc(0),
 134   _metaspace_used_bytes_before_gc(0),
 135   _eden_capacity_bytes_before_gc(0),
 136   _heap_capacity_bytes_before_gc(0),
 137 
 138   _eden_cset_region_length(0),
 139   _survivor_cset_region_length(0),
 140   _old_cset_region_length(0),
 141 
 142   _sigma(G1ConfidencePercent / 100.0),
 143 
 144   _collection_set(NULL),
 145   _collection_set_bytes_used_before(0),
 146 
 147   // Incremental CSet attributes
 148   _inc_cset_build_state(Inactive),
 149   _inc_cset_head(NULL),
 150   _inc_cset_tail(NULL),
 151   _inc_cset_bytes_used_before(0),
 152   _inc_cset_max_finger(NULL),
 153   _inc_cset_recorded_rs_lengths(0),
 154   _inc_cset_recorded_rs_lengths_diffs(0),
 155   _inc_cset_predicted_elapsed_time_ms(0.0),
 156   _inc_cset_predicted_elapsed_time_ms_diffs(0.0),
 157 
 158   // add here any more surv rate groups
 159   _recorded_survivor_regions(0),
 160   _recorded_survivor_head(NULL),
 161   _recorded_survivor_tail(NULL),
 162   _survivors_age_table(true),
 163 
 164   _gc_overhead_perc(0.0) {
 165 
 166   // SurvRateGroups below must be initialized after '_sigma' because they
 167   // indirectly access '_sigma' through this object passed to their constructor.
 168   _short_lived_surv_rate_group =
 169     new SurvRateGroup(this, "Short Lived", G1YoungSurvRateNumRegionsSummary);
 170   _survivor_surv_rate_group =
 171     new SurvRateGroup(this, "Survivor", G1YoungSurvRateNumRegionsSummary);
 172 
 173   // Set up the region size and associated fields. Given that the
 174   // policy is created before the heap, we have to set this up here,
 175   // so it's done as soon as possible.
 176 
 177   // It would have been natural to pass initial_heap_byte_size() and
 178   // max_heap_byte_size() to setup_heap_region_size() but those have
 179   // not been set up at this point since they should be aligned with
 180   // the region size. So, there is a circular dependency here. We base
 181   // the region size on the heap size, but the heap size should be
 182   // aligned with the region size. To get around this we use the
 183   // unaligned values for the heap.
 184   HeapRegion::setup_heap_region_size(InitialHeapSize, MaxHeapSize);
 185   HeapRegionRemSet::setup_remset_size();
 186 
 187   G1ErgoVerbose::initialize();
 188   if (PrintAdaptiveSizePolicy) {
 189     // Currently, we only use a single switch for all the heuristics.
 190     G1ErgoVerbose::set_enabled(true);
 191     // Given that we don't currently have a verboseness level
 192     // parameter, we'll hardcode this to high. This can be easily
 193     // changed in the future.
 194     G1ErgoVerbose::set_level(ErgoHigh);
 195   } else {
 196     G1ErgoVerbose::set_enabled(false);
 197   }
 198 
 199   // Verify PLAB sizes
 200   const size_t region_size = HeapRegion::GrainWords;
 201   if (YoungPLABSize > region_size || OldPLABSize > region_size) {
 202     char buffer[128];
 203     jio_snprintf(buffer, sizeof(buffer), "%sPLABSize should be at most "SIZE_FORMAT,
 204                  OldPLABSize > region_size ? "Old" : "Young", region_size);
 205     vm_exit_during_initialization(buffer);
 206   }
 207 
 208   _recent_prev_end_times_for_all_gcs_sec->add(os::elapsedTime());
 209   _prev_collection_pause_end_ms = os::elapsedTime() * 1000.0;
 210 
 211   _phase_times = new G1GCPhaseTimes(_parallel_gc_threads);
 212 
 213   int index = MIN2(_parallel_gc_threads - 1, 7);
 214 
 215   _rs_length_diff_seq->add(rs_length_diff_defaults[index]);
 216   _cost_per_card_ms_seq->add(cost_per_card_ms_defaults[index]);
 217   _young_cards_per_entry_ratio_seq->add(
 218                                   young_cards_per_entry_ratio_defaults[index]);
 219   _cost_per_entry_ms_seq->add(cost_per_entry_ms_defaults[index]);
 220   _cost_per_byte_ms_seq->add(cost_per_byte_ms_defaults[index]);
 221   _constant_other_time_ms_seq->add(constant_other_time_ms_defaults[index]);
 222   _young_other_cost_per_region_ms_seq->add(
 223                                young_other_cost_per_region_ms_defaults[index]);
 224   _non_young_other_cost_per_region_ms_seq->add(
 225                            non_young_other_cost_per_region_ms_defaults[index]);
 226 
 227   // Below, we might need to calculate the pause time target based on
 228   // the pause interval. When we do so we are going to give G1 maximum
 229   // flexibility and allow it to do pauses when it needs to. So, we'll
 230   // arrange that the pause interval to be pause time target + 1 to
 231   // ensure that a) the pause time target is maximized with respect to
 232   // the pause interval and b) we maintain the invariant that pause
 233   // time target < pause interval. If the user does not want this
 234   // maximum flexibility, they will have to set the pause interval
 235   // explicitly.
 236 
 237   // First make sure that, if either parameter is set, its value is
 238   // reasonable.
 239   if (!FLAG_IS_DEFAULT(MaxGCPauseMillis)) {
 240     if (MaxGCPauseMillis < 1) {
 241       vm_exit_during_initialization("MaxGCPauseMillis should be "
 242                                     "greater than 0");
 243     }
 244   }
 245   if (!FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
 246     if (GCPauseIntervalMillis < 1) {
 247       vm_exit_during_initialization("GCPauseIntervalMillis should be "
 248                                     "greater than 0");
 249     }
 250   }
 251 
 252   // Then, if the pause time target parameter was not set, set it to
 253   // the default value.
 254   if (FLAG_IS_DEFAULT(MaxGCPauseMillis)) {
 255     if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
 256       // The default pause time target in G1 is 200ms
 257       FLAG_SET_DEFAULT(MaxGCPauseMillis, 200);
 258     } else {
 259       // We do not allow the pause interval to be set without the
 260       // pause time target
 261       vm_exit_during_initialization("GCPauseIntervalMillis cannot be set "
 262                                     "without setting MaxGCPauseMillis");
 263     }
 264   }
 265 
 266   // Then, if the interval parameter was not set, set it according to
 267   // the pause time target (this will also deal with the case when the
 268   // pause time target is the default value).
 269   if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
 270     FLAG_SET_DEFAULT(GCPauseIntervalMillis, MaxGCPauseMillis + 1);
 271   }
 272 
 273   // Finally, make sure that the two parameters are consistent.
 274   if (MaxGCPauseMillis >= GCPauseIntervalMillis) {
 275     char buffer[256];
 276     jio_snprintf(buffer, 256,
 277                  "MaxGCPauseMillis (%u) should be less than "
 278                  "GCPauseIntervalMillis (%u)",
 279                  MaxGCPauseMillis, GCPauseIntervalMillis);
 280     vm_exit_during_initialization(buffer);
 281   }
 282 
 283   double max_gc_time = (double) MaxGCPauseMillis / 1000.0;
 284   double time_slice  = (double) GCPauseIntervalMillis / 1000.0;
 285   _mmu_tracker = new G1MMUTrackerQueue(time_slice, max_gc_time);
 286 
 287   // start conservatively (around 50ms is about right)
 288   _concurrent_mark_remark_times_ms->add(0.05);
 289   _concurrent_mark_cleanup_times_ms->add(0.20);
 290   _tenuring_threshold = MaxTenuringThreshold;
 291   // _max_survivor_regions will be calculated by
 292   // update_young_list_target_length() during initialization.
 293   _max_survivor_regions = 0;
 294 
 295   assert(GCTimeRatio > 0,
 296          "we should have set it to a default value set_g1_gc_flags() "
 297          "if a user set it to 0");
 298   _gc_overhead_perc = 100.0 * (1.0 / (1.0 + GCTimeRatio));
 299 
 300   uintx reserve_perc = G1ReservePercent;
 301   // Put an artificial ceiling on this so that it's not set to a silly value.
 302   if (reserve_perc > 50) {
 303     reserve_perc = 50;
 304     warning("G1ReservePercent is set to a value that is too large, "
 305             "it's been updated to %u", reserve_perc);
 306   }
 307   _reserve_factor = (double) reserve_perc / 100.0;
 308   // This will be set when the heap is expanded
 309   // for the first time during initialization.
 310   _reserve_regions = 0;
 311 
 312   _collectionSetChooser = new CollectionSetChooser();
 313 }
 314 
 315 void G1CollectorPolicy::initialize_alignments() {
 316   _space_alignment = HeapRegion::GrainBytes;
 317   size_t card_table_alignment = GenRemSet::max_alignment_constraint();
 318   size_t page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();
 319   _heap_alignment = MAX3(card_table_alignment, _space_alignment, page_size);
 320 }
 321 
 322 void G1CollectorPolicy::initialize_flags() {
 323   if (G1HeapRegionSize != HeapRegion::GrainBytes) {
 324     FLAG_SET_ERGO(uintx, G1HeapRegionSize, HeapRegion::GrainBytes);
 325   }
 326 
 327   if (SurvivorRatio < 1) {
 328     vm_exit_during_initialization("Invalid survivor ratio specified");
 329   }
 330   CollectorPolicy::initialize_flags();
 331   _young_gen_sizer = new G1YoungGenSizer(); // Must be after call to initialize_flags
 332 }
 333 
 334 void G1CollectorPolicy::post_heap_initialize() {
 335   uintx max_regions = G1CollectedHeap::heap()->max_regions();
 336   size_t max_young_size = (size_t)_young_gen_sizer->max_young_length(max_regions) * HeapRegion::GrainBytes;
 337   if (max_young_size != MaxNewSize) {
 338     FLAG_SET_ERGO(uintx, MaxNewSize, max_young_size);
 339   }
 340 }
 341 
 342 G1YoungGenSizer::G1YoungGenSizer() : _sizer_kind(SizerDefaults), _adaptive_size(true),
 343         _min_desired_young_length(0), _max_desired_young_length(0) {
 344   if (FLAG_IS_CMDLINE(NewRatio)) {
 345     if (FLAG_IS_CMDLINE(NewSize) || FLAG_IS_CMDLINE(MaxNewSize)) {
 346       warning("-XX:NewSize and -XX:MaxNewSize override -XX:NewRatio");
 347     } else {
 348       _sizer_kind = SizerNewRatio;
 349       _adaptive_size = false;
 350       return;
 351     }
 352   }
 353 
 354   if (NewSize > MaxNewSize) {
 355     if (FLAG_IS_CMDLINE(MaxNewSize)) {
 356       warning("NewSize (" SIZE_FORMAT "k) is greater than the MaxNewSize (" SIZE_FORMAT "k). "
 357               "A new max generation size of " SIZE_FORMAT "k will be used.",
 358               NewSize/K, MaxNewSize/K, NewSize/K);
 359     }
 360     MaxNewSize = NewSize;
 361   }
 362 
 363   if (FLAG_IS_CMDLINE(NewSize)) {
 364     _min_desired_young_length = MAX2((uint) (NewSize / HeapRegion::GrainBytes),
 365                                      1U);
 366     if (FLAG_IS_CMDLINE(MaxNewSize)) {
 367       _max_desired_young_length =
 368                              MAX2((uint) (MaxNewSize / HeapRegion::GrainBytes),
 369                                   1U);
 370       _sizer_kind = SizerMaxAndNewSize;
 371       _adaptive_size = _min_desired_young_length == _max_desired_young_length;
 372     } else {
 373       _sizer_kind = SizerNewSizeOnly;
 374     }
 375   } else if (FLAG_IS_CMDLINE(MaxNewSize)) {
 376     _max_desired_young_length =
 377                              MAX2((uint) (MaxNewSize / HeapRegion::GrainBytes),
 378                                   1U);
 379     _sizer_kind = SizerMaxNewSizeOnly;
 380   }
 381 }
 382 
 383 uint G1YoungGenSizer::calculate_default_min_length(uint new_number_of_heap_regions) {
 384   uint default_value = (new_number_of_heap_regions * G1NewSizePercent) / 100;
 385   return MAX2(1U, default_value);
 386 }
 387 
 388 uint G1YoungGenSizer::calculate_default_max_length(uint new_number_of_heap_regions) {
 389   uint default_value = (new_number_of_heap_regions * G1MaxNewSizePercent) / 100;
 390   return MAX2(1U, default_value);
 391 }
 392 
 393 void G1YoungGenSizer::recalculate_min_max_young_length(uint number_of_heap_regions, uint* min_young_length, uint* max_young_length) {
 394   assert(number_of_heap_regions > 0, "Heap must be initialized");
 395 
 396   switch (_sizer_kind) {
 397     case SizerDefaults:
 398       *min_young_length = calculate_default_min_length(number_of_heap_regions);
 399       *max_young_length = calculate_default_max_length(number_of_heap_regions);
 400       break;
 401     case SizerNewSizeOnly:
 402       *max_young_length = calculate_default_max_length(number_of_heap_regions);
 403       *max_young_length = MAX2(*min_young_length, *max_young_length);
 404       break;
 405     case SizerMaxNewSizeOnly:
 406       *min_young_length = calculate_default_min_length(number_of_heap_regions);
 407       *min_young_length = MIN2(*min_young_length, *max_young_length);
 408       break;
 409     case SizerMaxAndNewSize:
 410       // Do nothing. Values set on the command line, don't update them at runtime.
 411       break;
 412     case SizerNewRatio:
 413       *min_young_length = number_of_heap_regions / (NewRatio + 1);
 414       *max_young_length = *min_young_length;
 415       break;
 416     default:
 417       ShouldNotReachHere();
 418   }
 419 
 420   assert(*min_young_length <= *max_young_length, "Invalid min/max young gen size values");
 421 }
 422 
 423 uint G1YoungGenSizer::max_young_length(uint number_of_heap_regions) {
 424   // We need to pass the desired values because recalculation may not update these
 425   // values in some cases.
 426   uint temp = _min_desired_young_length;
 427   uint result = _max_desired_young_length;
 428   recalculate_min_max_young_length(number_of_heap_regions, &temp, &result);
 429   return result;
 430 }
 431 
 432 void G1YoungGenSizer::heap_size_changed(uint new_number_of_heap_regions) {
 433   recalculate_min_max_young_length(new_number_of_heap_regions, &_min_desired_young_length,
 434           &_max_desired_young_length);
 435 }
 436 
 437 void G1CollectorPolicy::init() {
 438   // Set aside an initial future to_space.
 439   _g1 = G1CollectedHeap::heap();
 440 
 441   assert(Heap_lock->owned_by_self(), "Locking discipline.");
 442 
 443   initialize_gc_policy_counters();
 444 
 445   if (adaptive_young_list_length()) {
 446     _young_list_fixed_length = 0;
 447   } else {
 448     _young_list_fixed_length = _young_gen_sizer->min_desired_young_length();
 449   }
 450   _free_regions_at_end_of_collection = _g1->num_free_regions();
 451   update_young_list_target_length();
 452 
 453   // We may immediately start allocating regions and placing them on the
 454   // collection set list. Initialize the per-collection set info
 455   start_incremental_cset_building();
 456 }
 457 
 458 // Create the jstat counters for the policy.
 459 void G1CollectorPolicy::initialize_gc_policy_counters() {
 460   _gc_policy_counters = new GCPolicyCounters("GarbageFirst", 1, 3);
 461 }
 462 
 463 bool G1CollectorPolicy::predict_will_fit(uint young_length,
 464                                          double base_time_ms,
 465                                          uint base_free_regions,
 466                                          double target_pause_time_ms) {
 467   if (young_length >= base_free_regions) {
 468     // end condition 1: not enough space for the young regions
 469     return false;
 470   }
 471 
 472   double accum_surv_rate = accum_yg_surv_rate_pred((int) young_length - 1);
 473   size_t bytes_to_copy =
 474                (size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);
 475   double copy_time_ms = predict_object_copy_time_ms(bytes_to_copy);
 476   double young_other_time_ms = predict_young_other_time_ms(young_length);
 477   double pause_time_ms = base_time_ms + copy_time_ms + young_other_time_ms;
 478   if (pause_time_ms > target_pause_time_ms) {
 479     // end condition 2: prediction is over the target pause time
 480     return false;
 481   }
 482 
 483   size_t free_bytes =
 484                    (base_free_regions - young_length) * HeapRegion::GrainBytes;
 485   if ((2.0 * sigma()) * (double) bytes_to_copy > (double) free_bytes) {
 486     // end condition 3: out-of-space (conservatively!)
 487     return false;
 488   }
 489 
 490   // success!
 491   return true;
 492 }
 493 
 494 void G1CollectorPolicy::record_new_heap_size(uint new_number_of_regions) {
 495   // re-calculate the necessary reserve
 496   double reserve_regions_d = (double) new_number_of_regions * _reserve_factor;
 497   // We use ceiling so that if reserve_regions_d is > 0.0 (but
 498   // smaller than 1.0) we'll get 1.
 499   _reserve_regions = (uint) ceil(reserve_regions_d);
 500 
 501   _young_gen_sizer->heap_size_changed(new_number_of_regions);
 502 }
 503 
 504 uint G1CollectorPolicy::calculate_young_list_desired_min_length(
 505                                                        uint base_min_length) {
 506   uint desired_min_length = 0;
 507   if (adaptive_young_list_length()) {
 508     if (_alloc_rate_ms_seq->num() > 3) {
 509       double now_sec = os::elapsedTime();
 510       double when_ms = _mmu_tracker->when_max_gc_sec(now_sec) * 1000.0;
 511       double alloc_rate_ms = predict_alloc_rate_ms();
 512       desired_min_length = (uint) ceil(alloc_rate_ms * when_ms);
 513     } else {
 514       // otherwise we don't have enough info to make the prediction
 515     }
 516   }
 517   desired_min_length += base_min_length;
 518   // make sure we don't go below any user-defined minimum bound
 519   return MAX2(_young_gen_sizer->min_desired_young_length(), desired_min_length);
 520 }
 521 
 522 uint G1CollectorPolicy::calculate_young_list_desired_max_length() {
 523   // Here, we might want to also take into account any additional
 524   // constraints (i.e., user-defined minimum bound). Currently, we
 525   // effectively don't set this bound.
 526   return _young_gen_sizer->max_desired_young_length();
 527 }
 528 
 529 void G1CollectorPolicy::update_young_list_target_length(size_t rs_lengths) {
 530   if (rs_lengths == (size_t) -1) {
 531     // if it's set to the default value (-1), we should predict it;
 532     // otherwise, use the given value.
 533     rs_lengths = (size_t) get_new_prediction(_rs_lengths_seq);
 534   }
 535 
 536   // Calculate the absolute and desired min bounds.
 537 
 538   // This is how many young regions we already have (currently: the survivors).
 539   uint base_min_length = recorded_survivor_regions();
 540   uint desired_min_length = calculate_young_list_desired_min_length(base_min_length);
 541   // This is the absolute minimum young length. Ensure that we
 542   // will at least have one eden region available for allocation.
 543   uint absolute_min_length = base_min_length + MAX2(_g1->young_list()->eden_length(), (uint)1);
 544   // If we shrank the young list target it should not shrink below the current size.
 545   desired_min_length = MAX2(desired_min_length, absolute_min_length);
 546   // Calculate the absolute and desired max bounds.
 547 
 548   // We will try our best not to "eat" into the reserve.
 549   uint absolute_max_length = 0;
 550   if (_free_regions_at_end_of_collection > _reserve_regions) {
 551     absolute_max_length = _free_regions_at_end_of_collection - _reserve_regions;
 552   }
 553   uint desired_max_length = calculate_young_list_desired_max_length();
 554   if (desired_max_length > absolute_max_length) {
 555     desired_max_length = absolute_max_length;
 556   }
 557 
 558   uint young_list_target_length = 0;
 559   if (adaptive_young_list_length()) {
 560     if (gcs_are_young()) {
 561       young_list_target_length =
 562                         calculate_young_list_target_length(rs_lengths,
 563                                                            base_min_length,
 564                                                            desired_min_length,
 565                                                            desired_max_length);
 566       _rs_lengths_prediction = rs_lengths;
 567     } else {
 568       // Don't calculate anything and let the code below bound it to
 569       // the desired_min_length, i.e., do the next GC as soon as
 570       // possible to maximize how many old regions we can add to it.
 571     }
 572   } else {
 573     // The user asked for a fixed young gen so we'll fix the young gen
 574     // whether the next GC is young or mixed.
 575     young_list_target_length = _young_list_fixed_length;
 576   }
 577 
 578   // Make sure we don't go over the desired max length, nor under the
 579   // desired min length. In case they clash, desired_min_length wins
 580   // which is why that test is second.
 581   if (young_list_target_length > desired_max_length) {
 582     young_list_target_length = desired_max_length;
 583   }
 584   if (young_list_target_length < desired_min_length) {
 585     young_list_target_length = desired_min_length;
 586   }
 587 
 588   assert(young_list_target_length > recorded_survivor_regions(),
 589          "we should be able to allocate at least one eden region");
 590   assert(young_list_target_length >= absolute_min_length, "post-condition");
 591   _young_list_target_length = young_list_target_length;
 592 
 593   update_max_gc_locker_expansion();
 594 }
 595 
 596 uint
 597 G1CollectorPolicy::calculate_young_list_target_length(size_t rs_lengths,
 598                                                      uint base_min_length,
 599                                                      uint desired_min_length,
 600                                                      uint desired_max_length) {
 601   assert(adaptive_young_list_length(), "pre-condition");
 602   assert(gcs_are_young(), "only call this for young GCs");
 603 
 604   // In case some edge-condition makes the desired max length too small...
 605   if (desired_max_length <= desired_min_length) {
 606     return desired_min_length;
 607   }
 608 
 609   // We'll adjust min_young_length and max_young_length not to include
 610   // the already allocated young regions (i.e., so they reflect the
 611   // min and max eden regions we'll allocate). The base_min_length
 612   // will be reflected in the predictions by the
 613   // survivor_regions_evac_time prediction.
 614   assert(desired_min_length > base_min_length, "invariant");
 615   uint min_young_length = desired_min_length - base_min_length;
 616   assert(desired_max_length > base_min_length, "invariant");
 617   uint max_young_length = desired_max_length - base_min_length;
 618 
 619   double target_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
 620   double survivor_regions_evac_time = predict_survivor_regions_evac_time();
 621   size_t pending_cards = (size_t) get_new_prediction(_pending_cards_seq);
 622   size_t adj_rs_lengths = rs_lengths + predict_rs_length_diff();
 623   size_t scanned_cards = predict_young_card_num(adj_rs_lengths);
 624   double base_time_ms =
 625     predict_base_elapsed_time_ms(pending_cards, scanned_cards) +
 626     survivor_regions_evac_time;
 627   uint available_free_regions = _free_regions_at_end_of_collection;
 628   uint base_free_regions = 0;
 629   if (available_free_regions > _reserve_regions) {
 630     base_free_regions = available_free_regions - _reserve_regions;
 631   }
 632 
 633   // Here, we will make sure that the shortest young length that
 634   // makes sense fits within the target pause time.
 635 
 636   if (predict_will_fit(min_young_length, base_time_ms,
 637                        base_free_regions, target_pause_time_ms)) {
 638     // The shortest young length will fit into the target pause time;
 639     // we'll now check whether the absolute maximum number of young
 640     // regions will fit in the target pause time. If not, we'll do
 641     // a binary search between min_young_length and max_young_length.
 642     if (predict_will_fit(max_young_length, base_time_ms,
 643                          base_free_regions, target_pause_time_ms)) {
 644       // The maximum young length will fit into the target pause time.
 645       // We are done so set min young length to the maximum length (as
 646       // the result is assumed to be returned in min_young_length).
 647       min_young_length = max_young_length;
 648     } else {
 649       // The maximum possible number of young regions will not fit within
 650       // the target pause time so we'll search for the optimal
 651       // length. The loop invariants are:
 652       //
 653       // min_young_length < max_young_length
 654       // min_young_length is known to fit into the target pause time
 655       // max_young_length is known not to fit into the target pause time
 656       //
 657       // Going into the loop we know the above hold as we've just
 658       // checked them. Every time around the loop we check whether
 659       // the middle value between min_young_length and
 660       // max_young_length fits into the target pause time. If it
 661       // does, it becomes the new min. If it doesn't, it becomes
 662       // the new max. This way we maintain the loop invariants.
 663 
 664       assert(min_young_length < max_young_length, "invariant");
 665       uint diff = (max_young_length - min_young_length) / 2;
 666       while (diff > 0) {
 667         uint young_length = min_young_length + diff;
 668         if (predict_will_fit(young_length, base_time_ms,
 669                              base_free_regions, target_pause_time_ms)) {
 670           min_young_length = young_length;
 671         } else {
 672           max_young_length = young_length;
 673         }
 674         assert(min_young_length <  max_young_length, "invariant");
 675         diff = (max_young_length - min_young_length) / 2;
 676       }
 677       // The results is min_young_length which, according to the
 678       // loop invariants, should fit within the target pause time.
 679 
 680       // These are the post-conditions of the binary search above:
 681       assert(min_young_length < max_young_length,
 682              "otherwise we should have discovered that max_young_length "
 683              "fits into the pause target and not done the binary search");
 684       assert(predict_will_fit(min_young_length, base_time_ms,
 685                               base_free_regions, target_pause_time_ms),
 686              "min_young_length, the result of the binary search, should "
 687              "fit into the pause target");
 688       assert(!predict_will_fit(min_young_length + 1, base_time_ms,
 689                                base_free_regions, target_pause_time_ms),
 690              "min_young_length, the result of the binary search, should be "
 691              "optimal, so no larger length should fit into the pause target");
 692     }
 693   } else {
 694     // Even the minimum length doesn't fit into the pause time
 695     // target, return it as the result nevertheless.
 696   }
 697   return base_min_length + min_young_length;
 698 }
 699 
 700 double G1CollectorPolicy::predict_survivor_regions_evac_time() {
 701   double survivor_regions_evac_time = 0.0;
 702   for (HeapRegion * r = _recorded_survivor_head;
 703        r != NULL && r != _recorded_survivor_tail->get_next_young_region();
 704        r = r->get_next_young_region()) {
 705     survivor_regions_evac_time += predict_region_elapsed_time_ms(r, gcs_are_young());
 706   }
 707   return survivor_regions_evac_time;
 708 }
 709 
 710 void G1CollectorPolicy::revise_young_list_target_length_if_necessary() {
 711   guarantee( adaptive_young_list_length(), "should not call this otherwise" );
 712 
 713   size_t rs_lengths = _g1->young_list()->sampled_rs_lengths();
 714   if (rs_lengths > _rs_lengths_prediction) {
 715     // add 10% to avoid having to recalculate often
 716     size_t rs_lengths_prediction = rs_lengths * 1100 / 1000;
 717     update_young_list_target_length(rs_lengths_prediction);
 718   }
 719 }
 720 
 721 
 722 
 723 HeapWord* G1CollectorPolicy::mem_allocate_work(size_t size,
 724                                                bool is_tlab,
 725                                                bool* gc_overhead_limit_was_exceeded) {
 726   guarantee(false, "Not using this policy feature yet.");
 727   return NULL;
 728 }
 729 
 730 // This method controls how a collector handles one or more
 731 // of its generations being fully allocated.
 732 HeapWord* G1CollectorPolicy::satisfy_failed_allocation(size_t size,
 733                                                        bool is_tlab) {
 734   guarantee(false, "Not using this policy feature yet.");
 735   return NULL;
 736 }
 737 
 738 
 739 #ifndef PRODUCT
 740 bool G1CollectorPolicy::verify_young_ages() {
 741   HeapRegion* head = _g1->young_list()->first_region();
 742   return
 743     verify_young_ages(head, _short_lived_surv_rate_group);
 744   // also call verify_young_ages on any additional surv rate groups
 745 }
 746 
 747 bool
 748 G1CollectorPolicy::verify_young_ages(HeapRegion* head,
 749                                      SurvRateGroup *surv_rate_group) {
 750   guarantee( surv_rate_group != NULL, "pre-condition" );
 751 
 752   const char* name = surv_rate_group->name();
 753   bool ret = true;
 754   int prev_age = -1;
 755 
 756   for (HeapRegion* curr = head;
 757        curr != NULL;
 758        curr = curr->get_next_young_region()) {
 759     SurvRateGroup* group = curr->surv_rate_group();
 760     if (group == NULL && !curr->is_survivor()) {
 761       gclog_or_tty->print_cr("## %s: encountered NULL surv_rate_group", name);
 762       ret = false;
 763     }
 764 
 765     if (surv_rate_group == group) {
 766       int age = curr->age_in_surv_rate_group();
 767 
 768       if (age < 0) {
 769         gclog_or_tty->print_cr("## %s: encountered negative age", name);
 770         ret = false;
 771       }
 772 
 773       if (age <= prev_age) {
 774         gclog_or_tty->print_cr("## %s: region ages are not strictly increasing "
 775                                "(%d, %d)", name, age, prev_age);
 776         ret = false;
 777       }
 778       prev_age = age;
 779     }
 780   }
 781 
 782   return ret;
 783 }
 784 #endif // PRODUCT
 785 
 786 void G1CollectorPolicy::record_full_collection_start() {
 787   _full_collection_start_sec = os::elapsedTime();
 788   record_heap_size_info_at_start(true /* full */);
 789   // Release the future to-space so that it is available for compaction into.
 790   _g1->set_full_collection();
 791 }
 792 
 793 void G1CollectorPolicy::record_full_collection_end() {
 794   // Consider this like a collection pause for the purposes of allocation
 795   // since last pause.
 796   double end_sec = os::elapsedTime();
 797   double full_gc_time_sec = end_sec - _full_collection_start_sec;
 798   double full_gc_time_ms = full_gc_time_sec * 1000.0;
 799 
 800   _trace_old_gen_time_data.record_full_collection(full_gc_time_ms);
 801 
 802   update_recent_gc_times(end_sec, full_gc_time_ms);
 803 
 804   _g1->clear_full_collection();
 805 
 806   // "Nuke" the heuristics that control the young/mixed GC
 807   // transitions and make sure we start with young GCs after the Full GC.
 808   set_gcs_are_young(true);
 809   _last_young_gc = false;
 810   clear_initiate_conc_mark_if_possible();
 811   clear_during_initial_mark_pause();
 812   _in_marking_window = false;
 813   _in_marking_window_im = false;
 814 
 815   _short_lived_surv_rate_group->start_adding_regions();
 816   // also call this on any additional surv rate groups
 817 
 818   record_survivor_regions(0, NULL, NULL);
 819 
 820   _free_regions_at_end_of_collection = _g1->num_free_regions();
 821   // Reset survivors SurvRateGroup.
 822   _survivor_surv_rate_group->reset();
 823   update_young_list_target_length();
 824   _collectionSetChooser->clear();
 825 }
 826 
 827 void G1CollectorPolicy::record_stop_world_start() {
 828   _stop_world_start = os::elapsedTime();
 829 }
 830 
 831 void G1CollectorPolicy::record_collection_pause_start(double start_time_sec) {
 832   // We only need to do this here as the policy will only be applied
 833   // to the GC we're about to start. so, no point is calculating this
 834   // every time we calculate / recalculate the target young length.
 835   update_survivors_policy();
 836 
 837   assert(_g1->used() == _g1->recalculate_used(),
 838          err_msg("sanity, used: "SIZE_FORMAT" recalculate_used: "SIZE_FORMAT,
 839                  _g1->used(), _g1->recalculate_used()));
 840 
 841   double s_w_t_ms = (start_time_sec - _stop_world_start) * 1000.0;
 842   _trace_young_gen_time_data.record_start_collection(s_w_t_ms);
 843   _stop_world_start = 0.0;
 844 
 845   record_heap_size_info_at_start(false /* full */);
 846 
 847   phase_times()->record_cur_collection_start_sec(start_time_sec);
 848   _pending_cards = _g1->pending_card_num();
 849 
 850   _collection_set_bytes_used_before = 0;
 851   _bytes_copied_during_gc = 0;
 852 
 853   _last_gc_was_young = false;
 854 
 855   // do that for any other surv rate groups
 856   _short_lived_surv_rate_group->stop_adding_regions();
 857   _survivors_age_table.clear();
 858 
 859   assert( verify_young_ages(), "region age verification" );
 860 }
 861 
 862 void G1CollectorPolicy::record_concurrent_mark_init_end(double
 863                                                    mark_init_elapsed_time_ms) {
 864   _during_marking = true;
 865   assert(!initiate_conc_mark_if_possible(), "we should have cleared it by now");
 866   clear_during_initial_mark_pause();
 867   _cur_mark_stop_world_time_ms = mark_init_elapsed_time_ms;
 868 }
 869 
 870 void G1CollectorPolicy::record_concurrent_mark_remark_start() {
 871   _mark_remark_start_sec = os::elapsedTime();
 872   _during_marking = false;
 873 }
 874 
 875 void G1CollectorPolicy::record_concurrent_mark_remark_end() {
 876   double end_time_sec = os::elapsedTime();
 877   double elapsed_time_ms = (end_time_sec - _mark_remark_start_sec)*1000.0;
 878   _concurrent_mark_remark_times_ms->add(elapsed_time_ms);
 879   _cur_mark_stop_world_time_ms += elapsed_time_ms;
 880   _prev_collection_pause_end_ms += elapsed_time_ms;
 881 
 882   _mmu_tracker->add_pause(_mark_remark_start_sec, end_time_sec, true);
 883 }
 884 
 885 void G1CollectorPolicy::record_concurrent_mark_cleanup_start() {
 886   _mark_cleanup_start_sec = os::elapsedTime();
 887 }
 888 
 889 void G1CollectorPolicy::record_concurrent_mark_cleanup_completed() {
 890   _last_young_gc = true;
 891   _in_marking_window = false;
 892 }
 893 
 894 void G1CollectorPolicy::record_concurrent_pause() {
 895   if (_stop_world_start > 0.0) {
 896     double yield_ms = (os::elapsedTime() - _stop_world_start) * 1000.0;
 897     _trace_young_gen_time_data.record_yield_time(yield_ms);
 898   }
 899 }
 900 
 901 bool G1CollectorPolicy::need_to_start_conc_mark(const char* source, size_t alloc_word_size) {
 902   if (_g1->concurrent_mark()->cmThread()->during_cycle()) {
 903     return false;
 904   }
 905 
 906   size_t marking_initiating_used_threshold =
 907     (_g1->capacity() / 100) * InitiatingHeapOccupancyPercent;
 908   size_t cur_used_bytes = _g1->non_young_capacity_bytes();
 909   size_t alloc_byte_size = alloc_word_size * HeapWordSize;
 910 
 911   if ((cur_used_bytes + alloc_byte_size) > marking_initiating_used_threshold) {
 912     if (gcs_are_young() && !_last_young_gc) {
 913       ergo_verbose5(ErgoConcCycles,
 914         "request concurrent cycle initiation",
 915         ergo_format_reason("occupancy higher than threshold")
 916         ergo_format_byte("occupancy")
 917         ergo_format_byte("allocation request")
 918         ergo_format_byte_perc("threshold")
 919         ergo_format_str("source"),
 920         cur_used_bytes,
 921         alloc_byte_size,
 922         marking_initiating_used_threshold,
 923         (double) InitiatingHeapOccupancyPercent,
 924         source);
 925       return true;
 926     } else {
 927       ergo_verbose5(ErgoConcCycles,
 928         "do not request concurrent cycle initiation",
 929         ergo_format_reason("still doing mixed collections")
 930         ergo_format_byte("occupancy")
 931         ergo_format_byte("allocation request")
 932         ergo_format_byte_perc("threshold")
 933         ergo_format_str("source"),
 934         cur_used_bytes,
 935         alloc_byte_size,
 936         marking_initiating_used_threshold,
 937         (double) InitiatingHeapOccupancyPercent,
 938         source);
 939     }
 940   }
 941 
 942   return false;
 943 }
 944 
 945 // Anything below that is considered to be zero
 946 #define MIN_TIMER_GRANULARITY 0.0000001
 947 
 948 void G1CollectorPolicy::record_collection_pause_end(double pause_time_ms, EvacuationInfo& evacuation_info) {
 949   double end_time_sec = os::elapsedTime();
 950   assert(_cur_collection_pause_used_regions_at_start >= cset_region_length(),
 951          "otherwise, the subtraction below does not make sense");
 952   size_t rs_size =
 953             _cur_collection_pause_used_regions_at_start - cset_region_length();
 954   size_t cur_used_bytes = _g1->used();
 955   assert(cur_used_bytes == _g1->recalculate_used(), "It should!");
 956   bool last_pause_included_initial_mark = false;
 957   bool update_stats = !_g1->evacuation_failed();
 958 
 959 #ifndef PRODUCT
 960   if (G1YoungSurvRateVerbose) {
 961     gclog_or_tty->cr();
 962     _short_lived_surv_rate_group->print();
 963     // do that for any other surv rate groups too
 964   }
 965 #endif // PRODUCT
 966 
 967   last_pause_included_initial_mark = during_initial_mark_pause();
 968   if (last_pause_included_initial_mark) {
 969     record_concurrent_mark_init_end(0.0);
 970   } else if (need_to_start_conc_mark("end of GC")) {
 971     // Note: this might have already been set, if during the last
 972     // pause we decided to start a cycle but at the beginning of
 973     // this pause we decided to postpone it. That's OK.
 974     set_initiate_conc_mark_if_possible();
 975   }
 976 
 977   _mmu_tracker->add_pause(end_time_sec - pause_time_ms/1000.0,
 978                           end_time_sec, false);
 979 
 980   evacuation_info.set_collectionset_used_before(_collection_set_bytes_used_before);
 981   evacuation_info.set_bytes_copied(_bytes_copied_during_gc);
 982 
 983   if (update_stats) {
 984     _trace_young_gen_time_data.record_end_collection(pause_time_ms, phase_times());
 985     // this is where we update the allocation rate of the application
 986     double app_time_ms =
 987       (phase_times()->cur_collection_start_sec() * 1000.0 - _prev_collection_pause_end_ms);
 988     if (app_time_ms < MIN_TIMER_GRANULARITY) {
 989       // This usually happens due to the timer not having the required
 990       // granularity. Some Linuxes are the usual culprits.
 991       // We'll just set it to something (arbitrarily) small.
 992       app_time_ms = 1.0;
 993     }
 994     // We maintain the invariant that all objects allocated by mutator
 995     // threads will be allocated out of eden regions. So, we can use
 996     // the eden region number allocated since the previous GC to
 997     // calculate the application's allocate rate. The only exception
 998     // to that is humongous objects that are allocated separately. But
 999     // given that humongous object allocations do not really affect
1000     // either the pause's duration nor when the next pause will take
1001     // place we can safely ignore them here.
1002     uint regions_allocated = eden_cset_region_length();
1003     double alloc_rate_ms = (double) regions_allocated / app_time_ms;
1004     _alloc_rate_ms_seq->add(alloc_rate_ms);
1005 
1006     double interval_ms =
1007       (end_time_sec - _recent_prev_end_times_for_all_gcs_sec->oldest()) * 1000.0;
1008     update_recent_gc_times(end_time_sec, pause_time_ms);
1009     _recent_avg_pause_time_ratio = _recent_gc_times_ms->sum()/interval_ms;
1010     if (recent_avg_pause_time_ratio() < 0.0 ||
1011         (recent_avg_pause_time_ratio() - 1.0 > 0.0)) {
1012 #ifndef PRODUCT
1013       // Dump info to allow post-facto debugging
1014       gclog_or_tty->print_cr("recent_avg_pause_time_ratio() out of bounds");
1015       gclog_or_tty->print_cr("-------------------------------------------");
1016       gclog_or_tty->print_cr("Recent GC Times (ms):");
1017       _recent_gc_times_ms->dump();
1018       gclog_or_tty->print_cr("(End Time=%3.3f) Recent GC End Times (s):", end_time_sec);
1019       _recent_prev_end_times_for_all_gcs_sec->dump();
1020       gclog_or_tty->print_cr("GC = %3.3f, Interval = %3.3f, Ratio = %3.3f",
1021                              _recent_gc_times_ms->sum(), interval_ms, recent_avg_pause_time_ratio());
1022       // In debug mode, terminate the JVM if the user wants to debug at this point.
1023       assert(!G1FailOnFPError, "Debugging data for CR 6898948 has been dumped above");
1024 #endif  // !PRODUCT
1025       // Clip ratio between 0.0 and 1.0, and continue. This will be fixed in
1026       // CR 6902692 by redoing the manner in which the ratio is incrementally computed.
1027       if (_recent_avg_pause_time_ratio < 0.0) {
1028         _recent_avg_pause_time_ratio = 0.0;
1029       } else {
1030         assert(_recent_avg_pause_time_ratio - 1.0 > 0.0, "Ctl-point invariant");
1031         _recent_avg_pause_time_ratio = 1.0;
1032       }
1033     }
1034   }
1035 
1036   bool new_in_marking_window = _in_marking_window;
1037   bool new_in_marking_window_im = false;
1038   if (last_pause_included_initial_mark) {
1039     new_in_marking_window = true;
1040     new_in_marking_window_im = true;
1041   }
1042 
1043   if (_last_young_gc) {
1044     // This is supposed to to be the "last young GC" before we start
1045     // doing mixed GCs. Here we decide whether to start mixed GCs or not.
1046 
1047     if (!last_pause_included_initial_mark) {
1048       if (next_gc_should_be_mixed("start mixed GCs",
1049                                   "do not start mixed GCs")) {
1050         set_gcs_are_young(false);
1051       }
1052     } else {
1053       ergo_verbose0(ErgoMixedGCs,
1054                     "do not start mixed GCs",
1055                     ergo_format_reason("concurrent cycle is about to start"));
1056     }
1057     _last_young_gc = false;
1058   }
1059 
1060   if (!_last_gc_was_young) {
1061     // This is a mixed GC. Here we decide whether to continue doing
1062     // mixed GCs or not.
1063 
1064     if (!next_gc_should_be_mixed("continue mixed GCs",
1065                                  "do not continue mixed GCs")) {
1066       set_gcs_are_young(true);
1067     }
1068   }
1069 
1070   _short_lived_surv_rate_group->start_adding_regions();
1071   // Do that for any other surv rate groups
1072 
1073   if (update_stats) {
1074     double cost_per_card_ms = 0.0;
1075     if (_pending_cards > 0) {
1076       cost_per_card_ms = phase_times()->average_time_ms(G1GCPhaseTimes::UpdateRS) / (double) _pending_cards;
1077       _cost_per_card_ms_seq->add(cost_per_card_ms);
1078     }
1079 
1080     size_t cards_scanned = _g1->cards_scanned();
1081 
1082     double cost_per_entry_ms = 0.0;
1083     if (cards_scanned > 10) {
1084       cost_per_entry_ms = phase_times()->average_time_ms(G1GCPhaseTimes::ScanRS) / (double) cards_scanned;
1085       if (_last_gc_was_young) {
1086         _cost_per_entry_ms_seq->add(cost_per_entry_ms);
1087       } else {
1088         _mixed_cost_per_entry_ms_seq->add(cost_per_entry_ms);
1089       }
1090     }
1091 
1092     if (_max_rs_lengths > 0) {
1093       double cards_per_entry_ratio =
1094         (double) cards_scanned / (double) _max_rs_lengths;
1095       if (_last_gc_was_young) {
1096         _young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
1097       } else {
1098         _mixed_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
1099       }
1100     }
1101 
1102     // This is defensive. For a while _max_rs_lengths could get
1103     // smaller than _recorded_rs_lengths which was causing
1104     // rs_length_diff to get very large and mess up the RSet length
1105     // predictions. The reason was unsafe concurrent updates to the
1106     // _inc_cset_recorded_rs_lengths field which the code below guards
1107     // against (see CR 7118202). This bug has now been fixed (see CR
1108     // 7119027). However, I'm still worried that
1109     // _inc_cset_recorded_rs_lengths might still end up somewhat
1110     // inaccurate. The concurrent refinement thread calculates an
1111     // RSet's length concurrently with other CR threads updating it
1112     // which might cause it to calculate the length incorrectly (if,
1113     // say, it's in mid-coarsening). So I'll leave in the defensive
1114     // conditional below just in case.
1115     size_t rs_length_diff = 0;
1116     if (_max_rs_lengths > _recorded_rs_lengths) {
1117       rs_length_diff = _max_rs_lengths - _recorded_rs_lengths;
1118     }
1119     _rs_length_diff_seq->add((double) rs_length_diff);
1120 
1121     size_t freed_bytes = _heap_used_bytes_before_gc - cur_used_bytes;
1122     size_t copied_bytes = _collection_set_bytes_used_before - freed_bytes;
1123     double cost_per_byte_ms = 0.0;
1124 
1125     if (copied_bytes > 0) {
1126       cost_per_byte_ms = phase_times()->average_time_ms(G1GCPhaseTimes::ObjCopy) / (double) copied_bytes;
1127       if (_in_marking_window) {
1128         _cost_per_byte_ms_during_cm_seq->add(cost_per_byte_ms);
1129       } else {
1130         _cost_per_byte_ms_seq->add(cost_per_byte_ms);
1131       }
1132     }
1133 
1134     double all_other_time_ms = pause_time_ms -
1135       (phase_times()->average_time_ms(G1GCPhaseTimes::UpdateRS) + phase_times()->average_time_ms(G1GCPhaseTimes::ScanRS) +
1136           phase_times()->average_time_ms(G1GCPhaseTimes::ObjCopy) + phase_times()->average_time_ms(G1GCPhaseTimes::Termination));
1137 
1138     double young_other_time_ms = 0.0;
1139     if (young_cset_region_length() > 0) {
1140       young_other_time_ms =
1141         phase_times()->young_cset_choice_time_ms() +
1142         phase_times()->young_free_cset_time_ms();
1143       _young_other_cost_per_region_ms_seq->add(young_other_time_ms /
1144                                           (double) young_cset_region_length());
1145     }
1146     double non_young_other_time_ms = 0.0;
1147     if (old_cset_region_length() > 0) {
1148       non_young_other_time_ms =
1149         phase_times()->non_young_cset_choice_time_ms() +
1150         phase_times()->non_young_free_cset_time_ms();
1151 
1152       _non_young_other_cost_per_region_ms_seq->add(non_young_other_time_ms /
1153                                             (double) old_cset_region_length());
1154     }
1155 
1156     double constant_other_time_ms = all_other_time_ms -
1157       (young_other_time_ms + non_young_other_time_ms);
1158     _constant_other_time_ms_seq->add(constant_other_time_ms);
1159 
1160     double survival_ratio = 0.0;
1161     if (_collection_set_bytes_used_before > 0) {
1162       survival_ratio = (double) _bytes_copied_during_gc /
1163                                    (double) _collection_set_bytes_used_before;
1164     }
1165 
1166     _pending_cards_seq->add((double) _pending_cards);
1167     _rs_lengths_seq->add((double) _max_rs_lengths);
1168   }
1169 
1170   _in_marking_window = new_in_marking_window;
1171   _in_marking_window_im = new_in_marking_window_im;
1172   _free_regions_at_end_of_collection = _g1->num_free_regions();
1173   update_young_list_target_length();
1174 
1175   // Note that _mmu_tracker->max_gc_time() returns the time in seconds.
1176   double update_rs_time_goal_ms = _mmu_tracker->max_gc_time() * MILLIUNITS * G1RSetUpdatingPauseTimePercent / 100.0;
1177   adjust_concurrent_refinement(phase_times()->average_time_ms(G1GCPhaseTimes::UpdateRS),
1178                                phase_times()->sum_thread_work_items(G1GCPhaseTimes::UpdateRS), update_rs_time_goal_ms);
1179 
1180   _collectionSetChooser->verify();
1181 }
1182 
1183 #define EXT_SIZE_FORMAT "%.1f%s"
1184 #define EXT_SIZE_PARAMS(bytes)                                  \
1185   byte_size_in_proper_unit((double)(bytes)),                    \
1186   proper_unit_for_byte_size((bytes))
1187 
1188 void G1CollectorPolicy::record_heap_size_info_at_start(bool full) {
1189   YoungList* young_list = _g1->young_list();
1190   _eden_used_bytes_before_gc = young_list->eden_used_bytes();
1191   _survivor_used_bytes_before_gc = young_list->survivor_used_bytes();
1192   _heap_capacity_bytes_before_gc = _g1->capacity();
1193   _heap_used_bytes_before_gc = _g1->used();
1194   _cur_collection_pause_used_regions_at_start = _g1->num_used_regions();
1195 
1196   _eden_capacity_bytes_before_gc =
1197          (_young_list_target_length * HeapRegion::GrainBytes) - _survivor_used_bytes_before_gc;
1198 
1199   if (full) {
1200     _metaspace_used_bytes_before_gc = MetaspaceAux::used_bytes();
1201   }
1202 }
1203 
1204 void G1CollectorPolicy::print_heap_transition() {
1205   _g1->print_size_transition(gclog_or_tty,
1206                              _heap_used_bytes_before_gc,
1207                              _g1->used(),
1208                              _g1->capacity());
1209 }
1210 
1211 void G1CollectorPolicy::print_detailed_heap_transition(bool full) {
1212   YoungList* young_list = _g1->young_list();
1213 
1214   size_t eden_used_bytes_after_gc = young_list->eden_used_bytes();
1215   size_t survivor_used_bytes_after_gc = young_list->survivor_used_bytes();
1216   size_t heap_used_bytes_after_gc = _g1->used();
1217 
1218   size_t heap_capacity_bytes_after_gc = _g1->capacity();
1219   size_t eden_capacity_bytes_after_gc =
1220     (_young_list_target_length * HeapRegion::GrainBytes) - survivor_used_bytes_after_gc;
1221 
1222   gclog_or_tty->print(
1223     "   [Eden: "EXT_SIZE_FORMAT"("EXT_SIZE_FORMAT")->"EXT_SIZE_FORMAT"("EXT_SIZE_FORMAT") "
1224     "Survivors: "EXT_SIZE_FORMAT"->"EXT_SIZE_FORMAT" "
1225     "Heap: "EXT_SIZE_FORMAT"("EXT_SIZE_FORMAT")->"
1226     EXT_SIZE_FORMAT"("EXT_SIZE_FORMAT")]",
1227     EXT_SIZE_PARAMS(_eden_used_bytes_before_gc),
1228     EXT_SIZE_PARAMS(_eden_capacity_bytes_before_gc),
1229     EXT_SIZE_PARAMS(eden_used_bytes_after_gc),
1230     EXT_SIZE_PARAMS(eden_capacity_bytes_after_gc),
1231     EXT_SIZE_PARAMS(_survivor_used_bytes_before_gc),
1232     EXT_SIZE_PARAMS(survivor_used_bytes_after_gc),
1233     EXT_SIZE_PARAMS(_heap_used_bytes_before_gc),
1234     EXT_SIZE_PARAMS(_heap_capacity_bytes_before_gc),
1235     EXT_SIZE_PARAMS(heap_used_bytes_after_gc),
1236     EXT_SIZE_PARAMS(heap_capacity_bytes_after_gc));
1237 
1238   if (full) {
1239     MetaspaceAux::print_metaspace_change(_metaspace_used_bytes_before_gc);
1240   }
1241 
1242   gclog_or_tty->cr();
1243 }
1244 
1245 void G1CollectorPolicy::adjust_concurrent_refinement(double update_rs_time,
1246                                                      double update_rs_processed_buffers,
1247                                                      double goal_ms) {
1248   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
1249   ConcurrentG1Refine *cg1r = G1CollectedHeap::heap()->concurrent_g1_refine();
1250 
1251   if (G1UseAdaptiveConcRefinement) {
1252     const int k_gy = 3, k_gr = 6;
1253     const double inc_k = 1.1, dec_k = 0.9;
1254 
1255     int g = cg1r->green_zone();
1256     if (update_rs_time > goal_ms) {
1257       g = (int)(g * dec_k);  // Can become 0, that's OK. That would mean a mutator-only processing.
1258     } else {
1259       if (update_rs_time < goal_ms && update_rs_processed_buffers > g) {
1260         g = (int)MAX2(g * inc_k, g + 1.0);
1261       }
1262     }
1263     // Change the refinement threads params
1264     cg1r->set_green_zone(g);
1265     cg1r->set_yellow_zone(g * k_gy);
1266     cg1r->set_red_zone(g * k_gr);
1267     cg1r->reinitialize_threads();
1268 
1269     int processing_threshold_delta = MAX2((int)(cg1r->green_zone() * sigma()), 1);
1270     int processing_threshold = MIN2(cg1r->green_zone() + processing_threshold_delta,
1271                                     cg1r->yellow_zone());
1272     // Change the barrier params
1273     dcqs.set_process_completed_threshold(processing_threshold);
1274     dcqs.set_max_completed_queue(cg1r->red_zone());
1275   }
1276 
1277   int curr_queue_size = dcqs.completed_buffers_num();
1278   if (curr_queue_size >= cg1r->yellow_zone()) {
1279     dcqs.set_completed_queue_padding(curr_queue_size);
1280   } else {
1281     dcqs.set_completed_queue_padding(0);
1282   }
1283   dcqs.notify_if_necessary();
1284 }
1285 
1286 double
1287 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards,
1288                                                 size_t scanned_cards) {
1289   return
1290     predict_rs_update_time_ms(pending_cards) +
1291     predict_rs_scan_time_ms(scanned_cards) +
1292     predict_constant_other_time_ms();
1293 }
1294 
1295 double
1296 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards) {
1297   size_t rs_length = predict_rs_length_diff();
1298   size_t card_num;
1299   if (gcs_are_young()) {
1300     card_num = predict_young_card_num(rs_length);
1301   } else {
1302     card_num = predict_non_young_card_num(rs_length);
1303   }
1304   return predict_base_elapsed_time_ms(pending_cards, card_num);
1305 }
1306 
1307 size_t G1CollectorPolicy::predict_bytes_to_copy(HeapRegion* hr) {
1308   size_t bytes_to_copy;
1309   if (hr->is_marked())
1310     bytes_to_copy = hr->max_live_bytes();
1311   else {
1312     assert(hr->is_young() && hr->age_in_surv_rate_group() != -1, "invariant");
1313     int age = hr->age_in_surv_rate_group();
1314     double yg_surv_rate = predict_yg_surv_rate(age, hr->surv_rate_group());
1315     bytes_to_copy = (size_t) ((double) hr->used() * yg_surv_rate);
1316   }
1317   return bytes_to_copy;
1318 }
1319 
1320 double
1321 G1CollectorPolicy::predict_region_elapsed_time_ms(HeapRegion* hr,
1322                                                   bool for_young_gc) {
1323   size_t rs_length = hr->rem_set()->occupied();
1324   size_t card_num;
1325 
1326   // Predicting the number of cards is based on which type of GC
1327   // we're predicting for.
1328   if (for_young_gc) {
1329     card_num = predict_young_card_num(rs_length);
1330   } else {
1331     card_num = predict_non_young_card_num(rs_length);
1332   }
1333   size_t bytes_to_copy = predict_bytes_to_copy(hr);
1334 
1335   double region_elapsed_time_ms =
1336     predict_rs_scan_time_ms(card_num) +
1337     predict_object_copy_time_ms(bytes_to_copy);
1338 
1339   // The prediction of the "other" time for this region is based
1340   // upon the region type and NOT the GC type.
1341   if (hr->is_young()) {
1342     region_elapsed_time_ms += predict_young_other_time_ms(1);
1343   } else {
1344     region_elapsed_time_ms += predict_non_young_other_time_ms(1);
1345   }
1346   return region_elapsed_time_ms;
1347 }
1348 
1349 void
1350 G1CollectorPolicy::init_cset_region_lengths(uint eden_cset_region_length,
1351                                             uint survivor_cset_region_length) {
1352   _eden_cset_region_length     = eden_cset_region_length;
1353   _survivor_cset_region_length = survivor_cset_region_length;
1354   _old_cset_region_length      = 0;
1355 }
1356 
1357 void G1CollectorPolicy::set_recorded_rs_lengths(size_t rs_lengths) {
1358   _recorded_rs_lengths = rs_lengths;
1359 }
1360 
1361 void G1CollectorPolicy::update_recent_gc_times(double end_time_sec,
1362                                                double elapsed_ms) {
1363   _recent_gc_times_ms->add(elapsed_ms);
1364   _recent_prev_end_times_for_all_gcs_sec->add(end_time_sec);
1365   _prev_collection_pause_end_ms = end_time_sec * 1000.0;
1366 }
1367 
1368 size_t G1CollectorPolicy::expansion_amount() {
1369   double recent_gc_overhead = recent_avg_pause_time_ratio() * 100.0;
1370   double threshold = _gc_overhead_perc;
1371   if (recent_gc_overhead > threshold) {
1372     // We will double the existing space, or take
1373     // G1ExpandByPercentOfAvailable % of the available expansion
1374     // space, whichever is smaller, bounded below by a minimum
1375     // expansion (unless that's all that's left.)
1376     const size_t min_expand_bytes = 1*M;
1377     size_t reserved_bytes = _g1->max_capacity();
1378     size_t committed_bytes = _g1->capacity();
1379     size_t uncommitted_bytes = reserved_bytes - committed_bytes;
1380     size_t expand_bytes;
1381     size_t expand_bytes_via_pct =
1382       uncommitted_bytes * G1ExpandByPercentOfAvailable / 100;
1383     expand_bytes = MIN2(expand_bytes_via_pct, committed_bytes);
1384     expand_bytes = MAX2(expand_bytes, min_expand_bytes);
1385     expand_bytes = MIN2(expand_bytes, uncommitted_bytes);
1386 
1387     ergo_verbose5(ErgoHeapSizing,
1388                   "attempt heap expansion",
1389                   ergo_format_reason("recent GC overhead higher than "
1390                                      "threshold after GC")
1391                   ergo_format_perc("recent GC overhead")
1392                   ergo_format_perc("threshold")
1393                   ergo_format_byte("uncommitted")
1394                   ergo_format_byte_perc("calculated expansion amount"),
1395                   recent_gc_overhead, threshold,
1396                   uncommitted_bytes,
1397                   expand_bytes_via_pct, (double) G1ExpandByPercentOfAvailable);
1398 
1399     return expand_bytes;
1400   } else {
1401     return 0;
1402   }
1403 }
1404 
1405 void G1CollectorPolicy::print_tracing_info() const {
1406   _trace_young_gen_time_data.print();
1407   _trace_old_gen_time_data.print();
1408 }
1409 
1410 void G1CollectorPolicy::print_yg_surv_rate_info() const {
1411 #ifndef PRODUCT
1412   _short_lived_surv_rate_group->print_surv_rate_summary();
1413   // add this call for any other surv rate groups
1414 #endif // PRODUCT
1415 }
1416 
1417 bool G1CollectorPolicy::is_young_list_full() {
1418   uint young_list_length = _g1->young_list()->length();
1419   uint young_list_target_length = _young_list_target_length;
1420   return young_list_length >= young_list_target_length;
1421 }
1422 
1423 bool G1CollectorPolicy::can_expand_young_list() {
1424   uint young_list_length = _g1->young_list()->length();
1425   uint young_list_max_length = _young_list_max_length;
1426   return young_list_length < young_list_max_length;
1427 }
1428 
1429 void G1CollectorPolicy::update_max_gc_locker_expansion() {
1430   uint expansion_region_num = 0;
1431   if (GCLockerEdenExpansionPercent > 0) {
1432     double perc = (double) GCLockerEdenExpansionPercent / 100.0;
1433     double expansion_region_num_d = perc * (double) _young_list_target_length;
1434     // We use ceiling so that if expansion_region_num_d is > 0.0 (but
1435     // less than 1.0) we'll get 1.
1436     expansion_region_num = (uint) ceil(expansion_region_num_d);
1437   } else {
1438     assert(expansion_region_num == 0, "sanity");
1439   }
1440   _young_list_max_length = _young_list_target_length + expansion_region_num;
1441   assert(_young_list_target_length <= _young_list_max_length, "post-condition");
1442 }
1443 
1444 // Calculates survivor space parameters.
1445 void G1CollectorPolicy::update_survivors_policy() {
1446   double max_survivor_regions_d =
1447                  (double) _young_list_target_length / (double) SurvivorRatio;
1448   // We use ceiling so that if max_survivor_regions_d is > 0.0 (but
1449   // smaller than 1.0) we'll get 1.
1450   _max_survivor_regions = (uint) ceil(max_survivor_regions_d);
1451 
1452   _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(
1453         HeapRegion::GrainWords * _max_survivor_regions);
1454 }
1455 
1456 bool G1CollectorPolicy::force_initial_mark_if_outside_cycle(
1457                                                      GCCause::Cause gc_cause) {
1458   bool during_cycle = _g1->concurrent_mark()->cmThread()->during_cycle();
1459   if (!during_cycle) {
1460     ergo_verbose1(ErgoConcCycles,
1461                   "request concurrent cycle initiation",
1462                   ergo_format_reason("requested by GC cause")
1463                   ergo_format_str("GC cause"),
1464                   GCCause::to_string(gc_cause));
1465     set_initiate_conc_mark_if_possible();
1466     return true;
1467   } else {
1468     ergo_verbose1(ErgoConcCycles,
1469                   "do not request concurrent cycle initiation",
1470                   ergo_format_reason("concurrent cycle already in progress")
1471                   ergo_format_str("GC cause"),
1472                   GCCause::to_string(gc_cause));
1473     return false;
1474   }
1475 }
1476 
1477 void
1478 G1CollectorPolicy::decide_on_conc_mark_initiation() {
1479   // We are about to decide on whether this pause will be an
1480   // initial-mark pause.
1481 
1482   // First, during_initial_mark_pause() should not be already set. We
1483   // will set it here if we have to. However, it should be cleared by
1484   // the end of the pause (it's only set for the duration of an
1485   // initial-mark pause).
1486   assert(!during_initial_mark_pause(), "pre-condition");
1487 
1488   if (initiate_conc_mark_if_possible()) {
1489     // We had noticed on a previous pause that the heap occupancy has
1490     // gone over the initiating threshold and we should start a
1491     // concurrent marking cycle. So we might initiate one.
1492 
1493     bool during_cycle = _g1->concurrent_mark()->cmThread()->during_cycle();
1494     if (!during_cycle) {
1495       // The concurrent marking thread is not "during a cycle", i.e.,
1496       // it has completed the last one. So we can go ahead and
1497       // initiate a new cycle.
1498 
1499       set_during_initial_mark_pause();
1500       // We do not allow mixed GCs during marking.
1501       if (!gcs_are_young()) {
1502         set_gcs_are_young(true);
1503         ergo_verbose0(ErgoMixedGCs,
1504                       "end mixed GCs",
1505                       ergo_format_reason("concurrent cycle is about to start"));
1506       }
1507 
1508       // And we can now clear initiate_conc_mark_if_possible() as
1509       // we've already acted on it.
1510       clear_initiate_conc_mark_if_possible();
1511 
1512       ergo_verbose0(ErgoConcCycles,
1513                   "initiate concurrent cycle",
1514                   ergo_format_reason("concurrent cycle initiation requested"));
1515     } else {
1516       // The concurrent marking thread is still finishing up the
1517       // previous cycle. If we start one right now the two cycles
1518       // overlap. In particular, the concurrent marking thread might
1519       // be in the process of clearing the next marking bitmap (which
1520       // we will use for the next cycle if we start one). Starting a
1521       // cycle now will be bad given that parts of the marking
1522       // information might get cleared by the marking thread. And we
1523       // cannot wait for the marking thread to finish the cycle as it
1524       // periodically yields while clearing the next marking bitmap
1525       // and, if it's in a yield point, it's waiting for us to
1526       // finish. So, at this point we will not start a cycle and we'll
1527       // let the concurrent marking thread complete the last one.
1528       ergo_verbose0(ErgoConcCycles,
1529                     "do not initiate concurrent cycle",
1530                     ergo_format_reason("concurrent cycle already in progress"));
1531     }
1532   }
1533 }
1534 
1535 class ParKnownGarbageHRClosure: public HeapRegionClosure {
1536   G1CollectedHeap* _g1h;
1537   CSetChooserParUpdater _cset_updater;
1538 
1539 public:
1540   ParKnownGarbageHRClosure(CollectionSetChooser* hrSorted,
1541                            uint chunk_size) :
1542     _g1h(G1CollectedHeap::heap()),
1543     _cset_updater(hrSorted, true /* parallel */, chunk_size) { }
1544 
1545   bool doHeapRegion(HeapRegion* r) {
1546     // Do we have any marking information for this region?
1547     if (r->is_marked()) {
1548       // We will skip any region that's currently used as an old GC
1549       // alloc region (we should not consider those for collection
1550       // before we fill them up).
1551       if (_cset_updater.should_add(r) && !_g1h->is_old_gc_alloc_region(r)) {
1552         _cset_updater.add_region(r);
1553       }
1554     }
1555     return false;
1556   }
1557 };
1558 
1559 class ParKnownGarbageTask: public AbstractGangTask {
1560   CollectionSetChooser* _hrSorted;
1561   uint _chunk_size;
1562   G1CollectedHeap* _g1;
1563   HeapRegionClaimer _hrclaimer;
1564 
1565 public:
1566   ParKnownGarbageTask(CollectionSetChooser* hrSorted, uint chunk_size, uint n_workers) :
1567       AbstractGangTask("ParKnownGarbageTask"),
1568       _hrSorted(hrSorted), _chunk_size(chunk_size),
1569       _g1(G1CollectedHeap::heap()), _hrclaimer(n_workers) {}
1570 
1571   void work(uint worker_id) {
1572     ParKnownGarbageHRClosure parKnownGarbageCl(_hrSorted, _chunk_size);
1573     _g1->heap_region_par_iterate(&parKnownGarbageCl, worker_id, &_hrclaimer);
1574   }
1575 };
1576 
1577 uint G1CollectorPolicy::calculate_parallel_work_chunk_size(uint n_workers, uint n_regions) {
1578   assert(n_workers > 0, "Active gc workers should be greater than 0");
1579   const uint overpartition_factor = 4;
1580   const uint min_chunk_size = MAX2(n_regions / n_workers, 1U);
1581   return MAX2(n_regions / (n_workers * overpartition_factor), min_chunk_size);
1582 }
1583 
1584 void
1585 G1CollectorPolicy::record_concurrent_mark_cleanup_end(uint n_workers) {
1586   _collectionSetChooser->clear();
1587 
1588   uint n_regions = _g1->num_regions();
1589   uint chunk_size = calculate_parallel_work_chunk_size(n_workers, n_regions);
1590   _collectionSetChooser->prepare_for_par_region_addition(n_regions, chunk_size);
1591   ParKnownGarbageTask par_known_garbage_task(_collectionSetChooser, chunk_size, n_workers);
1592   _g1->workers()->run_task(&par_known_garbage_task);
1593 
1594   _collectionSetChooser->sort_regions();
1595 
1596   double end_sec = os::elapsedTime();
1597   double elapsed_time_ms = (end_sec - _mark_cleanup_start_sec) * 1000.0;
1598   _concurrent_mark_cleanup_times_ms->add(elapsed_time_ms);
1599   _cur_mark_stop_world_time_ms += elapsed_time_ms;
1600   _prev_collection_pause_end_ms += elapsed_time_ms;
1601   _mmu_tracker->add_pause(_mark_cleanup_start_sec, end_sec, true);
1602 }
1603 
1604 // Add the heap region at the head of the non-incremental collection set
1605 void G1CollectorPolicy::add_old_region_to_cset(HeapRegion* hr) {
1606   assert(_inc_cset_build_state == Active, "Precondition");
1607   assert(hr->is_old(), "the region should be old");
1608 
1609   assert(!hr->in_collection_set(), "should not already be in the CSet");
1610   _g1->register_old_region_with_cset(hr);
1611   hr->set_next_in_collection_set(_collection_set);
1612   _collection_set = hr;
1613   _collection_set_bytes_used_before += hr->used();
1614   size_t rs_length = hr->rem_set()->occupied();
1615   _recorded_rs_lengths += rs_length;
1616   _old_cset_region_length += 1;
1617 }
1618 
1619 // Initialize the per-collection-set information
1620 void G1CollectorPolicy::start_incremental_cset_building() {
1621   assert(_inc_cset_build_state == Inactive, "Precondition");
1622 
1623   _inc_cset_head = NULL;
1624   _inc_cset_tail = NULL;
1625   _inc_cset_bytes_used_before = 0;
1626 
1627   _inc_cset_max_finger = 0;
1628   _inc_cset_recorded_rs_lengths = 0;
1629   _inc_cset_recorded_rs_lengths_diffs = 0;
1630   _inc_cset_predicted_elapsed_time_ms = 0.0;
1631   _inc_cset_predicted_elapsed_time_ms_diffs = 0.0;
1632   _inc_cset_build_state = Active;
1633 }
1634 
1635 void G1CollectorPolicy::finalize_incremental_cset_building() {
1636   assert(_inc_cset_build_state == Active, "Precondition");
1637   assert(SafepointSynchronize::is_at_safepoint(), "should be at a safepoint");
1638 
1639   // The two "main" fields, _inc_cset_recorded_rs_lengths and
1640   // _inc_cset_predicted_elapsed_time_ms, are updated by the thread
1641   // that adds a new region to the CSet. Further updates by the
1642   // concurrent refinement thread that samples the young RSet lengths
1643   // are accumulated in the *_diffs fields. Here we add the diffs to
1644   // the "main" fields.
1645 
1646   if (_inc_cset_recorded_rs_lengths_diffs >= 0) {
1647     _inc_cset_recorded_rs_lengths += _inc_cset_recorded_rs_lengths_diffs;
1648   } else {
1649     // This is defensive. The diff should in theory be always positive
1650     // as RSets can only grow between GCs. However, given that we
1651     // sample their size concurrently with other threads updating them
1652     // it's possible that we might get the wrong size back, which
1653     // could make the calculations somewhat inaccurate.
1654     size_t diffs = (size_t) (-_inc_cset_recorded_rs_lengths_diffs);
1655     if (_inc_cset_recorded_rs_lengths >= diffs) {
1656       _inc_cset_recorded_rs_lengths -= diffs;
1657     } else {
1658       _inc_cset_recorded_rs_lengths = 0;
1659     }
1660   }
1661   _inc_cset_predicted_elapsed_time_ms +=
1662                                      _inc_cset_predicted_elapsed_time_ms_diffs;
1663 
1664   _inc_cset_recorded_rs_lengths_diffs = 0;
1665   _inc_cset_predicted_elapsed_time_ms_diffs = 0.0;
1666 }
1667 
1668 void G1CollectorPolicy::add_to_incremental_cset_info(HeapRegion* hr, size_t rs_length) {
1669   // This routine is used when:
1670   // * adding survivor regions to the incremental cset at the end of an
1671   //   evacuation pause,
1672   // * adding the current allocation region to the incremental cset
1673   //   when it is retired, and
1674   // * updating existing policy information for a region in the
1675   //   incremental cset via young list RSet sampling.
1676   // Therefore this routine may be called at a safepoint by the
1677   // VM thread, or in-between safepoints by mutator threads (when
1678   // retiring the current allocation region) or a concurrent
1679   // refine thread (RSet sampling).
1680 
1681   double region_elapsed_time_ms = predict_region_elapsed_time_ms(hr, gcs_are_young());
1682   size_t used_bytes = hr->used();
1683   _inc_cset_recorded_rs_lengths += rs_length;
1684   _inc_cset_predicted_elapsed_time_ms += region_elapsed_time_ms;
1685   _inc_cset_bytes_used_before += used_bytes;
1686 
1687   // Cache the values we have added to the aggregated information
1688   // in the heap region in case we have to remove this region from
1689   // the incremental collection set, or it is updated by the
1690   // rset sampling code
1691   hr->set_recorded_rs_length(rs_length);
1692   hr->set_predicted_elapsed_time_ms(region_elapsed_time_ms);
1693 }
1694 
1695 void G1CollectorPolicy::update_incremental_cset_info(HeapRegion* hr,
1696                                                      size_t new_rs_length) {
1697   // Update the CSet information that is dependent on the new RS length
1698   assert(hr->is_young(), "Precondition");
1699   assert(!SafepointSynchronize::is_at_safepoint(),
1700                                                "should not be at a safepoint");
1701 
1702   // We could have updated _inc_cset_recorded_rs_lengths and
1703   // _inc_cset_predicted_elapsed_time_ms directly but we'd need to do
1704   // that atomically, as this code is executed by a concurrent
1705   // refinement thread, potentially concurrently with a mutator thread
1706   // allocating a new region and also updating the same fields. To
1707   // avoid the atomic operations we accumulate these updates on two
1708   // separate fields (*_diffs) and we'll just add them to the "main"
1709   // fields at the start of a GC.
1710 
1711   ssize_t old_rs_length = (ssize_t) hr->recorded_rs_length();
1712   ssize_t rs_lengths_diff = (ssize_t) new_rs_length - old_rs_length;
1713   _inc_cset_recorded_rs_lengths_diffs += rs_lengths_diff;
1714 
1715   double old_elapsed_time_ms = hr->predicted_elapsed_time_ms();
1716   double new_region_elapsed_time_ms = predict_region_elapsed_time_ms(hr, gcs_are_young());
1717   double elapsed_ms_diff = new_region_elapsed_time_ms - old_elapsed_time_ms;
1718   _inc_cset_predicted_elapsed_time_ms_diffs += elapsed_ms_diff;
1719 
1720   hr->set_recorded_rs_length(new_rs_length);
1721   hr->set_predicted_elapsed_time_ms(new_region_elapsed_time_ms);
1722 }
1723 
1724 void G1CollectorPolicy::add_region_to_incremental_cset_common(HeapRegion* hr) {
1725   assert(hr->is_young(), "invariant");
1726   assert(hr->young_index_in_cset() > -1, "should have already been set");
1727   assert(_inc_cset_build_state == Active, "Precondition");
1728 
1729   // We need to clear and set the cached recorded/cached collection set
1730   // information in the heap region here (before the region gets added
1731   // to the collection set). An individual heap region's cached values
1732   // are calculated, aggregated with the policy collection set info,
1733   // and cached in the heap region here (initially) and (subsequently)
1734   // by the Young List sampling code.
1735 
1736   size_t rs_length = hr->rem_set()->occupied();
1737   add_to_incremental_cset_info(hr, rs_length);
1738 
1739   HeapWord* hr_end = hr->end();
1740   _inc_cset_max_finger = MAX2(_inc_cset_max_finger, hr_end);
1741 
1742   assert(!hr->in_collection_set(), "invariant");
1743   _g1->register_young_region_with_cset(hr);
1744   assert(hr->next_in_collection_set() == NULL, "invariant");
1745 }
1746 
1747 // Add the region at the RHS of the incremental cset
1748 void G1CollectorPolicy::add_region_to_incremental_cset_rhs(HeapRegion* hr) {
1749   // We should only ever be appending survivors at the end of a pause
1750   assert(hr->is_survivor(), "Logic");
1751 
1752   // Do the 'common' stuff
1753   add_region_to_incremental_cset_common(hr);
1754 
1755   // Now add the region at the right hand side
1756   if (_inc_cset_tail == NULL) {
1757     assert(_inc_cset_head == NULL, "invariant");
1758     _inc_cset_head = hr;
1759   } else {
1760     _inc_cset_tail->set_next_in_collection_set(hr);
1761   }
1762   _inc_cset_tail = hr;
1763 }
1764 
1765 // Add the region to the LHS of the incremental cset
1766 void G1CollectorPolicy::add_region_to_incremental_cset_lhs(HeapRegion* hr) {
1767   // Survivors should be added to the RHS at the end of a pause
1768   assert(hr->is_eden(), "Logic");
1769 
1770   // Do the 'common' stuff
1771   add_region_to_incremental_cset_common(hr);
1772 
1773   // Add the region at the left hand side
1774   hr->set_next_in_collection_set(_inc_cset_head);
1775   if (_inc_cset_head == NULL) {
1776     assert(_inc_cset_tail == NULL, "Invariant");
1777     _inc_cset_tail = hr;
1778   }
1779   _inc_cset_head = hr;
1780 }
1781 
1782 #ifndef PRODUCT
1783 void G1CollectorPolicy::print_collection_set(HeapRegion* list_head, outputStream* st) {
1784   assert(list_head == inc_cset_head() || list_head == collection_set(), "must be");
1785 
1786   st->print_cr("\nCollection_set:");
1787   HeapRegion* csr = list_head;
1788   while (csr != NULL) {
1789     HeapRegion* next = csr->next_in_collection_set();
1790     assert(csr->in_collection_set(), "bad CS");
1791     st->print_cr("  "HR_FORMAT", P: "PTR_FORMAT "N: "PTR_FORMAT", age: %4d",
1792                  HR_FORMAT_PARAMS(csr),
1793                  csr->prev_top_at_mark_start(), csr->next_top_at_mark_start(),
1794                  csr->age_in_surv_rate_group_cond());
1795     csr = next;
1796   }
1797 }
1798 #endif // !PRODUCT
1799 
1800 double G1CollectorPolicy::reclaimable_bytes_perc(size_t reclaimable_bytes) {
1801   // Returns the given amount of reclaimable bytes (that represents
1802   // the amount of reclaimable space still to be collected) as a
1803   // percentage of the current heap capacity.
1804   size_t capacity_bytes = _g1->capacity();
1805   return (double) reclaimable_bytes * 100.0 / (double) capacity_bytes;
1806 }
1807 
1808 bool G1CollectorPolicy::next_gc_should_be_mixed(const char* true_action_str,
1809                                                 const char* false_action_str) {
1810   CollectionSetChooser* cset_chooser = _collectionSetChooser;
1811   if (cset_chooser->is_empty()) {
1812     ergo_verbose0(ErgoMixedGCs,
1813                   false_action_str,
1814                   ergo_format_reason("candidate old regions not available"));
1815     return false;
1816   }
1817 
1818   // Is the amount of uncollected reclaimable space above G1HeapWastePercent?
1819   size_t reclaimable_bytes = cset_chooser->remaining_reclaimable_bytes();
1820   double reclaimable_perc = reclaimable_bytes_perc(reclaimable_bytes);
1821   double threshold = (double) G1HeapWastePercent;
1822   if (reclaimable_perc <= threshold) {
1823     ergo_verbose4(ErgoMixedGCs,
1824               false_action_str,
1825               ergo_format_reason("reclaimable percentage not over threshold")
1826               ergo_format_region("candidate old regions")
1827               ergo_format_byte_perc("reclaimable")
1828               ergo_format_perc("threshold"),
1829               cset_chooser->remaining_regions(),
1830               reclaimable_bytes,
1831               reclaimable_perc, threshold);
1832     return false;
1833   }
1834 
1835   ergo_verbose4(ErgoMixedGCs,
1836                 true_action_str,
1837                 ergo_format_reason("candidate old regions available")
1838                 ergo_format_region("candidate old regions")
1839                 ergo_format_byte_perc("reclaimable")
1840                 ergo_format_perc("threshold"),
1841                 cset_chooser->remaining_regions(),
1842                 reclaimable_bytes,
1843                 reclaimable_perc, threshold);
1844   return true;
1845 }
1846 
1847 uint G1CollectorPolicy::calc_min_old_cset_length() {
1848   // The min old CSet region bound is based on the maximum desired
1849   // number of mixed GCs after a cycle. I.e., even if some old regions
1850   // look expensive, we should add them to the CSet anyway to make
1851   // sure we go through the available old regions in no more than the
1852   // maximum desired number of mixed GCs.
1853   //
1854   // The calculation is based on the number of marked regions we added
1855   // to the CSet chooser in the first place, not how many remain, so
1856   // that the result is the same during all mixed GCs that follow a cycle.
1857 
1858   const size_t region_num = (size_t) _collectionSetChooser->length();
1859   const size_t gc_num = (size_t) MAX2(G1MixedGCCountTarget, (uintx) 1);
1860   size_t result = region_num / gc_num;
1861   // emulate ceiling
1862   if (result * gc_num < region_num) {
1863     result += 1;
1864   }
1865   return (uint) result;
1866 }
1867 
1868 uint G1CollectorPolicy::calc_max_old_cset_length() {
1869   // The max old CSet region bound is based on the threshold expressed
1870   // as a percentage of the heap size. I.e., it should bound the
1871   // number of old regions added to the CSet irrespective of how many
1872   // of them are available.
1873 
1874   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1875   const size_t region_num = g1h->num_regions();
1876   const size_t perc = (size_t) G1OldCSetRegionThresholdPercent;
1877   size_t result = region_num * perc / 100;
1878   // emulate ceiling
1879   if (100 * result < region_num * perc) {
1880     result += 1;
1881   }
1882   return (uint) result;
1883 }
1884 
1885 
1886 void G1CollectorPolicy::finalize_cset(double target_pause_time_ms, EvacuationInfo& evacuation_info) {
1887   double young_start_time_sec = os::elapsedTime();
1888 
1889   YoungList* young_list = _g1->young_list();
1890   finalize_incremental_cset_building();
1891 
1892   guarantee(target_pause_time_ms > 0.0,
1893             err_msg("target_pause_time_ms = %1.6lf should be positive",
1894                     target_pause_time_ms));
1895   guarantee(_collection_set == NULL, "Precondition");
1896 
1897   double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);
1898   double predicted_pause_time_ms = base_time_ms;
1899   double time_remaining_ms = MAX2(target_pause_time_ms - base_time_ms, 0.0);
1900 
1901   ergo_verbose4(ErgoCSetConstruction | ErgoHigh,
1902                 "start choosing CSet",
1903                 ergo_format_size("_pending_cards")
1904                 ergo_format_ms("predicted base time")
1905                 ergo_format_ms("remaining time")
1906                 ergo_format_ms("target pause time"),
1907                 _pending_cards, base_time_ms, time_remaining_ms, target_pause_time_ms);
1908 
1909   _last_gc_was_young = gcs_are_young() ? true : false;
1910 
1911   if (_last_gc_was_young) {
1912     _trace_young_gen_time_data.increment_young_collection_count();
1913   } else {
1914     _trace_young_gen_time_data.increment_mixed_collection_count();
1915   }
1916 
1917   // The young list is laid with the survivor regions from the previous
1918   // pause are appended to the RHS of the young list, i.e.
1919   //   [Newly Young Regions ++ Survivors from last pause].
1920 
1921   uint survivor_region_length = young_list->survivor_length();
1922   uint eden_region_length = young_list->eden_length();
1923   init_cset_region_lengths(eden_region_length, survivor_region_length);
1924 
1925   HeapRegion* hr = young_list->first_survivor_region();
1926   while (hr != NULL) {
1927     assert(hr->is_survivor(), "badly formed young list");
1928     // There is a convention that all the young regions in the CSet
1929     // are tagged as "eden", so we do this for the survivors here. We
1930     // use the special set_eden_pre_gc() as it doesn't check that the
1931     // region is free (which is not the case here).
1932     hr->set_eden_pre_gc();
1933     hr = hr->get_next_young_region();
1934   }
1935 
1936   // Clear the fields that point to the survivor list - they are all young now.
1937   young_list->clear_survivors();
1938 
1939   _collection_set = _inc_cset_head;
1940   _collection_set_bytes_used_before = _inc_cset_bytes_used_before;
1941   time_remaining_ms = MAX2(time_remaining_ms - _inc_cset_predicted_elapsed_time_ms, 0.0);
1942   predicted_pause_time_ms += _inc_cset_predicted_elapsed_time_ms;
1943 
1944   ergo_verbose3(ErgoCSetConstruction | ErgoHigh,
1945                 "add young regions to CSet",
1946                 ergo_format_region("eden")
1947                 ergo_format_region("survivors")
1948                 ergo_format_ms("predicted young region time"),
1949                 eden_region_length, survivor_region_length,
1950                 _inc_cset_predicted_elapsed_time_ms);
1951 
1952   // The number of recorded young regions is the incremental
1953   // collection set's current size
1954   set_recorded_rs_lengths(_inc_cset_recorded_rs_lengths);
1955 
1956   double young_end_time_sec = os::elapsedTime();
1957   phase_times()->record_young_cset_choice_time_ms((young_end_time_sec - young_start_time_sec) * 1000.0);
1958 
1959   // Set the start of the non-young choice time.
1960   double non_young_start_time_sec = young_end_time_sec;
1961 
1962   if (!gcs_are_young()) {
1963     CollectionSetChooser* cset_chooser = _collectionSetChooser;
1964     cset_chooser->verify();
1965     const uint min_old_cset_length = calc_min_old_cset_length();
1966     const uint max_old_cset_length = calc_max_old_cset_length();
1967 
1968     uint expensive_region_num = 0;
1969     bool check_time_remaining = adaptive_young_list_length();
1970 
1971     HeapRegion* hr = cset_chooser->peek();
1972     while (hr != NULL) {
1973       if (old_cset_region_length() >= max_old_cset_length) {
1974         // Added maximum number of old regions to the CSet.
1975         ergo_verbose2(ErgoCSetConstruction,
1976                       "finish adding old regions to CSet",
1977                       ergo_format_reason("old CSet region num reached max")
1978                       ergo_format_region("old")
1979                       ergo_format_region("max"),
1980                       old_cset_region_length(), max_old_cset_length);
1981         break;
1982       }
1983 
1984 
1985       // Stop adding regions if the remaining reclaimable space is
1986       // not above G1HeapWastePercent.
1987       size_t reclaimable_bytes = cset_chooser->remaining_reclaimable_bytes();
1988       double reclaimable_perc = reclaimable_bytes_perc(reclaimable_bytes);
1989       double threshold = (double) G1HeapWastePercent;
1990       if (reclaimable_perc <= threshold) {
1991         // We've added enough old regions that the amount of uncollected
1992         // reclaimable space is at or below the waste threshold. Stop
1993         // adding old regions to the CSet.
1994         ergo_verbose5(ErgoCSetConstruction,
1995                       "finish adding old regions to CSet",
1996                       ergo_format_reason("reclaimable percentage not over threshold")
1997                       ergo_format_region("old")
1998                       ergo_format_region("max")
1999                       ergo_format_byte_perc("reclaimable")
2000                       ergo_format_perc("threshold"),
2001                       old_cset_region_length(),
2002                       max_old_cset_length,
2003                       reclaimable_bytes,
2004                       reclaimable_perc, threshold);
2005         break;
2006       }
2007 
2008       double predicted_time_ms = predict_region_elapsed_time_ms(hr, gcs_are_young());
2009       if (check_time_remaining) {
2010         if (predicted_time_ms > time_remaining_ms) {
2011           // Too expensive for the current CSet.
2012 
2013           if (old_cset_region_length() >= min_old_cset_length) {
2014             // We have added the minimum number of old regions to the CSet,
2015             // we are done with this CSet.
2016             ergo_verbose4(ErgoCSetConstruction,
2017                           "finish adding old regions to CSet",
2018                           ergo_format_reason("predicted time is too high")
2019                           ergo_format_ms("predicted time")
2020                           ergo_format_ms("remaining time")
2021                           ergo_format_region("old")
2022                           ergo_format_region("min"),
2023                           predicted_time_ms, time_remaining_ms,
2024                           old_cset_region_length(), min_old_cset_length);
2025             break;
2026           }
2027 
2028           // We'll add it anyway given that we haven't reached the
2029           // minimum number of old regions.
2030           expensive_region_num += 1;
2031         }
2032       } else {
2033         if (old_cset_region_length() >= min_old_cset_length) {
2034           // In the non-auto-tuning case, we'll finish adding regions
2035           // to the CSet if we reach the minimum.
2036           ergo_verbose2(ErgoCSetConstruction,
2037                         "finish adding old regions to CSet",
2038                         ergo_format_reason("old CSet region num reached min")
2039                         ergo_format_region("old")
2040                         ergo_format_region("min"),
2041                         old_cset_region_length(), min_old_cset_length);
2042           break;
2043         }
2044       }
2045 
2046       // We will add this region to the CSet.
2047       time_remaining_ms = MAX2(time_remaining_ms - predicted_time_ms, 0.0);
2048       predicted_pause_time_ms += predicted_time_ms;
2049       cset_chooser->remove_and_move_to_next(hr);
2050       _g1->old_set_remove(hr);
2051       add_old_region_to_cset(hr);
2052 
2053       hr = cset_chooser->peek();
2054     }
2055     if (hr == NULL) {
2056       ergo_verbose0(ErgoCSetConstruction,
2057                     "finish adding old regions to CSet",
2058                     ergo_format_reason("candidate old regions not available"));
2059     }
2060 
2061     if (expensive_region_num > 0) {
2062       // We print the information once here at the end, predicated on
2063       // whether we added any apparently expensive regions or not, to
2064       // avoid generating output per region.
2065       ergo_verbose4(ErgoCSetConstruction,
2066                     "added expensive regions to CSet",
2067                     ergo_format_reason("old CSet region num not reached min")
2068                     ergo_format_region("old")
2069                     ergo_format_region("expensive")
2070                     ergo_format_region("min")
2071                     ergo_format_ms("remaining time"),
2072                     old_cset_region_length(),
2073                     expensive_region_num,
2074                     min_old_cset_length,
2075                     time_remaining_ms);
2076     }
2077 
2078     cset_chooser->verify();
2079   }
2080 
2081   stop_incremental_cset_building();
2082 
2083   ergo_verbose5(ErgoCSetConstruction,
2084                 "finish choosing CSet",
2085                 ergo_format_region("eden")
2086                 ergo_format_region("survivors")
2087                 ergo_format_region("old")
2088                 ergo_format_ms("predicted pause time")
2089                 ergo_format_ms("target pause time"),
2090                 eden_region_length, survivor_region_length,
2091                 old_cset_region_length(),
2092                 predicted_pause_time_ms, target_pause_time_ms);
2093 
2094   double non_young_end_time_sec = os::elapsedTime();
2095   phase_times()->record_non_young_cset_choice_time_ms((non_young_end_time_sec - non_young_start_time_sec) * 1000.0);
2096   evacuation_info.set_collectionset_regions(cset_region_length());
2097 }
2098 
2099 void TraceYoungGenTimeData::record_start_collection(double time_to_stop_the_world_ms) {
2100   if(TraceYoungGenTime) {
2101     _all_stop_world_times_ms.add(time_to_stop_the_world_ms);
2102   }
2103 }
2104 
2105 void TraceYoungGenTimeData::record_yield_time(double yield_time_ms) {
2106   if(TraceYoungGenTime) {
2107     _all_yield_times_ms.add(yield_time_ms);
2108   }
2109 }
2110 
2111 void TraceYoungGenTimeData::record_end_collection(double pause_time_ms, G1GCPhaseTimes* phase_times) {
2112   if(TraceYoungGenTime) {
2113     _total.add(pause_time_ms);
2114     _other.add(pause_time_ms - phase_times->accounted_time_ms());
2115     _root_region_scan_wait.add(phase_times->root_region_scan_wait_time_ms());
2116     _parallel.add(phase_times->cur_collection_par_time_ms());
2117     _ext_root_scan.add(phase_times->average_time_ms(G1GCPhaseTimes::ExtRootScan));
2118     _satb_filtering.add(phase_times->average_time_ms(G1GCPhaseTimes::SATBFiltering));
2119     _update_rs.add(phase_times->average_time_ms(G1GCPhaseTimes::UpdateRS));
2120     _scan_rs.add(phase_times->average_time_ms(G1GCPhaseTimes::ScanRS));
2121     _obj_copy.add(phase_times->average_time_ms(G1GCPhaseTimes::ObjCopy));
2122     _termination.add(phase_times->average_time_ms(G1GCPhaseTimes::Termination));
2123 
2124     double parallel_known_time = phase_times->average_time_ms(G1GCPhaseTimes::ExtRootScan) +
2125       phase_times->average_time_ms(G1GCPhaseTimes::SATBFiltering) +
2126       phase_times->average_time_ms(G1GCPhaseTimes::UpdateRS) +
2127       phase_times->average_time_ms(G1GCPhaseTimes::ScanRS) +
2128       phase_times->average_time_ms(G1GCPhaseTimes::ObjCopy) +
2129       phase_times->average_time_ms(G1GCPhaseTimes::Termination);
2130 
2131     double parallel_other_time = phase_times->cur_collection_par_time_ms() - parallel_known_time;
2132     _parallel_other.add(parallel_other_time);
2133     _clear_ct.add(phase_times->cur_clear_ct_time_ms());
2134   }
2135 }
2136 
2137 void TraceYoungGenTimeData::increment_young_collection_count() {
2138   if(TraceYoungGenTime) {
2139     ++_young_pause_num;
2140   }
2141 }
2142 
2143 void TraceYoungGenTimeData::increment_mixed_collection_count() {
2144   if(TraceYoungGenTime) {
2145     ++_mixed_pause_num;
2146   }
2147 }
2148 
2149 void TraceYoungGenTimeData::print_summary(const char* str,
2150                                           const NumberSeq* seq) const {
2151   double sum = seq->sum();
2152   gclog_or_tty->print_cr("%-27s = %8.2lf s (avg = %8.2lf ms)",
2153                 str, sum / 1000.0, seq->avg());
2154 }
2155 
2156 void TraceYoungGenTimeData::print_summary_sd(const char* str,
2157                                              const NumberSeq* seq) const {
2158   print_summary(str, seq);
2159   gclog_or_tty->print_cr("%+45s = %5d, std dev = %8.2lf ms, max = %8.2lf ms)",
2160                 "(num", seq->num(), seq->sd(), seq->maximum());
2161 }
2162 
2163 void TraceYoungGenTimeData::print() const {
2164   if (!TraceYoungGenTime) {
2165     return;
2166   }
2167 
2168   gclog_or_tty->print_cr("ALL PAUSES");
2169   print_summary_sd("   Total", &_total);
2170   gclog_or_tty->cr();
2171   gclog_or_tty->cr();
2172   gclog_or_tty->print_cr("   Young GC Pauses: %8d", _young_pause_num);
2173   gclog_or_tty->print_cr("   Mixed GC Pauses: %8d", _mixed_pause_num);
2174   gclog_or_tty->cr();
2175 
2176   gclog_or_tty->print_cr("EVACUATION PAUSES");
2177 
2178   if (_young_pause_num == 0 && _mixed_pause_num == 0) {
2179     gclog_or_tty->print_cr("none");
2180   } else {
2181     print_summary_sd("   Evacuation Pauses", &_total);
2182     print_summary("      Root Region Scan Wait", &_root_region_scan_wait);
2183     print_summary("      Parallel Time", &_parallel);
2184     print_summary("         Ext Root Scanning", &_ext_root_scan);
2185     print_summary("         SATB Filtering", &_satb_filtering);
2186     print_summary("         Update RS", &_update_rs);
2187     print_summary("         Scan RS", &_scan_rs);
2188     print_summary("         Object Copy", &_obj_copy);
2189     print_summary("         Termination", &_termination);
2190     print_summary("         Parallel Other", &_parallel_other);
2191     print_summary("      Clear CT", &_clear_ct);
2192     print_summary("      Other", &_other);
2193   }
2194   gclog_or_tty->cr();
2195 
2196   gclog_or_tty->print_cr("MISC");
2197   print_summary_sd("   Stop World", &_all_stop_world_times_ms);
2198   print_summary_sd("   Yields", &_all_yield_times_ms);
2199 }
2200 
2201 void TraceOldGenTimeData::record_full_collection(double full_gc_time_ms) {
2202   if (TraceOldGenTime) {
2203     _all_full_gc_times.add(full_gc_time_ms);
2204   }
2205 }
2206 
2207 void TraceOldGenTimeData::print() const {
2208   if (!TraceOldGenTime) {
2209     return;
2210   }
2211 
2212   if (_all_full_gc_times.num() > 0) {
2213     gclog_or_tty->print("\n%4d full_gcs: total time = %8.2f s",
2214       _all_full_gc_times.num(),
2215       _all_full_gc_times.sum() / 1000.0);
2216     gclog_or_tty->print_cr(" (avg = %8.2fms).", _all_full_gc_times.avg());
2217     gclog_or_tty->print_cr("                     [std. dev = %8.2f ms, max = %8.2f ms]",
2218       _all_full_gc_times.sd(),
2219       _all_full_gc_times.maximum());
2220   }
2221 }