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