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