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