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